agents 0.0.80 → 0.0.82

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.
@@ -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,26 @@ declare class AIChatAgent<Env = unknown, State = unknown> extends Agent<
46
52
  messages: Message[],
47
53
  excludeBroadcastIds?: string[]
48
54
  ): Promise<void>;
55
+ private _reply;
56
+ /**
57
+ * For the given message id, look up its associated AbortController
58
+ * If the AbortController does not exist, create and store one in memory
59
+ *
60
+ * returns the AbortSignal associated with the AbortController
61
+ */
62
+ private _getAbortSignal;
63
+ /**
64
+ * Remove an abort controller from the cache of pending message responses
65
+ */
66
+ private _removeAbortController;
67
+ /**
68
+ * Propagate an abort signal for any requests associated with the given message id
69
+ */
70
+ private _cancelChatRequest;
71
+ /**
72
+ * Abort all pending requests and clear the cache of AbortControllers
73
+ */
74
+ private _destroyAbortControllers;
49
75
  /**
50
76
  * When the DO is destroyed, cancel all pending requests
51
77
  */
@@ -1,29 +1,16 @@
1
1
  import {
2
2
  Agent
3
- } from "./chunk-YFPCCSZO.js";
4
- import "./chunk-D6UOOELW.js";
5
- import "./chunk-RN4SNE73.js";
6
- import "./chunk-25YDMV4H.js";
7
- import {
8
- __privateAdd,
9
- __privateGet,
10
- __privateMethod,
11
- __privateSet
12
- } from "./chunk-HMLY7DHA.js";
3
+ } from "./chunk-RIYR6FR6.js";
4
+ import "./chunk-BZXOAZUX.js";
5
+ import "./chunk-QSGN3REV.js";
6
+ import "./chunk-Y67CHZBI.js";
13
7
 
14
8
  // src/ai-chat-agent.ts
15
9
  import { appendResponseMessages } from "ai";
16
10
  var decoder = new TextDecoder();
