agents 0.0.0-dc0e8de → 0.0.0-dc7a99c

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 (45) hide show
  1. package/dist/ai-chat-agent.d.ts +32 -5
  2. package/dist/ai-chat-agent.js +149 -115
  3. package/dist/ai-chat-agent.js.map +1 -1
  4. package/dist/ai-react.d.ts +17 -4
  5. package/dist/ai-react.js +28 -29
  6. package/dist/ai-react.js.map +1 -1
  7. package/dist/chunk-767EASBA.js +106 -0
  8. package/dist/chunk-767EASBA.js.map +1 -0
  9. package/dist/{chunk-Q5ZBHY4Z.js → chunk-E3LCYPCB.js} +49 -36
  10. package/dist/chunk-E3LCYPCB.js.map +1 -0
  11. package/dist/{chunk-HD4VEHBA.js → chunk-JFRK72K3.js} +463 -161
  12. package/dist/chunk-JFRK72K3.js.map +1 -0
  13. package/dist/chunk-NKZZ66QY.js +116 -0
  14. package/dist/chunk-NKZZ66QY.js.map +1 -0
  15. package/dist/client.d.ts +15 -1
  16. package/dist/client.js +6 -126
  17. package/dist/client.js.map +1 -1
  18. package/dist/index-CITGJflw.d.ts +486 -0
  19. package/dist/index.d.ts +25 -308
  20. package/dist/index.js +4 -3
  21. package/dist/mcp/client.d.ts +301 -23
  22. package/dist/mcp/client.js +1 -2
  23. package/dist/mcp/do-oauth-client-provider.d.ts +3 -3
  24. package/dist/mcp/do-oauth-client-provider.js +3 -103
  25. package/dist/mcp/do-oauth-client-provider.js.map +1 -1
  26. package/dist/mcp/index.d.ts +17 -7
  27. package/dist/mcp/index.js +147 -173
  28. package/dist/mcp/index.js.map +1 -1
  29. package/dist/observability/index.d.ts +12 -0
  30. package/dist/observability/index.js +10 -0
  31. package/dist/react.d.ts +85 -5
  32. package/dist/react.js +20 -8
  33. package/dist/react.js.map +1 -1
  34. package/dist/schedule.d.ts +6 -6
  35. package/dist/schedule.js +4 -6
  36. package/dist/schedule.js.map +1 -1
  37. package/dist/serializable.d.ts +32 -0
  38. package/dist/serializable.js +1 -0
  39. package/dist/serializable.js.map +1 -0
  40. package/package.json +75 -68
  41. package/src/index.ts +506 -83
  42. package/dist/chunk-HD4VEHBA.js.map +0 -1
  43. package/dist/chunk-HMLY7DHA.js +0 -16
  44. package/dist/chunk-Q5ZBHY4Z.js.map +0 -1
  45. /package/dist/{chunk-HMLY7DHA.js.map → observability/index.js.map} +0 -0
@@ -1,15 +1,15 @@
1
- import { Agent, AgentContext } from "./index.js";
2
1
  import { Message, StreamTextOnFinishCallback, ToolSet } from "ai";
2
+ import { A as Agent, a as AgentContext } from "./index-CITGJflw.js";
3
3
  import { Connection, WSMessage } from "partyserver";
4
+ import "@modelcontextprotocol/sdk/client/index.js";
5
+ import "@modelcontextprotocol/sdk/types.js";
4
6
  import "./mcp/client.js";
5
7
  import "zod";
6
- import "@modelcontextprotocol/sdk/types.js";
7
- import "@modelcontextprotocol/sdk/client/index.js";
8
8
  import "@modelcontextprotocol/sdk/client/sse.js";
9
+ import "@modelcontextprotocol/sdk/shared/protocol.js";
9
10
  import "./mcp/do-oauth-client-provider.js";
10
11
  import "@modelcontextprotocol/sdk/client/auth.js";
11
12
  import "@modelcontextprotocol/sdk/shared/auth.js";
12
- import "@modelcontextprotocol/sdk/shared/protocol.js";
13
13
 
14
14
  /**
15
15
  * Extension of Agent with built-in chat capabilities
@@ -19,12 +19,18 @@ declare class AIChatAgent<Env = unknown, State = unknown> extends Agent<
19
19
  Env,
20
20
  State
21
21
  > {
22
- #private;
22
+ /**
23
+ * Map of message `id`s to `AbortController`s
24
+ * useful to propagate request cancellation signals for any external calls made by the agent
25
+ */
26
+ private _chatMessageAbortControllers;
23
27
  /** Array of chat messages for the current conversation */
24
28
  messages: Message[];
25
29
  constructor(ctx: AgentContext, env: Env);
30
+ private _broadcastChatMessage;
26
31
  onMessage(connection: Connection, message: WSMessage): Promise<void>;
27
32
  onRequest(request: Request): Promise<Response>;
33
+ private _tryCatchChat;
28
34
  /**
29
35
  * Handle incoming chat messages and generate a response
30
36
  * @param onFinish Callback to be called when the response is finished
@@ -46,6 +52,27 @@ declare class AIChatAgent<Env = unknown, State = unknown> extends Agent<
46
52
  messages: Message[],
47
53
  excludeBroadcastIds?: string[]
48
54
  ): Promise<void>;
55
+ private _messagesNotAlreadyInAgent;
56
+ private _reply;
57
+ /**
58
+ * For the given message id, look up its associated AbortController
59
+ * If the AbortController does not exist, create and store one in memory
60
+ *
61
+ * returns the AbortSignal associated with the AbortController
62
+ */
63
+ private _getAbortSignal;
64
+ /**
65
+ * Remove an abort controller from the cache of pending message responses
66
+ */
67
+ private _removeAbortController;
68
+ /**
69
+ * Propagate an abort signal for any requests associated with the given message id
70
+ */
71
+ private _cancelChatRequest;
72
+ /**
73
+ * Abort all pending requests and clear the cache of AbortControllers
74
+ */
75
+ private _destroyAbortControllers;
49
76
  /**
50
77
  * When the DO is destroyed, cancel all pending requests
51
78
  */
