agents 0.0.0-fd36bbc → 0.0.0-fd59ae2

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 (48) hide show
  1. package/README.md +130 -28
  2. package/dist/ai-chat-agent.d.ts +52 -3
  3. package/dist/ai-chat-agent.js +170 -82
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-react.d.ts +26 -8
  6. package/dist/ai-react.js +62 -48
  7. package/dist/ai-react.js.map +1 -1
  8. package/dist/ai-types.d.ts +5 -0
  9. package/dist/chunk-DQJFYHG3.js +1290 -0
  10. package/dist/chunk-DQJFYHG3.js.map +1 -0
  11. package/dist/chunk-EM3J4KV7.js +598 -0
  12. package/dist/chunk-EM3J4KV7.js.map +1 -0
  13. package/dist/chunk-KUH345EY.js +116 -0
  14. package/dist/chunk-KUH345EY.js.map +1 -0
  15. package/dist/chunk-PVQZBKN7.js +106 -0
  16. package/dist/chunk-PVQZBKN7.js.map +1 -0
  17. package/dist/client-DgyzBU_8.d.ts +4601 -0
  18. package/dist/client.d.ts +16 -2
  19. package/dist/client.js +6 -133
  20. package/dist/client.js.map +1 -1
  21. package/dist/index.d.ts +265 -20
  22. package/dist/index.js +12 -4
  23. package/dist/mcp/client.d.ts +11 -0
  24. package/dist/mcp/client.js +9 -0
  25. package/dist/mcp/do-oauth-client-provider.d.ts +41 -0
  26. package/dist/mcp/do-oauth-client-provider.js +7 -0
  27. package/dist/mcp/do-oauth-client-provider.js.map +1 -0
  28. package/dist/mcp/index.d.ts +112 -0
  29. package/dist/mcp/index.js +955 -0
  30. package/dist/mcp/index.js.map +1 -0
  31. package/dist/observability/index.d.ts +46 -0
  32. package/dist/observability/index.js +10 -0
  33. package/dist/observability/index.js.map +1 -0
  34. package/dist/react.d.ts +88 -5
  35. package/dist/react.js +50 -31
  36. package/dist/react.js.map +1 -1
  37. package/dist/schedule.d.ts +6 -6
  38. package/dist/schedule.js +4 -6
  39. package/dist/schedule.js.map +1 -1
  40. package/dist/serializable.d.ts +32 -0
  41. package/dist/serializable.js +1 -0
  42. package/dist/serializable.js.map +1 -0
  43. package/package.json +87 -43
  44. package/src/index.ts +1217 -185
  45. package/dist/chunk-HMLY7DHA.js +0 -16
  46. package/dist/chunk-X6BBKLSC.js +0 -568
  47. package/dist/chunk-X6BBKLSC.js.map +0 -1
  48. /package/dist/{chunk-HMLY7DHA.js.map → mcp/client.js.map} +0 -0
@@ -1,19 +1,16 @@
1
1
  import {
2
2
  Agent
3
- } from "./chunk-X6BBKLSC.js";
4
- import {
5
- __privateAdd,
6
- __privateMethod
7
- } from "./chunk-HMLY7DHA.js";
3
+ } from "./chunk-DQJFYHG3.js";
4
+ import "./chunk-EM3J4KV7.js";
5
+ import "./chunk-PVQZBKN7.js";
6
+ import "./chunk-KUH345EY.js";
8
7
 
9
8
  // src/ai-chat-agent.ts
10
9
  import { appendResponseMessages } from "ai";
11
10
  var decoder = new TextDecoder();