17
- var _chatMessageAbortControllers, _AIChatAgent_instances, broadcastChatMessage_fn, tryCatch_fn, reply_fn, getAbortSignal_fn, removeAbortController_fn, cancelChatRequest_fn, destroyAbortControllers_fn;
18
11
  var AIChatAgent = class extends Agent {
19
12
  constructor(ctx, env) {
20
13
  super(ctx, env);
21
- __privateAdd(this, _AIChatAgent_instances);
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
- __privateAdd(this, _chatMessageAbortControllers);
27
14
  this.sql`create table if not exists cf_ai_chat_agent_messages (
28
15
  id text primary key,
29
16
  message text not null,
@@ -32,7 +19,10 @@ var AIChatAgent = class extends Agent {
32
19
  this.messages = (this.sql`select * from cf_ai_chat_agent_messages` || []).map((row) => {
33
20
  return JSON.parse(row.message);
34
21
  });
35
- __privateSet(this, _chatMessageAbortControllers, /* @__PURE__ */ new Map());
22
+ this._chatMessageAbortControllers = /* @__PURE__ */ new Map();
23
+ }
24
+ _broadcastChatMessage(message, exclude) {
25
+ this.broadcast(JSON.stringify(message), exclude);
36
26
  }
37
27
  async onMessage(connection, message) {
38
28
  if (typeof message === "string") {
@@ -60,14 +50,17 @@ var AIChatAgent = class extends Agent {
60
50
  // duplex
61
51
  } = data.init;
62
52
  const { messages } = JSON.parse(body);
63
- __privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
64
- type: "cf_agent_chat_messages",
65
- messages
66
- }, [connection.id]);
53
+ this._broadcastChatMessage(
54
+ {
55
+ type: "cf_agent_chat_messages",
56
+ messages
57
+ },
58
+ [connection.id]
59
+ );
67
60
  await this.persistMessages(messages, [connection.id]);
68
61
  const chatMessageId = data.id;
69
- const abortSignal = __privateMethod(this, _AIChatAgent_instances, getAbortSignal_fn).call(this, chatMessageId);
70
- return __privateMethod(this, _AIChatAgent_instances, tryCatch_fn).call(this, async () => {
62
+ const abortSignal = this._getAbortSignal(chatMessageId);
63
+ return this._tryCatchChat(async () => {
71
64
  const response = await this.onChatMessage(
72
65
  async ({ response: response2 }) => {
73
66
  const finalMessages = appendResponseMessages({
@@ -75,31 +68,34 @@ var AIChatAgent = class extends Agent {
75
68
  responseMessages: response2.messages
76
69
  });
77
70
  await this.persistMessages(finalMessages, [connection.id]);
78
- __privateMethod(this, _AIChatAgent_instances, removeAbortController_fn).call(this, chatMessageId);
71
+ this._removeAbortController(chatMessageId);
79
72
  },
80
73
  abortSignal ? { abortSignal } : void 0
81
74
  );
82
75
  if (response) {
83
- await __privateMethod(this, _AIChatAgent_instances, reply_fn).call(this, data.id, response);
76
+ await this._reply(data.id, response);
84
77
  }
85
78
  });
86
79
  }
87
80
  if (data.type === "cf_agent_chat_clear") {
88
- __privateMethod(this, _AIChatAgent_instances, destroyAbortControllers_fn).call(this);
81
+ this._destroyAbortControllers();
89
82
  this.sql`delete from cf_ai_chat_agent_messages`;
90
83
  this.messages = [];
91
- __privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
92
- type: "cf_agent_chat_clear"
93
- }, [connection.id]);
84
+ this._broadcastChatMessage(
85
+ {
86
+ type: "cf_agent_chat_clear"
87
+ },
88
+ [connection.id]
89
+ );
94
90
  } else if (data.type === "cf_agent_chat_messages") {
95
91
  await this.persistMessages(data.messages, [connection.id]);
96
92
  } else if (data.type === "cf_agent_chat_request_cancel") {
97
- __privateMethod(this, _AIChatAgent_instances, cancelChatRequest_fn).call(this, data.id);
93
+ this._cancelChatRequest(data.id);
98
94
  }
99
95
  }
100
96
  }
101
97
  async onRequest(request) {
102
- return __privateMethod(this, _AIChatAgent_instances, tryCatch_fn).call(this, () => {
98
+ return this._tryCatchChat(() => {
103
99
  const url = new URL(request.url);
104
100
  if (url.pathname.endsWith("/get-messages")) {
105
101
  const messages = (this.sql`select * from cf_ai_chat_agent_messages` || []).map((row) => {
@@ -110,6 +106,13 @@ var AIChatAgent = class extends Agent {
110
106
  return super.onRequest(request);
111
107
  });
112
108
  }
109
+ async _tryCatchChat(fn) {
110
+ try {
111
+ return await fn();
112
+ } catch (e) {
113
+ throw this.onError(e);
114
+ }
115
+ }
113
116
  /**
114
117
  * Handle incoming chat messages and generate a response
115
118
  * @param onFinish Callback to be called when the response is finished
@@ -147,88 +150,79 @@ var AIChatAgent = class extends Agent {
147
150
  this.sql`insert into cf_ai_chat_agent_messages (id, message) values (${message.id},${JSON.stringify(message)})`;
148
151
  }
149
152
  this.messages = messages;
150
- __privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
151
- type: "cf_agent_chat_messages",
152
- messages
153
- }, excludeBroadcastIds);
154
- }
155
- /**
156
- * When the DO is destroyed, cancel all pending requests
157
- */
158
- async destroy() {
159
- __privateMethod(this, _AIChatAgent_instances, destroyAbortControllers_fn).call(this);
160
- await super.destroy();
161
- }
162
- };
163
- _chatMessageAbortControllers = new WeakMap();
164
- _AIChatAgent_instances = new WeakSet();
165
- broadcastChatMessage_fn = function(message, exclude) {
166
- this.broadcast(JSON.stringify(message), exclude);
167
- };
168
- tryCatch_fn = async function(fn) {
169
- try {
170
- return await fn();
171
- } catch (e) {
172
- throw this.onError(e);
153
+ this._broadcastChatMessage(
154
+ {
155
+ type: "cf_agent_chat_messages",
156
+ messages
157
+ },
158
+ excludeBroadcastIds
159
+ );
173
160
  }
174
- };
175
- reply_fn = async function(id, response) {
176
- return __privateMethod(this, _AIChatAgent_instances, tryCatch_fn).call(this, async () => {
177
- for await (const chunk of response.body) {
178
- const body = decoder.decode(chunk);
179
- __privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
161
+ async _reply(id, response) {
162
+ return this._tryCatchChat(async () => {
163
+ for await (const chunk of response.body) {
164
+ const body = decoder.decode(chunk);
165
+ this._broadcastChatMessage({
166
+ id,
167
+ type: "cf_agent_use_chat_response",
168
+ body,
169
+ done: false
170
+ });
171
+ }
172
+ this._broadcastChatMessage({
180
173
  id,
181
174
  type: "cf_agent_use_chat_response",
182
- body,
183
- done: false
175
+ body: "",
176
+ done: true
184
177
  });
185
- }
186
- __privateMethod(this, _AIChatAgent_instances, broadcastChatMessage_fn).call(this, {
187
- id,
188
- type: "cf_agent_use_chat_response",
189
- body: "",
190
- done: true
191
178
  });
192
- });
193
- };
194
- /**
195
- * For the given message id, look up its associated AbortController
196
- * If the AbortController does not exist, create and store one in memory
197
- *
198
- * returns the AbortSignal associated with the AbortController
199
- */
200
- getAbortSignal_fn = function(id) {
201
- if (typeof id !== "string") {
202
- return void 0;
203
179
  }
204
- if (!__privateGet(this, _chatMessageAbortControllers).has(id)) {
205
- __privateGet(this, _chatMessageAbortControllers).set(id, new AbortController());
180
+ /**
181
+ * For the given message id, look up its associated AbortController
182
+ * If the AbortController does not exist, create and store one in memory
183
+ *
184
+ * returns the AbortSignal associated with the AbortController
185
+ */
186
+ _getAbortSignal(id) {
187
+ if (typeof id !== "string") {
188
+ return void 0;
189
+ }
190
+ if (!this._chatMessageAbortControllers.has(id)) {
191
+ this._chatMessageAbortControllers.set(id, new AbortController());
192
+ }
193
+ return this._chatMessageAbortControllers.get(id)?.signal;
206
194
  }
207
- return __privateGet(this, _chatMessageAbortControllers).get(id)?.signal;
208
- };
209
- /**
210
- * Remove an abort controller from the cache of pending message responses
211
- */
212
- removeAbortController_fn = function(id) {
213
- __privateGet(this, _chatMessageAbortControllers).delete(id);
214
- };
215
- /**
216
- * Propagate an abort signal for any requests associated with the given message id
217
- */
218
- cancelChatRequest_fn = function(id) {
219
- if (__privateGet(this, _chatMessageAbortControllers).has(id)) {
220
- const abortController = __privateGet(this, _chatMessageAbortControllers).get(id);
221
- abortController?.abort();
195
+ /**
196
+ * Remove an abort controller from the cache of pending message responses
197
+ */
198
+ _removeAbortController(id) {
199
+ this._chatMessageAbortControllers.delete(id);
222
200
  }
223
- };
224
- /**
225
- * Abort all pending requests and clear the cache of AbortControllers
226
- */
227
- destroyAbortControllers_fn = function() {
228
- for (const controller of __privateGet(this, _chatMessageAbortControllers).values()) {
229
- controller?.abort();
201
+ /**
202
+ * Propagate an abort signal for any requests associated with the given message id
203
+ */
204
+ _cancelChatRequest(id) {
205
+ if (this._chatMessageAbortControllers.has(id)) {
206
+ const abortController = this._chatMessageAbortControllers.get(id);
207
+ abortController?.abort();
208
+ }
209
+ }
210
+ /**
211
+ * Abort all pending requests and clear the cache of AbortControllers
212
+ */
213
+ _destroyAbortControllers() {
214
+ for (const controller of this._chatMessageAbortControllers.values()) {
215
+ controller?.abort();
216
+ }
217
+ this._chatMessageAbortControllers.clear();
218
+ }
219
+ /**
220
+ * When the DO is destroyed, cancel all pending requests
221
+ */
222
+ async destroy() {
223
+ this._destroyAbortControllers();
224
+ await super.destroy();
230
225
  }
231
- __privateGet(this, _chatMessageAbortControllers).clear();
232
226
  };
233
227
  export {
234
228
  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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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 { 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 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 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._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 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._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 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 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 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 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":";;;;;;;;AAMA,SAAS,8BAA8B;AAGvC,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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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"]}
package/dist/ai-react.js CHANGED
@@ -1,5 +1,3 @@
1
- import "./chunk-HMLY7DHA.js";
2
-
3
1
  // src/ai-react.tsx
4
2
  import { useChat } from "@ai-sdk/react";
5
3
  import { use, useEffect } from "react";
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ai-react.tsx"],"sourcesContent":["import { useChat } from \"@ai-sdk/react\";\nimport type { Message } from \"ai\";\nimport { use, useEffect } from \"react\";\nimport type { OutgoingMessage } from \"./ai-types\";\nimport type { useAgent } from \"./react\";\nimport { nanoid } from \"nanoid\";\n\ntype GetInitialMessagesOptions = {\n agent: string;\n name: string;\n url: string;\n};\n\n/**\n * Options for the useAgentChat hook\n */\ntype UseAgentChatOptions<State> = Omit<\n Parameters<typeof useChat>[0] & {\n /** Agent connection from useAgent */\n agent: ReturnType<typeof useAgent<State>>;\n getInitialMessages?:\n | undefined\n | null\n // | (() => Message[])\n | ((options: GetInitialMessagesOptions) => Promise<Message[]>);\n },\n \"fetch\"\n>;\n\nconst requestCache = new Map<string, Promise<Message[]>>();\n\n/**\n * React hook for building AI chat interfaces using an Agent\n * @param options Chat options including the agent connection\n * @returns Chat interface controls and state with added clearHistory method\n */\nexport function useAgentChat<State = unknown>(\n options: UseAgentChatOptions<State>\n) {\n const { agent, getInitialMessages, ...rest } = options;\n\n const agentUrl = new URL(\n `${// @ts-expect-error we're using a protected _url property that includes query params\n ((agent._url as string | null) || agent._pkurl)\n ?.replace(\"ws://\", \"http://\")\n .replace(\"wss://\", \"https://\")}`\n );\n\n // delete the _pk query param\n agentUrl.searchParams.delete(\"_pk\");\n const agentUrlString = agentUrl.toString();\n\n async function defaultGetInitialMessagesFetch({\n url,\n }: GetInitialMessagesOptions) {\n const getMessagesUrl = new URL(url);\n getMessagesUrl.pathname += \"/get-messages\";\n const response = await fetch(getMessagesUrl.toString(), {\n headers: options.headers,\n credentials: options.credentials,\n });\n return response.json<Message[]>();\n }\n\n const getInitialMessagesFetch =\n getInitialMessages || defaultGetInitialMessagesFetch;\n\n function doGetInitialMessages(\n getInitialMessagesOptions: GetInitialMessagesOptions\n ) {\n if (requestCache.has(agentUrlString)) {\n return requestCache.get(agentUrlString)!;\n }\n const promise = getInitialMessagesFetch(getInitialMessagesOptions);\n // immediately cache the promise so that we don't\n // create multiple requests for the same agent during multiple\n // concurrent renders\n requestCache.set(agentUrlString, promise);\n return promise;\n }\n\n const initialMessagesPromise =\n getInitialMessages === null\n ? null\n : doGetInitialMessages({\n agent: agent.agent,\n name: agent.name,\n url: agentUrlString,\n });\n const initialMessages = initialMessagesPromise\n ? use(initialMessagesPromise)\n : (rest.initialMessages ?? []);\n\n // manages adding and removing the promise from the cache\n useEffect(() => {\n if (!initialMessagesPromise) {\n return;\n }\n // this effect is responsible for removing the promise from the cache\n // when the component unmounts or the promise changes,\n // but that means it also must add the promise to the cache\n // so that multiple arbitrary effect runs produce the expected state\n // when resolved.\n requestCache.set(agentUrlString, initialMessagesPromise!);\n return () => {\n if (requestCache.get(agentUrlString) === initialMessagesPromise) {\n requestCache.delete(agentUrlString);\n }\n };\n }, [agentUrlString, initialMessagesPromise]);\n\n async function aiFetch(\n request: RequestInfo | URL,\n options: RequestInit = {}\n ) {\n // we're going to use a websocket to do the actual \"fetching\"\n // but still satisfy the type signature of the fetch function\n // so we'll return a promise that resolves to a response\n\n const {\n method,\n keepalive,\n headers,\n body,\n redirect,\n integrity,\n signal,\n credentials,\n mode,\n referrer,\n referrerPolicy,\n window,\n // dispatcher, duplex\n } = options;\n const id = nanoid(8);\n const abortController = new AbortController();\n\n signal?.addEventListener(\"abort\", () => {\n // Propagate request cancellation to the Agent\n // We need to communciate cancellation as a websocket message, instead of a request signal\n agent.send(\n JSON.stringify({\n type: \"cf_agent_chat_request_cancel\",\n id,\n })\n );\n\n // NOTE - If we wanted to, we could preserve the \"interrupted\" message here, with the code below\n // However, I think it might be the responsibility of the library user to implement that behavior manually?\n // Reasoning: This code could be subject to collisions, as it \"force saves\" the messages we have locally\n //\n // agent.send(JSON.stringify({\n // type: \"cf_agent_chat_messages\",\n // messages: ... /* some way of getting current messages ref? */\n // }))\n\n abortController.abort();\n // Make sure to also close the stream (cf. https://github.com/cloudflare/agents-starter/issues/69)\n controller.close();\n });\n\n agent.addEventListener(\n \"message\",\n (event) => {\n let data: OutgoingMessage;\n try {\n data = JSON.parse(event.data) as OutgoingMessage;\n } catch (error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (data.type === \"cf_agent_use_chat_response\") {\n if (data.id === id) {\n controller.enqueue(new TextEncoder().encode(data.body));\n if (data.done) {\n controller.close();\n abortController.abort();\n }\n }\n }\n },\n { signal: abortController.signal }\n );\n\n let controller: ReadableStreamDefaultController;\n\n const stream = new ReadableStream({\n start(c) {\n controller = c;\n },\n });\n\n agent.send(\n JSON.stringify({\n type: \"cf_agent_use_chat_request\",\n id,\n url: request.toString(),\n init: {\n method,\n keepalive,\n headers,\n body,\n redirect,\n integrity,\n credentials,\n mode,\n referrer,\n referrerPolicy,\n window,\n // dispatcher,\n // duplex\n },\n })\n );\n\n return new Response(stream);\n }\n const useChatHelpers = useChat({\n initialMessages,\n sendExtraMessageFields: true,\n fetch: aiFetch,\n ...rest,\n });\n\n useEffect(() => {\n function onClearHistory(event: MessageEvent) {\n if (typeof event.data !== \"string\") {\n return;\n }\n let data: OutgoingMessage;\n try {\n data = JSON.parse(event.data) as OutgoingMessage;\n } catch (error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (data.type === \"cf_agent_chat_clear\") {\n useChatHelpers.setMessages([]);\n }\n }\n\n function onMessages(event: MessageEvent) {\n if (typeof event.data !== \"string\") {\n return;\n }\n let data: OutgoingMessage;\n try {\n data = JSON.parse(event.data) as OutgoingMessage;\n } catch (error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (data.type === \"cf_agent_chat_messages\") {\n useChatHelpers.setMessages(data.messages);\n }\n }\n\n agent.addEventListener(\"message\", onClearHistory);\n agent.addEventListener(\"message\", onMessages);\n\n return () => {\n agent.removeEventListener(\"message\", onClearHistory);\n agent.removeEventListener(\"message\", onMessages);\n };\n }, [agent, useChatHelpers.setMessages]);\n\n return {\n ...useChatHelpers,\n /**\n * Set the chat messages and synchronize with the Agent\n * @param messages New messages to set\n */\n setMessages: (messages: Message[]) => {\n useChatHelpers.setMessages(messages);\n agent.send(\n JSON.stringify({\n type: \"cf_agent_chat_messages\",\n messages,\n })\n );\n },\n /**\n * Clear chat history on both client and Agent\n */\n clearHistory: () => {\n useChatHelpers.setMessages([]);\n agent.send(\n JSON.stringify({\n type: \"cf_agent_chat_clear\",\n })\n );\n },\n };\n}\n"],"mappings":";;;AAAA,SAAS,eAAe;AAExB,SAAS,KAAK,iBAAiB;AAG/B,SAAS,cAAc;AAwBvB,IAAM,eAAe,oBAAI,IAAgC;AAOlD,SAAS,aACd,SACA;AACA,QAAM,EAAE,OAAO,oBAAoB,GAAG,KAAK,IAAI;AAE/C,QAAM,WAAW,IAAI;AAAA,IACnB;AAAA,KACE,MAAM,QAA0B,MAAM,SACpC,QAAQ,SAAS,SAAS,EAC3B,QAAQ,UAAU,UAAU,CAAC;AAAA,EAClC;AAGA,WAAS,aAAa,OAAO,KAAK;AAClC,QAAM,iBAAiB,SAAS,SAAS;AAEzC,iBAAe,+BAA+B;AAAA,IAC5C;AAAA,EACF,GAA8B;AAC5B,UAAM,iBAAiB,IAAI,IAAI,GAAG;AAClC,mBAAe,YAAY;AAC3B,UAAM,WAAW,MAAM,MAAM,eAAe,SAAS,GAAG;AAAA,M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;AAAA,MAC/B;AAAA,IACF;AAEA,aAAS,WAAW,OAAqB;AACvC,UAAI,OAAO,MAAM,SAAS,UAAU;AAClC;AAAA,MACF;AACA,UAAI;AACJ,UAAI;AACF,eAAO,KAAK,MAAM,MAAM,IAAI;AAAA,MAC9B,SAAS,OAAO;AAGd;AAAA,MACF;AACA,UAAI,KAAK,SAAS,0BAA0B;AAC1C,uBAAe,YAAY,KAAK,QAAQ;AAAA,MAC1C;AAAA,IACF;AAEA,UAAM,iBAAiB,WAAW,cAAc;AAChD,UAAM,iBAAiB,WAAW,UAAU;AAE5C,WAAO,MAAM;AACX,YAAM,oBAAoB,WAAW,cAAc;AACnD,YAAM,oBAAoB,WAAW,UAAU;AAAA,IACjD;AAAA,EACF,GAAG,CAAC,OAAO,eAAe,WAAW,CAAC;AAEtC,SAAO;AAAA,IACL,GAAG;AAAA;AAAA;AAAA;AAAA;AAAA,IAKH,aAAa,CAAC,aAAwB;AACpC,qBAAe,YAAY,QAAQ;AACnC,YAAM;AAAA,QACJ,KAAK,UAAU;AAAA,UACb,MAAM;AAAA,UACN;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF;AAAA;AAAA;AAAA;AAAA,IAIA,cAAc,MAAM;AAClB,qBAAe,YAAY,CAAC,CAAC;AAC7B,YAAM;AAAA,QACJ,KAAK,UAAU;AAAA,UACb,MAAM;AAAA,QACR,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AACF;","names":["options"]}
1
+ {"version":3,"sources":["../src/ai-react.tsx"],"sourcesContent":["import { useChat } from \"@ai-sdk/react\";\nimport type { Message } from \"ai\";\nimport { use, useEffect } from \"react\";\nimport type { OutgoingMessage } from \"./ai-types\";\nimport type { useAgent } from \"./react\";\nimport { nanoid } from \"nanoid\";\n\ntype GetInitialMessagesOptions = {\n agent: string;\n name: string;\n url: string;\n};\n\n/**\n * Options for the useAgentChat hook\n */\ntype UseAgentChatOptions<State> = Omit<\n Parameters<typeof useChat>[0] & {\n /** Agent connection from useAgent */\n agent: ReturnType<typeof useAgent<State>>;\n getInitialMessages?:\n | undefined\n | null\n // | (() => Message[])\n | ((options: GetInitialMessagesOptions) => Promise<Message[]>);\n },\n \"fetch\"\n>;\n\nconst requestCache = new Map<string, Promise<Message[]>>();\n\n/**\n * React hook for building AI chat interfaces using an Agent\n * @param options Chat options including the agent connection\n * @returns Chat interface controls and state with added clearHistory method\n */\nexport function useAgentChat<State = unknown>(\n options: UseAgentChatOptions<State>\n) {\n const { agent, getInitialMessages, ...rest } = options;\n\n const agentUrl = new URL(\n `${// @ts-expect-error we're using a protected _url property that includes query params\n ((agent._url as string | null) || agent._pkurl)\n ?.replace(\"ws://\", \"http://\")\n .replace(\"wss://\", \"https://\")}`\n );\n\n // delete the _pk query param\n agentUrl.searchParams.delete(\"_pk\");\n const agentUrlString = agentUrl.toString();\n\n async function defaultGetInitialMessagesFetch({\n url,\n }: GetInitialMessagesOptions) {\n const getMessagesUrl = new URL(url);\n getMessagesUrl.pathname += \"/get-messages\";\n const response = await fetch(getMessagesUrl.toString(), {\n headers: options.headers,\n credentials: options.credentials,\n });\n return response.json<Message[]>();\n }\n\n const getInitialMessagesFetch =\n getInitialMessages || defaultGetInitialMessagesFetch;\n\n function doGetInitialMessages(\n getInitialMessagesOptions: GetInitialMessagesOptions\n ) {\n if (requestCache.has(agentUrlString)) {\n return requestCache.get(agentUrlString)!;\n }\n const promise = getInitialMessagesFetch(getInitialMessagesOptions);\n // immediately cache the promise so that we don't\n // create multiple requests for the same agent during multiple\n // concurrent renders\n requestCache.set(agentUrlString, promise);\n return promise;\n }\n\n const initialMessagesPromise =\n getInitialMessages === null\n ? null\n : doGetInitialMessages({\n agent: agent.agent,\n name: agent.name,\n url: agentUrlString,\n });\n const initialMessages = initialMessagesPromise\n ? use(initialMessagesPromise)\n : (rest.initialMessages ?? []);\n\n // manages adding and removing the promise from the cache\n useEffect(() => {\n if (!initialMessagesPromise) {\n return;\n }\n // this effect is responsible for removing the promise from the cache\n // when the component unmounts or the promise changes,\n // but that means it also must add the promise to the cache\n // so that multiple arbitrary effect runs produce the expected state\n // when resolved.\n requestCache.set(agentUrlString, initialMessagesPromise!);\n return () => {\n if (requestCache.get(agentUrlString) === initialMessagesPromise) {\n requestCache.delete(agentUrlString);\n }\n };\n }, [agentUrlString, initialMessagesPromise]);\n\n async function aiFetch(\n request: RequestInfo | URL,\n options: RequestInit = {}\n ) {\n // we're going to use a websocket to do the actual \"fetching\"\n // but still satisfy the type signature of the fetch function\n // so we'll return a promise that resolves to a response\n\n const {\n method,\n keepalive,\n headers,\n body,\n redirect,\n integrity,\n signal,\n credentials,\n mode,\n referrer,\n referrerPolicy,\n window,\n // dispatcher, duplex\n } = options;\n const id = nanoid(8);\n const abortController = new AbortController();\n\n signal?.addEventListener(\"abort\", () => {\n // Propagate request cancellation to the Agent\n // We need to communciate cancellation as a websocket message, instead of a request signal\n agent.send(\n JSON.stringify({\n type: \"cf_agent_chat_request_cancel\",\n id,\n })\n );\n\n // NOTE - If we wanted to, we could preserve the \"interrupted\" message here, with the code below\n // However, I think it might be the responsibility of the library user to implement that behavior manually?\n // Reasoning: This code could be subject to collisions, as it \"force saves\" the messages we have locally\n //\n // agent.send(JSON.stringify({\n // type: \"cf_agent_chat_messages\",\n // messages: ... /* some way of getting current messages ref? */\n // }))\n\n abortController.abort();\n // Make sure to also close the stream (cf. https://github.com/cloudflare/agents-starter/issues/69)\n controller.close();\n });\n\n agent.addEventListener(\n \"message\",\n (event) => {\n let data: OutgoingMessage;\n try {\n data = JSON.parse(event.data) as OutgoingMessage;\n } catch (error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (data.type === \"cf_agent_use_chat_response\") {\n if (data.id === id) {\n controller.enqueue(new TextEncoder().encode(data.body));\n if (data.done) {\n controller.close();\n abortController.abort();\n }\n }\n }\n },\n { signal: abortController.signal }\n );\n\n let controller: ReadableStreamDefaultController;\n\n const stream = new ReadableStream({\n start(c) {\n controller = c;\n },\n });\n\n agent.send(\n JSON.stringify({\n type: \"cf_agent_use_chat_request\",\n id,\n url: request.toString(),\n init: {\n method,\n keepalive,\n headers,\n body,\n redirect,\n integrity,\n credentials,\n mode,\n referrer,\n referrerPolicy,\n window,\n // dispatcher,\n // duplex\n },\n })\n );\n\n return new Response(stream);\n }\n const useChatHelpers = useChat({\n initialMessages,\n sendExtraMessageFields: true,\n fetch: aiFetch,\n ...rest,\n });\n\n useEffect(() => {\n function onClearHistory(event: MessageEvent) {\n if (typeof event.data !== \"string\") {\n return;\n }\n let data: OutgoingMessage;\n try {\n data = JSON.parse(event.data) as OutgoingMessage;\n } catch (error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (data.type === \"cf_agent_chat_clear\") {\n useChatHelpers.setMessages([]);\n }\n }\n\n function onMessages(event: MessageEvent) {\n if (typeof event.data !== \"string\") {\n return;\n }\n let data: OutgoingMessage;\n try {\n data = JSON.parse(event.data) as OutgoingMessage;\n } catch (error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (data.type === \"cf_agent_chat_messages\") {\n useChatHelpers.setMessages(data.messages);\n }\n }\n\n agent.addEventListener(\"message\", onClearHistory);\n agent.addEventListener(\"message\", onMessages);\n\n return () => {\n agent.removeEventListener(\"message\", onClearHistory);\n agent.removeEventListener(\"message\", onMessages);\n };\n }, [agent, useChatHelpers.setMessages]);\n\n return {\n ...useChatHelpers,\n /**\n * Set the chat messages and synchronize with the Agent\n * @param messages New messages to set\n */\n setMessages: (messages: Message[]) => {\n useChatHelpers.setMessages(messages);\n agent.send(\n JSON.stringify({\n type: \"cf_agent_chat_messages\",\n messages,\n })\n );\n },\n /**\n * Clear chat history on both client and Agent\n */\n clearHistory: () => {\n useChatHelpers.setMessages([]);\n agent.send(\n JSON.stringify({\n type: \"cf_agent_chat_clear\",\n })\n );\n },\n };\n}\n"],"mappings":";AAAA,SAAS,eAAe;AAExB,SAAS,KAAK,iBAAiB;AAG/B,SAAS,cAAc;AAw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B,qBAAe,YAAY,CAAC,CAAC;AAC7B,YAAM;AAAA,QACJ,KAAK,UAAU;AAAA,UACb,MAAM;AAAA,QACR,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AACF;","names":["options"]}
@@ -19,22 +19,22 @@ var DurableObjectOAuthClientProvider = class {
19
19
  return `${this.baseRedirectUrl}/${this.serverId}`;
20
20
  }
21
21
  get clientId() {
22
- if (!this.clientId_) {
22
+ if (!this._clientId_) {
23
23
  throw new Error("Trying to access clientId before it was set");
24
24
  }
25
- return this.clientId_;
25
+ return this._clientId_;
26
26
  }
27
27
  set clientId(clientId_) {
28
- this.clientId_ = clientId_;
28
+ this._clientId_ = clientId_;
29
29
  }
30
30
  get serverId() {
31
- if (!this.serverId_) {
31
+ if (!this._serverId_) {
32
32
  throw new Error("Trying to access serverId before it was set");
33
33
  }
34
- return this.serverId_;
34
+ return this._serverId_;
35
35
  }
36
36
  set serverId(serverId_) {
37
- this.serverId_ = serverId_;
37
+ this._serverId_ = serverId_;
38
38
  }
39
39
  keyPrefix(clientId) {
40
40
  return `/${this.clientName}/${this.serverId}/${clientId}`;
@@ -43,7 +43,7 @@ var DurableObjectOAuthClientProvider = class {
43
43
  return `${this.keyPrefix(clientId)}/client_info/`;
44
44
  }
45
45
  async clientInformation() {
46
- if (!this.clientId_) {
46
+ if (!this._clientId_) {
47
47
  return void 0;
48
48
  }
49
49
  return await this.storage.get(
@@ -61,7 +61,7 @@ var DurableObjectOAuthClientProvider = class {
61
61
  return `${this.keyPrefix(clientId)}/token`;
62
62
  }
63
63
  async tokens() {
64
- if (!this.clientId_) {
64
+ if (!this._clientId_) {
65
65
  return void 0;
66
66
  }
67
67
  return await this.storage.get(this.tokenKey(this.clientId)) ?? void 0;
@@ -70,7 +70,7 @@ var DurableObjectOAuthClientProvider = class {
70
70
  await this.storage.put(this.tokenKey(this.clientId), tokens);
71
71
  }
72
72
  get authUrl() {
73
- return this.authUrl_;
73
+ return this._authUrl_;
74
74
  }
75
75
  /**
76
76
  * Because this operates on the server side (but we need browser auth), we send this url back to the user
@@ -81,7 +81,7 @@ var DurableObjectOAuthClientProvider = class {
81
81
  if (client_id) {
82
82
  authUrl.searchParams.append("state", client_id);
83
83
  }
84
- this.authUrl_ = authUrl.toString();
84
+ this._authUrl_ = authUrl.toString();
85
85
  }
86
86
  codeVerifierKey(clientId) {
87
87
  return `${this.keyPrefix(clientId)}/code_verifier`;
@@ -103,4 +103,4 @@ var DurableObjectOAuthClientProvider = class {
103
103
  export {
104
104
  DurableObjectOAuthClientProvider
105
105
  };
106
- //# sourceMappingURL=chunk-D6UOOELW.js.map
106
+ //# sourceMappingURL=chunk-BZXOAZUX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/mcp/do-oauth-client-provider.ts"],"sourcesContent":["import type { OAuthClientProvider } from \"@modelcontextprotocol/sdk/client/auth.js\";\nimport type {\n OAuthTokens,\n OAuthClientMetadata,\n OAuthClientInformation,\n OAuthClientInformationFull,\n} from \"@modelcontextprotocol/sdk/shared/auth.js\";\n\n// A slight extension to the standard OAuthClientProvider interface because `redirectToAuthorization` doesn't give us the interface we need\n// This allows us to track authentication for a specific server and associated dynamic client registration\nexport interface AgentsOAuthProvider extends OAuthClientProvider {\n authUrl: string | undefined;\n clientId: string | undefined;\n serverId: string | undefined;\n}\n\nexport class DurableObjectOAuthClientProvider implements AgentsOAuthProvider {\n private _authUrl_: string | undefined;\n private _serverId_: string | undefined;\n private _clientId_: string | undefined;\n\n constructor(\n public storage: DurableObjectStorage,\n public clientName: string,\n public baseRedirectUrl: string\n ) {}\n\n get clientMetadata(): OAuthClientMetadata {\n return {\n redirect_uris: [this.redirectUrl],\n token_endpoint_auth_method: \"none\",\n grant_types: [\"authorization_code\", \"refresh_token\"],\n response_types: [\"code\"],\n client_name: this.clientName,\n client_uri: \"example.com\",\n };\n }\n\n get redirectUrl() {\n return `${this.baseRedirectUrl}/${this.serverId}`;\n }\n\n get clientId() {\n if (!this._clientId_) {\n throw new Error(\"Trying to access clientId before it was set\");\n }\n return this._clientId_;\n }\n\n set clientId(clientId_: string) {\n this._clientId_ = clientId_;\n }\n\n get serverId() {\n if (!this._serverId_) {\n throw new Error(\"Trying to access serverId before it was set\");\n }\n return this._serverId_;\n }\n\n set serverId(serverId_: string) {\n this._serverId_ = serverId_;\n }\n\n keyPrefix(clientId: string) {\n return `/${this.clientName}/${this.serverId}/${clientId}`;\n }\n\n clientInfoKey(clientId: string) {\n return `${this.keyPrefix(clientId)}/client_info/`;\n }\n\n async clientInformation(): Promise<OAuthClientInformation | undefined> {\n if (!this._clientId_) {\n return undefined;\n }\n return (\n (await this.storage.get<OAuthClientInformation>(\n this.clientInfoKey(this.clientId)\n )) ?? undefined\n );\n }\n\n async saveClientInformation(\n clientInformation: OAuthClientInformationFull\n ): Promise<void> {\n await this.storage.put(\n this.clientInfoKey(clientInformation.client_id),\n clientInformation\n );\n this.clientId = clientInformation.client_id;\n }\n\n tokenKey(clientId: string) {\n return `${this.keyPrefix(clientId)}/token`;\n }\n\n async tokens(): Promise<OAuthTokens | undefined> {\n if (!this._clientId_) {\n return undefined;\n }\n return (\n (await this.storage.get<OAuthTokens>(this.tokenKey(this.clientId))) ??\n undefined\n );\n }\n\n async saveTokens(tokens: OAuthTokens): Promise<void> {\n await this.storage.put(this.tokenKey(this.clientId), tokens);\n }\n\n get authUrl() {\n return this._authUrl_;\n }\n\n /**\n * Because this operates on the server side (but we need browser auth), we send this url back to the user\n * and require user interact to initiate the redirect flow\n */\n async redirectToAuthorization(authUrl: URL): Promise<void> {\n // We want to track the client ID in state here because the typescript SSE client sometimes does\n // a dynamic client registration AFTER generating this redirect URL.\n const client_id = authUrl.searchParams.get(\"client_id\");\n if (client_id) {\n authUrl.searchParams.append(\"state\", client_id);\n }\n this._authUrl_ = authUrl.toString();\n }\n\n codeVerifierKey(clientId: string) {\n return `${this.keyPrefix(clientId)}/code_verifier`;\n }\n\n async saveCodeVerifier(verifier: string): Promise<void> {\n await this.storage.put(this.codeVerifierKey(this.clientId), verifier);\n }\n\n async codeVerifier(): Promise<string> {\n const codeVerifier = await this.storage.get<string>(\n this.codeVerifierKey(this.clientId)\n );\n if (!codeVerifier) {\n throw new Error(\"No code verifier found\");\n }\n return codeVerifier;\n }\n}\n"],"mappings":";AAgBO,IAAM,mCAAN,MAAsE;AAAA,EAK3E,YACS,SACA,YACA,iBACP;AAHO;AACA;AACA;AAAA,EACN;AAAA,EAEH,IAAI,iBAAsC;AACxC,WAAO;AAAA,MACL,eAAe,CAAC,KAAK,WAAW;AAAA,MAChC,4BAA4B;AAAA,MAC5B,aAAa,CAAC,sBAAsB,eAAe;AAAA,MACnD,gBAAgB,CAAC,MAAM;AAAA,MACvB,aAAa,KAAK;AAAA,MAClB,YAAY;AAAA,IACd;AAAA,EACF;AAAA,EAEA,IAAI,cAAc;AAChB,WAAO,GAAG,KAAK,eAAe,IAAI,KAAK,QAAQ;AAAA,EACjD;AAAA,EAEA,IAAI,WAAW;AACb,QAAI,CAAC,KAAK,YAAY;AACpB,YAAM,IAAI,MAAM,6CAA6C;AAAA,IAC/D;AACA,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,IAAI,SAAS,WAAmB;AAC9B,SAAK,aAAa;AAAA,EACpB;AAAA,EAEA,IAAI,WAAW;AACb,QAAI,CAAC,KAAK,YAAY;AACpB,YAAM,IAAI,MAAM,6CAA6C;AAAA,IAC/D;AACA,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,IAAI,SAAS,WAAmB;AAC9B,SAAK,aAAa;AAAA,EACpB;AAAA,EAEA,UAAU,UAAkB;AAC1B,WAAO,IAAI,KAAK,UAAU,IAAI,KAAK,QAAQ,IAAI,QAAQ;AAAA,EACzD;AAAA,EAEA,cAAc,UAAkB;AAC9B,WAAO,GAAG,KAAK,UAAU,QAAQ,CAAC;AAAA,EACpC;AAAA,EAEA,MAAM,oBAAiE;AACrE,QAAI,CAAC,KAAK,YAAY;AACpB,aAAO;AAAA,IACT;AACA,WACG,MAAM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AAA,IAC1C;AACA,WAAO;AAAA,EACT;AACF;","names":[]}
@@ -1,9 +1,3 @@
1
- import {
2
- __privateAdd,
3
- __privateGet,
4
- __privateSet
5
- } from "./chunk-HMLY7DHA.js";
6
-
7
1
  // src/client.ts
8
2
  import {
9
3
  PartySocket
@@ -19,7 +13,6 @@ function camelCaseToKebabCase(str) {
19
13
  kebabified = kebabified.startsWith("-") ? kebabified.slice(1) : kebabified;
20
14
  return kebabified.replace(/_/g, "-").replace(/-$/, "");
21
15
  }
22
- var _options, _pendingCalls;
23
16
  var AgentClient = class extends PartySocket {
24
17
  constructor(options) {
25
18
  const agentNamespace = camelCaseToKebabCase(options.agent);
@@ -29,11 +22,10 @@ var AgentClient = class extends PartySocket {
29
22
  room: options.name || "default",
30
23
  ...options
31
24
  });
32
- __privateAdd(this, _options);
33
- __privateAdd(this, _pendingCalls, /* @__PURE__ */ new Map());
25
+ this._pendingCalls = /* @__PURE__ */ new Map();
34
26
  this.agent = agentNamespace;
35
27
  this.name = options.name || "default";
36
- __privateSet(this, _options, options);
28
+ this.options = options;
37
29
  this.addEventListener("message", (event) => {
38
30
  if (typeof event.data === "string") {
39
31
  let parsedMessage;
@@ -43,30 +35,30 @@ var AgentClient = class extends PartySocket {
43
35
  return;
44
36
  }
45
37
  if (parsedMessage.type === "cf_agent_state") {
46
- __privateGet(this, _options).onStateUpdate?.(parsedMessage.state, "server");
38
+ this.options.onStateUpdate?.(parsedMessage.state, "server");
47
39
  return;
48
40
  }
49
41
  if (parsedMessage.type === "rpc") {
50
42
  const response = parsedMessage;
51
- const pending = __privateGet(this, _pendingCalls).get(response.id);
43
+ const pending = this._pendingCalls.get(response.id);
52
44
  if (!pending) return;
53
45
  if (!response.success) {
54
46
  pending.reject(new Error(response.error));
55
- __privateGet(this, _pendingCalls).delete(response.id);
47
+ this._pendingCalls.delete(response.id);
56
48
  pending.stream?.onError?.(response.error);
57
49
  return;
58
50
  }
59
51
  if ("done" in response) {
60
52
  if (response.done) {
61
53
  pending.resolve(response.result);
62
- __privateGet(this, _pendingCalls).delete(response.id);
54
+ this._pendingCalls.delete(response.id);
63
55
  pending.stream?.onDone?.(response.result);
64
56
  } else {
65
57
  pending.stream?.onChunk?.(response.result);
66
58
  }
67
59
  } else {
68
60
  pending.resolve(response.result);
69
- __privateGet(this, _pendingCalls).delete(response.id);
61
+ this._pendingCalls.delete(response.id);
70
62
  }
71
63
  }
72
64
  }
@@ -82,7 +74,7 @@ var AgentClient = class extends PartySocket {
82
74
  }
83
75
  setState(state) {
84
76
  this.send(JSON.stringify({ type: "cf_agent_state", state }));
85
- __privateGet(this, _options).onStateUpdate?.(state, "client");
77
+ this.options.onStateUpdate?.(state, "client");
86
78
  }
87
79
  /**
88
80
  * Call a method on the Agent
@@ -94,7 +86,7 @@ var AgentClient = class extends PartySocket {
94
86
  async call(method, args = [], streamOptions) {
95
87
  return new Promise((resolve, reject) => {
96
88
  const id = Math.random().toString(36).slice(2);
97
- __privateGet(this, _pendingCalls).set(id, {
89
+ this._pendingCalls.set(id, {
98
90
  resolve: (value) => resolve(value),
99
91
  reject,
100
92
  stream: streamOptions,
@@ -110,8 +102,6 @@ var AgentClient = class extends PartySocket {
110
102
  });
111
103
  }
112
104
  };
113
- _options = new WeakMap();
114
- _pendingCalls = new WeakMap();
115
105
  function agentFetch(opts, init) {
116
106
  const agentNamespace = camelCaseToKebabCase(opts.agent);
117
107
  return PartySocket.fetch(
@@ -130,4 +120,4 @@ export {
130
120
  AgentClient,
131
121
  agentFetch
132
122
  };
133
- //# sourceMappingURL=chunk-RN4SNE73.js.map
123
+ //# sourceMappingURL=chunk-QSGN3REV.js.map