@@ -1,27 +1,16 @@
1
1
  import {
2
2
  Agent
3
- } from "./chunk-HD4VEHBA.js";
4
- import "./chunk-Q5ZBHY4Z.js";
5
- import {
6
- __privateAdd,
7
- __privateGet,
8
- __privateMethod,
9
- __privateSet
10
- } from "./chunk-HMLY7DHA.js";
3
+ } from "./chunk-JFRK72K3.js";
4
+ import "./chunk-E3LCYPCB.js";
5
+ import "./chunk-767EASBA.js";
6
+ import "./chunk-NKZZ66QY.js";
11
7
 
12
8
  // src/ai-chat-agent.ts
13
9
  import { appendResponseMessages } from "ai";
14
10
  var decoder = new TextDecoder();
15
- var _chatMessageAbortControllers, _AIChatAgent_instances, broadcastChatMessage_fn, tryCatch_fn, reply_fn, getAbortSignal_fn, removeAbortController_fn, cancelChatRequest_fn, destroyAbortControllers_fn;
16
11
  var AIChatAgent = class extends Agent {
17
12
  constructor(ctx, env) {
18
13
  super(ctx, env);
19
- __privateAdd(this, _AIChatAgent_instances);
20
- /**
21
- * Map of message `id`s to `AbortController`s
22
- * useful to propagate request cancellation signals for any external calls made by the agent
23
- */
24
- __privateAdd(this, _chatMessageAbortControllers);
25
14
  this.sql`create table if not exists cf_ai_chat_agent_messages (
26
15
  id text primary key,
27
16
  message text not null,
@@ -30,74 +19,117 @@ var AIChatAgent = class extends Agent {
30
19
  this.messages = (this.sql`select * from cf_ai_chat_agent_messages` || []).map((row) => {
31
20
  return JSON.parse(row.message);
32
21
  });
33
- __privateSet(this, _chatMessageAbortControllers, /* @__PURE__ */ new Map());
22
+ this._chatMessageAbortControllers = /* @__PURE__ */ new Map();
23
+ }
24
+ _broadcastChatMessage(message, exclude) {
25
+ this.broadcast(JSON.stringify(message), exclude);
34
26
  }
35
27
  async onMessage(connection, message) {
36
28
  if (typeof message === "string") {
37
29
  let data;
38
30
  try {
39
31
  data = JSON.parse(message);
40
- } catch (error) {
32
+ } catch (_error) {
41
33
  return;
42
34
  }
43
35
  if (data.type === "cf_agent_use_chat_request" && data.init.method === "POST") {
44
36
  const {
45
- method,
46
- keepalive,
47
- headers,
48
- body,
37
+ // method,
38
+ // keepalive,
39
+ // headers,
40
+ body
49
41
  // we're reading this
50
- redirect,
51
- integrity,
52
- credentials,
53
- mode,
54
- referrer,
55
- referrerPolicy,
56
- window
42
+ //
43
+ // // these might not exist?
57
44
  // dispatcher,
58
45
  // duplex
59
46
  } = data.init;
60
47
  const { messages } = JSON.parse(body);
61
- __privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
62
- type: "cf_agent_chat_messages",
63
- messages
64
- }, [connection.id]);
48
+ this._broadcastChatMessage(
49
+ {
50
+ messages,
51
+ type: "cf_agent_chat_messages"
52
+ },
53
+ [connection.id]
54
+ );
55
+ const incomingMessages = this._messagesNotAlreadyInAgent(messages);
65
56
  await this.persistMessages(messages, [connection.id]);
57
+ this.observability?.emit(
58
+ {
59
+ displayMessage: "Chat message request",
60
+ id: data.id,
61
+ payload: {
62
+ message: incomingMessages
63
+ },
64
+ timestamp: Date.now(),
65
+ type: "message:request"
66
+ },
67
+ this.ctx
68
+ );
66
69
  const chatMessageId = data.id;
67
- const abortSignal = __privateMethod(this, _AIChatAgent_instances, getAbortSignal_fn).call(this, chatMessageId);
68
- return __privateMethod(this, _AIChatAgent_instances, tryCatch_fn).call(this, async () => {
70
+ const abortSignal = this._getAbortSignal(chatMessageId);
71
+ return this._tryCatchChat(async () => {
69
72
  const response = await this.onChatMessage(
70
73
  async ({ response: response2 }) => {
71
74
  const finalMessages = appendResponseMessages({
72
75
  messages,
73
76
  responseMessages: response2.messages
74
77
  });
78
+ const outgoingMessages = this._messagesNotAlreadyInAgent(finalMessages);
75
79
  await this.persistMessages(finalMessages, [connection.id]);
76
- __privateMethod(this, _AIChatAgent_instances, removeAbortController_fn).call(this, chatMessageId);
80
+ this._removeAbortController(chatMessageId);
81
+ this.observability?.emit(
82
+ {
83
+ displayMessage: "Chat message response",
84
+ id: data.id,
85
+ payload: {
86
+ message: outgoingMessages
87
+ },
88
+ timestamp: Date.now(),
89
+ type: "message:response"
90
+ },
91
+ this.ctx
92
+ );
77
93
  },
78
94
  abortSignal ? { abortSignal } : void 0
79
95
  );
80
96
  if (response) {
81
- await __privateMethod(this, _AIChatAgent_instances, reply_fn).call(this, data.id, response);
97
+ await this._reply(data.id, response);
98
+ } else {
99
+ console.warn(
100
+ `[AIChatAgent] onChatMessage returned no response for chatMessageId: ${chatMessageId}`
101
+ );
102
+ this._broadcastChatMessage(
103
+ {
104
+ body: "No response was generated by the agent.",
105
+ done: true,
106
+ id: data.id,
107
+ type: "cf_agent_use_chat_response"
108
+ },
109
+ [connection.id]
110
+ );
82
111
  }
83
112
  });
84
113
  }
85
114
  if (data.type === "cf_agent_chat_clear") {
86
- __privateMethod(this, _AIChatAgent_instances, destroyAbortControllers_fn).call(this);
115
+ this._destroyAbortControllers();
87
116
  this.sql`delete from cf_ai_chat_agent_messages`;
88
117
  this.messages = [];
89
- __privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
90
- type: "cf_agent_chat_clear"
91
- }, [connection.id]);
118
+ this._broadcastChatMessage(
119
+ {
120
+ type: "cf_agent_chat_clear"
121
+ },
122
+ [connection.id]
123
+ );
92
124
  } else if (data.type === "cf_agent_chat_messages") {
93
125
  await this.persistMessages(data.messages, [connection.id]);
94
126
  } else if (data.type === "cf_agent_chat_request_cancel") {
95
- __privateMethod(this, _AIChatAgent_instances, cancelChatRequest_fn).call(this, data.id);
127
+ this._cancelChatRequest(data.id);
96
128
  }
97
129
  }
98
130
  }
99
131
  async onRequest(request) {
100
- return __privateMethod(this, _AIChatAgent_instances, tryCatch_fn).call(this, () => {
132
+ return this._tryCatchChat(() => {
101
133
  const url = new URL(request.url);
102
134
  if (url.pathname.endsWith("/get-messages")) {
103
135
  const messages = (this.sql`select * from cf_ai_chat_agent_messages` || []).map((row) => {
@@ -108,6 +140,13 @@ var AIChatAgent = class extends Agent {
108
140
  return super.onRequest(request);
109
141
  });
110
142
  }
143
+ async _tryCatchChat(fn) {
144
+ try {
145
+ return await fn();
146
+ } catch (e) {
147
+ throw this.onError(e);
148
+ }
149
+ }
111
150
  /**
112
151
  * Handle incoming chat messages and generate a response
113
152
  * @param onFinish Callback to be called when the response is finished
@@ -145,88 +184,83 @@ var AIChatAgent = class extends Agent {
145
184
  this.sql`insert into cf_ai_chat_agent_messages (id, message) values (${message.id},${JSON.stringify(message)})`;
146
185
  }
147
186
  this.messages = messages;
148
- __privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
149
- type: "cf_agent_chat_messages",
150
- messages
151
- }, excludeBroadcastIds);
152
- }
153
- /**
154
- * When the DO is destroyed, cancel all pending requests
155
- */
156
- async destroy() {
157
- __privateMethod(this, _AIChatAgent_instances, destroyAbortControllers_fn).call(this);
158
- await super.destroy();
187
+ this._broadcastChatMessage(
188
+ {
189
+ messages,
190
+ type: "cf_agent_chat_messages"
191
+ },
192
+ excludeBroadcastIds
193
+ );
159
194
  }
160
- };
161
- _chatMessageAbortControllers = new WeakMap();
162
- _AIChatAgent_instances = new WeakSet();
163
- broadcastChatMessage_fn = function(message, exclude) {
164
- this.broadcast(JSON.stringify(message), exclude);
165
- };
166
- tryCatch_fn = async function(fn) {
167
- try {
168
- return await fn();
169
- } catch (e) {
170
- throw this.onError(e);
195
+ _messagesNotAlreadyInAgent(messages) {
196
+ const existingIds = new Set(this.messages.map((message) => message.id));
197
+ return messages.filter((message) => !existingIds.has(message.id));
171
198
  }
172
- };
173
- reply_fn = async function(id, response) {
174
- return __privateMethod(this, _AIChatAgent_instances, tryCatch_fn).call(this, async () => {
175
- for await (const chunk of response.body) {
176
- const body = decoder.decode(chunk);
177
- __privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
199
+ async _reply(id, response) {
200
+ return this._tryCatchChat(async () => {
201
+ for await (const chunk of response.body) {
202
+ const body = decoder.decode(chunk);
203
+ this._broadcastChatMessage({
204
+ body,
205
+ done: false,
206
+ id,
207
+ type: "cf_agent_use_chat_response"
208
+ });
209
+ }
210
+ this._broadcastChatMessage({
211
+ body: "",
212
+ done: true,
178
213
  id,
179
- type: "cf_agent_use_chat_response",
180
- body,
181
- done: false
214
+ type: "cf_agent_use_chat_response"
182
215
  });
183
- }
184
- __privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
185
- id,
186
- type: "cf_agent_use_chat_response",
187
- body: "",
188
- done: true
189
216
  });
190
- });
191
- };
192
- /**
193
- * For the given message id, look up its associated AbortController
194
- * If the AbortController does not exist, create and store one in memory
195
- *
196
- * returns the AbortSignal associated with the AbortController
197
- */
198
- getAbortSignal_fn = function(id) {
199
- if (typeof id !== "string") {
200
- return void 0;
201
217
  }
202
- if (!__privateGet(this, _chatMessageAbortControllers).has(id)) {
203
- __privateGet(this, _chatMessageAbortControllers).set(id, new AbortController());
218
+ /**
219
+ * For the given message id, look up its associated AbortController
220
+ * If the AbortController does not exist, create and store one in memory
221
+ *
222
+ * returns the AbortSignal associated with the AbortController
223
+ */
224
+ _getAbortSignal(id) {
225
+ if (typeof id !== "string") {
226
+ return void 0;
227
+ }
228
+ if (!this._chatMessageAbortControllers.has(id)) {
229
+ this._chatMessageAbortControllers.set(id, new AbortController());
230
+ }
231
+ return this._chatMessageAbortControllers.get(id)?.signal;
204
232
  }
205
- return __privateGet(this, _chatMessageAbortControllers).get(id)?.signal;
206
- };
207
- /**
208
- * Remove an abort controller from the cache of pending message responses
209
- */
210
- removeAbortController_fn = function(id) {
211
- __privateGet(this, _chatMessageAbortControllers).delete(id);
212
- };
213
- /**
214
- * Propagate an abort signal for any requests associated with the given message id
215
- */
216
- cancelChatRequest_fn = function(id) {
217
- if (__privateGet(this, _chatMessageAbortControllers).has(id)) {
218
- const abortController = __privateGet(this, _chatMessageAbortControllers).get(id);
219
- abortController?.abort();
233
+ /**
234
+ * Remove an abort controller from the cache of pending message responses
235
+ */
236
+ _removeAbortController(id) {
237
+ this._chatMessageAbortControllers.delete(id);
220
238
  }
221
- };
222
- /**
223
- * Abort all pending requests and clear the cache of AbortControllers
224
- */
225
- destroyAbortControllers_fn = function() {
226
- for (const controller of __privateGet(this, _chatMessageAbortControllers).values()) {
227
- controller?.abort();
239
+ /**
240
+ * Propagate an abort signal for any requests associated with the given message id
241
+ */
242
+ _cancelChatRequest(id) {
243
+ if (this._chatMessageAbortControllers.has(id)) {
244
+ const abortController = this._chatMessageAbortControllers.get(id);
245
+ abortController?.abort();
246
+ }
247
+ }
248
+ /**
249
+ * Abort all pending requests and clear the cache of AbortControllers
250
+ */
251
+ _destroyAbortControllers() {
252
+ for (const controller of this._chatMessageAbortControllers.values()) {
253
+ controller?.abort();
254
+ }
255
+ this._chatMessageAbortControllers.clear();
256
+ }
257
+ /**
258
+ * When the DO is destroyed, cancel all pending requests
259
+ */
260
+ async destroy() {
261
+ this._destroyAbortControllers();
262
+ await super.destroy();
228
263
  }
229
- __privateGet(this, _chatMessageAbortControllers).clear();
230
264
  };
231
265
  export {
232
266
  AIChatAgent
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ai-chat-agent.ts"],"sourcesContent":["import { Agent, type AgentContext, type Connection, type WSMessage } from \"./\";\nimport type {\n Message as ChatMessage,\n StreamTextOnFinishCallback,\n ToolSet,\n} from \"ai\";\nimport { appendResponseMessages } from \"ai\";\nimport type { OutgoingMessage, IncomingMessage } from \"./ai-types\";\n\nconst decoder = new TextDecoder();\n\n/**\n * Extension of Agent with built-in chat capabilities\n * @template Env Environment type containing bindings\n */\nexport class AIChatAgent<Env = unknown, State = unknown> extends Agent<\n Env,\n State\n> {\n /**\n * Map of message `id`s to `AbortController`s\n * useful to propagate request cancellation signals for any external calls made by the agent\n */\n #chatMessageAbortControllers: Map<string, AbortController>;\n /** Array of chat messages for the current conversation */\n messages: ChatMessage[];\n constructor(ctx: AgentContext, env: Env) {\n super(ctx, env);\n this.sql`create table if not exists cf_ai_chat_agent_messages (\n id text primary key,\n message text not null,\n created_at datetime default current_timestamp\n )`;\n this.messages = (\n this.sql`select * from cf_ai_chat_agent_messages` || []\n ).map((row) => {\n return JSON.parse(row.message as string);\n });\n\n this.#chatMessageAbortControllers = new Map();\n }\n\n #broadcastChatMessage(message: OutgoingMessage, exclude?: string[]) {\n this.broadcast(JSON.stringify(message), exclude);\n }\n\n override async onMessage(connection: Connection, message: WSMessage) {\n if (typeof message === \"string\") {\n let data: IncomingMessage;\n try {\n data = JSON.parse(message) as IncomingMessage;\n } catch (error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (\n data.type === \"cf_agent_use_chat_request\" &&\n data.init.method === \"POST\"\n ) {\n const {\n method,\n keepalive,\n headers,\n body, // we're reading this\n redirect,\n integrity,\n credentials,\n mode,\n referrer,\n referrerPolicy,\n window,\n // dispatcher,\n // duplex\n } = data.init;\n const { messages } = JSON.parse(body as string);\n this.#broadcastChatMessage(\n {\n type: \"cf_agent_chat_messages\",\n messages,\n },\n [connection.id]\n );\n await this.persistMessages(messages, [connection.id]);\n\n const chatMessageId = data.id;\n const abortSignal = this.#getAbortSignal(chatMessageId);\n\n return this.#tryCatch(async () => {\n const response = await this.onChatMessage(\n async ({ response }) => {\n const finalMessages = appendResponseMessages({\n messages,\n responseMessages: response.messages,\n });\n\n await this.persistMessages(finalMessages, [connection.id]);\n this.#removeAbortController(chatMessageId);\n },\n abortSignal ? { abortSignal } : undefined\n );\n\n if (response) {\n await this.#reply(data.id, response);\n }\n });\n }\n if (data.type === \"cf_agent_chat_clear\") {\n this.#destroyAbortControllers();\n this.sql`delete from cf_ai_chat_agent_messages`;\n this.messages = [];\n this.#broadcastChatMessage(\n {\n type: \"cf_agent_chat_clear\",\n },\n [connection.id]\n );\n } else if (data.type === \"cf_agent_chat_messages\") {\n // replace the messages with the new ones\n await this.persistMessages(data.messages, [connection.id]);\n } else if (data.type === \"cf_agent_chat_request_cancel\") {\n // propagate an abort signal for the associated request\n this.#cancelChatRequest(data.id);\n }\n }\n }\n\n override async onRequest(request: Request): Promise<Response> {\n return this.#tryCatch(() => {\n const url = new URL(request.url);\n if (url.pathname.endsWith(\"/get-messages\")) {\n const messages = (\n this.sql`select * from cf_ai_chat_agent_messages` || []\n ).map((row) => {\n return JSON.parse(row.message as string);\n });\n return Response.json(messages);\n }\n return super.onRequest(request);\n });\n }\n\n async #tryCatch<T>(fn: () => T | Promise<T>) {\n try {\n return await fn();\n } catch (e) {\n throw this.onError(e);\n }\n }\n\n /**\n * Handle incoming chat messages and generate a response\n * @param onFinish Callback to be called when the response is finished\n * @param options.signal A signal to pass to any child requests which can be used to cancel them\n * @returns Response to send to the client or undefined\n */\n async onChatMessage(\n onFinish: StreamTextOnFinishCallback<ToolSet>,\n options?: { abortSignal: AbortSignal | undefined }\n ): Promise<Response | undefined> {\n throw new Error(\n \"recieved a chat message, override onChatMessage and return a Response to send to the client\"\n );\n }\n\n /**\n * Save messages on the server side and trigger AI response\n * @param messages Chat messages to save\n */\n async saveMessages(messages: ChatMessage[]) {\n await this.persistMessages(messages);\n const response = await this.onChatMessage(async ({ response }) => {\n const finalMessages = appendResponseMessages({\n messages,\n responseMessages: response.messages,\n });\n\n await this.persistMessages(finalMessages, []);\n });\n if (response) {\n // we're just going to drain the body\n // @ts-ignore TODO: fix this type error\n for await (const chunk of response.body!) {\n decoder.decode(chunk);\n }\n response.body?.cancel();\n }\n }\n\n async persistMessages(\n messages: ChatMessage[],\n excludeBroadcastIds: string[] = []\n ) {\n this.sql`delete from cf_ai_chat_agent_messages`;\n for (const message of messages) {\n this.sql`insert into cf_ai_chat_agent_messages (id, message) values (${\n message.id\n },${JSON.stringify(message)})`;\n }\n this.messages = messages;\n this.#broadcastChatMessage(\n {\n type: \"cf_agent_chat_messages\",\n messages: messages,\n },\n excludeBroadcastIds\n );\n }\n\n async #reply(id: string, response: Response) {\n // now take chunks out from dataStreamResponse and send them to the client\n return this.#tryCatch(async () => {\n // @ts-expect-error TODO: fix this type error\n for await (const chunk of response.body!) {\n const body = decoder.decode(chunk);\n\n this.#broadcastChatMessage({\n id,\n type: \"cf_agent_use_chat_response\",\n body,\n done: false,\n });\n }\n\n this.#broadcastChatMessage({\n id,\n type: \"cf_agent_use_chat_response\",\n body: \"\",\n done: true,\n });\n });\n }\n\n /**\n * For the given message id, look up its associated AbortController\n * If the AbortController does not exist, create and store one in memory\n *\n * returns the AbortSignal associated with the AbortController\n */\n #getAbortSignal(id: string): AbortSignal | undefined {\n // Defensive check, since we're coercing message types at the moment\n if (typeof id !== \"string\") {\n return undefined;\n }\n\n if (!this.#chatMessageAbortControllers.has(id)) {\n this.#chatMessageAbortControllers.set(id, new AbortController());\n }\n\n return this.#chatMessageAbortControllers.get(id)?.signal;\n }\n\n /**\n * Remove an abort controller from the cache of pending message responses\n */\n #removeAbortController(id: string) {\n this.#chatMessageAbortControllers.delete(id);\n }\n\n /**\n * Propagate an abort signal for any requests associated with the given message id\n */\n #cancelChatRequest(id: string) {\n if (this.#chatMessageAbortControllers.has(id)) {\n const abortController = this.#chatMessageAbortControllers.get(id);\n abortController?.abort();\n }\n }\n\n /**\n * Abort all pending requests and clear the cache of AbortControllers\n */\n #destroyAbortControllers() {\n for (const controller of this.#chatMessageAbortControllers.values()) {\n controller?.abort();\n }\n this.#chatMessageAbortControllers.clear();\n }\n\n /**\n * When the DO is destroyed, cancel all pending requests\n */\n async destroy() {\n this.#destroyAbortControllers();\n await super.destroy();\n }\n}\n"],"mappings":";;;;;;;;;;;;AAMA,SAAS,8BAA8B;AAGvC,IAAM,UAAU,IAAI,YAAY;AAThC;AAeO,IAAM,cAAN,cAA0D,MAG/D;AAAA,EAQA,YAAY,KAAmB,KAAU;AACvC,UAAM,KAAK,GAAG;AAZX;AAQL;AAAA;AAAA;AAAA;AAAA;AAKE,SAAK;AAAA;AAAA;AAAA;AAAA;AAKL,SAAK,YACH,KAAK,gDAAgD,CAAC,GACtD,IAAI,CAAC,QAAQ;AACb,aAAO,KAAK,MAAM,IAAI,OAAiB;AAAA,IACzC,CAAC;AAED,uBAAK,8BAA+B,oBAAI,IAAI;AAAA,EAC9C;AAAA,EAMA,MAAe,UAAU,YAAwB,SAAoB;AACnE,QAAI,OAAO,YAAY,UAAU;AAC/B,UAAI;AACJ,UAAI;AACF,eAAO,KAAK,MAAM,OAAO;AAAA,MAC3B,SAAS,OAAO;AAGd;AAAA,MACF;AACA,UACE,KAAK,SAAS,+BACd,KAAK,KAAK,WAAW,QACrB;AACA,cAAM;AAAA,UACJ;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA;AAAA;AAAA,QAGF,IAAI,KAAK;AACT,cAAM,EAAE,SAAS,IAAI,KAAK,MAAM,IAAc;AAC9C,8BAAK,iDAAL,WACE;AAAA,UACE,MAAM;AAAA,UACN;AAAA,QACF,GACA,CAAC,WAAW,EAAE;AAEhB,cAAM,KAAK,gBAAgB,UAAU,CAAC,WAAW,EAAE,CAAC;AAEpD,cAAM,gBAAgB,KAAK;AAC3B,cAAM,cAAc,sBAAK,2CAAL,WAAqB;AAEzC,eAAO,sBAAK,qCAA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Q,OAAO,KAAK;AAEjC,4BAAK,iDAAL,WAA2B;AAAA,QACzB;AAAA,QACA,MAAM;AAAA,QACN;AAAA,QACA,MAAM;AAAA,MACR;AAAA,IACF;AAEA,0BAAK,iDAAL,WAA2B;AAAA,MACzB;AAAA,MACA,MAAM;AAAA,MACN,MAAM;AAAA,MACN,MAAM;AAAA,IACR;AAAA,EACF;AACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,oBAAe,SAAC,IAAqC;AAEnD,MAAI,OAAO,OAAO,UAAU;AAC1B,WAAO;AAAA,EACT;AAEA,MAAI,CAAC,mBAAK,8BAA6B,IAAI,EAAE,GAAG;AAC9C,uBAAK,8BAA6B,IAAI,IAAI,IAAI,gBAAgB,CAAC;AAAA,EACjE;AAEA,SAAO,mBAAK,8BAA6B,IAAI,EAAE,GAAG;AACpD;AAAA;AAAA;AAAA;AAKA,2BAAsB,SAAC,IAAY;AACjC,qBAAK,8BAA6B,OAAO,EAAE;AAC7C;AAAA;AAAA;AAAA;AAKA,uBAAkB,SAAC,IAAY;AAC7B,MAAI,mBAAK,8BAA6B,IAAI,EAAE,GAAG;AAC7C,UAAM,kBAAkB,mBAAK,8BAA6B,IAAI,EAAE;AAChE,qBAAiB,MAAM;AAAA,EACzB;AACF;AAAA;AAAA;AAAA;AAKA,6BAAwB,WAAG;AACzB,aAAW,cAAc,mBAAK,8BAA6B,OAAO,GAAG;AACnE,gBAAY,MAAM;AAAA,EACpB;AACA,qBAAK,8BAA6B,MAAM;AAC1C;","names":["response"]}
1
+ {"version":3,"sources":["../src/ai-chat-agent.ts"],"sourcesContent":["import type {\n Message as ChatMessage,\n StreamTextOnFinishCallback,\n ToolSet,\n} from \"ai\";\nimport { appendResponseMessages } from \"ai\";\nimport { Agent, type AgentContext, type Connection, type WSMessage } from \"./\";\nimport type { IncomingMessage, OutgoingMessage } from \"./ai-types\";\n\nconst decoder = new TextDecoder();\n\n/**\n * Extension of Agent with built-in chat capabilities\n * @template Env Environment type containing bindings\n */\nexport class AIChatAgent<Env = unknown, State = unknown> extends Agent<\n Env,\n State\n> {\n /**\n * Map of message `id`s to `AbortController`s\n * useful to propagate request cancellation signals for any external calls made by the agent\n */\n private _chatMessageAbortControllers: Map<string, AbortController>;\n /** Array of chat messages for the current conversation */\n messages: ChatMessage[];\n constructor(ctx: AgentContext, env: Env) {\n super(ctx, env);\n this.sql`create table if not exists cf_ai_chat_agent_messages (\n id text primary key,\n message text not null,\n created_at datetime default current_timestamp\n )`;\n this.messages = (\n this.sql`select * from cf_ai_chat_agent_messages` || []\n ).map((row) => {\n return JSON.parse(row.message as string);\n });\n\n this._chatMessageAbortControllers = new Map();\n }\n\n private _broadcastChatMessage(message: OutgoingMessage, exclude?: string[]) {\n this.broadcast(JSON.stringify(message), exclude);\n }\n\n override async onMessage(connection: Connection, message: WSMessage) {\n if (typeof message === \"string\") {\n let data: IncomingMessage;\n try {\n data = JSON.parse(message) as IncomingMessage;\n } catch (_error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (\n data.type === \"cf_agent_use_chat_request\" &&\n data.init.method === \"POST\"\n ) {\n const {\n // method,\n // keepalive,\n // headers,\n body, // we're reading this\n //\n // // these might not exist?\n // dispatcher,\n // duplex\n } = data.init;\n const { messages } = JSON.parse(body as string);\n this._broadcastChatMessage(\n {\n messages,\n type: \"cf_agent_chat_messages\",\n },\n [connection.id]\n );\n\n const incomingMessages = this._messagesNotAlreadyInAgent(messages);\n await this.persistMessages(messages, [connection.id]);\n\n this.observability?.emit(\n {\n displayMessage: \"Chat message request\",\n id: data.id,\n payload: {\n message: incomingMessages,\n },\n timestamp: Date.now(),\n type: \"message:request\",\n },\n this.ctx\n );\n\n const chatMessageId = data.id;\n const abortSignal = this._getAbortSignal(chatMessageId);\n\n return this._tryCatchChat(async () => {\n const response = await this.onChatMessage(\n async ({ response }) => {\n const finalMessages = appendResponseMessages({\n messages,\n responseMessages: response.messages,\n });\n\n const outgoingMessages =\n this._messagesNotAlreadyInAgent(finalMessages);\n await this.persistMessages(finalMessages, [connection.id]);\n this._removeAbortController(chatMessageId);\n\n this.observability?.emit(\n {\n displayMessage: \"Chat message response\",\n id: data.id,\n payload: {\n message: outgoingMessages,\n },\n timestamp: Date.now(),\n type: \"message:response\",\n },\n this.ctx\n );\n },\n abortSignal ? { abortSignal } : undefined\n );\n\n if (response) {\n await this._reply(data.id, response);\n } else {\n // Log a warning for observability\n console.warn(\n `[AIChatAgent] onChatMessage returned no response for chatMessageId: ${chatMessageId}`\n );\n // Send a fallback message to the client\n this._broadcastChatMessage(\n {\n body: \"No response was generated by the agent.\",\n done: true,\n id: data.id,\n type: \"cf_agent_use_chat_response\",\n },\n [connection.id]\n );\n }\n });\n }\n if (data.type === \"cf_agent_chat_clear\") {\n this._destroyAbortControllers();\n this.sql`delete from cf_ai_chat_agent_messages`;\n this.messages = [];\n this._broadcastChatMessage(\n {\n type: \"cf_agent_chat_clear\",\n },\n [connection.id]\n );\n } else if (data.type === \"cf_agent_chat_messages\") {\n // replace the messages with the new ones\n await this.persistMessages(data.messages, [connection.id]);\n } else if (data.type === \"cf_agent_chat_request_cancel\") {\n // propagate an abort signal for the associated request\n this._cancelChatRequest(data.id);\n }\n }\n }\n\n override async onRequest(request: Request): Promise<Response> {\n return this._tryCatchChat(() => {\n const url = new URL(request.url);\n if (url.pathname.endsWith(\"/get-messages\")) {\n const messages = (\n this.sql`select * from cf_ai_chat_agent_messages` || []\n ).map((row) => {\n return JSON.parse(row.message as string);\n });\n return Response.json(messages);\n }\n return super.onRequest(request);\n });\n }\n\n private async _tryCatchChat<T>(fn: () => T | Promise<T>) {\n try {\n return await fn();\n } catch (e) {\n throw this.onError(e);\n }\n }\n\n /**\n * Handle incoming chat messages and generate a response\n * @param onFinish Callback to be called when the response is finished\n * @param options.signal A signal to pass to any child requests which can be used to cancel them\n * @returns Response to send to the client or undefined\n */\n async onChatMessage(\n // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later\n onFinish: StreamTextOnFinishCallback<ToolSet>,\n // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later\n options?: { abortSignal: AbortSignal | undefined }\n ): Promise<Response | undefined> {\n throw new Error(\n \"recieved a chat message, override onChatMessage and return a Response to send to the client\"\n );\n }\n\n /**\n * Save messages on the server side and trigger AI response\n * @param messages Chat messages to save\n */\n async saveMessages(messages: ChatMessage[]) {\n await this.persistMessages(messages);\n const response = await this.onChatMessage(async ({ response }) => {\n const finalMessages = appendResponseMessages({\n messages,\n responseMessages: response.messages,\n });\n\n await this.persistMessages(finalMessages, []);\n });\n if (response) {\n // we're just going to drain the body\n // @ts-ignore TODO: fix this type error\n for await (const chunk of response.body!) {\n decoder.decode(chunk);\n }\n response.body?.cancel();\n }\n }\n\n async persistMessages(\n messages: ChatMessage[],\n excludeBroadcastIds: string[] = []\n ) {\n this.sql`delete from cf_ai_chat_agent_messages`;\n for (const message of messages) {\n this.sql`insert into cf_ai_chat_agent_messages (id, message) values (${\n message.id\n },${JSON.stringify(message)})`;\n }\n this.messages = messages;\n this._broadcastChatMessage(\n {\n messages: messages,\n type: \"cf_agent_chat_messages\",\n },\n excludeBroadcastIds\n );\n }\n\n private _messagesNotAlreadyInAgent(messages: ChatMessage[]) {\n const existingIds = new Set(this.messages.map((message) => message.id));\n return messages.filter((message) => !existingIds.has(message.id));\n }\n\n private async _reply(id: string, response: Response) {\n // now take chunks out from dataStreamResponse and send them to the client\n return this._tryCatchChat(async () => {\n // @ts-expect-error TODO: fix this type error\n for await (const chunk of response.body!) {\n const body = decoder.decode(chunk);\n\n this._broadcastChatMessage({\n body,\n done: false,\n id,\n type: \"cf_agent_use_chat_response\",\n });\n }\n\n this._broadcastChatMessage({\n body: \"\",\n done: true,\n id,\n type: \"cf_agent_use_chat_response\",\n });\n });\n }\n\n /**\n * For the given message id, look up its associated AbortController\n * If the AbortController does not exist, create and store one in memory\n *\n * returns the AbortSignal associated with the AbortController\n */\n private _getAbortSignal(id: string): AbortSignal | undefined {\n // Defensive check, since we're coercing message types at the moment\n if (typeof id !== \"string\") {\n return undefined;\n }\n\n if (!this._chatMessageAbortControllers.has(id)) {\n this._chatMessageAbortControllers.set(id, new AbortController());\n }\n\n return this._chatMessageAbortControllers.get(id)?.signal;\n }\n\n /**\n * Remove an abort controller from the cache of pending message responses\n */\n private _removeAbortController(id: string) {\n this._chatMessageAbortControllers.delete(id);\n }\n\n /**\n * Propagate an abort signal for any requests associated with the given message id\n */\n private _cancelChatRequest(id: string) {\n if (this._chatMessageAbortControllers.has(id)) {\n const abortController = this._chatMessageAbortControllers.get(id);\n abortController?.abort();\n }\n }\n\n /**\n * Abort all pending requests and clear the cache of AbortControllers\n */\n private _destroyAbortControllers() {\n for (const controller of this._chatMessageAbortControllers.values()) {\n controller?.abort();\n }\n this._chatMessageAbortControllers.clear();\n }\n\n /**\n * When the DO is destroyed, cancel all pending requests\n */\n async destroy() {\n this._destroyAbortControllers();\n await super.destroy();\n }\n}\n"],"mappings":";;;;;;;;AAKA,SAAS,8BAA8B;AAIvC,IAAM,UAAU,IAAI,YAAY;AAMzB,IAAM,cAAN,cAA0D,MAG/D;AAAA,EAQA,YAAY,KAAmB,KAAU;AACvC,UAAM,KAAK,GAAG;AACd,SAAK;AAAA;AAAA;AAAA;AAAA;AAKL,SAAK,YACH,KAAK,gDAAgD,CAAC,GACtD,IAAI,CAAC,QAAQ;AACb,aAAO,KAAK,MAAM,IAAI,OAAiB;AAAA,IACzC,CAAC;AAED,SAAK,+BAA+B,oBAAI,IAAI;AAAA,EAC9C;AAAA,EAEQ,sBAAsB,SAA0B,SAAoB;AAC1E,SAAK,UAAU,KAAK,UAAU,OAAO,GAAG,OAAO;AAAA,EACjD;AAAA,EAEA,MAAe,UAAU,YAAwB,SAAoB;AACnE,QAAI,OAAO,YAAY,UAAU;AAC/B,UAAI;AACJ,UAAI;AACF,eAAO,KAAK,MAAM,OAAO;AAAA,MAC3B,SAAS,QAAQ;AAGf;AAAA,MACF;AACA,UACE,KAAK,SAAS,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M;AAAA,UACN;AAAA,UACA,MAAM;AAAA,QACR,CAAC;AAAA,MACH;AAEA,WAAK,sBAAsB;AAAA,QACzB,MAAM;AAAA,QACN,MAAM;AAAA,QACN;AAAA,QACA,MAAM;AAAA,MACR,CAAC;AAAA,IACH,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQQ,gBAAgB,IAAqC;AAE3D,QAAI,OAAO,OAAO,UAAU;AAC1B,aAAO;AAAA,IACT;AAEA,QAAI,CAAC,KAAK,6BAA6B,IAAI,EAAE,GAAG;AAC9C,WAAK,6BAA6B,IAAI,IAAI,IAAI,gBAAgB,CAAC;AAAA,IACjE;AAEA,WAAO,KAAK,6BAA6B,IAAI,EAAE,GAAG;AAAA,EACpD;AAAA;AAAA;AAAA;AAAA,EAKQ,uBAAuB,IAAY;AACzC,SAAK,6BAA6B,OAAO,EAAE;AAAA,EAC7C;AAAA;AAAA;AAAA;AAAA,EAKQ,mBAAmB,IAAY;AACrC,QAAI,KAAK,6BAA6B,IAAI,EAAE,GAAG;AAC7C,YAAM,kBAAkB,KAAK,6BAA6B,IAAI,EAAE;AAChE,uBAAiB,MAAM;AAAA,IACzB;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKQ,2BAA2B;AACjC,eAAW,cAAc,KAAK,6BAA6B,OAAO,GAAG;AACnE,kBAAY,MAAM;AAAA,IACpB;AACA,SAAK,6BAA6B,MAAM;AAAA,EAC1C;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,UAAU;AACd,SAAK,yBAAyB;AAC9B,UAAM,MAAM,QAAQ;AAAA,EACtB;AACF;","names":["response"]}
@@ -4,7 +4,19 @@ import { useChat } from "@ai-sdk/react";
4
4
  import { useAgent } from "./react.js";
5
5
  import "partysocket";
6
6
  import "partysocket/react";
7
+ import "./index-CITGJflw.js";
8
+ import "@modelcontextprotocol/sdk/client/index.js";
9
+ import "@modelcontextprotocol/sdk/types.js";
10
+ import "partyserver";
11
+ import "./mcp/client.js";
12
+ import "zod";
13
+ import "@modelcontextprotocol/sdk/client/sse.js";
14
+ import "@modelcontextprotocol/sdk/shared/protocol.js";
15
+ import "./mcp/do-oauth-client-provider.js";
16
+ import "@modelcontextprotocol/sdk/client/auth.js";
17
+ import "@modelcontextprotocol/sdk/shared/auth.js";
7
18
  import "./client.js";
19
+ import "./serializable.js";
8
20
 
9
21
  type GetInitialMessagesOptions = {
10
22
  agent: string;
@@ -33,15 +45,15 @@ type UseAgentChatOptions<State> = Omit<
33
45
  declare function useAgentChat<State = unknown>(
34
46
  options: UseAgentChatOptions<State>
35
47
  ): {
48
+ /**
49
+ * Clear chat history on both client and Agent
50
+ */
51
+ clearHistory: () => void;
36
52
  /**
37
53
  * Set the chat messages and synchronize with the Agent
38
54
  * @param messages New messages to set
39
55
  */
40
56
  setMessages: (messages: Message[]) => void;
41
- /**
42
- * Clear chat history on both client and Agent
43
- */
44
- clearHistory: () => void;
45
57
  messages: ai.UIMessage[];
46
58
  error: undefined | Error;
47
59
  append: (
@@ -52,6 +64,7 @@ declare function useAgentChat<State = unknown>(
52
64
  chatRequestOptions?: ai.ChatRequestOptions
53
65
  ) => Promise<string | null | undefined>;
54
66
  stop: () => void;
67
+ experimental_resume: () => void;
55
68
  input: string;
56
69
  setInput: React.Dispatch<React.SetStateAction<string>>;
57
70
  handleInputChange: (
package/dist/ai-react.js CHANGED
@@ -1,9 +1,7 @@
1
- import "./chunk-HMLY7DHA.js";
2
-
3
1
  // src/ai-react.tsx
4
2
  import { useChat } from "@ai-sdk/react";
5
- import { use, useEffect } from "react";
6
3
  import { nanoid } from "nanoid";
4
+ import { use, useEffect } from "react";
7
5
  var requestCache = /* @__PURE__ */ new Map();
8
6
  function useAgentChat(options) {
9
7
  const { agent, getInitialMessages, ...rest } = options;
@@ -19,8 +17,8 @@ function useAgentChat(options) {
19
17
  const getMessagesUrl = new URL(url);
20
18
  getMessagesUrl.pathname += "/get-messages";
21
19
  const response = await fetch(getMessagesUrl.toString(), {
22
- headers: options.headers,
23
- credentials: options.credentials
20
+ credentials: options.credentials,
21
+ headers: options.headers
24
22
  });
25
23
  return response.json();
26
24
  }
@@ -71,11 +69,12 @@ function useAgentChat(options) {
71
69
  signal?.addEventListener("abort", () => {
72
70
  agent.send(
73
71
  JSON.stringify({
74
- type: "cf_agent_chat_request_cancel",
75
- id
72
+ id,
73
+ type: "cf_agent_chat_request_cancel"
76
74
  })
77
75
  );
78
76
  abortController.abort();
77
+ controller.close();
79
78
  });
80
79
  agent.addEventListener(
81
80
  "message",
@@ -83,7 +82,7 @@ function useAgentChat(options) {
83
82
  let data;
84
83
  try {
85
84
  data = JSON.parse(event.data);
86
- } catch (error) {
85
+ } catch (_error) {
87
86
  return;
88
87
  }
89
88
  if (data.type === "cf_agent_use_chat_response") {
@@ -106,32 +105,32 @@ function useAgentChat(options) {
106
105
  });
107
106
  agent.send(
108
107
  JSON.stringify({
109
- type: "cf_agent_use_chat_request",
110
108
  id,
111
- url: request.toString(),
112
109
  init: {
113
- method,
114
- keepalive,
115
- headers,
116
110
  body,
117
- redirect,
118
- integrity,
119
111
  credentials,
112
+ headers,
113
+ integrity,
114
+ keepalive,
115
+ method,
120
116
  mode,
117
+ redirect,
121
118
  referrer,
122
119
  referrerPolicy,
123
120
  window
124
121
  // dispatcher,
125
122
  // duplex
126
- }
123
+ },
124
+ type: "cf_agent_use_chat_request",
125
+ url: request.toString()
127
126
  })
128
127
  );
129
128
  return new Response(stream);
130
129
  }
131
130
  const useChatHelpers = useChat({
131
+ fetch: aiFetch,
132
132
  initialMessages,
133
133
  sendExtraMessageFields: true,
134
- fetch: aiFetch,
135
134
  ...rest
136
135
  });
137
136
  useEffect(() => {
@@ -142,7 +141,7 @@ function useAgentChat(options) {
142
141
  let data;
143
142
  try {
144
143
  data = JSON.parse(event.data);
145
- } catch (error) {
144
+ } catch (_error) {
146
145
  return;
147
146
  }
148
147
  if (data.type === "cf_agent_chat_clear") {
@@ -156,7 +155,7 @@ function useAgentChat(options) {
156
155
  let data;
157
156
  try {
158
157
  data = JSON.parse(event.data);
159
- } catch (error) {
158
+ } catch (_error) {
160
159
  return;
161
160
  }
162
161
  if (data.type === "cf_agent_chat_messages") {
@@ -173,26 +172,26 @@ function useAgentChat(options) {
173
172
  return {
174
173
  ...useChatHelpers,
175
174
  /**
176
- * Set the chat messages and synchronize with the Agent
177
- * @param messages New messages to set
175
+ * Clear chat history on both client and Agent
178
176
  */
179
- setMessages: (messages) => {
180
- useChatHelpers.setMessages(messages);
177
+ clearHistory: () => {
178
+ useChatHelpers.setMessages([]);
181
179
  agent.send(
182
180
  JSON.stringify({
183
- type: "cf_agent_chat_messages",
184
- messages
181
+ type: "cf_agent_chat_clear"
185
182
  })
186
183
  );
187
184
  },
188
185
  /**
189
- * Clear chat history on both client and Agent
186
+ * Set the chat messages and synchronize with the Agent
187
+ * @param messages New messages to set
190
188
  */
191
- clearHistory: () => {
192
- useChatHelpers.setMessages([]);
189
+ setMessages: (messages) => {
190
+ useChatHelpers.setMessages(messages);
193
191
  agent.send(
194
192
  JSON.stringify({
195
- type: "cf_agent_chat_clear"
193
+ messages,
194
+ type: "cf_agent_chat_messages"
196
195
  })
197
196
  );
198
197
  }