hono-agents 0.0.0-e03246e → 0.0.0-e135cf5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,48 +1,1932 @@
1
- // src/index.ts
1
+ import "partysocket";
2
+ import { nanoid } from "nanoid";
3
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
4
+ import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
5
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
6
+ import { ElicitRequestSchema, PromptListChangedNotificationSchema, ResourceListChangedNotificationSchema, ToolListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js";
7
+ import { AsyncLocalStorage } from "node:async_hooks";
8
+ import { parseCronExpression } from "cron-schedule";
9
+ import "cloudflare:email";
10
+ import { Server, routePartykitRequest } from "partyserver";
2
11
  import { env } from "hono/adapter";
3
12
  import { createMiddleware } from "hono/factory";
4
- import { routeAgentRequest } from "agents";
13
+
14
+ //#region ../agents/dist/ai-types-B3aQaFv3.js
15
+ /**
16
+ * Enum for message types to improve type safety and maintainability
17
+ */
18
+ let MessageType = /* @__PURE__ */ function(MessageType$1) {
19
+ MessageType$1["CF_AGENT_CHAT_MESSAGES"] = "cf_agent_chat_messages";
20
+ MessageType$1["CF_AGENT_USE_CHAT_REQUEST"] = "cf_agent_use_chat_request";
21
+ MessageType$1["CF_AGENT_USE_CHAT_RESPONSE"] = "cf_agent_use_chat_response";
22
+ MessageType$1["CF_AGENT_CHAT_CLEAR"] = "cf_agent_chat_clear";
23
+ MessageType$1["CF_AGENT_CHAT_REQUEST_CANCEL"] = "cf_agent_chat_request_cancel";
24
+ MessageType$1["CF_AGENT_MCP_SERVERS"] = "cf_agent_mcp_servers";
25
+ MessageType$1["CF_MCP_AGENT_EVENT"] = "cf_mcp_agent_event";
26
+ MessageType$1["CF_AGENT_STATE"] = "cf_agent_state";
27
+ MessageType$1["RPC"] = "rpc";
28
+ return MessageType$1;
29
+ }({});
30
+
31
+ //#endregion
32
+ //#region ../agents/dist/client-BfiZ3HQd.js
33
+ /**
34
+ * Convert a camelCase string to a kebab-case string
35
+ * @param str The string to convert
36
+ * @returns The kebab-case string
37
+ */
38
+ function camelCaseToKebabCase(str) {
39
+ if (str === str.toUpperCase() && str !== str.toLowerCase()) return str.toLowerCase().replace(/_/g, "-");
40
+ let kebabified = str.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
41
+ kebabified = kebabified.startsWith("-") ? kebabified.slice(1) : kebabified;
42
+ return kebabified.replace(/_/g, "-").replace(/-$/, "");
43
+ }
44
+
45
+ //#endregion
46
+ //#region ../agents/dist/client-DZhjV_XA.js
47
+ function toDisposable(fn) {
48
+ return { dispose: fn };
49
+ }
50
+ var DisposableStore = class {
51
+ constructor() {
52
+ this._items = [];
53
+ }
54
+ add(d) {
55
+ this._items.push(d);
56
+ return d;
57
+ }
58
+ dispose() {
59
+ while (this._items.length) try {
60
+ this._items.pop().dispose();
61
+ } catch {}
62
+ }
63
+ };
64
+ var Emitter = class {
65
+ constructor() {
66
+ this._listeners = /* @__PURE__ */ new Set();
67
+ this.event = (listener) => {
68
+ this._listeners.add(listener);
69
+ return toDisposable(() => this._listeners.delete(listener));
70
+ };
71
+ }
72
+ fire(data) {
73
+ for (const listener of [...this._listeners]) try {
74
+ listener(data);
75
+ } catch (err) {
76
+ console.error("Emitter listener error:", err);
77
+ }
78
+ }
79
+ dispose() {
80
+ this._listeners.clear();
81
+ }
82
+ };
83
+ function toErrorMessage(error) {
84
+ return error instanceof Error ? error.message : String(error);
85
+ }
86
+ function isUnauthorized(error) {
87
+ const msg = toErrorMessage(error);
88
+ return msg.includes("Unauthorized") || msg.includes("401");
89
+ }
90
+ function isTransportNotImplemented(error) {
91
+ const msg = toErrorMessage(error);
92
+ return msg.includes("404") || msg.includes("405") || msg.includes("Not Implemented") || msg.includes("not implemented");
93
+ }
94
+ var MCPClientConnection = class {
95
+ constructor(url, info, options = {
96
+ client: {},
97
+ transport: {}
98
+ }) {
99
+ this.url = url;
100
+ this.options = options;
101
+ this.connectionState = "connecting";
102
+ this.tools = [];
103
+ this.prompts = [];
104
+ this.resources = [];
105
+ this.resourceTemplates = [];
106
+ this._onObservabilityEvent = new Emitter();
107
+ this.onObservabilityEvent = this._onObservabilityEvent.event;
108
+ this.client = new Client(info, {
109
+ ...options.client,
110
+ capabilities: {
111
+ ...options.client?.capabilities,
112
+ elicitation: {}
113
+ }
114
+ });
115
+ }
116
+ /**
117
+ * Initialize a client connection
118
+ *
119
+ * @returns
120
+ */
121
+ async init() {
122
+ const transportType = this.options.transport.type;
123
+ if (!transportType) throw new Error("Transport type must be specified");
124
+ try {
125
+ await this.tryConnect(transportType);
126
+ } catch (e) {
127
+ if (isUnauthorized(e)) {
128
+ this.connectionState = "authenticating";
129
+ return;
130
+ }
131
+ this._onObservabilityEvent.fire({
132
+ type: "mcp:client:connect",
133
+ displayMessage: `Connection initialization failed for ${this.url.toString()}`,
134
+ payload: {
135
+ url: this.url.toString(),
136
+ transport: transportType,
137
+ state: this.connectionState,
138
+ error: toErrorMessage(e)
139
+ },
140
+ timestamp: Date.now(),
141
+ id: nanoid()
142
+ });
143
+ this.connectionState = "failed";
144
+ return;
145
+ }
146
+ await this.discoverAndRegister();
147
+ }
148
+ /**
149
+ * Finish OAuth by probing transports based on configured type.
150
+ * - Explicit: finish on that transport
151
+ * - Auto: try streamable-http, then sse on 404/405/Not Implemented
152
+ */
153
+ async finishAuthProbe(code) {
154
+ if (!this.options.transport.authProvider) throw new Error("No auth provider configured");
155
+ const configuredType = this.options.transport.type;
156
+ if (!configuredType) throw new Error("Transport type must be specified");
157
+ const finishAuth = async (base) => {
158
+ await this.getTransport(base).finishAuth(code);
159
+ };
160
+ if (configuredType === "sse" || configuredType === "streamable-http") {
161
+ await finishAuth(configuredType);
162
+ return;
163
+ }
164
+ try {
165
+ await finishAuth("streamable-http");
166
+ } catch (e) {
167
+ if (isTransportNotImplemented(e)) {
168
+ await finishAuth("sse");
169
+ return;
170
+ }
171
+ throw e;
172
+ }
173
+ }
174
+ /**
175
+ * Complete OAuth authorization
176
+ */
177
+ async completeAuthorization(code) {
178
+ if (this.connectionState !== "authenticating") throw new Error("Connection must be in authenticating state to complete authorization");
179
+ try {
180
+ await this.finishAuthProbe(code);
181
+ this.connectionState = "connecting";
182
+ } catch (error) {
183
+ this.connectionState = "failed";
184
+ throw error;
185
+ }
186
+ }
187
+ /**
188
+ * Establish connection after successful authorization
189
+ */
190
+ async establishConnection() {
191
+ if (this.connectionState !== "connecting") throw new Error("Connection must be in connecting state to establish connection");
192
+ try {
193
+ const transportType = this.options.transport.type;
194
+ if (!transportType) throw new Error("Transport type must be specified");
195
+ await this.tryConnect(transportType);
196
+ await this.discoverAndRegister();
197
+ } catch (error) {
198
+ this.connectionState = "failed";
199
+ throw error;
200
+ }
201
+ }
202
+ /**
203
+ * Discover server capabilities and register tools, resources, prompts, and templates
204
+ */
205
+ async discoverAndRegister() {
206
+ this.connectionState = "discovering";
207
+ this.serverCapabilities = this.client.getServerCapabilities();
208
+ if (!this.serverCapabilities) throw new Error("The MCP Server failed to return server capabilities");
209
+ const [instructionsResult, toolsResult, resourcesResult, promptsResult, resourceTemplatesResult] = await Promise.allSettled([
210
+ this.client.getInstructions(),
211
+ this.registerTools(),
212
+ this.registerResources(),
213
+ this.registerPrompts(),
214
+ this.registerResourceTemplates()
215
+ ]);
216
+ const operations = [
217
+ {
218
+ name: "instructions",
219
+ result: instructionsResult
220
+ },
221
+ {
222
+ name: "tools",
223
+ result: toolsResult
224
+ },
225
+ {
226
+ name: "resources",
227
+ result: resourcesResult
228
+ },
229
+ {
230
+ name: "prompts",
231
+ result: promptsResult
232
+ },
233
+ {
234
+ name: "resource templates",
235
+ result: resourceTemplatesResult
236
+ }
237
+ ];
238
+ for (const { name, result } of operations) if (result.status === "rejected") {
239
+ const url = this.url.toString();
240
+ this._onObservabilityEvent.fire({
241
+ type: "mcp:client:discover",
242
+ displayMessage: `Failed to discover ${name} for ${url}`,
243
+ payload: {
244
+ url,
245
+ capability: name,
246
+ error: result.reason
247
+ },
248
+ timestamp: Date.now(),
249
+ id: nanoid()
250
+ });
251
+ }
252
+ this.instructions = instructionsResult.status === "fulfilled" ? instructionsResult.value : void 0;
253
+ this.tools = toolsResult.status === "fulfilled" ? toolsResult.value : [];
254
+ this.resources = resourcesResult.status === "fulfilled" ? resourcesResult.value : [];
255
+ this.prompts = promptsResult.status === "fulfilled" ? promptsResult.value : [];
256
+ this.resourceTemplates = resourceTemplatesResult.status === "fulfilled" ? resourceTemplatesResult.value : [];
257
+ this.connectionState = "ready";
258
+ }
259
+ /**
260
+ * Notification handler registration
261
+ */
262
+ async registerTools() {
263
+ if (!this.serverCapabilities || !this.serverCapabilities.tools) return [];
264
+ if (this.serverCapabilities.tools.listChanged) this.client.setNotificationHandler(ToolListChangedNotificationSchema, async (_notification) => {
265
+ this.tools = await this.fetchTools();
266
+ });
267
+ return this.fetchTools();
268
+ }
269
+ async registerResources() {
270
+ if (!this.serverCapabilities || !this.serverCapabilities.resources) return [];
271
+ if (this.serverCapabilities.resources.listChanged) this.client.setNotificationHandler(ResourceListChangedNotificationSchema, async (_notification) => {
272
+ this.resources = await this.fetchResources();
273
+ });
274
+ return this.fetchResources();
275
+ }
276
+ async registerPrompts() {
277
+ if (!this.serverCapabilities || !this.serverCapabilities.prompts) return [];
278
+ if (this.serverCapabilities.prompts.listChanged) this.client.setNotificationHandler(PromptListChangedNotificationSchema, async (_notification) => {
279
+ this.prompts = await this.fetchPrompts();
280
+ });
281
+ return this.fetchPrompts();
282
+ }
283
+ async registerResourceTemplates() {
284
+ if (!this.serverCapabilities || !this.serverCapabilities.resources) return [];
285
+ return this.fetchResourceTemplates();
286
+ }
287
+ async fetchTools() {
288
+ let toolsAgg = [];
289
+ let toolsResult = { tools: [] };
290
+ do {
291
+ toolsResult = await this.client.listTools({ cursor: toolsResult.nextCursor }).catch(this._capabilityErrorHandler({ tools: [] }, "tools/list"));
292
+ toolsAgg = toolsAgg.concat(toolsResult.tools);
293
+ } while (toolsResult.nextCursor);
294
+ return toolsAgg;
295
+ }
296
+ async fetchResources() {
297
+ let resourcesAgg = [];
298
+ let resourcesResult = { resources: [] };
299
+ do {
300
+ resourcesResult = await this.client.listResources({ cursor: resourcesResult.nextCursor }).catch(this._capabilityErrorHandler({ resources: [] }, "resources/list"));
301
+ resourcesAgg = resourcesAgg.concat(resourcesResult.resources);
302
+ } while (resourcesResult.nextCursor);
303
+ return resourcesAgg;
304
+ }
305
+ async fetchPrompts() {
306
+ let promptsAgg = [];
307
+ let promptsResult = { prompts: [] };
308
+ do {
309
+ promptsResult = await this.client.listPrompts({ cursor: promptsResult.nextCursor }).catch(this._capabilityErrorHandler({ prompts: [] }, "prompts/list"));
310
+ promptsAgg = promptsAgg.concat(promptsResult.prompts);
311
+ } while (promptsResult.nextCursor);
312
+ return promptsAgg;
313
+ }
314
+ async fetchResourceTemplates() {
315
+ let templatesAgg = [];
316
+ let templatesResult = { resourceTemplates: [] };
317
+ do {
318
+ templatesResult = await this.client.listResourceTemplates({ cursor: templatesResult.nextCursor }).catch(this._capabilityErrorHandler({ resourceTemplates: [] }, "resources/templates/list"));
319
+ templatesAgg = templatesAgg.concat(templatesResult.resourceTemplates);
320
+ } while (templatesResult.nextCursor);
321
+ return templatesAgg;
322
+ }
323
+ /**
324
+ * Handle elicitation request from server
325
+ * Automatically uses the Agent's built-in elicitation handling if available
326
+ */
327
+ async handleElicitationRequest(_request) {
328
+ throw new Error("Elicitation handler must be implemented for your platform. Override handleElicitationRequest method.");
329
+ }
330
+ /**
331
+ * Get the transport for the client
332
+ * @param transportType - The transport type to get
333
+ * @returns The transport for the client
334
+ */
335
+ getTransport(transportType) {
336
+ switch (transportType) {
337
+ case "streamable-http": return new StreamableHTTPClientTransport(this.url, this.options.transport);
338
+ case "sse": return new SSEClientTransport(this.url, this.options.transport);
339
+ default: throw new Error(`Unsupported transport type: ${transportType}`);
340
+ }
341
+ }
342
+ async tryConnect(transportType) {
343
+ const transports = transportType === "auto" ? ["streamable-http", "sse"] : [transportType];
344
+ for (const currentTransportType of transports) {
345
+ const isLastTransport = currentTransportType === transports[transports.length - 1];
346
+ const hasFallback = transportType === "auto" && currentTransportType === "streamable-http" && !isLastTransport;
347
+ const transport = this.getTransport(currentTransportType);
348
+ try {
349
+ await this.client.connect(transport);
350
+ this.lastConnectedTransport = currentTransportType;
351
+ const url = this.url.toString();
352
+ this._onObservabilityEvent.fire({
353
+ type: "mcp:client:connect",
354
+ displayMessage: `Connected successfully using ${currentTransportType} transport for ${url}`,
355
+ payload: {
356
+ url,
357
+ transport: currentTransportType,
358
+ state: this.connectionState
359
+ },
360
+ timestamp: Date.now(),
361
+ id: nanoid()
362
+ });
363
+ break;
364
+ } catch (e) {
365
+ const error = e instanceof Error ? e : new Error(String(e));
366
+ if (isUnauthorized(error)) throw e;
367
+ if (hasFallback && isTransportNotImplemented(error)) {
368
+ const url = this.url.toString();
369
+ this._onObservabilityEvent.fire({
370
+ type: "mcp:client:connect",
371
+ displayMessage: `${currentTransportType} transport not available, trying ${transports[transports.indexOf(currentTransportType) + 1]} for ${url}`,
372
+ payload: {
373
+ url,
374
+ transport: currentTransportType,
375
+ state: this.connectionState
376
+ },
377
+ timestamp: Date.now(),
378
+ id: nanoid()
379
+ });
380
+ continue;
381
+ }
382
+ throw e;
383
+ }
384
+ }
385
+ this.client.setRequestHandler(ElicitRequestSchema, async (request) => {
386
+ return await this.handleElicitationRequest(request);
387
+ });
388
+ }
389
+ _capabilityErrorHandler(empty, method) {
390
+ return (e) => {
391
+ if (e.code === -32601) {
392
+ const url = this.url.toString();
393
+ this._onObservabilityEvent.fire({
394
+ type: "mcp:client:discover",
395
+ displayMessage: `The server advertised support for the capability ${method.split("/")[0]}, but returned "Method not found" for '${method}' for ${url}`,
396
+ payload: {
397
+ url,
398
+ capability: method.split("/")[0],
399
+ error: toErrorMessage(e)
400
+ },
401
+ timestamp: Date.now(),
402
+ id: nanoid()
403
+ });
404
+ return empty;
405
+ }
406
+ throw e;
407
+ };
408
+ }
409
+ };
410
+ /**
411
+ * Utility class that aggregates multiple MCP clients into one
412
+ */
413
+ var MCPClientManager = class {
414
+ /**
415
+ * @param _name Name of the MCP client
416
+ * @param _version Version of the MCP Client
417
+ * @param auth Auth paramters if being used to create a DurableObjectOAuthClientProvider
418
+ */
419
+ constructor(_name, _version) {
420
+ this._name = _name;
421
+ this._version = _version;
422
+ this.mcpConnections = {};
423
+ this._callbackUrls = [];
424
+ this._didWarnAboutUnstableGetAITools = false;
425
+ this._connectionDisposables = /* @__PURE__ */ new Map();
426
+ this._onObservabilityEvent = new Emitter();
427
+ this.onObservabilityEvent = this._onObservabilityEvent.event;
428
+ this._onConnected = new Emitter();
429
+ this.onConnected = this._onConnected.event;
430
+ }
431
+ /**
432
+ * Connect to and register an MCP server
433
+ *
434
+ * @param transportConfig Transport config
435
+ * @param clientConfig Client config
436
+ * @param capabilities Client capabilities (i.e. if the client supports roots/sampling)
437
+ */
438
+ async connect(url, options = {}) {
439
+ /**
440
+ * We need to delay loading ai sdk, because putting it in module scope is
441
+ * causing issues with startup time.
442
+ * The only place it's used is in getAITools, which only matters after
443
+ * .connect() is called on at least one server.
444
+ * So it's safe to delay loading it until .connect() is called.
445
+ */
446
+ if (!this.jsonSchema) {
447
+ const { jsonSchema } = await import("ai");
448
+ this.jsonSchema = jsonSchema;
449
+ }
450
+ const id = options.reconnect?.id ?? nanoid(8);
451
+ if (options.transport?.authProvider) {
452
+ options.transport.authProvider.serverId = id;
453
+ if (options.reconnect?.oauthClientId) options.transport.authProvider.clientId = options.reconnect?.oauthClientId;
454
+ }
455
+ if (!options.reconnect?.oauthCode || !this.mcpConnections[id]) {
456
+ const normalizedTransport = {
457
+ ...options.transport,
458
+ type: options.transport?.type ?? "auto"
459
+ };
460
+ this.mcpConnections[id] = new MCPClientConnection(new URL(url), {
461
+ name: this._name,
462
+ version: this._version
463
+ }, {
464
+ client: options.client ?? {},
465
+ transport: normalizedTransport
466
+ });
467
+ const store = new DisposableStore();
468
+ const existing = this._connectionDisposables.get(id);
469
+ if (existing) existing.dispose();
470
+ this._connectionDisposables.set(id, store);
471
+ store.add(this.mcpConnections[id].onObservabilityEvent((event) => {
472
+ this._onObservabilityEvent.fire(event);
473
+ }));
474
+ }
475
+ await this.mcpConnections[id].init();
476
+ if (options.reconnect?.oauthCode) try {
477
+ await this.mcpConnections[id].completeAuthorization(options.reconnect.oauthCode);
478
+ await this.mcpConnections[id].establishConnection();
479
+ } catch (error) {
480
+ this._onObservabilityEvent.fire({
481
+ type: "mcp:client:connect",
482
+ displayMessage: `Failed to complete OAuth reconnection for ${id} for ${url}`,
483
+ payload: {
484
+ url,
485
+ transport: options.transport?.type ?? "auto",
486
+ state: this.mcpConnections[id].connectionState,
487
+ error: toErrorMessage(error)
488
+ },
489
+ timestamp: Date.now(),
490
+ id
491
+ });
492
+ throw error;
493
+ }
494
+ const authUrl = options.transport?.authProvider?.authUrl;
495
+ if (this.mcpConnections[id].connectionState === "authenticating" && authUrl && options.transport?.authProvider?.redirectUrl) {
496
+ this._callbackUrls.push(options.transport.authProvider.redirectUrl.toString());
497
+ return {
498
+ authUrl,
499
+ clientId: options.transport?.authProvider?.clientId,
500
+ id
501
+ };
502
+ }
503
+ return { id };
504
+ }
505
+ isCallbackRequest(req) {
506
+ return req.method === "GET" && !!this._callbackUrls.find((url) => {
507
+ return req.url.startsWith(url);
508
+ });
509
+ }
510
+ async handleCallbackRequest(req) {
511
+ const url = new URL(req.url);
512
+ const urlMatch = this._callbackUrls.find((url$1) => {
513
+ return req.url.startsWith(url$1);
514
+ });
515
+ if (!urlMatch) throw new Error(`No callback URI match found for the request url: ${req.url}. Was the request matched with \`isCallbackRequest()\`?`);
516
+ const code = url.searchParams.get("code");
517
+ const state = url.searchParams.get("state");
518
+ const error = url.searchParams.get("error");
519
+ const errorDescription = url.searchParams.get("error_description");
520
+ const urlParams = urlMatch.split("/");
521
+ const serverId = urlParams[urlParams.length - 1];
522
+ if (error) return {
523
+ serverId,
524
+ authSuccess: false,
525
+ authError: errorDescription || error
526
+ };
527
+ if (!code) throw new Error("Unauthorized: no code provided");
528
+ if (!state) throw new Error("Unauthorized: no state provided");
529
+ if (this.mcpConnections[serverId] === void 0) throw new Error(`Could not find serverId: ${serverId}`);
530
+ if (this.mcpConnections[serverId].connectionState !== "authenticating") throw new Error("Failed to authenticate: the client isn't in the `authenticating` state");
531
+ const conn = this.mcpConnections[serverId];
532
+ if (!conn.options.transport.authProvider) throw new Error("Trying to finalize authentication for a server connection without an authProvider");
533
+ const clientId = conn.options.transport.authProvider.clientId || state;
534
+ conn.options.transport.authProvider.clientId = clientId;
535
+ conn.options.transport.authProvider.serverId = serverId;
536
+ try {
537
+ await conn.completeAuthorization(code);
538
+ return {
539
+ serverId,
540
+ authSuccess: true
541
+ };
542
+ } catch (error$1) {
543
+ return {
544
+ serverId,
545
+ authSuccess: false,
546
+ authError: error$1 instanceof Error ? error$1.message : String(error$1)
547
+ };
548
+ }
549
+ }
550
+ /**
551
+ * Establish connection in the background after OAuth completion
552
+ * This method is called asynchronously and doesn't block the OAuth callback response
553
+ * @param serverId The server ID to establish connection for
554
+ */
555
+ async establishConnection(serverId) {
556
+ const conn = this.mcpConnections[serverId];
557
+ if (!conn) {
558
+ this._onObservabilityEvent.fire({
559
+ type: "mcp:client:preconnect",
560
+ displayMessage: `Connection not found for serverId: ${serverId}`,
561
+ payload: { serverId },
562
+ timestamp: Date.now(),
563
+ id: nanoid()
564
+ });
565
+ return;
566
+ }
567
+ try {
568
+ await conn.establishConnection();
569
+ this._onConnected.fire(serverId);
570
+ } catch (error) {
571
+ const url = conn.url.toString();
572
+ this._onObservabilityEvent.fire({
573
+ type: "mcp:client:connect",
574
+ displayMessage: `Failed to establish connection to server ${serverId} with url ${url}`,
575
+ payload: {
576
+ url,
577
+ transport: conn.options.transport.type ?? "auto",
578
+ state: conn.connectionState,
579
+ error: toErrorMessage(error)
580
+ },
581
+ timestamp: Date.now(),
582
+ id: nanoid()
583
+ });
584
+ }
585
+ }
586
+ /**
587
+ * Register a callback URL for OAuth handling
588
+ * @param url The callback URL to register
589
+ */
590
+ registerCallbackUrl(url) {
591
+ if (!this._callbackUrls.includes(url)) this._callbackUrls.push(url);
592
+ }
593
+ /**
594
+ * Unregister a callback URL
595
+ * @param serverId The server ID whose callback URL should be removed
596
+ */
597
+ unregisterCallbackUrl(serverId) {
598
+ this._callbackUrls = this._callbackUrls.filter((url) => !url.endsWith(`/${serverId}`));
599
+ }
600
+ /**
601
+ * Configure OAuth callback handling
602
+ * @param config OAuth callback configuration
603
+ */
604
+ configureOAuthCallback(config) {
605
+ this._oauthCallbackConfig = config;
606
+ }
607
+ /**
608
+ * Get the current OAuth callback configuration
609
+ * @returns The current OAuth callback configuration
610
+ */
611
+ getOAuthCallbackConfig() {
612
+ return this._oauthCallbackConfig;
613
+ }
614
+ /**
615
+ * @returns namespaced list of tools
616
+ */
617
+ listTools() {
618
+ return getNamespacedData(this.mcpConnections, "tools");
619
+ }
620
+ /**
621
+ * @returns a set of tools that you can use with the AI SDK
622
+ */
623
+ getAITools() {
624
+ return Object.fromEntries(getNamespacedData(this.mcpConnections, "tools").map((tool) => {
625
+ return [`tool_${tool.serverId.replace(/-/g, "")}_${tool.name}`, {
626
+ description: tool.description,
627
+ execute: async (args) => {
628
+ const result = await this.callTool({
629
+ arguments: args,
630
+ name: tool.name,
631
+ serverId: tool.serverId
632
+ });
633
+ if (result.isError) throw new Error(result.content[0].text);
634
+ return result;
635
+ },
636
+ inputSchema: this.jsonSchema(tool.inputSchema),
637
+ outputSchema: tool.outputSchema ? this.jsonSchema(tool.outputSchema) : void 0
638
+ }];
639
+ }));
640
+ }
641
+ /**
642
+ * @deprecated this has been renamed to getAITools(), and unstable_getAITools will be removed in the next major version
643
+ * @returns a set of tools that you can use with the AI SDK
644
+ */
645
+ unstable_getAITools() {
646
+ if (!this._didWarnAboutUnstableGetAITools) {
647
+ this._didWarnAboutUnstableGetAITools = true;
648
+ console.warn("unstable_getAITools is deprecated, use getAITools instead. unstable_getAITools will be removed in the next major version.");
649
+ }
650
+ return this.getAITools();
651
+ }
652
+ /**
653
+ * Closes all connections to MCP servers
654
+ */
655
+ async closeAllConnections() {
656
+ const ids = Object.keys(this.mcpConnections);
657
+ await Promise.all(ids.map(async (id) => {
658
+ await this.mcpConnections[id].client.close();
659
+ }));
660
+ for (const id of ids) {
661
+ const store = this._connectionDisposables.get(id);
662
+ if (store) store.dispose();
663
+ this._connectionDisposables.delete(id);
664
+ delete this.mcpConnections[id];
665
+ }
666
+ }
667
+ /**
668
+ * Closes a connection to an MCP server
669
+ * @param id The id of the connection to close
670
+ */
671
+ async closeConnection(id) {
672
+ if (!this.mcpConnections[id]) throw new Error(`Connection with id "${id}" does not exist.`);
673
+ await this.mcpConnections[id].client.close();
674
+ delete this.mcpConnections[id];
675
+ const store = this._connectionDisposables.get(id);
676
+ if (store) store.dispose();
677
+ this._connectionDisposables.delete(id);
678
+ }
679
+ /**
680
+ * Dispose the manager and all resources.
681
+ */
682
+ async dispose() {
683
+ try {
684
+ await this.closeAllConnections();
685
+ } finally {
686
+ this._onConnected.dispose();
687
+ this._onObservabilityEvent.dispose();
688
+ }
689
+ }
690
+ /**
691
+ * @returns namespaced list of prompts
692
+ */
693
+ listPrompts() {
694
+ return getNamespacedData(this.mcpConnections, "prompts");
695
+ }
696
+ /**
697
+ * @returns namespaced list of tools
698
+ */
699
+ listResources() {
700
+ return getNamespacedData(this.mcpConnections, "resources");
701
+ }
702
+ /**
703
+ * @returns namespaced list of resource templates
704
+ */
705
+ listResourceTemplates() {
706
+ return getNamespacedData(this.mcpConnections, "resourceTemplates");
707
+ }
708
+ /**
709
+ * Namespaced version of callTool
710
+ */
711
+ async callTool(params, resultSchema, options) {
712
+ const unqualifiedName = params.name.replace(`${params.serverId}.`, "");
713
+ return this.mcpConnections[params.serverId].client.callTool({
714
+ ...params,
715
+ name: unqualifiedName
716
+ }, resultSchema, options);
717
+ }
718
+ /**
719
+ * Namespaced version of readResource
720
+ */
721
+ readResource(params, options) {
722
+ return this.mcpConnections[params.serverId].client.readResource(params, options);
723
+ }
724
+ /**
725
+ * Namespaced version of getPrompt
726
+ */
727
+ getPrompt(params, options) {
728
+ return this.mcpConnections[params.serverId].client.getPrompt(params, options);
729
+ }
730
+ };
731
+ function getNamespacedData(mcpClients, type) {
732
+ return Object.entries(mcpClients).map(([name, conn]) => {
733
+ return {
734
+ data: conn[type],
735
+ name
736
+ };
737
+ }).flatMap(({ name: serverId, data }) => {
738
+ return data.map((item) => {
739
+ return {
740
+ ...item,
741
+ serverId
742
+ };
743
+ });
744
+ });
745
+ }
746
+
747
+ //#endregion
748
+ //#region ../agents/dist/do-oauth-client-provider-CswoD5Lu.js
749
+ var DurableObjectOAuthClientProvider = class {
750
+ constructor(storage, clientName, baseRedirectUrl) {
751
+ this.storage = storage;
752
+ this.clientName = clientName;
753
+ this.baseRedirectUrl = baseRedirectUrl;
754
+ }
755
+ get clientMetadata() {
756
+ return {
757
+ client_name: this.clientName,
758
+ client_uri: this.clientUri,
759
+ grant_types: ["authorization_code", "refresh_token"],
760
+ redirect_uris: [this.redirectUrl],
761
+ response_types: ["code"],
762
+ token_endpoint_auth_method: "none"
763
+ };
764
+ }
765
+ get clientUri() {
766
+ return new URL(this.redirectUrl).origin;
767
+ }
768
+ get redirectUrl() {
769
+ return `${this.baseRedirectUrl}/${this.serverId}`;
770
+ }
771
+ get clientId() {
772
+ if (!this._clientId_) throw new Error("Trying to access clientId before it was set");
773
+ return this._clientId_;
774
+ }
775
+ set clientId(clientId_) {
776
+ this._clientId_ = clientId_;
777
+ }
778
+ get serverId() {
779
+ if (!this._serverId_) throw new Error("Trying to access serverId before it was set");
780
+ return this._serverId_;
781
+ }
782
+ set serverId(serverId_) {
783
+ this._serverId_ = serverId_;
784
+ }
785
+ keyPrefix(clientId) {
786
+ return `/${this.clientName}/${this.serverId}/${clientId}`;
787
+ }
788
+ clientInfoKey(clientId) {
789
+ return `${this.keyPrefix(clientId)}/client_info/`;
790
+ }
791
+ async clientInformation() {
792
+ if (!this._clientId_) return;
793
+ return await this.storage.get(this.clientInfoKey(this.clientId)) ?? void 0;
794
+ }
795
+ async saveClientInformation(clientInformation) {
796
+ await this.storage.put(this.clientInfoKey(clientInformation.client_id), clientInformation);
797
+ this.clientId = clientInformation.client_id;
798
+ }
799
+ tokenKey(clientId) {
800
+ return `${this.keyPrefix(clientId)}/token`;
801
+ }
802
+ async tokens() {
803
+ if (!this._clientId_) return;
804
+ return await this.storage.get(this.tokenKey(this.clientId)) ?? void 0;
805
+ }
806
+ async saveTokens(tokens) {
807
+ await this.storage.put(this.tokenKey(this.clientId), tokens);
808
+ }
809
+ get authUrl() {
810
+ return this._authUrl_;
811
+ }
812
+ /**
813
+ * Because this operates on the server side (but we need browser auth), we send this url back to the user
814
+ * and require user interact to initiate the redirect flow
815
+ */
816
+ async redirectToAuthorization(authUrl) {
817
+ const stateToken = nanoid();
818
+ authUrl.searchParams.set("state", stateToken);
819
+ this._authUrl_ = authUrl.toString();
820
+ }
821
+ codeVerifierKey(clientId) {
822
+ return `${this.keyPrefix(clientId)}/code_verifier`;
823
+ }
824
+ async saveCodeVerifier(verifier) {
825
+ const key = this.codeVerifierKey(this.clientId);
826
+ if (await this.storage.get(key)) return;
827
+ await this.storage.put(key, verifier);
828
+ }
829
+ async codeVerifier() {
830
+ const codeVerifier = await this.storage.get(this.codeVerifierKey(this.clientId));
831
+ if (!codeVerifier) throw new Error("No code verifier found");
832
+ return codeVerifier;
833
+ }
834
+ };
835
+
836
+ //#endregion
837
+ //#region ../agents/dist/src-C8K3lu37.js
838
+ /**
839
+ * A generic observability implementation that logs events to the console.
840
+ */
841
+ const genericObservability = { emit(event) {
842
+ if (isLocalMode()) {
843
+ console.log(event.displayMessage);
844
+ return;
845
+ }
846
+ console.log(event);
847
+ } };
848
+ let localMode = false;
849
+ function isLocalMode() {
850
+ if (localMode) return true;
851
+ const { request } = getCurrentAgent();
852
+ if (!request) return false;
853
+ localMode = new URL(request.url).hostname === "localhost";
854
+ return localMode;
855
+ }
856
+ /**
857
+ * Type guard for RPC request messages
858
+ */
859
+ function isRPCRequest(msg) {
860
+ return typeof msg === "object" && msg !== null && "type" in msg && msg.type === MessageType.RPC && "id" in msg && typeof msg.id === "string" && "method" in msg && typeof msg.method === "string" && "args" in msg && Array.isArray(msg.args);
861
+ }
862
+ /**
863
+ * Type guard for state update messages
864
+ */
865
+ function isStateUpdateMessage(msg) {
866
+ return typeof msg === "object" && msg !== null && "type" in msg && msg.type === MessageType.CF_AGENT_STATE && "state" in msg;
867
+ }
868
+ const callableMetadata = /* @__PURE__ */ new Map();
869
+ function getNextCronTime(cron) {
870
+ return parseCronExpression(cron).getNextDate();
871
+ }
872
+ const STATE_ROW_ID = "cf_state_row_id";
873
+ const STATE_WAS_CHANGED = "cf_state_was_changed";
874
+ const DEFAULT_STATE = {};
875
+ const agentContext = new AsyncLocalStorage();
876
+ function getCurrentAgent() {
877
+ const store = agentContext.getStore();
878
+ if (!store) return {
879
+ agent: void 0,
880
+ connection: void 0,
881
+ request: void 0,
882
+ email: void 0
883
+ };
884
+ return store;
885
+ }
886
+ /**
887
+ * Wraps a method to run within the agent context, ensuring getCurrentAgent() works properly
888
+ * @param agent The agent instance
889
+ * @param method The method to wrap
890
+ * @returns A wrapped method that runs within the agent context
891
+ */
892
+ function withAgentContext(method) {
893
+ return function(...args) {
894
+ const { connection, request, email, agent } = getCurrentAgent();
895
+ if (agent === this) return method.apply(this, args);
896
+ return agentContext.run({
897
+ agent: this,
898
+ connection,
899
+ request,
900
+ email
901
+ }, () => {
902
+ return method.apply(this, args);
903
+ });
904
+ };
905
+ }
906
+ /**
907
+ * Base class for creating Agent implementations
908
+ * @template Env Environment type containing bindings
909
+ * @template State State type to store within the Agent
910
+ */
911
+ var Agent = class Agent$1 extends Server {
912
+ /**
913
+ * Current state of the Agent
914
+ */
915
+ get state() {
916
+ if (this._state !== DEFAULT_STATE) return this._state;
917
+ const wasChanged = this.sql`
918
+ SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}
919
+ `;
920
+ const result = this.sql`
921
+ SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}
922
+ `;
923
+ if (wasChanged[0]?.state === "true" || result[0]?.state) {
924
+ const state = result[0]?.state;
925
+ this._state = JSON.parse(state);
926
+ return this._state;
927
+ }
928
+ if (this.initialState === DEFAULT_STATE) return;
929
+ this.setState(this.initialState);
930
+ return this.initialState;
931
+ }
932
+ static {
933
+ this.options = { hibernate: true };
934
+ }
935
+ /**
936
+ * Execute SQL queries against the Agent's database
937
+ * @template T Type of the returned rows
938
+ * @param strings SQL query template strings
939
+ * @param values Values to be inserted into the query
940
+ * @returns Array of query results
941
+ */
942
+ sql(strings, ...values) {
943
+ let query = "";
944
+ try {
945
+ query = strings.reduce((acc, str, i) => acc + str + (i < values.length ? "?" : ""), "");
946
+ return [...this.ctx.storage.sql.exec(query, ...values)];
947
+ } catch (e) {
948
+ console.error(`failed to execute sql query: ${query}`, e);
949
+ throw this.onError(e);
950
+ }
951
+ }
952
+ constructor(ctx, env$1) {
953
+ super(ctx, env$1);
954
+ this._state = DEFAULT_STATE;
955
+ this._disposables = new DisposableStore();
956
+ this._mcpStateRestored = false;
957
+ this._ParentClass = Object.getPrototypeOf(this).constructor;
958
+ this.mcp = new MCPClientManager(this._ParentClass.name, "0.0.1");
959
+ this.initialState = DEFAULT_STATE;
960
+ this.observability = genericObservability;
961
+ this._flushingQueue = false;
962
+ this.alarm = async () => {
963
+ const now = Math.floor(Date.now() / 1e3);
964
+ const result = this.sql`
965
+ SELECT * FROM cf_agents_schedules WHERE time <= ${now}
966
+ `;
967
+ if (result && Array.isArray(result)) for (const row of result) {
968
+ const callback = this[row.callback];
969
+ if (!callback) {
970
+ console.error(`callback ${row.callback} not found`);
971
+ continue;
972
+ }
973
+ await agentContext.run({
974
+ agent: this,
975
+ connection: void 0,
976
+ request: void 0,
977
+ email: void 0
978
+ }, async () => {
979
+ try {
980
+ this.observability?.emit({
981
+ displayMessage: `Schedule ${row.id} executed`,
982
+ id: nanoid(),
983
+ payload: {
984
+ callback: row.callback,
985
+ id: row.id
986
+ },
987
+ timestamp: Date.now(),
988
+ type: "schedule:execute"
989
+ }, this.ctx);
990
+ await callback.bind(this)(JSON.parse(row.payload), row);
991
+ } catch (e) {
992
+ console.error(`error executing callback "${row.callback}"`, e);
993
+ }
994
+ });
995
+ if (row.type === "cron") {
996
+ const nextExecutionTime = getNextCronTime(row.cron);
997
+ const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
998
+ this.sql`
999
+ UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
1000
+ `;
1001
+ } else this.sql`
1002
+ DELETE FROM cf_agents_schedules WHERE id = ${row.id}
1003
+ `;
1004
+ }
1005
+ await this._scheduleNextAlarm();
1006
+ };
1007
+ if (!wrappedClasses.has(this.constructor)) {
1008
+ this._autoWrapCustomMethods();
1009
+ wrappedClasses.add(this.constructor);
1010
+ }
1011
+ this._disposables.add(this.mcp.onConnected(async () => {
1012
+ this.broadcastMcpServers();
1013
+ }));
1014
+ this._disposables.add(this.mcp.onObservabilityEvent((event) => {
1015
+ this.observability?.emit(event);
1016
+ }));
1017
+ this.sql`
1018
+ CREATE TABLE IF NOT EXISTS cf_agents_state (
1019
+ id TEXT PRIMARY KEY NOT NULL,
1020
+ state TEXT
1021
+ )
1022
+ `;
1023
+ this.sql`
1024
+ CREATE TABLE IF NOT EXISTS cf_agents_queues (
1025
+ id TEXT PRIMARY KEY NOT NULL,
1026
+ payload TEXT,
1027
+ callback TEXT,
1028
+ created_at INTEGER DEFAULT (unixepoch())
1029
+ )
1030
+ `;
1031
+ this.ctx.blockConcurrencyWhile(async () => {
1032
+ return this._tryCatch(async () => {
1033
+ this.sql`
1034
+ CREATE TABLE IF NOT EXISTS cf_agents_schedules (
1035
+ id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
1036
+ callback TEXT,
1037
+ payload TEXT,
1038
+ type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),
1039
+ time INTEGER,
1040
+ delayInSeconds INTEGER,
1041
+ cron TEXT,
1042
+ created_at INTEGER DEFAULT (unixepoch())
1043
+ )
1044
+ `;
1045
+ await this.alarm();
1046
+ });
1047
+ });
1048
+ this.sql`
1049
+ CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
1050
+ id TEXT PRIMARY KEY NOT NULL,
1051
+ name TEXT NOT NULL,
1052
+ server_url TEXT NOT NULL,
1053
+ callback_url TEXT NOT NULL,
1054
+ client_id TEXT,
1055
+ auth_url TEXT,
1056
+ server_options TEXT
1057
+ )
1058
+ `;
1059
+ const _onRequest = this.onRequest.bind(this);
1060
+ this.onRequest = (request) => {
1061
+ return agentContext.run({
1062
+ agent: this,
1063
+ connection: void 0,
1064
+ request,
1065
+ email: void 0
1066
+ }, async () => {
1067
+ await this._ensureMcpStateRestored();
1068
+ if (this.mcp.isCallbackRequest(request)) {
1069
+ const result = await this.mcp.handleCallbackRequest(request);
1070
+ this.broadcastMcpServers();
1071
+ if (result.authSuccess) {
1072
+ this.clearMcpServerAuthUrl(result.serverId);
1073
+ this.mcp.establishConnection(result.serverId).catch((error) => {
1074
+ console.error("Background connection failed:", error);
1075
+ }).finally(() => {
1076
+ this.broadcastMcpServers();
1077
+ });
1078
+ }
1079
+ return this.handleOAuthCallbackResponse(result, request);
1080
+ }
1081
+ return this._tryCatch(() => _onRequest(request));
1082
+ });
1083
+ };
1084
+ const _onMessage = this.onMessage.bind(this);
1085
+ this.onMessage = async (connection, message) => {
1086
+ return agentContext.run({
1087
+ agent: this,
1088
+ connection,
1089
+ request: void 0,
1090
+ email: void 0
1091
+ }, async () => {
1092
+ if (typeof message !== "string") return this._tryCatch(() => _onMessage(connection, message));
1093
+ let parsed;
1094
+ try {
1095
+ parsed = JSON.parse(message);
1096
+ } catch (_e) {
1097
+ return this._tryCatch(() => _onMessage(connection, message));
1098
+ }
1099
+ if (isStateUpdateMessage(parsed)) {
1100
+ this._setStateInternal(parsed.state, connection);
1101
+ return;
1102
+ }
1103
+ if (isRPCRequest(parsed)) {
1104
+ try {
1105
+ const { id, method, args } = parsed;
1106
+ const methodFn = this[method];
1107
+ if (typeof methodFn !== "function") throw new Error(`Method ${method} does not exist`);
1108
+ if (!this._isCallable(method)) throw new Error(`Method ${method} is not callable`);
1109
+ const metadata = callableMetadata.get(methodFn);
1110
+ if (metadata?.streaming) {
1111
+ const stream = new StreamingResponse(connection, id);
1112
+ await methodFn.apply(this, [stream, ...args]);
1113
+ return;
1114
+ }
1115
+ const result = await methodFn.apply(this, args);
1116
+ this.observability?.emit({
1117
+ displayMessage: `RPC call to ${method}`,
1118
+ id: nanoid(),
1119
+ payload: {
1120
+ method,
1121
+ streaming: metadata?.streaming
1122
+ },
1123
+ timestamp: Date.now(),
1124
+ type: "rpc"
1125
+ }, this.ctx);
1126
+ const response = {
1127
+ done: true,
1128
+ id,
1129
+ result,
1130
+ success: true,
1131
+ type: MessageType.RPC
1132
+ };
1133
+ connection.send(JSON.stringify(response));
1134
+ } catch (e) {
1135
+ const response = {
1136
+ error: e instanceof Error ? e.message : "Unknown error occurred",
1137
+ id: parsed.id,
1138
+ success: false,
1139
+ type: MessageType.RPC
1140
+ };
1141
+ connection.send(JSON.stringify(response));
1142
+ console.error("RPC error:", e);
1143
+ }
1144
+ return;
1145
+ }
1146
+ return this._tryCatch(() => _onMessage(connection, message));
1147
+ });
1148
+ };
1149
+ const _onConnect = this.onConnect.bind(this);
1150
+ this.onConnect = (connection, ctx$1) => {
1151
+ return agentContext.run({
1152
+ agent: this,
1153
+ connection,
1154
+ request: ctx$1.request,
1155
+ email: void 0
1156
+ }, () => {
1157
+ if (this.state) connection.send(JSON.stringify({
1158
+ state: this.state,
1159
+ type: MessageType.CF_AGENT_STATE
1160
+ }));
1161
+ connection.send(JSON.stringify({
1162
+ mcp: this.getMcpServers(),
1163
+ type: MessageType.CF_AGENT_MCP_SERVERS
1164
+ }));
1165
+ this.observability?.emit({
1166
+ displayMessage: "Connection established",
1167
+ id: nanoid(),
1168
+ payload: { connectionId: connection.id },
1169
+ timestamp: Date.now(),
1170
+ type: "connect"
1171
+ }, this.ctx);
1172
+ return this._tryCatch(() => _onConnect(connection, ctx$1));
1173
+ });
1174
+ };
1175
+ const _onStart = this.onStart.bind(this);
1176
+ this.onStart = async (props) => {
1177
+ return agentContext.run({
1178
+ agent: this,
1179
+ connection: void 0,
1180
+ request: void 0,
1181
+ email: void 0
1182
+ }, async () => {
1183
+ await this._tryCatch(async () => {
1184
+ await this._ensureMcpStateRestored();
1185
+ this.broadcastMcpServers();
1186
+ return _onStart(props);
1187
+ });
1188
+ });
1189
+ };
1190
+ }
1191
+ _setStateInternal(state, source = "server") {
1192
+ this._state = state;
1193
+ this.sql`
1194
+ INSERT OR REPLACE INTO cf_agents_state (id, state)
1195
+ VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
1196
+ `;
1197
+ this.sql`
1198
+ INSERT OR REPLACE INTO cf_agents_state (id, state)
1199
+ VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})
1200
+ `;
1201
+ this.broadcast(JSON.stringify({
1202
+ state,
1203
+ type: MessageType.CF_AGENT_STATE
1204
+ }), source !== "server" ? [source.id] : []);
1205
+ return this._tryCatch(() => {
1206
+ const { connection, request, email } = agentContext.getStore() || {};
1207
+ return agentContext.run({
1208
+ agent: this,
1209
+ connection,
1210
+ request,
1211
+ email
1212
+ }, async () => {
1213
+ this.observability?.emit({
1214
+ displayMessage: "State updated",
1215
+ id: nanoid(),
1216
+ payload: {},
1217
+ timestamp: Date.now(),
1218
+ type: "state:update"
1219
+ }, this.ctx);
1220
+ return this.onStateUpdate(state, source);
1221
+ });
1222
+ });
1223
+ }
1224
+ /**
1225
+ * Update the Agent's state
1226
+ * @param state New state to set
1227
+ */
1228
+ setState(state) {
1229
+ this._setStateInternal(state, "server");
1230
+ }
1231
+ /**
1232
+ * Called when the Agent's state is updated
1233
+ * @param state Updated state
1234
+ * @param source Source of the state update ("server" or a client connection)
1235
+ */
1236
+ onStateUpdate(state, source) {}
1237
+ /**
1238
+ * Called when the Agent receives an email via routeAgentEmail()
1239
+ * Override this method to handle incoming emails
1240
+ * @param email Email message to process
1241
+ */
1242
+ async _onEmail(email) {
1243
+ return agentContext.run({
1244
+ agent: this,
1245
+ connection: void 0,
1246
+ request: void 0,
1247
+ email
1248
+ }, async () => {
1249
+ if ("onEmail" in this && typeof this.onEmail === "function") return this._tryCatch(() => this.onEmail(email));
1250
+ else {
1251
+ console.log("Received email from:", email.from, "to:", email.to);
1252
+ console.log("Subject:", email.headers.get("subject"));
1253
+ console.log("Implement onEmail(email: AgentEmail): Promise<void> in your agent to process emails");
1254
+ }
1255
+ });
1256
+ }
1257
+ /**
1258
+ * Reply to an email
1259
+ * @param email The email to reply to
1260
+ * @param options Options for the reply
1261
+ * @returns void
1262
+ */
1263
+ async replyToEmail(email, options) {
1264
+ return this._tryCatch(async () => {
1265
+ const agentName = camelCaseToKebabCase(this._ParentClass.name);
1266
+ const agentId = this.name;
1267
+ const { createMimeMessage } = await import("mimetext");
1268
+ const msg = createMimeMessage();
1269
+ msg.setSender({
1270
+ addr: email.to,
1271
+ name: options.fromName
1272
+ });
1273
+ msg.setRecipient(email.from);
1274
+ msg.setSubject(options.subject || `Re: ${email.headers.get("subject")}` || "No subject");
1275
+ msg.addMessage({
1276
+ contentType: options.contentType || "text/plain",
1277
+ data: options.body
1278
+ });
1279
+ const messageId = `<${agentId}@${email.from.split("@")[1]}>`;
1280
+ msg.setHeader("In-Reply-To", email.headers.get("Message-ID"));
1281
+ msg.setHeader("Message-ID", messageId);
1282
+ msg.setHeader("X-Agent-Name", agentName);
1283
+ msg.setHeader("X-Agent-ID", agentId);
1284
+ if (options.headers) for (const [key, value] of Object.entries(options.headers)) msg.setHeader(key, value);
1285
+ await email.reply({
1286
+ from: email.to,
1287
+ raw: msg.asRaw(),
1288
+ to: email.from
1289
+ });
1290
+ });
1291
+ }
1292
+ async _tryCatch(fn) {
1293
+ try {
1294
+ return await fn();
1295
+ } catch (e) {
1296
+ throw this.onError(e);
1297
+ }
1298
+ }
1299
+ /**
1300
+ * Automatically wrap custom methods with agent context
1301
+ * This ensures getCurrentAgent() works in all custom methods without decorators
1302
+ */
1303
+ _autoWrapCustomMethods() {
1304
+ const basePrototypes = [Agent$1.prototype, Server.prototype];
1305
+ const baseMethods = /* @__PURE__ */ new Set();
1306
+ for (const baseProto of basePrototypes) {
1307
+ let proto$1 = baseProto;
1308
+ while (proto$1 && proto$1 !== Object.prototype) {
1309
+ const methodNames = Object.getOwnPropertyNames(proto$1);
1310
+ for (const methodName of methodNames) baseMethods.add(methodName);
1311
+ proto$1 = Object.getPrototypeOf(proto$1);
1312
+ }
1313
+ }
1314
+ let proto = Object.getPrototypeOf(this);
1315
+ let depth = 0;
1316
+ while (proto && proto !== Object.prototype && depth < 10) {
1317
+ const methodNames = Object.getOwnPropertyNames(proto);
1318
+ for (const methodName of methodNames) {
1319
+ const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);
1320
+ if (baseMethods.has(methodName) || methodName.startsWith("_") || !descriptor || !!descriptor.get || typeof descriptor.value !== "function") continue;
1321
+ const wrappedFunction = withAgentContext(this[methodName]);
1322
+ if (this._isCallable(methodName)) callableMetadata.set(wrappedFunction, callableMetadata.get(this[methodName]));
1323
+ this.constructor.prototype[methodName] = wrappedFunction;
1324
+ }
1325
+ proto = Object.getPrototypeOf(proto);
1326
+ depth++;
1327
+ }
1328
+ }
1329
+ onError(connectionOrError, error) {
1330
+ let theError;
1331
+ if (connectionOrError && error) {
1332
+ theError = error;
1333
+ console.error("Error on websocket connection:", connectionOrError.id, theError);
1334
+ console.error("Override onError(connection, error) to handle websocket connection errors");
1335
+ } else {
1336
+ theError = connectionOrError;
1337
+ console.error("Error on server:", theError);
1338
+ console.error("Override onError(error) to handle server errors");
1339
+ }
1340
+ throw theError;
1341
+ }
1342
+ /**
1343
+ * Render content (not implemented in base class)
1344
+ */
1345
+ render() {
1346
+ throw new Error("Not implemented");
1347
+ }
1348
+ /**
1349
+ * Queue a task to be executed in the future
1350
+ * @param payload Payload to pass to the callback
1351
+ * @param callback Name of the method to call
1352
+ * @returns The ID of the queued task
1353
+ */
1354
+ async queue(callback, payload) {
1355
+ const id = nanoid(9);
1356
+ if (typeof callback !== "string") throw new Error("Callback must be a string");
1357
+ if (typeof this[callback] !== "function") throw new Error(`this.${callback} is not a function`);
1358
+ this.sql`
1359
+ INSERT OR REPLACE INTO cf_agents_queues (id, payload, callback)
1360
+ VALUES (${id}, ${JSON.stringify(payload)}, ${callback})
1361
+ `;
1362
+ this._flushQueue().catch((e) => {
1363
+ console.error("Error flushing queue:", e);
1364
+ });
1365
+ return id;
1366
+ }
1367
+ async _flushQueue() {
1368
+ if (this._flushingQueue) return;
1369
+ this._flushingQueue = true;
1370
+ while (true) {
1371
+ const result = this.sql`
1372
+ SELECT * FROM cf_agents_queues
1373
+ ORDER BY created_at ASC
1374
+ `;
1375
+ if (!result || result.length === 0) break;
1376
+ for (const row of result || []) {
1377
+ const callback = this[row.callback];
1378
+ if (!callback) {
1379
+ console.error(`callback ${row.callback} not found`);
1380
+ continue;
1381
+ }
1382
+ const { connection, request, email } = agentContext.getStore() || {};
1383
+ await agentContext.run({
1384
+ agent: this,
1385
+ connection,
1386
+ request,
1387
+ email
1388
+ }, async () => {
1389
+ await callback.bind(this)(JSON.parse(row.payload), row);
1390
+ await this.dequeue(row.id);
1391
+ });
1392
+ }
1393
+ }
1394
+ this._flushingQueue = false;
1395
+ }
1396
+ /**
1397
+ * Dequeue a task by ID
1398
+ * @param id ID of the task to dequeue
1399
+ */
1400
+ async dequeue(id) {
1401
+ this.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;
1402
+ }
1403
+ /**
1404
+ * Dequeue all tasks
1405
+ */
1406
+ async dequeueAll() {
1407
+ this.sql`DELETE FROM cf_agents_queues`;
1408
+ }
1409
+ /**
1410
+ * Dequeue all tasks by callback
1411
+ * @param callback Name of the callback to dequeue
1412
+ */
1413
+ async dequeueAllByCallback(callback) {
1414
+ this.sql`DELETE FROM cf_agents_queues WHERE callback = ${callback}`;
1415
+ }
1416
+ /**
1417
+ * Get a queued task by ID
1418
+ * @param id ID of the task to get
1419
+ * @returns The task or undefined if not found
1420
+ */
1421
+ async getQueue(id) {
1422
+ const result = this.sql`
1423
+ SELECT * FROM cf_agents_queues WHERE id = ${id}
1424
+ `;
1425
+ return result ? {
1426
+ ...result[0],
1427
+ payload: JSON.parse(result[0].payload)
1428
+ } : void 0;
1429
+ }
1430
+ /**
1431
+ * Get all queues by key and value
1432
+ * @param key Key to filter by
1433
+ * @param value Value to filter by
1434
+ * @returns Array of matching QueueItem objects
1435
+ */
1436
+ async getQueues(key, value) {
1437
+ return this.sql`
1438
+ SELECT * FROM cf_agents_queues
1439
+ `.filter((row) => JSON.parse(row.payload)[key] === value);
1440
+ }
1441
+ /**
1442
+ * Schedule a task to be executed in the future
1443
+ * @template T Type of the payload data
1444
+ * @param when When to execute the task (Date, seconds delay, or cron expression)
1445
+ * @param callback Name of the method to call
1446
+ * @param payload Data to pass to the callback
1447
+ * @returns Schedule object representing the scheduled task
1448
+ */
1449
+ async schedule(when, callback, payload) {
1450
+ const id = nanoid(9);
1451
+ const emitScheduleCreate = (schedule) => this.observability?.emit({
1452
+ displayMessage: `Schedule ${schedule.id} created`,
1453
+ id: nanoid(),
1454
+ payload: {
1455
+ callback,
1456
+ id
1457
+ },
1458
+ timestamp: Date.now(),
1459
+ type: "schedule:create"
1460
+ }, this.ctx);
1461
+ if (typeof callback !== "string") throw new Error("Callback must be a string");
1462
+ if (typeof this[callback] !== "function") throw new Error(`this.${callback} is not a function`);
1463
+ if (when instanceof Date) {
1464
+ const timestamp = Math.floor(when.getTime() / 1e3);
1465
+ this.sql`
1466
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)
1467
+ VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'scheduled', ${timestamp})
1468
+ `;
1469
+ await this._scheduleNextAlarm();
1470
+ const schedule = {
1471
+ callback,
1472
+ id,
1473
+ payload,
1474
+ time: timestamp,
1475
+ type: "scheduled"
1476
+ };
1477
+ emitScheduleCreate(schedule);
1478
+ return schedule;
1479
+ }
1480
+ if (typeof when === "number") {
1481
+ const time = new Date(Date.now() + when * 1e3);
1482
+ const timestamp = Math.floor(time.getTime() / 1e3);
1483
+ this.sql`
1484
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)
1485
+ VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'delayed', ${when}, ${timestamp})
1486
+ `;
1487
+ await this._scheduleNextAlarm();
1488
+ const schedule = {
1489
+ callback,
1490
+ delayInSeconds: when,
1491
+ id,
1492
+ payload,
1493
+ time: timestamp,
1494
+ type: "delayed"
1495
+ };
1496
+ emitScheduleCreate(schedule);
1497
+ return schedule;
1498
+ }
1499
+ if (typeof when === "string") {
1500
+ const nextExecutionTime = getNextCronTime(when);
1501
+ const timestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
1502
+ this.sql`
1503
+ INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)
1504
+ VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'cron', ${when}, ${timestamp})
1505
+ `;
1506
+ await this._scheduleNextAlarm();
1507
+ const schedule = {
1508
+ callback,
1509
+ cron: when,
1510
+ id,
1511
+ payload,
1512
+ time: timestamp,
1513
+ type: "cron"
1514
+ };
1515
+ emitScheduleCreate(schedule);
1516
+ return schedule;
1517
+ }
1518
+ throw new Error("Invalid schedule type");
1519
+ }
1520
+ /**
1521
+ * Get a scheduled task by ID
1522
+ * @template T Type of the payload data
1523
+ * @param id ID of the scheduled task
1524
+ * @returns The Schedule object or undefined if not found
1525
+ */
1526
+ async getSchedule(id) {
1527
+ const result = this.sql`
1528
+ SELECT * FROM cf_agents_schedules WHERE id = ${id}
1529
+ `;
1530
+ if (!result) {
1531
+ console.error(`schedule ${id} not found`);
1532
+ return;
1533
+ }
1534
+ return {
1535
+ ...result[0],
1536
+ payload: JSON.parse(result[0].payload)
1537
+ };
1538
+ }
1539
+ /**
1540
+ * Get scheduled tasks matching the given criteria
1541
+ * @template T Type of the payload data
1542
+ * @param criteria Criteria to filter schedules
1543
+ * @returns Array of matching Schedule objects
1544
+ */
1545
+ getSchedules(criteria = {}) {
1546
+ let query = "SELECT * FROM cf_agents_schedules WHERE 1=1";
1547
+ const params = [];
1548
+ if (criteria.id) {
1549
+ query += " AND id = ?";
1550
+ params.push(criteria.id);
1551
+ }
1552
+ if (criteria.type) {
1553
+ query += " AND type = ?";
1554
+ params.push(criteria.type);
1555
+ }
1556
+ if (criteria.timeRange) {
1557
+ query += " AND time >= ? AND time <= ?";
1558
+ const start = criteria.timeRange.start || /* @__PURE__ */ new Date(0);
1559
+ const end = criteria.timeRange.end || /* @__PURE__ */ new Date(999999999999999);
1560
+ params.push(Math.floor(start.getTime() / 1e3), Math.floor(end.getTime() / 1e3));
1561
+ }
1562
+ return this.ctx.storage.sql.exec(query, ...params).toArray().map((row) => ({
1563
+ ...row,
1564
+ payload: JSON.parse(row.payload)
1565
+ }));
1566
+ }
1567
+ /**
1568
+ * Cancel a scheduled task
1569
+ * @param id ID of the task to cancel
1570
+ * @returns true if the task was cancelled, false otherwise
1571
+ */
1572
+ async cancelSchedule(id) {
1573
+ const schedule = await this.getSchedule(id);
1574
+ if (schedule) this.observability?.emit({
1575
+ displayMessage: `Schedule ${id} cancelled`,
1576
+ id: nanoid(),
1577
+ payload: {
1578
+ callback: schedule.callback,
1579
+ id: schedule.id
1580
+ },
1581
+ timestamp: Date.now(),
1582
+ type: "schedule:cancel"
1583
+ }, this.ctx);
1584
+ this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
1585
+ await this._scheduleNextAlarm();
1586
+ return true;
1587
+ }
1588
+ async _scheduleNextAlarm() {
1589
+ const result = this.sql`
1590
+ SELECT time FROM cf_agents_schedules
1591
+ WHERE time > ${Math.floor(Date.now() / 1e3)}
1592
+ ORDER BY time ASC
1593
+ LIMIT 1
1594
+ `;
1595
+ if (!result) return;
1596
+ if (result.length > 0 && "time" in result[0]) {
1597
+ const nextTime = result[0].time * 1e3;
1598
+ await this.ctx.storage.setAlarm(nextTime);
1599
+ }
1600
+ }
1601
+ /**
1602
+ * Destroy the Agent, removing all state and scheduled tasks
1603
+ */
1604
+ async destroy() {
1605
+ this.sql`DROP TABLE IF EXISTS cf_agents_state`;
1606
+ this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
1607
+ this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;
1608
+ this.sql`DROP TABLE IF EXISTS cf_agents_queues`;
1609
+ await this.ctx.storage.deleteAlarm();
1610
+ await this.ctx.storage.deleteAll();
1611
+ this._disposables.dispose();
1612
+ await this.mcp.dispose?.();
1613
+ this.ctx.abort("destroyed");
1614
+ this.observability?.emit({
1615
+ displayMessage: "Agent destroyed",
1616
+ id: nanoid(),
1617
+ payload: {},
1618
+ timestamp: Date.now(),
1619
+ type: "destroy"
1620
+ }, this.ctx);
1621
+ }
1622
+ /**
1623
+ * Get all methods marked as callable on this Agent
1624
+ * @returns A map of method names to their metadata
1625
+ */
1626
+ _isCallable(method) {
1627
+ return callableMetadata.has(this[method]);
1628
+ }
1629
+ async _ensureMcpStateRestored() {
1630
+ if (this._mcpStateRestored) return;
1631
+ this._mcpStateRestored = true;
1632
+ const servers = this.sql`
1633
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options
1634
+ FROM cf_agents_mcp_servers
1635
+ `;
1636
+ if (!servers || !Array.isArray(servers) || servers.length === 0) return;
1637
+ for (const server of servers) if (server.callback_url) this.mcp.registerCallbackUrl(`${server.callback_url}/${server.id}`);
1638
+ for (const server of servers) if (!!server.auth_url) {
1639
+ const authProvider = new DurableObjectOAuthClientProvider(this.ctx.storage, this.name, server.callback_url);
1640
+ authProvider.serverId = server.id;
1641
+ if (server.client_id) authProvider.clientId = server.client_id;
1642
+ const parsedOptions = server.server_options ? JSON.parse(server.server_options) : void 0;
1643
+ const conn = new MCPClientConnection(new URL(server.server_url), {
1644
+ name: this.name,
1645
+ version: "1.0.0"
1646
+ }, {
1647
+ client: parsedOptions?.client ?? {},
1648
+ transport: {
1649
+ ...parsedOptions?.transport ?? {},
1650
+ type: parsedOptions?.transport?.type ?? "auto",
1651
+ authProvider
1652
+ }
1653
+ });
1654
+ conn.connectionState = "authenticating";
1655
+ this.mcp.mcpConnections[server.id] = conn;
1656
+ } else {
1657
+ const parsedOptions = server.server_options ? JSON.parse(server.server_options) : void 0;
1658
+ this._connectToMcpServerInternal(server.name, server.server_url, server.callback_url, parsedOptions, {
1659
+ id: server.id,
1660
+ oauthClientId: server.client_id ?? void 0
1661
+ }).catch((error) => {
1662
+ console.error(`Error restoring ${server.id}:`, error);
1663
+ });
1664
+ }
1665
+ }
1666
+ /**
1667
+ * Connect to a new MCP Server
1668
+ *
1669
+ * @param serverName Name of the MCP server
1670
+ * @param url MCP Server SSE URL
1671
+ * @param callbackHost Base host for the agent, used for the redirect URI. If not provided, will be derived from the current request.
1672
+ * @param agentsPrefix agents routing prefix if not using `agents`
1673
+ * @param options MCP client and transport options
1674
+ * @returns authUrl
1675
+ */
1676
+ async addMcpServer(serverName, url, callbackHost, agentsPrefix = "agents", options) {
1677
+ let resolvedCallbackHost = callbackHost;
1678
+ if (!resolvedCallbackHost) {
1679
+ const { request } = getCurrentAgent();
1680
+ if (!request) throw new Error("callbackHost is required when not called within a request context");
1681
+ const requestUrl = new URL(request.url);
1682
+ resolvedCallbackHost = `${requestUrl.protocol}//${requestUrl.host}`;
1683
+ }
1684
+ const callbackUrl = `${resolvedCallbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
1685
+ const result = await this._connectToMcpServerInternal(serverName, url, callbackUrl, options);
1686
+ this.sql`
1687
+ INSERT
1688
+ OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
1689
+ VALUES (
1690
+ ${result.id},
1691
+ ${serverName},
1692
+ ${url},
1693
+ ${result.clientId ?? null},
1694
+ ${result.authUrl ?? null},
1695
+ ${callbackUrl},
1696
+ ${options ? JSON.stringify(options) : null}
1697
+ );
1698
+ `;
1699
+ this.broadcastMcpServers();
1700
+ return result;
1701
+ }
1702
+ async _connectToMcpServerInternal(_serverName, url, callbackUrl, options, reconnect) {
1703
+ const authProvider = new DurableObjectOAuthClientProvider(this.ctx.storage, this.name, callbackUrl);
1704
+ if (reconnect) {
1705
+ authProvider.serverId = reconnect.id;
1706
+ if (reconnect.oauthClientId) authProvider.clientId = reconnect.oauthClientId;
1707
+ }
1708
+ const transportType = options?.transport?.type ?? "auto";
1709
+ let headerTransportOpts = {};
1710
+ if (options?.transport?.headers) headerTransportOpts = {
1711
+ eventSourceInit: { fetch: (url$1, init) => fetch(url$1, {
1712
+ ...init,
1713
+ headers: options?.transport?.headers
1714
+ }) },
1715
+ requestInit: { headers: options?.transport?.headers }
1716
+ };
1717
+ const { id, authUrl, clientId } = await this.mcp.connect(url, {
1718
+ client: options?.client,
1719
+ reconnect,
1720
+ transport: {
1721
+ ...headerTransportOpts,
1722
+ authProvider,
1723
+ type: transportType
1724
+ }
1725
+ });
1726
+ return {
1727
+ authUrl,
1728
+ clientId,
1729
+ id
1730
+ };
1731
+ }
1732
+ async removeMcpServer(id) {
1733
+ this.mcp.closeConnection(id);
1734
+ this.mcp.unregisterCallbackUrl(id);
1735
+ this.sql`
1736
+ DELETE FROM cf_agents_mcp_servers WHERE id = ${id};
1737
+ `;
1738
+ this.broadcastMcpServers();
1739
+ }
1740
+ /**
1741
+ * Clear the auth_url for an MCP server after successful OAuth authentication
1742
+ * This prevents the agent from continuously asking for OAuth on reconnect
1743
+ * @param id The server ID to clear auth_url for
1744
+ */
1745
+ clearMcpServerAuthUrl(id) {
1746
+ this.sql`
1747
+ UPDATE cf_agents_mcp_servers
1748
+ SET auth_url = NULL
1749
+ WHERE id = ${id}
1750
+ `;
1751
+ }
1752
+ getMcpServers() {
1753
+ const mcpState = {
1754
+ prompts: this.mcp.listPrompts(),
1755
+ resources: this.mcp.listResources(),
1756
+ servers: {},
1757
+ tools: this.mcp.listTools()
1758
+ };
1759
+ const servers = this.sql`
1760
+ SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;
1761
+ `;
1762
+ if (servers && Array.isArray(servers) && servers.length > 0) for (const server of servers) {
1763
+ const serverConn = this.mcp.mcpConnections[server.id];
1764
+ mcpState.servers[server.id] = {
1765
+ auth_url: server.auth_url,
1766
+ capabilities: serverConn?.serverCapabilities ?? null,
1767
+ instructions: serverConn?.instructions ?? null,
1768
+ name: server.name,
1769
+ server_url: server.server_url,
1770
+ state: serverConn?.connectionState ?? "authenticating"
1771
+ };
1772
+ }
1773
+ return mcpState;
1774
+ }
1775
+ broadcastMcpServers() {
1776
+ this.broadcast(JSON.stringify({
1777
+ mcp: this.getMcpServers(),
1778
+ type: MessageType.CF_AGENT_MCP_SERVERS
1779
+ }));
1780
+ }
1781
+ /**
1782
+ * Handle OAuth callback response using MCPClientManager configuration
1783
+ * @param result OAuth callback result
1784
+ * @param request The original request (needed for base URL)
1785
+ * @returns Response for the OAuth callback
1786
+ */
1787
+ handleOAuthCallbackResponse(result, request) {
1788
+ const config = this.mcp.getOAuthCallbackConfig();
1789
+ if (config?.customHandler) return config.customHandler(result);
1790
+ const baseOrigin = new URL(request.url).origin;
1791
+ if (config?.successRedirect && result.authSuccess) try {
1792
+ return Response.redirect(new URL(config.successRedirect, baseOrigin).href);
1793
+ } catch (e) {
1794
+ console.error("Invalid successRedirect URL:", config.successRedirect, e);
1795
+ return Response.redirect(baseOrigin);
1796
+ }
1797
+ if (config?.errorRedirect && !result.authSuccess) try {
1798
+ const errorUrl = `${config.errorRedirect}?error=${encodeURIComponent(result.authError || "Unknown error")}`;
1799
+ return Response.redirect(new URL(errorUrl, baseOrigin).href);
1800
+ } catch (e) {
1801
+ console.error("Invalid errorRedirect URL:", config.errorRedirect, e);
1802
+ return Response.redirect(baseOrigin);
1803
+ }
1804
+ return Response.redirect(baseOrigin);
1805
+ }
1806
+ };
1807
+ const wrappedClasses = /* @__PURE__ */ new Set();
1808
+ /**
1809
+ * Route a request to the appropriate Agent
1810
+ * @param request Request to route
1811
+ * @param env Environment containing Agent bindings
1812
+ * @param options Routing options
1813
+ * @returns Response from the Agent or undefined if no route matched
1814
+ */
1815
+ async function routeAgentRequest(request, env$1, options) {
1816
+ const corsHeaders = options?.cors === true ? {
1817
+ "Access-Control-Allow-Credentials": "true",
1818
+ "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
1819
+ "Access-Control-Allow-Origin": "*",
1820
+ "Access-Control-Max-Age": "86400"
1821
+ } : options?.cors;
1822
+ if (request.method === "OPTIONS") {
1823
+ if (corsHeaders) return new Response(null, { headers: corsHeaders });
1824
+ console.warn("Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS.");
1825
+ }
1826
+ let response = await routePartykitRequest(request, env$1, {
1827
+ prefix: "agents",
1828
+ ...options
1829
+ });
1830
+ if (response && corsHeaders && request.headers.get("upgrade")?.toLowerCase() !== "websocket" && request.headers.get("Upgrade")?.toLowerCase() !== "websocket") {
1831
+ const newHeaders = new Headers(response.headers);
1832
+ for (const [key, value] of Object.entries(corsHeaders)) newHeaders.set(key, value);
1833
+ response = new Response(response.body, {
1834
+ status: response.status,
1835
+ statusText: response.statusText,
1836
+ headers: newHeaders
1837
+ });
1838
+ }
1839
+ return response;
1840
+ }
1841
+ /**
1842
+ * A wrapper for streaming responses in callable methods
1843
+ */
1844
+ var StreamingResponse = class {
1845
+ constructor(connection, id) {
1846
+ this._closed = false;
1847
+ this._connection = connection;
1848
+ this._id = id;
1849
+ }
1850
+ /**
1851
+ * Send a chunk of data to the client
1852
+ * @param chunk The data to send
1853
+ */
1854
+ send(chunk) {
1855
+ if (this._closed) throw new Error("StreamingResponse is already closed");
1856
+ const response = {
1857
+ done: false,
1858
+ id: this._id,
1859
+ result: chunk,
1860
+ success: true,
1861
+ type: MessageType.RPC
1862
+ };
1863
+ this._connection.send(JSON.stringify(response));
1864
+ }
1865
+ /**
1866
+ * End the stream and send the final chunk (if any)
1867
+ * @param finalChunk Optional final chunk of data to send
1868
+ */
1869
+ end(finalChunk) {
1870
+ if (this._closed) throw new Error("StreamingResponse is already closed");
1871
+ this._closed = true;
1872
+ const response = {
1873
+ done: true,
1874
+ id: this._id,
1875
+ result: finalChunk,
1876
+ success: true,
1877
+ type: MessageType.RPC
1878
+ };
1879
+ this._connection.send(JSON.stringify(response));
1880
+ }
1881
+ };
1882
+
1883
+ //#endregion
1884
+ //#region src/index.ts
1885
+ /**
1886
+ * Creates a middleware for handling Cloudflare Agents WebSocket and HTTP requests
1887
+ * Processes both WebSocket upgrades and standard HTTP requests, delegating them to Cloudflare Agents
1888
+ */
5
1889
  function agentsMiddleware(ctx) {
6
- return createMiddleware(async (c, next) => {
7
- try {
8
- const handler = isWebSocketUpgrade(c) ? handleWebSocketUpgrade : handleHttpRequest;
9
- const response = await handler(c, ctx?.options);
10
- return response === null ? await next() : response;
11
- } catch (error) {
12
- if (ctx?.onError) {
13
- ctx.onError(error);
14
- return next();
15
- }
16
- throw error;
17
- }
18
- });
1890
+ return createMiddleware(async (c, next) => {
1891
+ try {
1892
+ const response = await (isWebSocketUpgrade(c) ? handleWebSocketUpgrade : handleHttpRequest)(c, ctx?.options);
1893
+ return response === null ? await next() : response;
1894
+ } catch (error) {
1895
+ if (ctx?.onError) {
1896
+ ctx.onError(error);
1897
+ return next();
1898
+ }
1899
+ throw error;
1900
+ }
1901
+ });
19
1902
  }
1903
+ /**
1904
+ * Checks if the incoming request is a WebSocket upgrade request
1905
+ * Looks for the 'upgrade' header with a value of 'websocket' (case-insensitive)
1906
+ */
20
1907
  function isWebSocketUpgrade(c) {
21
- return c.req.header("upgrade")?.toLowerCase() === "websocket";
22
- }
23
- function createRequestFromContext(c) {
24
- return new Request(c.req.url, {
25
- method: c.req.method,
26
- headers: c.req.header(),
27
- body: c.req.raw.body
28
- });
1908
+ return c.req.header("upgrade")?.toLowerCase() === "websocket";
29
1909
  }
1910
+ /**
1911
+ * Handles WebSocket upgrade requests
1912
+ * Returns a WebSocket upgrade response if successful, null otherwise
1913
+ */
30
1914
  async function handleWebSocketUpgrade(c, options) {
31
- const req = createRequestFromContext(c);
32
- const response = await routeAgentRequest(req, env(c), options);
33
- if (!response?.webSocket) {
34
- return null;
35
- }
36
- return new Response(null, {
37
- status: 101,
38
- webSocket: response.webSocket
39
- });
1915
+ const response = await routeAgentRequest(c.req.raw, env(c), options);
1916
+ if (!response?.webSocket) return null;
1917
+ return new Response(null, {
1918
+ status: 101,
1919
+ webSocket: response.webSocket
1920
+ });
40
1921
  }
1922
+ /**
1923
+ * Handles standard HTTP requests
1924
+ * Forwards the request to Cloudflare Agents and returns the response
1925
+ */
41
1926
  async function handleHttpRequest(c, options) {
42
- const req = createRequestFromContext(c);
43
- return routeAgentRequest(req, env(c), options);
1927
+ return routeAgentRequest(c.req.raw, env(c), options);
44
1928
  }
45
- export {
46
- agentsMiddleware
47
- };
1929
+
1930
+ //#endregion
1931
+ export { agentsMiddleware };
48
1932
  //# sourceMappingURL=index.js.map