12
- var _AIChatAgent_instances, sendChatMessage_fn, broadcastChatMessage_fn, tryCatch_fn, persistMessages_fn, reply_fn;
13
11
  var AIChatAgent = class extends Agent {
14
12
  constructor(ctx, env) {
15
13
  super(ctx, env);
16
- __privateAdd(this, _AIChatAgent_instances);
17
14
  this.sql`create table if not exists cf_ai_chat_agent_messages (
18
15
  id text primary key,
19
16
  message text not null,
@@ -22,65 +19,113 @@ var AIChatAgent = class extends Agent {
22
19
  this.messages = (this.sql`select * from cf_ai_chat_agent_messages` || []).map((row) => {
23
20
  return JSON.parse(row.message);
24
21
  });
22
+ this._chatMessageAbortControllers = /* @__PURE__ */ new Map();
23
+ }
24
+ _broadcastChatMessage(message, exclude) {
25
+ this.broadcast(JSON.stringify(message), exclude);
25
26
  }
26
27
  async onMessage(connection, message) {
27
28
  if (typeof message === "string") {
28
29
  let data;
29
30
  try {
30
31
  data = JSON.parse(message);
31
- } catch (error) {
32
+ } catch (_error) {
32
33
  return;
33
34
  }
34
35
  if (data.type === "cf_agent_use_chat_request" && data.init.method === "POST") {
35
36
  const {
36
- method,
37
- keepalive,
38
- headers,
39
- body,
37
+ // method,
38
+ // keepalive,
39
+ // headers,
40
+ body
40
41
  // we're reading this
41
- redirect,
42
- integrity,
43
- credentials,
44
- mode,
45
- referrer,
46
- referrerPolicy,
47
- window
42
+ //
43
+ // // these might not exist?
48
44
  // dispatcher,
49
45
  // duplex
50
46
  } = data.init;
51
47
  const { messages } = JSON.parse(body);
52
- __privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
53
- type: "cf_agent_chat_messages",
54
- messages
55
- }, [connection.id]);
56
- await __privateMethod(this, _AIChatAgent_instances, persistMessages_fn).call(this, messages, [connection.id]);
57
- return __privateMethod(this, _AIChatAgent_instances, tryCatch_fn).call(this, async () => {
58
- const response = await this.onChatMessage(async ({ response: response2 }) => {
59
- const finalMessages = appendResponseMessages({
60
- messages,
61
- responseMessages: response2.messages
62
- });
63
- await __privateMethod(this, _AIChatAgent_instances, persistMessages_fn).call(this, finalMessages, [connection.id]);
64
- });
48
+ this._broadcastChatMessage(
49
+ {
50
+ messages,
51
+ type: "cf_agent_chat_messages"
52
+ },
53
+ [connection.id]
54
+ );
55
+ await this.persistMessages(messages, [connection.id]);
56
+ this.observability?.emit(
57
+ {
58
+ displayMessage: "Chat message request",
59
+ id: data.id,
60
+ payload: {},
61
+ timestamp: Date.now(),
62
+ type: "message:request"
63
+ },
64
+ this.ctx
65
+ );
66
+ const chatMessageId = data.id;
67
+ const abortSignal = this._getAbortSignal(chatMessageId);
68
+ return this._tryCatchChat(async () => {
69
+ const response = await this.onChatMessage(
70
+ async ({ response: response2 }) => {
71
+ const finalMessages = appendResponseMessages({
72
+ messages,
73
+ responseMessages: response2.messages
74
+ });
75
+ await this.persistMessages(finalMessages, [connection.id]);
76
+ this._removeAbortController(chatMessageId);
77
+ this.observability?.emit(
78
+ {
79
+ displayMessage: "Chat message response",
80
+ id: data.id,
81
+ payload: {},
82
+ timestamp: Date.now(),
83
+ type: "message:response"
84
+ },
85
+ this.ctx
86
+ );
87
+ },
88
+ abortSignal ? { abortSignal } : void 0
89
+ );
65
90
  if (response) {
66
- await __privateMethod(this, _AIChatAgent_instances, reply_fn).call(this, data.id, response);
91
+ await this._reply(data.id, response);
92
+ } else {
93
+ console.warn(
94
+ `[AIChatAgent] onChatMessage returned no response for chatMessageId: ${chatMessageId}`
95
+ );
96
+ this._broadcastChatMessage(
97
+ {
98
+ body: "No response was generated by the agent.",
99
+ done: true,
100
+ id: data.id,
101
+ type: "cf_agent_use_chat_response"
102
+ },
103
+ [connection.id]
104
+ );
67
105
  }
68
106
  });
69
107
  }
70
108
  if (data.type === "cf_agent_chat_clear") {
109
+ this._destroyAbortControllers();
71
110
  this.sql`delete from cf_ai_chat_agent_messages`;
72
111
  this.messages = [];
73
- __privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
74
- type: "cf_agent_chat_clear"
75
- }, [connection.id]);
112
+ this._broadcastChatMessage(
113
+ {
114
+ type: "cf_agent_chat_clear"
115
+ },
116
+ [connection.id]
117
+ );
76
118
  } else if (data.type === "cf_agent_chat_messages") {
77
- await __privateMethod(this, _AIChatAgent_instances, persistMessages_fn).call(this, data.messages, [connection.id]);
119
+ await this.persistMessages(data.messages, [connection.id]);
120
+ } else if (data.type === "cf_agent_chat_request_cancel") {
121
+ this._cancelChatRequest(data.id);
78
122
  }
79
123
  }
80
124
  }
81
125
  async onRequest(request) {
82
- return __privateMethod(this, _AIChatAgent_instances, tryCatch_fn).call(this, () => {
83
- if (request.url.endsWith("/get-messages")) {
126
+ return this._tryCatchChat(() => {
127
+ const url = new URL(request.url);
128
+ if (url.pathname.endsWith("/get-messages")) {
84
129
  const messages = (this.sql`select * from cf_ai_chat_agent_messages` || []).map((row) => {
85
130
  return JSON.parse(row.message);
86
131
  });
@@ -89,12 +134,20 @@ var AIChatAgent = class extends Agent {
89
134
  return super.onRequest(request);
90
135
  });
91
136
  }
137
+ async _tryCatchChat(fn) {
138
+ try {
139
+ return await fn();
140
+ } catch (e) {
141
+ throw this.onError(e);
142
+ }
143
+ }
92
144
  /**
93
145
  * Handle incoming chat messages and generate a response
94
146
  * @param onFinish Callback to be called when the response is finished
147
+ * @param options.signal A signal to pass to any child requests which can be used to cancel them
95
148
  * @returns Response to send to the client or undefined
96
149
  */
97
- async onChatMessage(onFinish) {
150
+ async onChatMessage(onFinish, options) {
98
151
  throw new Error(
99
152
  "recieved a chat message, override onChatMessage and return a Response to send to the client"
100
153
  );
@@ -104,13 +157,13 @@ var AIChatAgent = class extends Agent {
104
157
  * @param messages Chat messages to save
105
158
  */
106
159
  async saveMessages(messages) {
107
- await __privateMethod(this, _AIChatAgent_instances, persistMessages_fn).call(this, messages);
160
+ await this.persistMessages(messages);
108
161
  const response = await this.onChatMessage(async ({ response: response2 }) => {
109
162
  const finalMessages = appendResponseMessages({
110
163
  messages,
111
164
  responseMessages: response2.messages
112
165
  });
113
- await __privateMethod(this, _AIChatAgent_instances, persistMessages_fn).call(this, finalMessages, []);
166
+ await this.persistMessages(finalMessages, []);
114
167
  });
115
168
  if (response) {
116
169
  for await (const chunk of response.body) {
@@ -119,50 +172,85 @@ var AIChatAgent = class extends Agent {
119
172
  response.body?.cancel();
120
173
  }
121
174
  }
122
- };
123
- _AIChatAgent_instances = new WeakSet();
124
- sendChatMessage_fn = function(connection, message) {
125
- connection.send(JSON.stringify(message));
126
- };
127
- broadcastChatMessage_fn = function(message, exclude) {
128
- this.broadcast(JSON.stringify(message), exclude);
129
- };
130
- tryCatch_fn = async function(fn) {
131
- try {
132
- return await fn();
133
- } catch (e) {
134
- throw this.onError(e);
135
- }
136
- };
137
- persistMessages_fn = async function(messages, excludeBroadcastIds = []) {
138
- this.sql`delete from cf_ai_chat_agent_messages`;
139
- for (const message of messages) {
140
- this.sql`insert into cf_ai_chat_agent_messages (id, message) values (${message.id},${JSON.stringify(message)})`;
175
+ async persistMessages(messages, excludeBroadcastIds = []) {
176
+ this.sql`delete from cf_ai_chat_agent_messages`;
177
+ for (const message of messages) {
178
+ this.sql`insert into cf_ai_chat_agent_messages (id, message) values (${message.id},${JSON.stringify(message)})`;
179
+ }
180
+ this.messages = messages;
181
+ this._broadcastChatMessage(
182
+ {
183
+ messages,
184
+ type: "cf_agent_chat_messages"
185
+ },
186
+ excludeBroadcastIds
187
+ );
141
188
  }
142
- this.messages = messages;
143
- __privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
144
- type: "cf_agent_chat_messages",
145
- messages
146
- }, excludeBroadcastIds);
147
- };
148
- reply_fn = async function(id, response) {
149
- return __privateMethod(this, _AIChatAgent_instances, tryCatch_fn).call(this, async () => {
150
- for await (const chunk of response.body) {
151
- const body = decoder.decode(chunk);
152
- __privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
189
+ async _reply(id, response) {
190
+ return this._tryCatchChat(async () => {
191
+ for await (const chunk of response.body) {
192
+ const body = decoder.decode(chunk);
193
+ this._broadcastChatMessage({
194
+ body,
195
+ done: false,
196
+ id,
197
+ type: "cf_agent_use_chat_response"
198
+ });
199
+ }
200
+ this._broadcastChatMessage({
201
+ body: "",
202
+ done: true,
153
203
  id,
154
- type: "cf_agent_use_chat_response",
155
- body,
156
- done: false
204
+ type: "cf_agent_use_chat_response"
157
205
  });
158
- }
159
- __privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
160
- id,
161
- type: "cf_agent_use_chat_response",
162
- body: "",
163
- done: true
164
206
  });
165
- });
207
+ }
208
+ /**
209
+ * For the given message id, look up its associated AbortController
210
+ * If the AbortController does not exist, create and store one in memory
211
+ *
212
+ * returns the AbortSignal associated with the AbortController
213
+ */
214
+ _getAbortSignal(id) {
215
+ if (typeof id !== "string") {
216
+ return void 0;
217
+ }
218
+ if (!this._chatMessageAbortControllers.has(id)) {
219
+ this._chatMessageAbortControllers.set(id, new AbortController());
220
+ }
221
+ return this._chatMessageAbortControllers.get(id)?.signal;
222
+ }
223
+ /**
224
+ * Remove an abort controller from the cache of pending message responses
225
+ */
226
+ _removeAbortController(id) {
227
+ this._chatMessageAbortControllers.delete(id);
228
+ }
229
+ /**
230
+ * Propagate an abort signal for any requests associated with the given message id
231
+ */
232
+ _cancelChatRequest(id) {
233
+ if (this._chatMessageAbortControllers.has(id)) {
234
+ const abortController = this._chatMessageAbortControllers.get(id);
235
+ abortController?.abort();
236
+ }
237
+ }
238
+ /**
239
+ * Abort all pending requests and clear the cache of AbortControllers
240
+ */
241
+ _destroyAbortControllers() {
242
+ for (const controller of this._chatMessageAbortControllers.values()) {
243
+ controller?.abort();
244
+ }
245
+ this._chatMessageAbortControllers.clear();
246
+ }
247
+ /**
248
+ * When the DO is destroyed, cancel all pending requests
249
+ */
250
+ async destroy() {
251
+ this._destroyAbortControllers();
252
+ await super.destroy();
253
+ }
166
254
  };
167
255
  export {
168
256
  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\";\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 /** 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\n #sendChatMessage(connection: Connection, message: OutgoingMessage) {\n connection.send(JSON.stringify(message));\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 return this.#tryCatch(async () => {\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, [connection.id]);\n });\n if (response) {\n await this.#reply(data.id, response);\n }\n });\n }\n if (data.type === \"cf_agent_chat_clear\") {\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 }\n }\n }\n\n override async onRequest(request: Request): Promise<Response> {\n return this.#tryCatch(() => {\n if (request.url.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 * @returns Response to send to the client or undefined\n */\n async onChatMessage(\n onFinish: StreamTextOnFinishCallback<ToolSet>\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"],"mappings":";;;;;;;;;AAMA,SAAS,8BAA8B;AAEvC,IAAM,UAAU,IAAI,YAAY;AARhC;AAcO,IAAM,cAAN,cAA0D,MAG/D;AAAA,EAGA,YAAY,KAAmB,KAAU;AACvC,UAAM,KAAK,GAAG;AAPX;AAQH,SAAK;AAAA;AAAA;AAAA;AAAA;AAKL,SAAK,YACH,KAAK,gDAAgD,CAAC,GACtD,IAAI,CAAC,QAAQ;AACb,aAAO,KAAK,MAA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,CAAC;AAAA,EACtB;AACF;AAuCM,qBAAgB,eACpB,UACA,sBAAgC,CAAC,GACjC;AACA,OAAK;AACL,aAAW,WAAW,UAAU;AAC9B,SAAK,kEACH,QAAQ,EACV,IAAI,KAAK,UAAU,OAAO,CAAC;AAAA,EAC7B;AACA,OAAK,WAAW;AAChB,wBAAK,iDAAL,WACE;AAAA,IACE,MAAM;AAAA,IACN;AAAA,EACF,GACA;AAEJ;AAEM,WAAM,eAAC,IAAY,UAAoB;AAE3C,SAAO,sBAAK,qCAAL,WAAe,YAAY;AAEhC,qBAAiB,SAAS,SAAS,MAAO;AACxC,YAAM,OAAO,QAAQ,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;","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 await this.persistMessages(messages, [connection.id]);\n\n this.observability?.emit(\n {\n displayMessage: \"Chat message request\",\n id: data.id,\n payload: {},\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 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 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 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,+BACd,KAAK,KAAK,WAAW,QACrB;AACA,cAAM;AAAA;AAAA;AAAA;AAAA,UAIJ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,QAKF,IAAI,KAAK;AACT,cAAM,EAAE,SAAS,IAAI,KAAK,MAAM,IAAc;AAC9C,aAAK;AAAA,UACH;AAAA,YACE;AAAA,YACA,MAAM;AAAA,UACR;AAAA,UACA,CAAC,WAAW,EAAE;AAAA,QAChB;AAEA,cAAM,KAAK,gBAAgB,UAAU,CAAC,WAAW,EAAE,CAAC;AAEpD,aAAK,eAAe;AAAA,UAClB;AAAA,YACE,gBAAgB;AAAA,YAChB,IAAI,KAAK;AAAA,YACT,SAAS,CAAC;AAAA,YACV,WAAW,KAAK,IAAI;AAAA,YACpB,MAAM;AAAA,UACR;AAAA,UACA,KAAK;AAAA,QACP;AAEA,cA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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,22 @@ 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.js";
8
+ import "cloudflare:workers";
9
+ import "@modelcontextprotocol/sdk/client/index.js";
10
+ import "@modelcontextprotocol/sdk/types.js";
11
+ import "partyserver";
12
+ import "./client-DgyzBU_8.js";
13
+ import "zod";
14
+ import "@modelcontextprotocol/sdk/shared/protocol.js";
15
+ import "@modelcontextprotocol/sdk/client/sse.js";
16
+ import "@modelcontextprotocol/sdk/client/streamableHttp.js";
17
+ import "./mcp/do-oauth-client-provider.js";
18
+ import "@modelcontextprotocol/sdk/client/auth.js";
19
+ import "@modelcontextprotocol/sdk/shared/auth.js";
20
+ import "./observability/index.js";
7
21
  import "./client.js";
22
+ import "./serializable.js";
8
23
 
9
24
  type GetInitialMessagesOptions = {
10
25
  agent: string;
@@ -14,10 +29,10 @@ type GetInitialMessagesOptions = {
14
29
  /**
15
30
  * Options for the useAgentChat hook
16
31
  */
17
- type UseAgentChatOptions = Omit<
32
+ type UseAgentChatOptions<State> = Omit<
18
33
  Parameters<typeof useChat>[0] & {
19
34
  /** Agent connection from useAgent */
20
- agent: ReturnType<typeof useAgent>;
35
+ agent: ReturnType<typeof useAgent<State>>;
21
36
  getInitialMessages?:
22
37
  | undefined
23
38
  | null
@@ -30,16 +45,18 @@ type UseAgentChatOptions = Omit<
30
45
  * @param options Chat options including the agent connection
31
46
  * @returns Chat interface controls and state with added clearHistory method
32
47
  */
33
- declare function useAgentChat(options: UseAgentChatOptions): {
48
+ declare function useAgentChat<State = unknown>(
49
+ options: UseAgentChatOptions<State>
50
+ ): {
51
+ /**
52
+ * Clear chat history on both client and Agent
53
+ */
54
+ clearHistory: () => void;
34
55
  /**
35
56
  * Set the chat messages and synchronize with the Agent
36
57
  * @param messages New messages to set
37
58
  */
38
59
  setMessages: (messages: Message[]) => void;
39
- /**
40
- * Clear chat history on both client and Agent
41
- */
42
- clearHistory: () => void;
43
60
  messages: ai.UIMessage[];
44
61
  error: undefined | Error;
45
62
  append: (
@@ -50,6 +67,7 @@ declare function useAgentChat(options: UseAgentChatOptions): {
50
67
  chatRequestOptions?: ai.ChatRequestOptions
51
68
  ) => Promise<string | null | undefined>;
52
69
  stop: () => void;
70
+ experimental_resume: () => void;
53
71
  input: string;
54
72
  setInput: React.Dispatch<React.SetStateAction<string>>;
55
73
  handleInputChange: (
@@ -76,7 +94,7 @@ declare function useAgentChat(options: UseAgentChatOptions): {
76
94
  id: string;
77
95
  addToolResult: ({
78
96
  toolCallId,
79
- result,
97
+ result
80
98
  }: {
81
99
  toolCallId: string;
82
100
  result: any;
package/dist/ai-react.js CHANGED
@@ -1,42 +1,53 @@
1
- import "./chunk-HMLY7DHA.js";
2
-
3
1
  // src/ai-react.tsx
4
2
  import { useChat } from "@ai-sdk/react";
5
- import { useEffect, use } from "react";
3
+ import { nanoid } from "nanoid";
4
+ import { use, useEffect } from "react";
6
5
  var requestCache = /* @__PURE__ */ new Map();
7
6
  function useAgentChat(options) {
8
7
  const { agent, getInitialMessages, ...rest } = options;
9
- const url = `${agent._pkurl.replace("ws://", "http://").replace("wss://", "https://")}`;
8
+ const agentUrl = new URL(
9
+ `${// @ts-expect-error we're using a protected _url property that includes query params
10
+ (agent._url || agent._pkurl)?.replace("ws://", "http://").replace("wss://", "https://")}`
11
+ );
12
+ agentUrl.searchParams.delete("_pk");
13
+ const agentUrlString = agentUrl.toString();
10
14
  async function defaultGetInitialMessagesFetch({
11
- url: url2
15
+ url
12
16
  }) {
13
- const response = await fetch(new Request(`${url2}/get-messages`), {
14
- headers: options.headers,
15
- credentials: options.credentials
17
+ const getMessagesUrl = new URL(url);
18
+ getMessagesUrl.pathname += "/get-messages";
19
+ const response = await fetch(getMessagesUrl.toString(), {
20
+ credentials: options.credentials,
21
+ headers: options.headers
16
22
  });
17
23
  return response.json();
18
24
  }
19
25
  const getInitialMessagesFetch = getInitialMessages || defaultGetInitialMessagesFetch;
20
26
  function doGetInitialMessages(getInitialMessagesOptions) {
21
- if (requestCache.has(url)) {
22
- return requestCache.get(url);
27
+ if (requestCache.has(agentUrlString)) {
28
+ return requestCache.get(agentUrlString);
23
29
  }
24
30
  const promise = getInitialMessagesFetch(getInitialMessagesOptions);
25
- requestCache.set(url, promise);
31
+ requestCache.set(agentUrlString, promise);
26
32
  return promise;
27
33
  }
28
- const initialMessages = getInitialMessages !== null ? use(
29
- doGetInitialMessages({
30
- agent: agent.agent,
31
- name: agent.name,
32
- url
33
- })
34
- ) : rest.initialMessages;
34
+ const initialMessagesPromise = getInitialMessages === null ? null : doGetInitialMessages({
35
+ agent: agent.agent,
36
+ name: agent.name,
37
+ url: agentUrlString
38
+ });
39
+ const initialMessages = initialMessagesPromise ? use(initialMessagesPromise) : rest.initialMessages ?? [];
35
40
  useEffect(() => {
41
+ if (!initialMessagesPromise) {
42
+ return;
43
+ }
44
+ requestCache.set(agentUrlString, initialMessagesPromise);
36
45
  return () => {
37
- requestCache.delete(url);
46
+ if (requestCache.get(agentUrlString) === initialMessagesPromise) {
47
+ requestCache.delete(agentUrlString);
48
+ }
38
49
  };
39
- }, [url]);
50
+ }, [agentUrlString, initialMessagesPromise]);
40
51
  async function aiFetch(request, options2 = {}) {
41
52
  const {
42
53
  method,
@@ -53,10 +64,17 @@ function useAgentChat(options) {
53
64
  window
54
65
  // dispatcher, duplex
55
66
  } = options2;
56
- const id = crypto.randomUUID();
67
+ const id = nanoid(8);
57
68
  const abortController = new AbortController();
58
69
  signal?.addEventListener("abort", () => {
70
+ agent.send(
71
+ JSON.stringify({
72
+ id,
73
+ type: "cf_agent_chat_request_cancel"
74
+ })
75
+ );
59
76
  abortController.abort();
77
+ controller.close();
60
78
  });
61
79
  agent.addEventListener(
62
80
  "message",
@@ -64,7 +82,7 @@ function useAgentChat(options) {
64
82
  let data;
65
83
  try {
66
84
  data = JSON.parse(event.data);
67
- } catch (error) {
85
+ } catch (_error) {
68
86
  return;
69
87
  }
70
88
  if (data.type === "cf_agent_use_chat_response") {
@@ -87,32 +105,32 @@ function useAgentChat(options) {
87
105
  });
88
106
  agent.send(
89
107
  JSON.stringify({
90
- type: "cf_agent_use_chat_request",
91
108
  id,
92
- url: request.toString(),
93
109
  init: {
94
- method,
95
- keepalive,
96
- headers,
97
110
  body,
98
- redirect,
99
- integrity,
100
111
  credentials,
112
+ headers,
113
+ integrity,
114
+ keepalive,
115
+ method,
101
116
  mode,
117
+ redirect,
102
118
  referrer,
103
119
  referrerPolicy,
104
120
  window
105
121
  // dispatcher,
106
122
  // duplex
107
- }
123
+ },
124
+ type: "cf_agent_use_chat_request",
125
+ url: request.toString()
108
126
  })
109
127
  );
110
128
  return new Response(stream);
111
129
  }
112
130
  const useChatHelpers = useChat({
131
+ fetch: aiFetch,
113
132
  initialMessages,
114
133
  sendExtraMessageFields: true,
115
- fetch: aiFetch,
116
134
  ...rest
117
135
  });
118
136
  useEffect(() => {
@@ -123,7 +141,7 @@ function useAgentChat(options) {
123
141
  let data;
124
142
  try {
125
143
  data = JSON.parse(event.data);
126
- } catch (error) {
144
+ } catch (_error) {
127
145
  return;
128
146
  }
129
147
  if (data.type === "cf_agent_chat_clear") {
@@ -137,7 +155,7 @@ function useAgentChat(options) {
137
155
  let data;
138
156
  try {
139
157
  data = JSON.parse(event.data);
140
- } catch (error) {
158
+ } catch (_error) {
141
159
  return;
142
160
  }
143
161
  if (data.type === "cf_agent_chat_messages") {
@@ -150,34 +168,30 @@ function useAgentChat(options) {
150
168
  agent.removeEventListener("message", onClearHistory);
151
169
  agent.removeEventListener("message", onMessages);
152
170
  };
153
- }, [
154
- agent.addEventListener,
155
- agent.removeEventListener,
156
- useChatHelpers.setMessages
157
- ]);
171
+ }, [agent, useChatHelpers.setMessages]);
158
172
  return {
159
173
  ...useChatHelpers,
160
174
  /**
161
- * Set the chat messages and synchronize with the Agent
162
- * @param messages New messages to set
175
+ * Clear chat history on both client and Agent
163
176
  */
164
- setMessages: (messages) => {
165
- useChatHelpers.setMessages(messages);
177
+ clearHistory: () => {
178
+ useChatHelpers.setMessages([]);
166
179
  agent.send(
167
180
  JSON.stringify({
168
- type: "cf_agent_chat_messages",
169
- messages
181
+ type: "cf_agent_chat_clear"
170
182
  })
171
183
  );
172
184
  },
173
185
  /**
174
- * 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
175
188
  */
176
- clearHistory: () => {
177
- useChatHelpers.setMessages([]);
189
+ setMessages: (messages) => {
190
+ useChatHelpers.setMessages(messages);
178
191
  agent.send(
179
192
  JSON.stringify({
180
- type: "cf_agent_chat_clear"
193
+ messages,
194
+ type: "cf_agent_chat_messages"
181
195
  })
182
196
  );
183
197
  }