hono-agents 2.0.4 → 2.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1 -1
- package/dist/index.js +117 -64
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/dist/index.d.ts
CHANGED
|
@@ -18,7 +18,7 @@ type AgentMiddlewareContext<E extends Env> = {
|
|
|
18
18
|
*/
|
|
19
19
|
declare function agentsMiddleware<E extends Env = Env>(
|
|
20
20
|
ctx?: AgentMiddlewareContext<E>
|
|
21
|
-
): hono0.MiddlewareHandler<Env, string, {}>;
|
|
21
|
+
): hono0.MiddlewareHandler<Env, string, {}, Response>;
|
|
22
22
|
//#endregion
|
|
23
23
|
export { agentsMiddleware };
|
|
24
24
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
import
|
|
1
|
+
import "partysocket";
|
|
2
2
|
import { nanoid } from "nanoid";
|
|
3
3
|
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
4
4
|
import { ElicitRequestSchema, PromptListChangedNotificationSchema, ResourceListChangedNotificationSchema, ToolListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
5
5
|
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
|
|
6
6
|
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
7
|
-
import "partysocket";
|
|
8
7
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
9
8
|
import { parseCronExpression } from "cron-schedule";
|
|
10
9
|
import "cloudflare:email";
|
|
@@ -12,8 +11,39 @@ import { Server, routePartykitRequest } from "partyserver";
|
|
|
12
11
|
import { env } from "hono/adapter";
|
|
13
12
|
import { createMiddleware } from "hono/factory";
|
|
14
13
|
|
|
15
|
-
//#region ../agents/dist/
|
|
16
|
-
|
|
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-CIvp_OWw.js
|
|
17
47
|
function toDisposable(fn) {
|
|
18
48
|
return { dispose: fn };
|
|
19
49
|
}
|
|
@@ -445,14 +475,6 @@ var MCPClientConnection = class {
|
|
|
445
475
|
};
|
|
446
476
|
}
|
|
447
477
|
};
|
|
448
|
-
let jsonSchemaFn;
|
|
449
|
-
function getJsonSchema() {
|
|
450
|
-
if (!jsonSchemaFn) {
|
|
451
|
-
const { jsonSchema } = __require("ai");
|
|
452
|
-
jsonSchemaFn = jsonSchema;
|
|
453
|
-
}
|
|
454
|
-
return jsonSchemaFn;
|
|
455
|
-
}
|
|
456
478
|
/**
|
|
457
479
|
* Utility class that aggregates multiple MCP clients into one
|
|
458
480
|
*/
|
|
@@ -482,6 +504,17 @@ var MCPClientManager = class {
|
|
|
482
504
|
* @param capabilities Client capabilities (i.e. if the client supports roots/sampling)
|
|
483
505
|
*/
|
|
484
506
|
async connect(url, options = {}) {
|
|
507
|
+
/**
|
|
508
|
+
* We need to delay loading ai sdk, because putting it in module scope is
|
|
509
|
+
* causing issues with startup time.
|
|
510
|
+
* The only place it's used is in getAITools, which only matters after
|
|
511
|
+
* .connect() is called on at least one server.
|
|
512
|
+
* So it's safe to delay loading it until .connect() is called.
|
|
513
|
+
*/
|
|
514
|
+
if (!this.jsonSchema) {
|
|
515
|
+
const { jsonSchema } = await import("ai");
|
|
516
|
+
this.jsonSchema = jsonSchema;
|
|
517
|
+
}
|
|
485
518
|
const id = options.reconnect?.id ?? nanoid(8);
|
|
486
519
|
if (options.transport?.authProvider) {
|
|
487
520
|
options.transport.authProvider.serverId = id;
|
|
@@ -661,8 +694,8 @@ var MCPClientManager = class {
|
|
|
661
694
|
if (result.isError) throw new Error(result.content[0].text);
|
|
662
695
|
return result;
|
|
663
696
|
},
|
|
664
|
-
inputSchema:
|
|
665
|
-
outputSchema: tool.outputSchema ?
|
|
697
|
+
inputSchema: this.jsonSchema(tool.inputSchema),
|
|
698
|
+
outputSchema: tool.outputSchema ? this.jsonSchema(tool.outputSchema) : void 0
|
|
666
699
|
}];
|
|
667
700
|
}));
|
|
668
701
|
}
|
|
@@ -773,39 +806,7 @@ function getNamespacedData(mcpClients, type) {
|
|
|
773
806
|
}
|
|
774
807
|
|
|
775
808
|
//#endregion
|
|
776
|
-
//#region ../agents/dist/
|
|
777
|
-
/**
|
|
778
|
-
* Enum for message types to improve type safety and maintainability
|
|
779
|
-
*/
|
|
780
|
-
let MessageType = /* @__PURE__ */ function(MessageType$1) {
|
|
781
|
-
MessageType$1["CF_AGENT_CHAT_MESSAGES"] = "cf_agent_chat_messages";
|
|
782
|
-
MessageType$1["CF_AGENT_USE_CHAT_REQUEST"] = "cf_agent_use_chat_request";
|
|
783
|
-
MessageType$1["CF_AGENT_USE_CHAT_RESPONSE"] = "cf_agent_use_chat_response";
|
|
784
|
-
MessageType$1["CF_AGENT_CHAT_CLEAR"] = "cf_agent_chat_clear";
|
|
785
|
-
MessageType$1["CF_AGENT_CHAT_REQUEST_CANCEL"] = "cf_agent_chat_request_cancel";
|
|
786
|
-
MessageType$1["CF_AGENT_MCP_SERVERS"] = "cf_agent_mcp_servers";
|
|
787
|
-
MessageType$1["CF_MCP_AGENT_EVENT"] = "cf_mcp_agent_event";
|
|
788
|
-
MessageType$1["CF_AGENT_STATE"] = "cf_agent_state";
|
|
789
|
-
MessageType$1["RPC"] = "rpc";
|
|
790
|
-
return MessageType$1;
|
|
791
|
-
}({});
|
|
792
|
-
|
|
793
|
-
//#endregion
|
|
794
|
-
//#region ../agents/dist/client-zS-OCVJA.js
|
|
795
|
-
/**
|
|
796
|
-
* Convert a camelCase string to a kebab-case string
|
|
797
|
-
* @param str The string to convert
|
|
798
|
-
* @returns The kebab-case string
|
|
799
|
-
*/
|
|
800
|
-
function camelCaseToKebabCase(str) {
|
|
801
|
-
if (str === str.toUpperCase() && str !== str.toLowerCase()) return str.toLowerCase().replace(/_/g, "-");
|
|
802
|
-
let kebabified = str.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
|
|
803
|
-
kebabified = kebabified.startsWith("-") ? kebabified.slice(1) : kebabified;
|
|
804
|
-
return kebabified.replace(/_/g, "-").replace(/-$/, "");
|
|
805
|
-
}
|
|
806
|
-
|
|
807
|
-
//#endregion
|
|
808
|
-
//#region ../agents/dist/do-oauth-client-provider-B2jr6UNq.js
|
|
809
|
+
//#region ../agents/dist/do-oauth-client-provider-CswoD5Lu.js
|
|
809
810
|
var DurableObjectOAuthClientProvider = class {
|
|
810
811
|
constructor(storage, clientName, baseRedirectUrl) {
|
|
811
812
|
this.storage = storage;
|
|
@@ -894,7 +895,7 @@ var DurableObjectOAuthClientProvider = class {
|
|
|
894
895
|
};
|
|
895
896
|
|
|
896
897
|
//#endregion
|
|
897
|
-
//#region ../agents/dist/src-
|
|
898
|
+
//#region ../agents/dist/src-CTtjSFyX.js
|
|
898
899
|
/**
|
|
899
900
|
* A generic observability implementation that logs events to the console.
|
|
900
901
|
*/
|
|
@@ -1123,16 +1124,8 @@ var Agent = class Agent$1 extends Server {
|
|
|
1123
1124
|
request,
|
|
1124
1125
|
email: void 0
|
|
1125
1126
|
}, async () => {
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
this.broadcastMcpServers();
|
|
1129
|
-
if (result.authSuccess) this.mcp.establishConnection(result.serverId).catch((error) => {
|
|
1130
|
-
console.error("Background connection failed:", error);
|
|
1131
|
-
}).finally(() => {
|
|
1132
|
-
this.broadcastMcpServers();
|
|
1133
|
-
});
|
|
1134
|
-
return this.handleOAuthCallbackResponse(result, request);
|
|
1135
|
-
}
|
|
1127
|
+
const callbackResult = await this._handlePotentialOAuthCallback(request);
|
|
1128
|
+
if (callbackResult) return callbackResult;
|
|
1136
1129
|
return this._tryCatch(() => _onRequest(request));
|
|
1137
1130
|
});
|
|
1138
1131
|
};
|
|
@@ -1718,23 +1711,83 @@ var Agent = class Agent$1 extends Server {
|
|
|
1718
1711
|
resolvedCallbackHost = `${requestUrl.protocol}//${requestUrl.host}`;
|
|
1719
1712
|
}
|
|
1720
1713
|
const callbackUrl = `${resolvedCallbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;
|
|
1721
|
-
const
|
|
1714
|
+
const serverId = nanoid(8);
|
|
1722
1715
|
this.sql`
|
|
1723
|
-
INSERT
|
|
1724
|
-
OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
|
|
1716
|
+
INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)
|
|
1725
1717
|
VALUES (
|
|
1726
|
-
${
|
|
1718
|
+
${serverId},
|
|
1727
1719
|
${serverName},
|
|
1728
1720
|
${url},
|
|
1729
|
-
${
|
|
1730
|
-
${
|
|
1721
|
+
${null},
|
|
1722
|
+
${null},
|
|
1731
1723
|
${callbackUrl},
|
|
1732
1724
|
${options ? JSON.stringify(options) : null}
|
|
1733
1725
|
);
|
|
1734
1726
|
`;
|
|
1727
|
+
const result = await this._connectToMcpServerInternal(serverName, url, callbackUrl, options, { id: serverId });
|
|
1728
|
+
if (result.clientId || result.authUrl) this.sql`
|
|
1729
|
+
UPDATE cf_agents_mcp_servers
|
|
1730
|
+
SET client_id = ${result.clientId ?? null}, auth_url = ${result.authUrl ?? null}
|
|
1731
|
+
WHERE id = ${serverId}
|
|
1732
|
+
`;
|
|
1735
1733
|
this.broadcastMcpServers();
|
|
1736
1734
|
return result;
|
|
1737
1735
|
}
|
|
1736
|
+
/**
|
|
1737
|
+
* Handle potential OAuth callback requests after DO hibernation.
|
|
1738
|
+
* Detects OAuth callbacks, restores state from database, and processes the callback.
|
|
1739
|
+
* Returns a Response if this was an OAuth callback, otherwise returns undefined.
|
|
1740
|
+
*/
|
|
1741
|
+
async _handlePotentialOAuthCallback(request) {
|
|
1742
|
+
if (request.method !== "GET") return;
|
|
1743
|
+
const url = new URL(request.url);
|
|
1744
|
+
if (!(url.pathname.includes("/callback/") && url.searchParams.has("code"))) return;
|
|
1745
|
+
const pathParts = url.pathname.split("/");
|
|
1746
|
+
const callbackIndex = pathParts.indexOf("callback");
|
|
1747
|
+
const serverId = callbackIndex !== -1 ? pathParts[callbackIndex + 1] : null;
|
|
1748
|
+
if (!serverId) return new Response("Invalid callback URL: missing serverId", { status: 400 });
|
|
1749
|
+
if (this.mcp.isCallbackRequest(request) && this.mcp.mcpConnections[serverId]) return this._processOAuthCallback(request);
|
|
1750
|
+
try {
|
|
1751
|
+
const server = this.sql`
|
|
1752
|
+
SELECT id, name, server_url, client_id, auth_url, callback_url, server_options
|
|
1753
|
+
FROM cf_agents_mcp_servers
|
|
1754
|
+
WHERE id = ${serverId}
|
|
1755
|
+
`.find((s) => s.id === serverId);
|
|
1756
|
+
if (!server) return new Response(`OAuth callback failed: Server ${serverId} not found in database`, { status: 404 });
|
|
1757
|
+
if (!server.callback_url) return new Response(`OAuth callback failed: No callback URL stored for server ${serverId}`, { status: 500 });
|
|
1758
|
+
this.mcp.registerCallbackUrl(`${server.callback_url}/${server.id}`);
|
|
1759
|
+
if (!this.mcp.mcpConnections[serverId]) {
|
|
1760
|
+
let parsedOptions;
|
|
1761
|
+
try {
|
|
1762
|
+
parsedOptions = server.server_options ? JSON.parse(server.server_options) : void 0;
|
|
1763
|
+
} catch {
|
|
1764
|
+
return new Response(`OAuth callback failed: Invalid server options in database for ${serverId}`, { status: 500 });
|
|
1765
|
+
}
|
|
1766
|
+
await this._connectToMcpServerInternal(server.name, server.server_url, server.callback_url, parsedOptions, {
|
|
1767
|
+
id: server.id,
|
|
1768
|
+
oauthClientId: server.client_id ?? void 0
|
|
1769
|
+
});
|
|
1770
|
+
}
|
|
1771
|
+
return this._processOAuthCallback(request);
|
|
1772
|
+
} catch (error) {
|
|
1773
|
+
const errorMsg = error instanceof Error ? error.message : "Unknown error";
|
|
1774
|
+
console.error(`Failed to restore MCP state for ${serverId}:`, error);
|
|
1775
|
+
return new Response(`OAuth callback failed during state restoration: ${errorMsg}`, { status: 500 });
|
|
1776
|
+
}
|
|
1777
|
+
}
|
|
1778
|
+
/**
|
|
1779
|
+
* Process an OAuth callback request (assumes state is already restored)
|
|
1780
|
+
*/
|
|
1781
|
+
async _processOAuthCallback(request) {
|
|
1782
|
+
const result = await this.mcp.handleCallbackRequest(request);
|
|
1783
|
+
this.broadcastMcpServers();
|
|
1784
|
+
if (result.authSuccess) this.mcp.establishConnection(result.serverId).catch((error) => {
|
|
1785
|
+
console.error("Background connection failed:", error);
|
|
1786
|
+
}).finally(() => {
|
|
1787
|
+
this.broadcastMcpServers();
|
|
1788
|
+
});
|
|
1789
|
+
return this.handleOAuthCallbackResponse(result, request);
|
|
1790
|
+
}
|
|
1738
1791
|
async _connectToMcpServerInternal(_serverName, url, callbackUrl, options, reconnect) {
|
|
1739
1792
|
const authProvider = new DurableObjectOAuthClientProvider(this.ctx.storage, this.name, callbackUrl);
|
|
1740
1793
|
if (reconnect) {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["Agent","env"],"sources":["../../agents/dist/client-WbaRgKYN.js","../../agents/dist/ai-types-B0GBFDwi.js","../../agents/dist/client-zS-OCVJA.js","../../agents/dist/do-oauth-client-provider-B2jr6UNq.js","../../agents/dist/src-C9xZ0CrH.js","../src/index.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\nimport { nanoid } from \"nanoid\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { ElicitRequestSchema, PromptListChangedNotificationSchema, ResourceListChangedNotificationSchema, ToolListChangedNotificationSchema } from \"@modelcontextprotocol/sdk/types.js\";\nimport { SSEClientTransport } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\n\n//#region rolldown:runtime\nvar __require = /* @__PURE__ */ createRequire(import.meta.url);\n\n//#endregion\n//#region src/core/events.ts\nfunction toDisposable(fn) {\n\treturn { dispose: fn };\n}\nvar DisposableStore = class {\n\tconstructor() {\n\t\tthis._items = [];\n\t}\n\tadd(d) {\n\t\tthis._items.push(d);\n\t\treturn d;\n\t}\n\tdispose() {\n\t\twhile (this._items.length) try {\n\t\t\tthis._items.pop().dispose();\n\t\t} catch {}\n\t}\n};\nvar Emitter = class {\n\tconstructor() {\n\t\tthis._listeners = /* @__PURE__ */ new Set();\n\t\tthis.event = (listener) => {\n\t\t\tthis._listeners.add(listener);\n\t\t\treturn toDisposable(() => this._listeners.delete(listener));\n\t\t};\n\t}\n\tfire(data) {\n\t\tfor (const listener of [...this._listeners]) try {\n\t\t\tlistener(data);\n\t\t} catch (err) {\n\t\t\tconsole.error(\"Emitter listener error:\", err);\n\t\t}\n\t}\n\tdispose() {\n\t\tthis._listeners.clear();\n\t}\n};\n\n//#endregion\n//#region src/mcp/errors.ts\nfunction toErrorMessage(error) {\n\treturn error instanceof Error ? error.message : String(error);\n}\nfunction isUnauthorized(error) {\n\tconst msg = toErrorMessage(error);\n\treturn msg.includes(\"Unauthorized\") || msg.includes(\"401\");\n}\nfunction isTransportNotImplemented(error) {\n\tconst msg = toErrorMessage(error);\n\treturn msg.includes(\"404\") || msg.includes(\"405\") || msg.includes(\"Not Implemented\") || msg.includes(\"not implemented\");\n}\n\n//#endregion\n//#region src/mcp/sse-edge.ts\nvar SSEEdgeClientTransport = class extends SSEClientTransport {\n\t/**\n\t* Creates a new EdgeSSEClientTransport, which overrides fetch to be compatible with the CF workers environment\n\t*/\n\tconstructor(url, options) {\n\t\tconst fetchOverride = async (fetchUrl, fetchInit = {}) => {\n\t\t\tconst headers = await this.authHeaders();\n\t\t\tconst workerOptions = {\n\t\t\t\t...fetchInit,\n\t\t\t\theaders: {\n\t\t\t\t\t...options.requestInit?.headers,\n\t\t\t\t\t...fetchInit?.headers,\n\t\t\t\t\t...headers\n\t\t\t\t}\n\t\t\t};\n\t\t\tdelete workerOptions.mode;\n\t\t\treturn options.eventSourceInit?.fetch?.(fetchUrl, workerOptions) || fetch(fetchUrl, workerOptions);\n\t\t};\n\t\tsuper(url, {\n\t\t\t...options,\n\t\t\teventSourceInit: {\n\t\t\t\t...options.eventSourceInit,\n\t\t\t\tfetch: fetchOverride\n\t\t\t}\n\t\t});\n\t\tthis.authProvider = options.authProvider;\n\t}\n\tasync authHeaders() {\n\t\tif (this.authProvider) {\n\t\t\tconst tokens = await this.authProvider.tokens();\n\t\t\tif (tokens) return { Authorization: `Bearer ${tokens.access_token}` };\n\t\t}\n\t}\n};\n\n//#endregion\n//#region src/mcp/streamable-http-edge.ts\nvar StreamableHTTPEdgeClientTransport = class extends StreamableHTTPClientTransport {\n\t/**\n\t* Creates a new StreamableHTTPEdgeClientTransport, which overrides fetch to be compatible with the CF workers environment\n\t*/\n\tconstructor(url, options) {\n\t\tconst fetchOverride = async (fetchUrl, fetchInit = {}) => {\n\t\t\tconst headers = await this.authHeaders();\n\t\t\tconst workerOptions = {\n\t\t\t\t...fetchInit,\n\t\t\t\theaders: {\n\t\t\t\t\t...options.requestInit?.headers,\n\t\t\t\t\t...fetchInit?.headers,\n\t\t\t\t\t...headers\n\t\t\t\t}\n\t\t\t};\n\t\t\tdelete workerOptions.mode;\n\t\t\treturn options.requestInit?.fetch?.(fetchUrl, workerOptions) || fetch(fetchUrl, workerOptions);\n\t\t};\n\t\tsuper(url, {\n\t\t\t...options,\n\t\t\trequestInit: {\n\t\t\t\t...options.requestInit,\n\t\t\t\tfetch: fetchOverride\n\t\t\t}\n\t\t});\n\t\tthis.authProvider = options.authProvider;\n\t}\n\tasync authHeaders() {\n\t\tif (this.authProvider) {\n\t\t\tconst tokens = await this.authProvider.tokens();\n\t\t\tif (tokens) return { Authorization: `Bearer ${tokens.access_token}` };\n\t\t}\n\t}\n};\n\n//#endregion\n//#region src/mcp/client-connection.ts\nvar MCPClientConnection = class {\n\tconstructor(url, info, options = {\n\t\tclient: {},\n\t\ttransport: {}\n\t}) {\n\t\tthis.url = url;\n\t\tthis.options = options;\n\t\tthis.connectionState = \"connecting\";\n\t\tthis.tools = [];\n\t\tthis.prompts = [];\n\t\tthis.resources = [];\n\t\tthis.resourceTemplates = [];\n\t\tthis._onObservabilityEvent = new Emitter();\n\t\tthis.onObservabilityEvent = this._onObservabilityEvent.event;\n\t\tthis.client = new Client(info, {\n\t\t\t...options.client,\n\t\t\tcapabilities: {\n\t\t\t\t...options.client?.capabilities,\n\t\t\t\telicitation: {}\n\t\t\t}\n\t\t});\n\t}\n\t/**\n\t* Initialize a client connection\n\t*\n\t* @returns\n\t*/\n\tasync init() {\n\t\tconst transportType = this.options.transport.type;\n\t\tif (!transportType) throw new Error(\"Transport type must be specified\");\n\t\ttry {\n\t\t\tawait this.tryConnect(transportType);\n\t\t} catch (e) {\n\t\t\tif (isUnauthorized(e)) {\n\t\t\t\tthis.connectionState = \"authenticating\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\ttype: \"mcp:client:connect\",\n\t\t\t\tdisplayMessage: `Connection initialization failed for ${this.url.toString()}`,\n\t\t\t\tpayload: {\n\t\t\t\t\turl: this.url.toString(),\n\t\t\t\t\ttransport: transportType,\n\t\t\t\t\tstate: this.connectionState,\n\t\t\t\t\terror: toErrorMessage(e)\n\t\t\t\t},\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tid: nanoid()\n\t\t\t});\n\t\t\tthis.connectionState = \"failed\";\n\t\t\treturn;\n\t\t}\n\t\tawait this.discoverAndRegister();\n\t}\n\t/**\n\t* Finish OAuth by probing transports based on configured type.\n\t* - Explicit: finish on that transport\n\t* - Auto: try streamable-http, then sse on 404/405/Not Implemented\n\t*/\n\tasync finishAuthProbe(code) {\n\t\tif (!this.options.transport.authProvider) throw new Error(\"No auth provider configured\");\n\t\tconst configuredType = this.options.transport.type;\n\t\tif (!configuredType) throw new Error(\"Transport type must be specified\");\n\t\tconst finishAuth = async (base) => {\n\t\t\tawait this.getTransport(base).finishAuth(code);\n\t\t};\n\t\tif (configuredType === \"sse\" || configuredType === \"streamable-http\") {\n\t\t\tawait finishAuth(configuredType);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tawait finishAuth(\"streamable-http\");\n\t\t} catch (e) {\n\t\t\tif (isTransportNotImplemented(e)) {\n\t\t\t\tawait finishAuth(\"sse\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\t}\n\t/**\n\t* Complete OAuth authorization\n\t*/\n\tasync completeAuthorization(code) {\n\t\tif (this.connectionState !== \"authenticating\") throw new Error(\"Connection must be in authenticating state to complete authorization\");\n\t\ttry {\n\t\t\tawait this.finishAuthProbe(code);\n\t\t\tthis.connectionState = \"connecting\";\n\t\t} catch (error) {\n\t\t\tthis.connectionState = \"failed\";\n\t\t\tthrow error;\n\t\t}\n\t}\n\t/**\n\t* Establish connection after successful authorization\n\t*/\n\tasync establishConnection() {\n\t\tif (this.connectionState !== \"connecting\") throw new Error(\"Connection must be in connecting state to establish connection\");\n\t\ttry {\n\t\t\tconst transportType = this.options.transport.type;\n\t\t\tif (!transportType) throw new Error(\"Transport type must be specified\");\n\t\t\tawait this.tryConnect(transportType);\n\t\t\tawait this.discoverAndRegister();\n\t\t} catch (error) {\n\t\t\tthis.connectionState = \"failed\";\n\t\t\tthrow error;\n\t\t}\n\t}\n\t/**\n\t* Discover server capabilities and register tools, resources, prompts, and templates\n\t*/\n\tasync discoverAndRegister() {\n\t\tthis.connectionState = \"discovering\";\n\t\tthis.serverCapabilities = this.client.getServerCapabilities();\n\t\tif (!this.serverCapabilities) throw new Error(\"The MCP Server failed to return server capabilities\");\n\t\tconst [instructionsResult, toolsResult, resourcesResult, promptsResult, resourceTemplatesResult] = await Promise.allSettled([\n\t\t\tthis.client.getInstructions(),\n\t\t\tthis.registerTools(),\n\t\t\tthis.registerResources(),\n\t\t\tthis.registerPrompts(),\n\t\t\tthis.registerResourceTemplates()\n\t\t]);\n\t\tconst operations = [\n\t\t\t{\n\t\t\t\tname: \"instructions\",\n\t\t\t\tresult: instructionsResult\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"tools\",\n\t\t\t\tresult: toolsResult\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"resources\",\n\t\t\t\tresult: resourcesResult\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"prompts\",\n\t\t\t\tresult: promptsResult\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"resource templates\",\n\t\t\t\tresult: resourceTemplatesResult\n\t\t\t}\n\t\t];\n\t\tfor (const { name, result } of operations) if (result.status === \"rejected\") {\n\t\t\tconst url = this.url.toString();\n\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\ttype: \"mcp:client:discover\",\n\t\t\t\tdisplayMessage: `Failed to discover ${name} for ${url}`,\n\t\t\t\tpayload: {\n\t\t\t\t\turl,\n\t\t\t\t\tcapability: name,\n\t\t\t\t\terror: result.reason\n\t\t\t\t},\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tid: nanoid()\n\t\t\t});\n\t\t}\n\t\tthis.instructions = instructionsResult.status === \"fulfilled\" ? instructionsResult.value : void 0;\n\t\tthis.tools = toolsResult.status === \"fulfilled\" ? toolsResult.value : [];\n\t\tthis.resources = resourcesResult.status === \"fulfilled\" ? resourcesResult.value : [];\n\t\tthis.prompts = promptsResult.status === \"fulfilled\" ? promptsResult.value : [];\n\t\tthis.resourceTemplates = resourceTemplatesResult.status === \"fulfilled\" ? resourceTemplatesResult.value : [];\n\t\tthis.connectionState = \"ready\";\n\t}\n\t/**\n\t* Notification handler registration\n\t*/\n\tasync registerTools() {\n\t\tif (!this.serverCapabilities || !this.serverCapabilities.tools) return [];\n\t\tif (this.serverCapabilities.tools.listChanged) this.client.setNotificationHandler(ToolListChangedNotificationSchema, async (_notification) => {\n\t\t\tthis.tools = await this.fetchTools();\n\t\t});\n\t\treturn this.fetchTools();\n\t}\n\tasync registerResources() {\n\t\tif (!this.serverCapabilities || !this.serverCapabilities.resources) return [];\n\t\tif (this.serverCapabilities.resources.listChanged) this.client.setNotificationHandler(ResourceListChangedNotificationSchema, async (_notification) => {\n\t\t\tthis.resources = await this.fetchResources();\n\t\t});\n\t\treturn this.fetchResources();\n\t}\n\tasync registerPrompts() {\n\t\tif (!this.serverCapabilities || !this.serverCapabilities.prompts) return [];\n\t\tif (this.serverCapabilities.prompts.listChanged) this.client.setNotificationHandler(PromptListChangedNotificationSchema, async (_notification) => {\n\t\t\tthis.prompts = await this.fetchPrompts();\n\t\t});\n\t\treturn this.fetchPrompts();\n\t}\n\tasync registerResourceTemplates() {\n\t\tif (!this.serverCapabilities || !this.serverCapabilities.resources) return [];\n\t\treturn this.fetchResourceTemplates();\n\t}\n\tasync fetchTools() {\n\t\tlet toolsAgg = [];\n\t\tlet toolsResult = { tools: [] };\n\t\tdo {\n\t\t\ttoolsResult = await this.client.listTools({ cursor: toolsResult.nextCursor }).catch(this._capabilityErrorHandler({ tools: [] }, \"tools/list\"));\n\t\t\ttoolsAgg = toolsAgg.concat(toolsResult.tools);\n\t\t} while (toolsResult.nextCursor);\n\t\treturn toolsAgg;\n\t}\n\tasync fetchResources() {\n\t\tlet resourcesAgg = [];\n\t\tlet resourcesResult = { resources: [] };\n\t\tdo {\n\t\t\tresourcesResult = await this.client.listResources({ cursor: resourcesResult.nextCursor }).catch(this._capabilityErrorHandler({ resources: [] }, \"resources/list\"));\n\t\t\tresourcesAgg = resourcesAgg.concat(resourcesResult.resources);\n\t\t} while (resourcesResult.nextCursor);\n\t\treturn resourcesAgg;\n\t}\n\tasync fetchPrompts() {\n\t\tlet promptsAgg = [];\n\t\tlet promptsResult = { prompts: [] };\n\t\tdo {\n\t\t\tpromptsResult = await this.client.listPrompts({ cursor: promptsResult.nextCursor }).catch(this._capabilityErrorHandler({ prompts: [] }, \"prompts/list\"));\n\t\t\tpromptsAgg = promptsAgg.concat(promptsResult.prompts);\n\t\t} while (promptsResult.nextCursor);\n\t\treturn promptsAgg;\n\t}\n\tasync fetchResourceTemplates() {\n\t\tlet templatesAgg = [];\n\t\tlet templatesResult = { resourceTemplates: [] };\n\t\tdo {\n\t\t\ttemplatesResult = await this.client.listResourceTemplates({ cursor: templatesResult.nextCursor }).catch(this._capabilityErrorHandler({ resourceTemplates: [] }, \"resources/templates/list\"));\n\t\t\ttemplatesAgg = templatesAgg.concat(templatesResult.resourceTemplates);\n\t\t} while (templatesResult.nextCursor);\n\t\treturn templatesAgg;\n\t}\n\t/**\n\t* Handle elicitation request from server\n\t* Automatically uses the Agent's built-in elicitation handling if available\n\t*/\n\tasync handleElicitationRequest(_request) {\n\t\tthrow new Error(\"Elicitation handler must be implemented for your platform. Override handleElicitationRequest method.\");\n\t}\n\t/**\n\t* Get the transport for the client\n\t* @param transportType - The transport type to get\n\t* @returns The transport for the client\n\t*/\n\tgetTransport(transportType) {\n\t\tswitch (transportType) {\n\t\t\tcase \"streamable-http\": return new StreamableHTTPEdgeClientTransport(this.url, this.options.transport);\n\t\t\tcase \"sse\": return new SSEEdgeClientTransport(this.url, this.options.transport);\n\t\t\tdefault: throw new Error(`Unsupported transport type: ${transportType}`);\n\t\t}\n\t}\n\tasync tryConnect(transportType) {\n\t\tconst transports = transportType === \"auto\" ? [\"streamable-http\", \"sse\"] : [transportType];\n\t\tfor (const currentTransportType of transports) {\n\t\t\tconst isLastTransport = currentTransportType === transports[transports.length - 1];\n\t\t\tconst hasFallback = transportType === \"auto\" && currentTransportType === \"streamable-http\" && !isLastTransport;\n\t\t\tconst transport = this.getTransport(currentTransportType);\n\t\t\ttry {\n\t\t\t\tawait this.client.connect(transport);\n\t\t\t\tthis.lastConnectedTransport = currentTransportType;\n\t\t\t\tconst url = this.url.toString();\n\t\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\t\ttype: \"mcp:client:connect\",\n\t\t\t\t\tdisplayMessage: `Connected successfully using ${currentTransportType} transport for ${url}`,\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\turl,\n\t\t\t\t\t\ttransport: currentTransportType,\n\t\t\t\t\t\tstate: this.connectionState\n\t\t\t\t\t},\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\tid: nanoid()\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t} catch (e) {\n\t\t\t\tconst error = e instanceof Error ? e : new Error(String(e));\n\t\t\t\tif (isUnauthorized(error)) throw e;\n\t\t\t\tif (hasFallback && isTransportNotImplemented(error)) {\n\t\t\t\t\tconst url = this.url.toString();\n\t\t\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\t\t\ttype: \"mcp:client:connect\",\n\t\t\t\t\t\tdisplayMessage: `${currentTransportType} transport not available, trying ${transports[transports.indexOf(currentTransportType) + 1]} for ${url}`,\n\t\t\t\t\t\tpayload: {\n\t\t\t\t\t\t\turl,\n\t\t\t\t\t\t\ttransport: currentTransportType,\n\t\t\t\t\t\t\tstate: this.connectionState\n\t\t\t\t\t\t},\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\tid: nanoid()\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t\tthis.client.setRequestHandler(ElicitRequestSchema, async (request) => {\n\t\t\treturn await this.handleElicitationRequest(request);\n\t\t});\n\t}\n\t_capabilityErrorHandler(empty, method) {\n\t\treturn (e) => {\n\t\t\tif (e.code === -32601) {\n\t\t\t\tconst url = this.url.toString();\n\t\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\t\ttype: \"mcp:client:discover\",\n\t\t\t\t\tdisplayMessage: `The server advertised support for the capability ${method.split(\"/\")[0]}, but returned \"Method not found\" for '${method}' for ${url}`,\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\turl,\n\t\t\t\t\t\tcapability: method.split(\"/\")[0],\n\t\t\t\t\t\terror: toErrorMessage(e)\n\t\t\t\t\t},\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\tid: nanoid()\n\t\t\t\t});\n\t\t\t\treturn empty;\n\t\t\t}\n\t\t\tthrow e;\n\t\t};\n\t}\n};\n\n//#endregion\n//#region src/mcp/client.ts\nlet jsonSchemaFn;\nfunction getJsonSchema() {\n\tif (!jsonSchemaFn) {\n\t\tconst { jsonSchema } = __require(\"ai\");\n\t\tjsonSchemaFn = jsonSchema;\n\t}\n\treturn jsonSchemaFn;\n}\n/**\n* Utility class that aggregates multiple MCP clients into one\n*/\nvar MCPClientManager = class {\n\t/**\n\t* @param _name Name of the MCP client\n\t* @param _version Version of the MCP Client\n\t* @param auth Auth paramters if being used to create a DurableObjectOAuthClientProvider\n\t*/\n\tconstructor(_name, _version) {\n\t\tthis._name = _name;\n\t\tthis._version = _version;\n\t\tthis.mcpConnections = {};\n\t\tthis._callbackUrls = [];\n\t\tthis._didWarnAboutUnstableGetAITools = false;\n\t\tthis._connectionDisposables = /* @__PURE__ */ new Map();\n\t\tthis._onObservabilityEvent = new Emitter();\n\t\tthis.onObservabilityEvent = this._onObservabilityEvent.event;\n\t\tthis._onConnected = new Emitter();\n\t\tthis.onConnected = this._onConnected.event;\n\t}\n\t/**\n\t* Connect to and register an MCP server\n\t*\n\t* @param transportConfig Transport config\n\t* @param clientConfig Client config\n\t* @param capabilities Client capabilities (i.e. if the client supports roots/sampling)\n\t*/\n\tasync connect(url, options = {}) {\n\t\tconst id = options.reconnect?.id ?? nanoid(8);\n\t\tif (options.transport?.authProvider) {\n\t\t\toptions.transport.authProvider.serverId = id;\n\t\t\tif (options.reconnect?.oauthClientId) options.transport.authProvider.clientId = options.reconnect?.oauthClientId;\n\t\t}\n\t\tif (!options.reconnect?.oauthCode || !this.mcpConnections[id]) {\n\t\t\tconst normalizedTransport = {\n\t\t\t\t...options.transport,\n\t\t\t\ttype: options.transport?.type ?? \"auto\"\n\t\t\t};\n\t\t\tthis.mcpConnections[id] = new MCPClientConnection(new URL(url), {\n\t\t\t\tname: this._name,\n\t\t\t\tversion: this._version\n\t\t\t}, {\n\t\t\t\tclient: options.client ?? {},\n\t\t\t\ttransport: normalizedTransport\n\t\t\t});\n\t\t\tconst store = new DisposableStore();\n\t\t\tconst existing = this._connectionDisposables.get(id);\n\t\t\tif (existing) existing.dispose();\n\t\t\tthis._connectionDisposables.set(id, store);\n\t\t\tstore.add(this.mcpConnections[id].onObservabilityEvent((event) => {\n\t\t\t\tthis._onObservabilityEvent.fire(event);\n\t\t\t}));\n\t\t}\n\t\tawait this.mcpConnections[id].init();\n\t\tif (options.reconnect?.oauthCode) try {\n\t\t\tawait this.mcpConnections[id].completeAuthorization(options.reconnect.oauthCode);\n\t\t\tawait this.mcpConnections[id].establishConnection();\n\t\t} catch (error) {\n\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\ttype: \"mcp:client:connect\",\n\t\t\t\tdisplayMessage: `Failed to complete OAuth reconnection for ${id} for ${url}`,\n\t\t\t\tpayload: {\n\t\t\t\t\turl,\n\t\t\t\t\ttransport: options.transport?.type ?? \"auto\",\n\t\t\t\t\tstate: this.mcpConnections[id].connectionState,\n\t\t\t\t\terror: toErrorMessage(error)\n\t\t\t\t},\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tid\n\t\t\t});\n\t\t\tthrow error;\n\t\t}\n\t\tconst authUrl = options.transport?.authProvider?.authUrl;\n\t\tif (this.mcpConnections[id].connectionState === \"authenticating\" && authUrl && options.transport?.authProvider?.redirectUrl) {\n\t\t\tthis._callbackUrls.push(options.transport.authProvider.redirectUrl.toString());\n\t\t\treturn {\n\t\t\t\tauthUrl,\n\t\t\t\tclientId: options.transport?.authProvider?.clientId,\n\t\t\t\tid\n\t\t\t};\n\t\t}\n\t\treturn { id };\n\t}\n\tisCallbackRequest(req) {\n\t\treturn req.method === \"GET\" && !!this._callbackUrls.find((url) => {\n\t\t\treturn req.url.startsWith(url);\n\t\t});\n\t}\n\tasync handleCallbackRequest(req) {\n\t\tconst url = new URL(req.url);\n\t\tconst urlMatch = this._callbackUrls.find((url$1) => {\n\t\t\treturn req.url.startsWith(url$1);\n\t\t});\n\t\tif (!urlMatch) throw new Error(`No callback URI match found for the request url: ${req.url}. Was the request matched with \\`isCallbackRequest()\\`?`);\n\t\tconst code = url.searchParams.get(\"code\");\n\t\tconst state = url.searchParams.get(\"state\");\n\t\tconst urlParams = urlMatch.split(\"/\");\n\t\tconst serverId = urlParams[urlParams.length - 1];\n\t\tif (!code) throw new Error(\"Unauthorized: no code provided\");\n\t\tif (!state) throw new Error(\"Unauthorized: no state provided\");\n\t\tif (this.mcpConnections[serverId] === void 0) throw new Error(`Could not find serverId: ${serverId}`);\n\t\tif (this.mcpConnections[serverId].connectionState !== \"authenticating\") throw new Error(\"Failed to authenticate: the client isn't in the `authenticating` state\");\n\t\tconst conn = this.mcpConnections[serverId];\n\t\tif (!conn.options.transport.authProvider) throw new Error(\"Trying to finalize authentication for a server connection without an authProvider\");\n\t\tconst clientId = conn.options.transport.authProvider.clientId || state;\n\t\tconn.options.transport.authProvider.clientId = clientId;\n\t\tconn.options.transport.authProvider.serverId = serverId;\n\t\ttry {\n\t\t\tawait conn.completeAuthorization(code);\n\t\t\treturn {\n\t\t\t\tserverId,\n\t\t\t\tauthSuccess: true\n\t\t\t};\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tserverId,\n\t\t\t\tauthSuccess: false,\n\t\t\t\tauthError: error instanceof Error ? error.message : String(error)\n\t\t\t};\n\t\t}\n\t}\n\t/**\n\t* Establish connection in the background after OAuth completion\n\t* This method is called asynchronously and doesn't block the OAuth callback response\n\t* @param serverId The server ID to establish connection for\n\t*/\n\tasync establishConnection(serverId) {\n\t\tconst conn = this.mcpConnections[serverId];\n\t\tif (!conn) {\n\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\ttype: \"mcp:client:preconnect\",\n\t\t\t\tdisplayMessage: `Connection not found for serverId: ${serverId}`,\n\t\t\t\tpayload: { serverId },\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tid: nanoid()\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tawait conn.establishConnection();\n\t\t\tthis._onConnected.fire(serverId);\n\t\t} catch (error) {\n\t\t\tconst url = conn.url.toString();\n\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\ttype: \"mcp:client:connect\",\n\t\t\t\tdisplayMessage: `Failed to establish connection to server ${serverId} with url ${url}`,\n\t\t\t\tpayload: {\n\t\t\t\t\turl,\n\t\t\t\t\ttransport: conn.options.transport.type ?? \"auto\",\n\t\t\t\t\tstate: conn.connectionState,\n\t\t\t\t\terror: toErrorMessage(error)\n\t\t\t\t},\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tid: nanoid()\n\t\t\t});\n\t\t}\n\t}\n\t/**\n\t* Register a callback URL for OAuth handling\n\t* @param url The callback URL to register\n\t*/\n\tregisterCallbackUrl(url) {\n\t\tif (!this._callbackUrls.includes(url)) this._callbackUrls.push(url);\n\t}\n\t/**\n\t* Unregister a callback URL\n\t* @param serverId The server ID whose callback URL should be removed\n\t*/\n\tunregisterCallbackUrl(serverId) {\n\t\tthis._callbackUrls = this._callbackUrls.filter((url) => !url.endsWith(`/${serverId}`));\n\t}\n\t/**\n\t* Configure OAuth callback handling\n\t* @param config OAuth callback configuration\n\t*/\n\tconfigureOAuthCallback(config) {\n\t\tthis._oauthCallbackConfig = config;\n\t}\n\t/**\n\t* Get the current OAuth callback configuration\n\t* @returns The current OAuth callback configuration\n\t*/\n\tgetOAuthCallbackConfig() {\n\t\treturn this._oauthCallbackConfig;\n\t}\n\t/**\n\t* @returns namespaced list of tools\n\t*/\n\tlistTools() {\n\t\treturn getNamespacedData(this.mcpConnections, \"tools\");\n\t}\n\t/**\n\t* @returns a set of tools that you can use with the AI SDK\n\t*/\n\tgetAITools() {\n\t\treturn Object.fromEntries(getNamespacedData(this.mcpConnections, \"tools\").map((tool) => {\n\t\t\treturn [`tool_${tool.serverId.replace(/-/g, \"\")}_${tool.name}`, {\n\t\t\t\tdescription: tool.description,\n\t\t\t\texecute: async (args) => {\n\t\t\t\t\tconst result = await this.callTool({\n\t\t\t\t\t\targuments: args,\n\t\t\t\t\t\tname: tool.name,\n\t\t\t\t\t\tserverId: tool.serverId\n\t\t\t\t\t});\n\t\t\t\t\tif (result.isError) throw new Error(result.content[0].text);\n\t\t\t\t\treturn result;\n\t\t\t\t},\n\t\t\t\tinputSchema: getJsonSchema()(tool.inputSchema),\n\t\t\t\toutputSchema: tool.outputSchema ? getJsonSchema()(tool.outputSchema) : void 0\n\t\t\t}];\n\t\t}));\n\t}\n\t/**\n\t* @deprecated this has been renamed to getAITools(), and unstable_getAITools will be removed in the next major version\n\t* @returns a set of tools that you can use with the AI SDK\n\t*/\n\tunstable_getAITools() {\n\t\tif (!this._didWarnAboutUnstableGetAITools) {\n\t\t\tthis._didWarnAboutUnstableGetAITools = true;\n\t\t\tconsole.warn(\"unstable_getAITools is deprecated, use getAITools instead. unstable_getAITools will be removed in the next major version.\");\n\t\t}\n\t\treturn this.getAITools();\n\t}\n\t/**\n\t* Closes all connections to MCP servers\n\t*/\n\tasync closeAllConnections() {\n\t\tconst ids = Object.keys(this.mcpConnections);\n\t\tawait Promise.all(ids.map(async (id) => {\n\t\t\tawait this.mcpConnections[id].client.close();\n\t\t}));\n\t\tfor (const id of ids) {\n\t\t\tconst store = this._connectionDisposables.get(id);\n\t\t\tif (store) store.dispose();\n\t\t\tthis._connectionDisposables.delete(id);\n\t\t\tdelete this.mcpConnections[id];\n\t\t}\n\t}\n\t/**\n\t* Closes a connection to an MCP server\n\t* @param id The id of the connection to close\n\t*/\n\tasync closeConnection(id) {\n\t\tif (!this.mcpConnections[id]) throw new Error(`Connection with id \"${id}\" does not exist.`);\n\t\tawait this.mcpConnections[id].client.close();\n\t\tdelete this.mcpConnections[id];\n\t\tconst store = this._connectionDisposables.get(id);\n\t\tif (store) store.dispose();\n\t\tthis._connectionDisposables.delete(id);\n\t}\n\t/**\n\t* Dispose the manager and all resources.\n\t*/\n\tasync dispose() {\n\t\ttry {\n\t\t\tawait this.closeAllConnections();\n\t\t} finally {\n\t\t\tthis._onConnected.dispose();\n\t\t\tthis._onObservabilityEvent.dispose();\n\t\t}\n\t}\n\t/**\n\t* @returns namespaced list of prompts\n\t*/\n\tlistPrompts() {\n\t\treturn getNamespacedData(this.mcpConnections, \"prompts\");\n\t}\n\t/**\n\t* @returns namespaced list of tools\n\t*/\n\tlistResources() {\n\t\treturn getNamespacedData(this.mcpConnections, \"resources\");\n\t}\n\t/**\n\t* @returns namespaced list of resource templates\n\t*/\n\tlistResourceTemplates() {\n\t\treturn getNamespacedData(this.mcpConnections, \"resourceTemplates\");\n\t}\n\t/**\n\t* Namespaced version of callTool\n\t*/\n\tasync callTool(params, resultSchema, options) {\n\t\tconst unqualifiedName = params.name.replace(`${params.serverId}.`, \"\");\n\t\treturn this.mcpConnections[params.serverId].client.callTool({\n\t\t\t...params,\n\t\t\tname: unqualifiedName\n\t\t}, resultSchema, options);\n\t}\n\t/**\n\t* Namespaced version of readResource\n\t*/\n\treadResource(params, options) {\n\t\treturn this.mcpConnections[params.serverId].client.readResource(params, options);\n\t}\n\t/**\n\t* Namespaced version of getPrompt\n\t*/\n\tgetPrompt(params, options) {\n\t\treturn this.mcpConnections[params.serverId].client.getPrompt(params, options);\n\t}\n};\nfunction getNamespacedData(mcpClients, type) {\n\treturn Object.entries(mcpClients).map(([name, conn]) => {\n\t\treturn {\n\t\t\tdata: conn[type],\n\t\t\tname\n\t\t};\n\t}).flatMap(({ name: serverId, data }) => {\n\t\treturn data.map((item) => {\n\t\t\treturn {\n\t\t\t\t...item,\n\t\t\t\tserverId\n\t\t\t};\n\t\t});\n\t});\n}\n\n//#endregion\nexport { DisposableStore, MCPClientManager, SSEEdgeClientTransport, StreamableHTTPEdgeClientTransport, __require, getNamespacedData };\n//# sourceMappingURL=client-WbaRgKYN.js.map","//#region src/ai-types.ts\n/**\n* Enum for message types to improve type safety and maintainability\n*/\nlet MessageType = /* @__PURE__ */ function(MessageType$1) {\n\tMessageType$1[\"CF_AGENT_CHAT_MESSAGES\"] = \"cf_agent_chat_messages\";\n\tMessageType$1[\"CF_AGENT_USE_CHAT_REQUEST\"] = \"cf_agent_use_chat_request\";\n\tMessageType$1[\"CF_AGENT_USE_CHAT_RESPONSE\"] = \"cf_agent_use_chat_response\";\n\tMessageType$1[\"CF_AGENT_CHAT_CLEAR\"] = \"cf_agent_chat_clear\";\n\tMessageType$1[\"CF_AGENT_CHAT_REQUEST_CANCEL\"] = \"cf_agent_chat_request_cancel\";\n\tMessageType$1[\"CF_AGENT_MCP_SERVERS\"] = \"cf_agent_mcp_servers\";\n\tMessageType$1[\"CF_MCP_AGENT_EVENT\"] = \"cf_mcp_agent_event\";\n\tMessageType$1[\"CF_AGENT_STATE\"] = \"cf_agent_state\";\n\tMessageType$1[\"RPC\"] = \"rpc\";\n\treturn MessageType$1;\n}({});\n\n//#endregion\nexport { MessageType };\n//# sourceMappingURL=ai-types-B0GBFDwi.js.map","import { MessageType } from \"./ai-types-B0GBFDwi.js\";\nimport { PartySocket } from \"partysocket\";\n\n//#region src/client.ts\n/**\n* Convert a camelCase string to a kebab-case string\n* @param str The string to convert\n* @returns The kebab-case string\n*/\nfunction camelCaseToKebabCase(str) {\n\tif (str === str.toUpperCase() && str !== str.toLowerCase()) return str.toLowerCase().replace(/_/g, \"-\");\n\tlet kebabified = str.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n\tkebabified = kebabified.startsWith(\"-\") ? kebabified.slice(1) : kebabified;\n\treturn kebabified.replace(/_/g, \"-\").replace(/-$/, \"\");\n}\n/**\n* WebSocket client for connecting to an Agent\n*/\nvar AgentClient = class extends PartySocket {\n\t/**\n\t* @deprecated Use agentFetch instead\n\t*/\n\tstatic fetch(_opts) {\n\t\tthrow new Error(\"AgentClient.fetch is not implemented, use agentFetch instead\");\n\t}\n\tconstructor(options) {\n\t\tconst agentNamespace = camelCaseToKebabCase(options.agent);\n\t\tsuper({\n\t\t\tparty: agentNamespace,\n\t\t\tprefix: \"agents\",\n\t\t\troom: options.name || \"default\",\n\t\t\t...options\n\t\t});\n\t\tthis._pendingCalls = /* @__PURE__ */ new Map();\n\t\tthis.agent = agentNamespace;\n\t\tthis.name = options.name || \"default\";\n\t\tthis.options = options;\n\t\tthis.addEventListener(\"message\", (event) => {\n\t\t\tif (typeof event.data === \"string\") {\n\t\t\t\tlet parsedMessage;\n\t\t\t\ttry {\n\t\t\t\t\tparsedMessage = JSON.parse(event.data);\n\t\t\t\t} catch (_error) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (parsedMessage.type === MessageType.CF_AGENT_STATE) {\n\t\t\t\t\tthis.options.onStateUpdate?.(parsedMessage.state, \"server\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (parsedMessage.type === MessageType.RPC) {\n\t\t\t\t\tconst response = parsedMessage;\n\t\t\t\t\tconst pending = this._pendingCalls.get(response.id);\n\t\t\t\t\tif (!pending) return;\n\t\t\t\t\tif (!response.success) {\n\t\t\t\t\t\tpending.reject(new Error(response.error));\n\t\t\t\t\t\tthis._pendingCalls.delete(response.id);\n\t\t\t\t\t\tpending.stream?.onError?.(response.error);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (\"done\" in response) if (response.done) {\n\t\t\t\t\t\tpending.resolve(response.result);\n\t\t\t\t\t\tthis._pendingCalls.delete(response.id);\n\t\t\t\t\t\tpending.stream?.onDone?.(response.result);\n\t\t\t\t\t} else pending.stream?.onChunk?.(response.result);\n\t\t\t\t\telse {\n\t\t\t\t\t\tpending.resolve(response.result);\n\t\t\t\t\t\tthis._pendingCalls.delete(response.id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\tsetState(state) {\n\t\tthis.send(JSON.stringify({\n\t\t\tstate,\n\t\t\ttype: MessageType.CF_AGENT_STATE\n\t\t}));\n\t\tthis.options.onStateUpdate?.(state, \"client\");\n\t}\n\tasync call(method, args = [], streamOptions) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst id = Math.random().toString(36).slice(2);\n\t\t\tthis._pendingCalls.set(id, {\n\t\t\t\treject,\n\t\t\t\tresolve: (value) => resolve(value),\n\t\t\t\tstream: streamOptions,\n\t\t\t\ttype: null\n\t\t\t});\n\t\t\tconst request = {\n\t\t\t\targs,\n\t\t\t\tid,\n\t\t\t\tmethod,\n\t\t\t\ttype: MessageType.RPC\n\t\t\t};\n\t\t\tthis.send(JSON.stringify(request));\n\t\t});\n\t}\n};\n/**\n* Make an HTTP request to an Agent\n* @param opts Connection options\n* @param init Request initialization options\n* @returns Promise resolving to a Response\n*/\nfunction agentFetch(opts, init) {\n\tconst agentNamespace = camelCaseToKebabCase(opts.agent);\n\treturn PartySocket.fetch({\n\t\tparty: agentNamespace,\n\t\tprefix: \"agents\",\n\t\troom: opts.name || \"default\",\n\t\t...opts\n\t}, init);\n}\n\n//#endregion\nexport { AgentClient, agentFetch, camelCaseToKebabCase };\n//# sourceMappingURL=client-zS-OCVJA.js.map","import { nanoid } from \"nanoid\";\n\n//#region src/mcp/do-oauth-client-provider.ts\nvar DurableObjectOAuthClientProvider = class {\n\tconstructor(storage, clientName, baseRedirectUrl) {\n\t\tthis.storage = storage;\n\t\tthis.clientName = clientName;\n\t\tthis.baseRedirectUrl = baseRedirectUrl;\n\t}\n\tget clientMetadata() {\n\t\treturn {\n\t\t\tclient_name: this.clientName,\n\t\t\tclient_uri: this.clientUri,\n\t\t\tgrant_types: [\"authorization_code\", \"refresh_token\"],\n\t\t\tredirect_uris: [this.redirectUrl],\n\t\t\tresponse_types: [\"code\"],\n\t\t\ttoken_endpoint_auth_method: \"none\"\n\t\t};\n\t}\n\tget clientUri() {\n\t\treturn new URL(this.redirectUrl).origin;\n\t}\n\tget redirectUrl() {\n\t\treturn `${this.baseRedirectUrl}/${this.serverId}`;\n\t}\n\tget clientId() {\n\t\tif (!this._clientId_) throw new Error(\"Trying to access clientId before it was set\");\n\t\treturn this._clientId_;\n\t}\n\tset clientId(clientId_) {\n\t\tthis._clientId_ = clientId_;\n\t}\n\tget serverId() {\n\t\tif (!this._serverId_) throw new Error(\"Trying to access serverId before it was set\");\n\t\treturn this._serverId_;\n\t}\n\tset serverId(serverId_) {\n\t\tthis._serverId_ = serverId_;\n\t}\n\tkeyPrefix(clientId) {\n\t\treturn `/${this.clientName}/${this.serverId}/${clientId}`;\n\t}\n\tclientInfoKey(clientId) {\n\t\treturn `${this.keyPrefix(clientId)}/client_info/`;\n\t}\n\tasync clientInformation() {\n\t\tif (!this._clientId_) return;\n\t\treturn await this.storage.get(this.clientInfoKey(this.clientId)) ?? void 0;\n\t}\n\tasync saveClientInformation(clientInformation) {\n\t\tawait this.storage.put(this.clientInfoKey(clientInformation.client_id), clientInformation);\n\t\tthis.clientId = clientInformation.client_id;\n\t}\n\ttokenKey(clientId) {\n\t\treturn `${this.keyPrefix(clientId)}/token`;\n\t}\n\tasync tokens() {\n\t\tif (!this._clientId_) return;\n\t\treturn await this.storage.get(this.tokenKey(this.clientId)) ?? void 0;\n\t}\n\tasync saveTokens(tokens) {\n\t\tawait this.storage.put(this.tokenKey(this.clientId), tokens);\n\t}\n\tget authUrl() {\n\t\treturn this._authUrl_;\n\t}\n\t/**\n\t* Because this operates on the server side (but we need browser auth), we send this url back to the user\n\t* and require user interact to initiate the redirect flow\n\t*/\n\tasync redirectToAuthorization(authUrl) {\n\t\tconst stateToken = nanoid();\n\t\tauthUrl.searchParams.set(\"state\", stateToken);\n\t\tthis._authUrl_ = authUrl.toString();\n\t}\n\tcodeVerifierKey(clientId) {\n\t\treturn `${this.keyPrefix(clientId)}/code_verifier`;\n\t}\n\tasync saveCodeVerifier(verifier) {\n\t\tconst key = this.codeVerifierKey(this.clientId);\n\t\tif (await this.storage.get(key)) return;\n\t\tawait this.storage.put(key, verifier);\n\t}\n\tasync codeVerifier() {\n\t\tconst codeVerifier = await this.storage.get(this.codeVerifierKey(this.clientId));\n\t\tif (!codeVerifier) throw new Error(\"No code verifier found\");\n\t\treturn codeVerifier;\n\t}\n};\n\n//#endregion\nexport { DurableObjectOAuthClientProvider };\n//# sourceMappingURL=do-oauth-client-provider-B2jr6UNq.js.map","import { DisposableStore, MCPClientManager } from \"./client-WbaRgKYN.js\";\nimport { MessageType } from \"./ai-types-B0GBFDwi.js\";\nimport { camelCaseToKebabCase } from \"./client-zS-OCVJA.js\";\nimport { DurableObjectOAuthClientProvider } from \"./do-oauth-client-provider-B2jr6UNq.js\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { parseCronExpression } from \"cron-schedule\";\nimport { nanoid } from \"nanoid\";\nimport { EmailMessage } from \"cloudflare:email\";\nimport { Server, getServerByName, routePartykitRequest } from \"partyserver\";\n\n//#region src/observability/index.ts\n/**\n* A generic observability implementation that logs events to the console.\n*/\nconst genericObservability = { emit(event) {\n\tif (isLocalMode()) {\n\t\tconsole.log(event.displayMessage);\n\t\treturn;\n\t}\n\tconsole.log(event);\n} };\nlet localMode = false;\nfunction isLocalMode() {\n\tif (localMode) return true;\n\tconst { request } = getCurrentAgent();\n\tif (!request) return false;\n\tlocalMode = new URL(request.url).hostname === \"localhost\";\n\treturn localMode;\n}\n\n//#endregion\n//#region src/index.ts\n/**\n* Type guard for RPC request messages\n*/\nfunction isRPCRequest(msg) {\n\treturn 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);\n}\n/**\n* Type guard for state update messages\n*/\nfunction isStateUpdateMessage(msg) {\n\treturn typeof msg === \"object\" && msg !== null && \"type\" in msg && msg.type === MessageType.CF_AGENT_STATE && \"state\" in msg;\n}\nconst callableMetadata = /* @__PURE__ */ new Map();\n/**\n* Decorator that marks a method as callable by clients\n* @param metadata Optional metadata about the callable method\n*/\nfunction callable(metadata = {}) {\n\treturn function callableDecorator(target, context) {\n\t\tif (!callableMetadata.has(target)) callableMetadata.set(target, metadata);\n\t\treturn target;\n\t};\n}\nlet didWarnAboutUnstableCallable = false;\n/**\n* Decorator that marks a method as callable by clients\n* @deprecated this has been renamed to callable, and unstable_callable will be removed in the next major version\n* @param metadata Optional metadata about the callable method\n*/\nconst unstable_callable = (metadata = {}) => {\n\tif (!didWarnAboutUnstableCallable) {\n\t\tdidWarnAboutUnstableCallable = true;\n\t\tconsole.warn(\"unstable_callable is deprecated, use callable instead. unstable_callable will be removed in the next major version.\");\n\t}\n\tcallable(metadata);\n};\nfunction getNextCronTime(cron) {\n\treturn parseCronExpression(cron).getNextDate();\n}\nconst STATE_ROW_ID = \"cf_state_row_id\";\nconst STATE_WAS_CHANGED = \"cf_state_was_changed\";\nconst DEFAULT_STATE = {};\nconst agentContext = new AsyncLocalStorage();\nfunction getCurrentAgent() {\n\tconst store = agentContext.getStore();\n\tif (!store) return {\n\t\tagent: void 0,\n\t\tconnection: void 0,\n\t\trequest: void 0,\n\t\temail: void 0\n\t};\n\treturn store;\n}\n/**\n* Wraps a method to run within the agent context, ensuring getCurrentAgent() works properly\n* @param agent The agent instance\n* @param method The method to wrap\n* @returns A wrapped method that runs within the agent context\n*/\nfunction withAgentContext(method) {\n\treturn function(...args) {\n\t\tconst { connection, request, email, agent } = getCurrentAgent();\n\t\tif (agent === this) return method.apply(this, args);\n\t\treturn agentContext.run({\n\t\t\tagent: this,\n\t\t\tconnection,\n\t\t\trequest,\n\t\t\temail\n\t\t}, () => {\n\t\t\treturn method.apply(this, args);\n\t\t});\n\t};\n}\n/**\n* Base class for creating Agent implementations\n* @template Env Environment type containing bindings\n* @template State State type to store within the Agent\n*/\nvar Agent = class Agent extends Server {\n\t/**\n\t* Current state of the Agent\n\t*/\n\tget state() {\n\t\tif (this._state !== DEFAULT_STATE) return this._state;\n\t\tconst wasChanged = this.sql`\n SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}\n `;\n\t\tconst result = this.sql`\n SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}\n `;\n\t\tif (wasChanged[0]?.state === \"true\" || result[0]?.state) {\n\t\t\tconst state = result[0]?.state;\n\t\t\tthis._state = JSON.parse(state);\n\t\t\treturn this._state;\n\t\t}\n\t\tif (this.initialState === DEFAULT_STATE) return;\n\t\tthis.setState(this.initialState);\n\t\treturn this.initialState;\n\t}\n\tstatic {\n\t\tthis.options = { hibernate: true };\n\t}\n\t/**\n\t* Execute SQL queries against the Agent's database\n\t* @template T Type of the returned rows\n\t* @param strings SQL query template strings\n\t* @param values Values to be inserted into the query\n\t* @returns Array of query results\n\t*/\n\tsql(strings, ...values) {\n\t\tlet query = \"\";\n\t\ttry {\n\t\t\tquery = strings.reduce((acc, str, i) => acc + str + (i < values.length ? \"?\" : \"\"), \"\");\n\t\t\treturn [...this.ctx.storage.sql.exec(query, ...values)];\n\t\t} catch (e) {\n\t\t\tconsole.error(`failed to execute sql query: ${query}`, e);\n\t\t\tthrow this.onError(e);\n\t\t}\n\t}\n\tconstructor(ctx, env) {\n\t\tsuper(ctx, env);\n\t\tthis._state = DEFAULT_STATE;\n\t\tthis._disposables = new DisposableStore();\n\t\tthis._ParentClass = Object.getPrototypeOf(this).constructor;\n\t\tthis.mcp = new MCPClientManager(this._ParentClass.name, \"0.0.1\");\n\t\tthis.initialState = DEFAULT_STATE;\n\t\tthis.observability = genericObservability;\n\t\tthis._flushingQueue = false;\n\t\tthis.alarm = async () => {\n\t\t\tconst now = Math.floor(Date.now() / 1e3);\n\t\t\tconst result = this.sql`\n SELECT * FROM cf_agents_schedules WHERE time <= ${now}\n `;\n\t\t\tif (result && Array.isArray(result)) for (const row of result) {\n\t\t\t\tconst callback = this[row.callback];\n\t\t\t\tif (!callback) {\n\t\t\t\t\tconsole.error(`callback ${row.callback} not found`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tawait agentContext.run({\n\t\t\t\t\tagent: this,\n\t\t\t\t\tconnection: void 0,\n\t\t\t\t\trequest: void 0,\n\t\t\t\t\temail: void 0\n\t\t\t\t}, async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tthis.observability?.emit({\n\t\t\t\t\t\t\tdisplayMessage: `Schedule ${row.id} executed`,\n\t\t\t\t\t\t\tid: nanoid(),\n\t\t\t\t\t\t\tpayload: {\n\t\t\t\t\t\t\t\tcallback: row.callback,\n\t\t\t\t\t\t\t\tid: row.id\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\t\ttype: \"schedule:execute\"\n\t\t\t\t\t\t}, this.ctx);\n\t\t\t\t\t\tawait callback.bind(this)(JSON.parse(row.payload), row);\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tconsole.error(`error executing callback \"${row.callback}\"`, e);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tif (row.type === \"cron\") {\n\t\t\t\t\tconst nextExecutionTime = getNextCronTime(row.cron);\n\t\t\t\t\tconst nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);\n\t\t\t\t\tthis.sql`\n UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}\n `;\n\t\t\t\t} else this.sql`\n DELETE FROM cf_agents_schedules WHERE id = ${row.id}\n `;\n\t\t\t}\n\t\t\tawait this._scheduleNextAlarm();\n\t\t};\n\t\tif (!wrappedClasses.has(this.constructor)) {\n\t\t\tthis._autoWrapCustomMethods();\n\t\t\twrappedClasses.add(this.constructor);\n\t\t}\n\t\tthis._disposables.add(this.mcp.onConnected(async () => {\n\t\t\tthis.broadcastMcpServers();\n\t\t}));\n\t\tthis._disposables.add(this.mcp.onObservabilityEvent((event) => {\n\t\t\tthis.observability?.emit(event);\n\t\t}));\n\t\tthis.sql`\n CREATE TABLE IF NOT EXISTS cf_agents_state (\n id TEXT PRIMARY KEY NOT NULL,\n state TEXT\n )\n `;\n\t\tthis.sql`\n CREATE TABLE IF NOT EXISTS cf_agents_queues (\n id TEXT PRIMARY KEY NOT NULL,\n payload TEXT,\n callback TEXT,\n created_at INTEGER DEFAULT (unixepoch())\n )\n `;\n\t\tthis.ctx.blockConcurrencyWhile(async () => {\n\t\t\treturn this._tryCatch(async () => {\n\t\t\t\tthis.sql`\n CREATE TABLE IF NOT EXISTS cf_agents_schedules (\n id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),\n callback TEXT,\n payload TEXT,\n type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),\n time INTEGER,\n delayInSeconds INTEGER,\n cron TEXT,\n created_at INTEGER DEFAULT (unixepoch())\n )\n `;\n\t\t\t\tawait this.alarm();\n\t\t\t});\n\t\t});\n\t\tthis.sql`\n CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (\n id TEXT PRIMARY KEY NOT NULL,\n name TEXT NOT NULL,\n server_url TEXT NOT NULL,\n callback_url TEXT NOT NULL,\n client_id TEXT,\n auth_url TEXT,\n server_options TEXT\n )\n `;\n\t\tconst _onRequest = this.onRequest.bind(this);\n\t\tthis.onRequest = (request) => {\n\t\t\treturn agentContext.run({\n\t\t\t\tagent: this,\n\t\t\t\tconnection: void 0,\n\t\t\t\trequest,\n\t\t\t\temail: void 0\n\t\t\t}, async () => {\n\t\t\t\tif (this.mcp.isCallbackRequest(request)) {\n\t\t\t\t\tconst result = await this.mcp.handleCallbackRequest(request);\n\t\t\t\t\tthis.broadcastMcpServers();\n\t\t\t\t\tif (result.authSuccess) this.mcp.establishConnection(result.serverId).catch((error) => {\n\t\t\t\t\t\tconsole.error(\"Background connection failed:\", error);\n\t\t\t\t\t}).finally(() => {\n\t\t\t\t\t\tthis.broadcastMcpServers();\n\t\t\t\t\t});\n\t\t\t\t\treturn this.handleOAuthCallbackResponse(result, request);\n\t\t\t\t}\n\t\t\t\treturn this._tryCatch(() => _onRequest(request));\n\t\t\t});\n\t\t};\n\t\tconst _onMessage = this.onMessage.bind(this);\n\t\tthis.onMessage = async (connection, message) => {\n\t\t\treturn agentContext.run({\n\t\t\t\tagent: this,\n\t\t\t\tconnection,\n\t\t\t\trequest: void 0,\n\t\t\t\temail: void 0\n\t\t\t}, async () => {\n\t\t\t\tif (typeof message !== \"string\") return this._tryCatch(() => _onMessage(connection, message));\n\t\t\t\tlet parsed;\n\t\t\t\ttry {\n\t\t\t\t\tparsed = JSON.parse(message);\n\t\t\t\t} catch (_e) {\n\t\t\t\t\treturn this._tryCatch(() => _onMessage(connection, message));\n\t\t\t\t}\n\t\t\t\tif (isStateUpdateMessage(parsed)) {\n\t\t\t\t\tthis._setStateInternal(parsed.state, connection);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (isRPCRequest(parsed)) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst { id, method, args } = parsed;\n\t\t\t\t\t\tconst methodFn = this[method];\n\t\t\t\t\t\tif (typeof methodFn !== \"function\") throw new Error(`Method ${method} does not exist`);\n\t\t\t\t\t\tif (!this._isCallable(method)) throw new Error(`Method ${method} is not callable`);\n\t\t\t\t\t\tconst metadata = callableMetadata.get(methodFn);\n\t\t\t\t\t\tif (metadata?.streaming) {\n\t\t\t\t\t\t\tconst stream = new StreamingResponse(connection, id);\n\t\t\t\t\t\t\tawait methodFn.apply(this, [stream, ...args]);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst result = await methodFn.apply(this, args);\n\t\t\t\t\t\tthis.observability?.emit({\n\t\t\t\t\t\t\tdisplayMessage: `RPC call to ${method}`,\n\t\t\t\t\t\t\tid: nanoid(),\n\t\t\t\t\t\t\tpayload: {\n\t\t\t\t\t\t\t\tmethod,\n\t\t\t\t\t\t\t\tstreaming: metadata?.streaming\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\t\ttype: \"rpc\"\n\t\t\t\t\t\t}, this.ctx);\n\t\t\t\t\t\tconst response = {\n\t\t\t\t\t\t\tdone: true,\n\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\tresult,\n\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\ttype: MessageType.RPC\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconnection.send(JSON.stringify(response));\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tconst response = {\n\t\t\t\t\t\t\terror: e instanceof Error ? e.message : \"Unknown error occurred\",\n\t\t\t\t\t\t\tid: parsed.id,\n\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\ttype: MessageType.RPC\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconnection.send(JSON.stringify(response));\n\t\t\t\t\t\tconsole.error(\"RPC error:\", e);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treturn this._tryCatch(() => _onMessage(connection, message));\n\t\t\t});\n\t\t};\n\t\tconst _onConnect = this.onConnect.bind(this);\n\t\tthis.onConnect = (connection, ctx$1) => {\n\t\t\treturn agentContext.run({\n\t\t\t\tagent: this,\n\t\t\t\tconnection,\n\t\t\t\trequest: ctx$1.request,\n\t\t\t\temail: void 0\n\t\t\t}, () => {\n\t\t\t\tif (this.state) connection.send(JSON.stringify({\n\t\t\t\t\tstate: this.state,\n\t\t\t\t\ttype: MessageType.CF_AGENT_STATE\n\t\t\t\t}));\n\t\t\t\tconnection.send(JSON.stringify({\n\t\t\t\t\tmcp: this.getMcpServers(),\n\t\t\t\t\ttype: MessageType.CF_AGENT_MCP_SERVERS\n\t\t\t\t}));\n\t\t\t\tthis.observability?.emit({\n\t\t\t\t\tdisplayMessage: \"Connection established\",\n\t\t\t\t\tid: nanoid(),\n\t\t\t\t\tpayload: { connectionId: connection.id },\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\ttype: \"connect\"\n\t\t\t\t}, this.ctx);\n\t\t\t\treturn this._tryCatch(() => _onConnect(connection, ctx$1));\n\t\t\t});\n\t\t};\n\t\tconst _onStart = this.onStart.bind(this);\n\t\tthis.onStart = async (props) => {\n\t\t\treturn agentContext.run({\n\t\t\t\tagent: this,\n\t\t\t\tconnection: void 0,\n\t\t\t\trequest: void 0,\n\t\t\t\temail: void 0\n\t\t\t}, async () => {\n\t\t\t\tawait this._tryCatch(() => {\n\t\t\t\t\tconst servers = this.sql`\n SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;\n `;\n\t\t\t\t\tthis.broadcastMcpServers();\n\t\t\t\t\tif (servers && Array.isArray(servers) && servers.length > 0) {\n\t\t\t\t\t\tservers.forEach((server) => {\n\t\t\t\t\t\t\tif (server.callback_url) this.mcp.registerCallbackUrl(`${server.callback_url}/${server.id}`);\n\t\t\t\t\t\t});\n\t\t\t\t\t\tservers.forEach((server) => {\n\t\t\t\t\t\t\tthis._connectToMcpServerInternal(server.name, server.server_url, server.callback_url, server.server_options ? JSON.parse(server.server_options) : void 0, {\n\t\t\t\t\t\t\t\tid: server.id,\n\t\t\t\t\t\t\t\toauthClientId: server.client_id ?? void 0\n\t\t\t\t\t\t\t}).then(() => {\n\t\t\t\t\t\t\t\tthis.broadcastMcpServers();\n\t\t\t\t\t\t\t}).catch((error) => {\n\t\t\t\t\t\t\t\tconsole.error(`Error connecting to MCP server: ${server.name} (${server.server_url})`, error);\n\t\t\t\t\t\t\t\tthis.broadcastMcpServers();\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\treturn _onStart(props);\n\t\t\t\t});\n\t\t\t});\n\t\t};\n\t}\n\t_setStateInternal(state, source = \"server\") {\n\t\tthis._state = state;\n\t\tthis.sql`\n INSERT OR REPLACE INTO cf_agents_state (id, state)\n VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})\n `;\n\t\tthis.sql`\n INSERT OR REPLACE INTO cf_agents_state (id, state)\n VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})\n `;\n\t\tthis.broadcast(JSON.stringify({\n\t\t\tstate,\n\t\t\ttype: MessageType.CF_AGENT_STATE\n\t\t}), source !== \"server\" ? [source.id] : []);\n\t\treturn this._tryCatch(() => {\n\t\t\tconst { connection, request, email } = agentContext.getStore() || {};\n\t\t\treturn agentContext.run({\n\t\t\t\tagent: this,\n\t\t\t\tconnection,\n\t\t\t\trequest,\n\t\t\t\temail\n\t\t\t}, async () => {\n\t\t\t\tthis.observability?.emit({\n\t\t\t\t\tdisplayMessage: \"State updated\",\n\t\t\t\t\tid: nanoid(),\n\t\t\t\t\tpayload: {},\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\ttype: \"state:update\"\n\t\t\t\t}, this.ctx);\n\t\t\t\treturn this.onStateUpdate(state, source);\n\t\t\t});\n\t\t});\n\t}\n\t/**\n\t* Update the Agent's state\n\t* @param state New state to set\n\t*/\n\tsetState(state) {\n\t\tthis._setStateInternal(state, \"server\");\n\t}\n\t/**\n\t* Called when the Agent's state is updated\n\t* @param state Updated state\n\t* @param source Source of the state update (\"server\" or a client connection)\n\t*/\n\tonStateUpdate(state, source) {}\n\t/**\n\t* Called when the Agent receives an email via routeAgentEmail()\n\t* Override this method to handle incoming emails\n\t* @param email Email message to process\n\t*/\n\tasync _onEmail(email) {\n\t\treturn agentContext.run({\n\t\t\tagent: this,\n\t\t\tconnection: void 0,\n\t\t\trequest: void 0,\n\t\t\temail\n\t\t}, async () => {\n\t\t\tif (\"onEmail\" in this && typeof this.onEmail === \"function\") return this._tryCatch(() => this.onEmail(email));\n\t\t\telse {\n\t\t\t\tconsole.log(\"Received email from:\", email.from, \"to:\", email.to);\n\t\t\t\tconsole.log(\"Subject:\", email.headers.get(\"subject\"));\n\t\t\t\tconsole.log(\"Implement onEmail(email: AgentEmail): Promise<void> in your agent to process emails\");\n\t\t\t}\n\t\t});\n\t}\n\t/**\n\t* Reply to an email\n\t* @param email The email to reply to\n\t* @param options Options for the reply\n\t* @returns void\n\t*/\n\tasync replyToEmail(email, options) {\n\t\treturn this._tryCatch(async () => {\n\t\t\tconst agentName = camelCaseToKebabCase(this._ParentClass.name);\n\t\t\tconst agentId = this.name;\n\t\t\tconst { createMimeMessage } = await import(\"mimetext\");\n\t\t\tconst msg = createMimeMessage();\n\t\t\tmsg.setSender({\n\t\t\t\taddr: email.to,\n\t\t\t\tname: options.fromName\n\t\t\t});\n\t\t\tmsg.setRecipient(email.from);\n\t\t\tmsg.setSubject(options.subject || `Re: ${email.headers.get(\"subject\")}` || \"No subject\");\n\t\t\tmsg.addMessage({\n\t\t\t\tcontentType: options.contentType || \"text/plain\",\n\t\t\t\tdata: options.body\n\t\t\t});\n\t\t\tconst messageId = `<${agentId}@${email.from.split(\"@\")[1]}>`;\n\t\t\tmsg.setHeader(\"In-Reply-To\", email.headers.get(\"Message-ID\"));\n\t\t\tmsg.setHeader(\"Message-ID\", messageId);\n\t\t\tmsg.setHeader(\"X-Agent-Name\", agentName);\n\t\t\tmsg.setHeader(\"X-Agent-ID\", agentId);\n\t\t\tif (options.headers) for (const [key, value] of Object.entries(options.headers)) msg.setHeader(key, value);\n\t\t\tawait email.reply({\n\t\t\t\tfrom: email.to,\n\t\t\t\traw: msg.asRaw(),\n\t\t\t\tto: email.from\n\t\t\t});\n\t\t});\n\t}\n\tasync _tryCatch(fn) {\n\t\ttry {\n\t\t\treturn await fn();\n\t\t} catch (e) {\n\t\t\tthrow this.onError(e);\n\t\t}\n\t}\n\t/**\n\t* Automatically wrap custom methods with agent context\n\t* This ensures getCurrentAgent() works in all custom methods without decorators\n\t*/\n\t_autoWrapCustomMethods() {\n\t\tconst basePrototypes = [Agent.prototype, Server.prototype];\n\t\tconst baseMethods = /* @__PURE__ */ new Set();\n\t\tfor (const baseProto of basePrototypes) {\n\t\t\tlet proto$1 = baseProto;\n\t\t\twhile (proto$1 && proto$1 !== Object.prototype) {\n\t\t\t\tconst methodNames = Object.getOwnPropertyNames(proto$1);\n\t\t\t\tfor (const methodName of methodNames) baseMethods.add(methodName);\n\t\t\t\tproto$1 = Object.getPrototypeOf(proto$1);\n\t\t\t}\n\t\t}\n\t\tlet proto = Object.getPrototypeOf(this);\n\t\tlet depth = 0;\n\t\twhile (proto && proto !== Object.prototype && depth < 10) {\n\t\t\tconst methodNames = Object.getOwnPropertyNames(proto);\n\t\t\tfor (const methodName of methodNames) {\n\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(proto, methodName);\n\t\t\t\tif (baseMethods.has(methodName) || methodName.startsWith(\"_\") || !descriptor || !!descriptor.get || typeof descriptor.value !== \"function\") continue;\n\t\t\t\tconst wrappedFunction = withAgentContext(this[methodName]);\n\t\t\t\tif (this._isCallable(methodName)) callableMetadata.set(wrappedFunction, callableMetadata.get(this[methodName]));\n\t\t\t\tthis.constructor.prototype[methodName] = wrappedFunction;\n\t\t\t}\n\t\t\tproto = Object.getPrototypeOf(proto);\n\t\t\tdepth++;\n\t\t}\n\t}\n\tonError(connectionOrError, error) {\n\t\tlet theError;\n\t\tif (connectionOrError && error) {\n\t\t\ttheError = error;\n\t\t\tconsole.error(\"Error on websocket connection:\", connectionOrError.id, theError);\n\t\t\tconsole.error(\"Override onError(connection, error) to handle websocket connection errors\");\n\t\t} else {\n\t\t\ttheError = connectionOrError;\n\t\t\tconsole.error(\"Error on server:\", theError);\n\t\t\tconsole.error(\"Override onError(error) to handle server errors\");\n\t\t}\n\t\tthrow theError;\n\t}\n\t/**\n\t* Render content (not implemented in base class)\n\t*/\n\trender() {\n\t\tthrow new Error(\"Not implemented\");\n\t}\n\t/**\n\t* Queue a task to be executed in the future\n\t* @param payload Payload to pass to the callback\n\t* @param callback Name of the method to call\n\t* @returns The ID of the queued task\n\t*/\n\tasync queue(callback, payload) {\n\t\tconst id = nanoid(9);\n\t\tif (typeof callback !== \"string\") throw new Error(\"Callback must be a string\");\n\t\tif (typeof this[callback] !== \"function\") throw new Error(`this.${callback} is not a function`);\n\t\tthis.sql`\n INSERT OR REPLACE INTO cf_agents_queues (id, payload, callback)\n VALUES (${id}, ${JSON.stringify(payload)}, ${callback})\n `;\n\t\tthis._flushQueue().catch((e) => {\n\t\t\tconsole.error(\"Error flushing queue:\", e);\n\t\t});\n\t\treturn id;\n\t}\n\tasync _flushQueue() {\n\t\tif (this._flushingQueue) return;\n\t\tthis._flushingQueue = true;\n\t\twhile (true) {\n\t\t\tconst result = this.sql`\n SELECT * FROM cf_agents_queues\n ORDER BY created_at ASC\n `;\n\t\t\tif (!result || result.length === 0) break;\n\t\t\tfor (const row of result || []) {\n\t\t\t\tconst callback = this[row.callback];\n\t\t\t\tif (!callback) {\n\t\t\t\t\tconsole.error(`callback ${row.callback} not found`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst { connection, request, email } = agentContext.getStore() || {};\n\t\t\t\tawait agentContext.run({\n\t\t\t\t\tagent: this,\n\t\t\t\t\tconnection,\n\t\t\t\t\trequest,\n\t\t\t\t\temail\n\t\t\t\t}, async () => {\n\t\t\t\t\tawait callback.bind(this)(JSON.parse(row.payload), row);\n\t\t\t\t\tawait this.dequeue(row.id);\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tthis._flushingQueue = false;\n\t}\n\t/**\n\t* Dequeue a task by ID\n\t* @param id ID of the task to dequeue\n\t*/\n\tasync dequeue(id) {\n\t\tthis.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;\n\t}\n\t/**\n\t* Dequeue all tasks\n\t*/\n\tasync dequeueAll() {\n\t\tthis.sql`DELETE FROM cf_agents_queues`;\n\t}\n\t/**\n\t* Dequeue all tasks by callback\n\t* @param callback Name of the callback to dequeue\n\t*/\n\tasync dequeueAllByCallback(callback) {\n\t\tthis.sql`DELETE FROM cf_agents_queues WHERE callback = ${callback}`;\n\t}\n\t/**\n\t* Get a queued task by ID\n\t* @param id ID of the task to get\n\t* @returns The task or undefined if not found\n\t*/\n\tasync getQueue(id) {\n\t\tconst result = this.sql`\n SELECT * FROM cf_agents_queues WHERE id = ${id}\n `;\n\t\treturn result ? {\n\t\t\t...result[0],\n\t\t\tpayload: JSON.parse(result[0].payload)\n\t\t} : void 0;\n\t}\n\t/**\n\t* Get all queues by key and value\n\t* @param key Key to filter by\n\t* @param value Value to filter by\n\t* @returns Array of matching QueueItem objects\n\t*/\n\tasync getQueues(key, value) {\n\t\treturn this.sql`\n SELECT * FROM cf_agents_queues\n `.filter((row) => JSON.parse(row.payload)[key] === value);\n\t}\n\t/**\n\t* Schedule a task to be executed in the future\n\t* @template T Type of the payload data\n\t* @param when When to execute the task (Date, seconds delay, or cron expression)\n\t* @param callback Name of the method to call\n\t* @param payload Data to pass to the callback\n\t* @returns Schedule object representing the scheduled task\n\t*/\n\tasync schedule(when, callback, payload) {\n\t\tconst id = nanoid(9);\n\t\tconst emitScheduleCreate = (schedule) => this.observability?.emit({\n\t\t\tdisplayMessage: `Schedule ${schedule.id} created`,\n\t\t\tid: nanoid(),\n\t\t\tpayload: {\n\t\t\t\tcallback,\n\t\t\t\tid\n\t\t\t},\n\t\t\ttimestamp: Date.now(),\n\t\t\ttype: \"schedule:create\"\n\t\t}, this.ctx);\n\t\tif (typeof callback !== \"string\") throw new Error(\"Callback must be a string\");\n\t\tif (typeof this[callback] !== \"function\") throw new Error(`this.${callback} is not a function`);\n\t\tif (when instanceof Date) {\n\t\t\tconst timestamp = Math.floor(when.getTime() / 1e3);\n\t\t\tthis.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)\n VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'scheduled', ${timestamp})\n `;\n\t\t\tawait this._scheduleNextAlarm();\n\t\t\tconst schedule = {\n\t\t\t\tcallback,\n\t\t\t\tid,\n\t\t\t\tpayload,\n\t\t\t\ttime: timestamp,\n\t\t\t\ttype: \"scheduled\"\n\t\t\t};\n\t\t\temitScheduleCreate(schedule);\n\t\t\treturn schedule;\n\t\t}\n\t\tif (typeof when === \"number\") {\n\t\t\tconst time = new Date(Date.now() + when * 1e3);\n\t\t\tconst timestamp = Math.floor(time.getTime() / 1e3);\n\t\t\tthis.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)\n VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'delayed', ${when}, ${timestamp})\n `;\n\t\t\tawait this._scheduleNextAlarm();\n\t\t\tconst schedule = {\n\t\t\t\tcallback,\n\t\t\t\tdelayInSeconds: when,\n\t\t\t\tid,\n\t\t\t\tpayload,\n\t\t\t\ttime: timestamp,\n\t\t\t\ttype: \"delayed\"\n\t\t\t};\n\t\t\temitScheduleCreate(schedule);\n\t\t\treturn schedule;\n\t\t}\n\t\tif (typeof when === \"string\") {\n\t\t\tconst nextExecutionTime = getNextCronTime(when);\n\t\t\tconst timestamp = Math.floor(nextExecutionTime.getTime() / 1e3);\n\t\t\tthis.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)\n VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'cron', ${when}, ${timestamp})\n `;\n\t\t\tawait this._scheduleNextAlarm();\n\t\t\tconst schedule = {\n\t\t\t\tcallback,\n\t\t\t\tcron: when,\n\t\t\t\tid,\n\t\t\t\tpayload,\n\t\t\t\ttime: timestamp,\n\t\t\t\ttype: \"cron\"\n\t\t\t};\n\t\t\temitScheduleCreate(schedule);\n\t\t\treturn schedule;\n\t\t}\n\t\tthrow new Error(\"Invalid schedule type\");\n\t}\n\t/**\n\t* Get a scheduled task by ID\n\t* @template T Type of the payload data\n\t* @param id ID of the scheduled task\n\t* @returns The Schedule object or undefined if not found\n\t*/\n\tasync getSchedule(id) {\n\t\tconst result = this.sql`\n SELECT * FROM cf_agents_schedules WHERE id = ${id}\n `;\n\t\tif (!result) {\n\t\t\tconsole.error(`schedule ${id} not found`);\n\t\t\treturn;\n\t\t}\n\t\treturn {\n\t\t\t...result[0],\n\t\t\tpayload: JSON.parse(result[0].payload)\n\t\t};\n\t}\n\t/**\n\t* Get scheduled tasks matching the given criteria\n\t* @template T Type of the payload data\n\t* @param criteria Criteria to filter schedules\n\t* @returns Array of matching Schedule objects\n\t*/\n\tgetSchedules(criteria = {}) {\n\t\tlet query = \"SELECT * FROM cf_agents_schedules WHERE 1=1\";\n\t\tconst params = [];\n\t\tif (criteria.id) {\n\t\t\tquery += \" AND id = ?\";\n\t\t\tparams.push(criteria.id);\n\t\t}\n\t\tif (criteria.type) {\n\t\t\tquery += \" AND type = ?\";\n\t\t\tparams.push(criteria.type);\n\t\t}\n\t\tif (criteria.timeRange) {\n\t\t\tquery += \" AND time >= ? AND time <= ?\";\n\t\t\tconst start = criteria.timeRange.start || /* @__PURE__ */ new Date(0);\n\t\t\tconst end = criteria.timeRange.end || /* @__PURE__ */ new Date(999999999999999);\n\t\t\tparams.push(Math.floor(start.getTime() / 1e3), Math.floor(end.getTime() / 1e3));\n\t\t}\n\t\treturn this.ctx.storage.sql.exec(query, ...params).toArray().map((row) => ({\n\t\t\t...row,\n\t\t\tpayload: JSON.parse(row.payload)\n\t\t}));\n\t}\n\t/**\n\t* Cancel a scheduled task\n\t* @param id ID of the task to cancel\n\t* @returns true if the task was cancelled, false otherwise\n\t*/\n\tasync cancelSchedule(id) {\n\t\tconst schedule = await this.getSchedule(id);\n\t\tif (schedule) this.observability?.emit({\n\t\t\tdisplayMessage: `Schedule ${id} cancelled`,\n\t\t\tid: nanoid(),\n\t\t\tpayload: {\n\t\t\t\tcallback: schedule.callback,\n\t\t\t\tid: schedule.id\n\t\t\t},\n\t\t\ttimestamp: Date.now(),\n\t\t\ttype: \"schedule:cancel\"\n\t\t}, this.ctx);\n\t\tthis.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;\n\t\tawait this._scheduleNextAlarm();\n\t\treturn true;\n\t}\n\tasync _scheduleNextAlarm() {\n\t\tconst result = this.sql`\n SELECT time FROM cf_agents_schedules\n WHERE time > ${Math.floor(Date.now() / 1e3)}\n ORDER BY time ASC\n LIMIT 1\n `;\n\t\tif (!result) return;\n\t\tif (result.length > 0 && \"time\" in result[0]) {\n\t\t\tconst nextTime = result[0].time * 1e3;\n\t\t\tawait this.ctx.storage.setAlarm(nextTime);\n\t\t}\n\t}\n\t/**\n\t* Destroy the Agent, removing all state and scheduled tasks\n\t*/\n\tasync destroy() {\n\t\tthis.sql`DROP TABLE IF EXISTS cf_agents_state`;\n\t\tthis.sql`DROP TABLE IF EXISTS cf_agents_schedules`;\n\t\tthis.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;\n\t\tthis.sql`DROP TABLE IF EXISTS cf_agents_queues`;\n\t\tawait this.ctx.storage.deleteAlarm();\n\t\tawait this.ctx.storage.deleteAll();\n\t\tthis._disposables.dispose();\n\t\tawait this.mcp.dispose?.();\n\t\tthis.ctx.abort(\"destroyed\");\n\t\tthis.observability?.emit({\n\t\t\tdisplayMessage: \"Agent destroyed\",\n\t\t\tid: nanoid(),\n\t\t\tpayload: {},\n\t\t\ttimestamp: Date.now(),\n\t\t\ttype: \"destroy\"\n\t\t}, this.ctx);\n\t}\n\t/**\n\t* Get all methods marked as callable on this Agent\n\t* @returns A map of method names to their metadata\n\t*/\n\t_isCallable(method) {\n\t\treturn callableMetadata.has(this[method]);\n\t}\n\t/**\n\t* Connect to a new MCP Server\n\t*\n\t* @param serverName Name of the MCP server\n\t* @param url MCP Server SSE URL\n\t* @param callbackHost Base host for the agent, used for the redirect URI. If not provided, will be derived from the current request.\n\t* @param agentsPrefix agents routing prefix if not using `agents`\n\t* @param options MCP client and transport options\n\t* @returns authUrl\n\t*/\n\tasync addMcpServer(serverName, url, callbackHost, agentsPrefix = \"agents\", options) {\n\t\tlet resolvedCallbackHost = callbackHost;\n\t\tif (!resolvedCallbackHost) {\n\t\t\tconst { request } = getCurrentAgent();\n\t\t\tif (!request) throw new Error(\"callbackHost is required when not called within a request context\");\n\t\t\tconst requestUrl = new URL(request.url);\n\t\t\tresolvedCallbackHost = `${requestUrl.protocol}//${requestUrl.host}`;\n\t\t}\n\t\tconst callbackUrl = `${resolvedCallbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;\n\t\tconst result = await this._connectToMcpServerInternal(serverName, url, callbackUrl, options);\n\t\tthis.sql`\n INSERT\n OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)\n VALUES (\n ${result.id},\n ${serverName},\n ${url},\n ${result.clientId ?? null},\n ${result.authUrl ?? null},\n ${callbackUrl},\n ${options ? JSON.stringify(options) : null}\n );\n `;\n\t\tthis.broadcastMcpServers();\n\t\treturn result;\n\t}\n\tasync _connectToMcpServerInternal(_serverName, url, callbackUrl, options, reconnect) {\n\t\tconst authProvider = new DurableObjectOAuthClientProvider(this.ctx.storage, this.name, callbackUrl);\n\t\tif (reconnect) {\n\t\t\tauthProvider.serverId = reconnect.id;\n\t\t\tif (reconnect.oauthClientId) authProvider.clientId = reconnect.oauthClientId;\n\t\t}\n\t\tconst transportType = options?.transport?.type ?? \"auto\";\n\t\tlet headerTransportOpts = {};\n\t\tif (options?.transport?.headers) headerTransportOpts = {\n\t\t\teventSourceInit: { fetch: (url$1, init) => fetch(url$1, {\n\t\t\t\t...init,\n\t\t\t\theaders: options?.transport?.headers\n\t\t\t}) },\n\t\t\trequestInit: { headers: options?.transport?.headers }\n\t\t};\n\t\tconst { id, authUrl, clientId } = await this.mcp.connect(url, {\n\t\t\tclient: options?.client,\n\t\t\treconnect,\n\t\t\ttransport: {\n\t\t\t\t...headerTransportOpts,\n\t\t\t\tauthProvider,\n\t\t\t\ttype: transportType\n\t\t\t}\n\t\t});\n\t\treturn {\n\t\t\tauthUrl,\n\t\t\tclientId,\n\t\t\tid\n\t\t};\n\t}\n\tasync removeMcpServer(id) {\n\t\tthis.mcp.closeConnection(id);\n\t\tthis.mcp.unregisterCallbackUrl(id);\n\t\tthis.sql`\n DELETE FROM cf_agents_mcp_servers WHERE id = ${id};\n `;\n\t\tthis.broadcastMcpServers();\n\t}\n\tgetMcpServers() {\n\t\tconst mcpState = {\n\t\t\tprompts: this.mcp.listPrompts(),\n\t\t\tresources: this.mcp.listResources(),\n\t\t\tservers: {},\n\t\t\ttools: this.mcp.listTools()\n\t\t};\n\t\tconst servers = this.sql`\n SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;\n `;\n\t\tif (servers && Array.isArray(servers) && servers.length > 0) for (const server of servers) {\n\t\t\tconst serverConn = this.mcp.mcpConnections[server.id];\n\t\t\tmcpState.servers[server.id] = {\n\t\t\t\tauth_url: server.auth_url,\n\t\t\t\tcapabilities: serverConn?.serverCapabilities ?? null,\n\t\t\t\tinstructions: serverConn?.instructions ?? null,\n\t\t\t\tname: server.name,\n\t\t\t\tserver_url: server.server_url,\n\t\t\t\tstate: serverConn?.connectionState ?? \"authenticating\"\n\t\t\t};\n\t\t}\n\t\treturn mcpState;\n\t}\n\tbroadcastMcpServers() {\n\t\tthis.broadcast(JSON.stringify({\n\t\t\tmcp: this.getMcpServers(),\n\t\t\ttype: MessageType.CF_AGENT_MCP_SERVERS\n\t\t}));\n\t}\n\t/**\n\t* Handle OAuth callback response using MCPClientManager configuration\n\t* @param result OAuth callback result\n\t* @param request The original request (needed for base URL)\n\t* @returns Response for the OAuth callback\n\t*/\n\thandleOAuthCallbackResponse(result, request) {\n\t\tconst config = this.mcp.getOAuthCallbackConfig();\n\t\tif (config?.customHandler) return config.customHandler(result);\n\t\tif (config?.successRedirect && result.authSuccess) return Response.redirect(config.successRedirect);\n\t\tif (config?.errorRedirect && !result.authSuccess) return Response.redirect(`${config.errorRedirect}?error=${encodeURIComponent(result.authError || \"Unknown error\")}`);\n\t\tconst baseUrl = new URL(request.url).origin;\n\t\treturn Response.redirect(baseUrl);\n\t}\n};\nconst wrappedClasses = /* @__PURE__ */ new Set();\n/**\n* Route a request to the appropriate Agent\n* @param request Request to route\n* @param env Environment containing Agent bindings\n* @param options Routing options\n* @returns Response from the Agent or undefined if no route matched\n*/\nasync function routeAgentRequest(request, env, options) {\n\tconst corsHeaders = options?.cors === true ? {\n\t\t\"Access-Control-Allow-Credentials\": \"true\",\n\t\t\"Access-Control-Allow-Methods\": \"GET, POST, HEAD, OPTIONS\",\n\t\t\"Access-Control-Allow-Origin\": \"*\",\n\t\t\"Access-Control-Max-Age\": \"86400\"\n\t} : options?.cors;\n\tif (request.method === \"OPTIONS\") {\n\t\tif (corsHeaders) return new Response(null, { headers: corsHeaders });\n\t\tconsole.warn(\"Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS.\");\n\t}\n\tlet response = await routePartykitRequest(request, env, {\n\t\tprefix: \"agents\",\n\t\t...options\n\t});\n\tif (response && corsHeaders && request.headers.get(\"upgrade\")?.toLowerCase() !== \"websocket\" && request.headers.get(\"Upgrade\")?.toLowerCase() !== \"websocket\") response = new Response(response.body, { headers: {\n\t\t...response.headers,\n\t\t...corsHeaders\n\t} });\n\treturn response;\n}\n/**\n* Create a resolver that uses the message-id header to determine the agent to route the email to\n* @returns A function that resolves the agent to route the email to\n*/\nfunction createHeaderBasedEmailResolver() {\n\treturn async (email, _env) => {\n\t\tconst messageId = email.headers.get(\"message-id\");\n\t\tif (messageId) {\n\t\t\tconst messageIdMatch = messageId.match(/<([^@]+)@([^>]+)>/);\n\t\t\tif (messageIdMatch) {\n\t\t\t\tconst [, agentId$1, domain] = messageIdMatch;\n\t\t\t\treturn {\n\t\t\t\t\tagentName: domain.split(\".\")[0],\n\t\t\t\t\tagentId: agentId$1\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\tconst references = email.headers.get(\"references\");\n\t\tif (references) {\n\t\t\tconst referencesMatch = references.match(/<([A-Za-z0-9+/]{43}=)@([^>]+)>/);\n\t\t\tif (referencesMatch) {\n\t\t\t\tconst [, base64Id, domain] = referencesMatch;\n\t\t\t\tconst agentId$1 = Buffer.from(base64Id, \"base64\").toString(\"hex\");\n\t\t\t\treturn {\n\t\t\t\t\tagentName: domain.split(\".\")[0],\n\t\t\t\t\tagentId: agentId$1\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\tconst agentName = email.headers.get(\"x-agent-name\");\n\t\tconst agentId = email.headers.get(\"x-agent-id\");\n\t\tif (agentName && agentId) return {\n\t\t\tagentName,\n\t\t\tagentId\n\t\t};\n\t\treturn null;\n\t};\n}\n/**\n* Create a resolver that uses the email address to determine the agent to route the email to\n* @param defaultAgentName The default agent name to use if the email address does not contain a sub-address\n* @returns A function that resolves the agent to route the email to\n*/\nfunction createAddressBasedEmailResolver(defaultAgentName) {\n\treturn async (email, _env) => {\n\t\tconst emailMatch = email.to.match(/^([^+@]+)(?:\\+([^@]+))?@(.+)$/);\n\t\tif (!emailMatch) return null;\n\t\tconst [, localPart, subAddress] = emailMatch;\n\t\tif (subAddress) return {\n\t\t\tagentName: localPart,\n\t\t\tagentId: subAddress\n\t\t};\n\t\treturn {\n\t\t\tagentName: defaultAgentName,\n\t\t\tagentId: localPart\n\t\t};\n\t};\n}\n/**\n* Create a resolver that uses the agentName and agentId to determine the agent to route the email to\n* @param agentName The name of the agent to route the email to\n* @param agentId The id of the agent to route the email to\n* @returns A function that resolves the agent to route the email to\n*/\nfunction createCatchAllEmailResolver(agentName, agentId) {\n\treturn async () => ({\n\t\tagentName,\n\t\tagentId\n\t});\n}\nconst agentMapCache = /* @__PURE__ */ new WeakMap();\n/**\n* Route an email to the appropriate Agent\n* @param email The email to route\n* @param env The environment containing the Agent bindings\n* @param options The options for routing the email\n* @returns A promise that resolves when the email has been routed\n*/\nasync function routeAgentEmail(email, env, options) {\n\tconst routingInfo = await options.resolver(email, env);\n\tif (!routingInfo) {\n\t\tconsole.warn(\"No routing information found for email, dropping message\");\n\t\treturn;\n\t}\n\tif (!agentMapCache.has(env)) {\n\t\tconst map = {};\n\t\tfor (const [key, value] of Object.entries(env)) if (value && typeof value === \"object\" && \"idFromName\" in value && typeof value.idFromName === \"function\") {\n\t\t\tmap[key] = value;\n\t\t\tmap[camelCaseToKebabCase(key)] = value;\n\t\t}\n\t\tagentMapCache.set(env, map);\n\t}\n\tconst agentMap = agentMapCache.get(env);\n\tconst namespace = agentMap[routingInfo.agentName];\n\tif (!namespace) {\n\t\tconst availableAgents = Object.keys(agentMap).filter((key) => !key.includes(\"-\")).join(\", \");\n\t\tthrow new Error(`Agent namespace '${routingInfo.agentName}' not found in environment. Available agents: ${availableAgents}`);\n\t}\n\tconst agent = await getAgentByName(namespace, routingInfo.agentId);\n\tconst serialisableEmail = {\n\t\tgetRaw: async () => {\n\t\t\tconst reader = email.raw.getReader();\n\t\t\tconst chunks = [];\n\t\t\tlet done = false;\n\t\t\twhile (!done) {\n\t\t\t\tconst { value, done: readerDone } = await reader.read();\n\t\t\t\tdone = readerDone;\n\t\t\t\tif (value) chunks.push(value);\n\t\t\t}\n\t\t\tconst totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);\n\t\t\tconst combined = new Uint8Array(totalLength);\n\t\t\tlet offset = 0;\n\t\t\tfor (const chunk of chunks) {\n\t\t\t\tcombined.set(chunk, offset);\n\t\t\t\toffset += chunk.length;\n\t\t\t}\n\t\t\treturn combined;\n\t\t},\n\t\theaders: email.headers,\n\t\trawSize: email.rawSize,\n\t\tsetReject: (reason) => {\n\t\t\temail.setReject(reason);\n\t\t},\n\t\tforward: (rcptTo, headers) => {\n\t\t\treturn email.forward(rcptTo, headers);\n\t\t},\n\t\treply: (options$1) => {\n\t\t\treturn email.reply(new EmailMessage(options$1.from, options$1.to, options$1.raw));\n\t\t},\n\t\tfrom: email.from,\n\t\tto: email.to\n\t};\n\tawait agent._onEmail(serialisableEmail);\n}\n/**\n* Get or create an Agent by name\n* @template Env Environment type containing bindings\n* @template T Type of the Agent class\n* @param namespace Agent namespace\n* @param name Name of the Agent instance\n* @param options Options for Agent creation\n* @returns Promise resolving to an Agent instance stub\n*/\nasync function getAgentByName(namespace, name, options) {\n\treturn getServerByName(namespace, name, options);\n}\n/**\n* A wrapper for streaming responses in callable methods\n*/\nvar StreamingResponse = class {\n\tconstructor(connection, id) {\n\t\tthis._closed = false;\n\t\tthis._connection = connection;\n\t\tthis._id = id;\n\t}\n\t/**\n\t* Send a chunk of data to the client\n\t* @param chunk The data to send\n\t*/\n\tsend(chunk) {\n\t\tif (this._closed) throw new Error(\"StreamingResponse is already closed\");\n\t\tconst response = {\n\t\t\tdone: false,\n\t\t\tid: this._id,\n\t\t\tresult: chunk,\n\t\t\tsuccess: true,\n\t\t\ttype: MessageType.RPC\n\t\t};\n\t\tthis._connection.send(JSON.stringify(response));\n\t}\n\t/**\n\t* End the stream and send the final chunk (if any)\n\t* @param finalChunk Optional final chunk of data to send\n\t*/\n\tend(finalChunk) {\n\t\tif (this._closed) throw new Error(\"StreamingResponse is already closed\");\n\t\tthis._closed = true;\n\t\tconst response = {\n\t\t\tdone: true,\n\t\t\tid: this._id,\n\t\t\tresult: finalChunk,\n\t\t\tsuccess: true,\n\t\t\ttype: MessageType.RPC\n\t\t};\n\t\tthis._connection.send(JSON.stringify(response));\n\t}\n};\n\n//#endregion\nexport { Agent, StreamingResponse, callable, createAddressBasedEmailResolver, createCatchAllEmailResolver, createHeaderBasedEmailResolver, genericObservability, getAgentByName, getCurrentAgent, routeAgentEmail, routeAgentRequest, unstable_callable };\n//# sourceMappingURL=src-C9xZ0CrH.js.map","import type { AgentOptions } from \"agents\";\nimport { routeAgentRequest } from \"agents\";\nimport type { Context, Env } from \"hono\";\nimport { env } from \"hono/adapter\";\nimport { createMiddleware } from \"hono/factory\";\n\n/**\n * Configuration options for the Cloudflare Agents middleware\n */\ntype AgentMiddlewareContext<E extends Env> = {\n /** Cloudflare Agents-specific configuration options */\n options?: AgentOptions<E>;\n /** Optional error handler for caught errors */\n onError?: (error: Error) => void;\n};\n\n/**\n * Creates a middleware for handling Cloudflare Agents WebSocket and HTTP requests\n * Processes both WebSocket upgrades and standard HTTP requests, delegating them to Cloudflare Agents\n */\nexport function agentsMiddleware<E extends Env = Env>(\n ctx?: AgentMiddlewareContext<E>\n) {\n return createMiddleware<Env>(async (c, next) => {\n try {\n const handler = isWebSocketUpgrade(c)\n ? handleWebSocketUpgrade\n : handleHttpRequest;\n\n const response = await handler(c, ctx?.options);\n\n return response === null ? await next() : response;\n } catch (error) {\n if (ctx?.onError) {\n ctx.onError(error as Error);\n return next();\n }\n throw error;\n }\n });\n}\n\n/**\n * Checks if the incoming request is a WebSocket upgrade request\n * Looks for the 'upgrade' header with a value of 'websocket' (case-insensitive)\n */\nfunction isWebSocketUpgrade(c: Context): boolean {\n return c.req.header(\"upgrade\")?.toLowerCase() === \"websocket\";\n}\n\n/**\n * Handles WebSocket upgrade requests\n * Returns a WebSocket upgrade response if successful, null otherwise\n */\nasync function handleWebSocketUpgrade<E extends Env>(\n c: Context<E>,\n options?: AgentOptions<E>\n) {\n const response = await routeAgentRequest(\n c.req.raw,\n env(c) satisfies Env,\n options\n );\n\n if (!response?.webSocket) {\n return null;\n }\n\n return new Response(null, {\n status: 101,\n webSocket: response.webSocket\n });\n}\n\n/**\n * Handles standard HTTP requests\n * Forwards the request to Cloudflare Agents and returns the response\n */\nasync function handleHttpRequest<E extends Env>(\n c: Context<E>,\n options?: AgentOptions<E>\n) {\n return routeAgentRequest(c.req.raw, env(c) satisfies Env, options);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAQA,IAAI,YAA4B,8BAAc,OAAO,KAAK,IAAI;AAI9D,SAAS,aAAa,IAAI;AACzB,QAAO,EAAE,SAAS,IAAI;;AAEvB,IAAI,kBAAkB,MAAM;CAC3B,cAAc;AACb,OAAK,SAAS,EAAE;;CAEjB,IAAI,GAAG;AACN,OAAK,OAAO,KAAK,EAAE;AACnB,SAAO;;CAER,UAAU;AACT,SAAO,KAAK,OAAO,OAAQ,KAAI;AAC9B,QAAK,OAAO,KAAK,CAAC,SAAS;UACpB;;;AAGV,IAAI,UAAU,MAAM;CACnB,cAAc;AACb,OAAK,6BAA6B,IAAI,KAAK;AAC3C,OAAK,SAAS,aAAa;AAC1B,QAAK,WAAW,IAAI,SAAS;AAC7B,UAAO,mBAAmB,KAAK,WAAW,OAAO,SAAS,CAAC;;;CAG7D,KAAK,MAAM;AACV,OAAK,MAAM,YAAY,CAAC,GAAG,KAAK,WAAW,CAAE,KAAI;AAChD,YAAS,KAAK;WACN,KAAK;AACb,WAAQ,MAAM,2BAA2B,IA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K,IAAI,EAAE,EAAgB,QAAQ"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["Agent","env"],"sources":["../../agents/dist/ai-types-B3aQaFv3.js","../../agents/dist/client-BfiZ3HQd.js","../../agents/dist/client-CIvp_OWw.js","../../agents/dist/do-oauth-client-provider-CswoD5Lu.js","../../agents/dist/src-CTtjSFyX.js","../src/index.ts"],"sourcesContent":["//#region src/ai-types.ts\n/**\n* Enum for message types to improve type safety and maintainability\n*/\nlet MessageType = /* @__PURE__ */ function(MessageType$1) {\n\tMessageType$1[\"CF_AGENT_CHAT_MESSAGES\"] = \"cf_agent_chat_messages\";\n\tMessageType$1[\"CF_AGENT_USE_CHAT_REQUEST\"] = \"cf_agent_use_chat_request\";\n\tMessageType$1[\"CF_AGENT_USE_CHAT_RESPONSE\"] = \"cf_agent_use_chat_response\";\n\tMessageType$1[\"CF_AGENT_CHAT_CLEAR\"] = \"cf_agent_chat_clear\";\n\tMessageType$1[\"CF_AGENT_CHAT_REQUEST_CANCEL\"] = \"cf_agent_chat_request_cancel\";\n\tMessageType$1[\"CF_AGENT_MCP_SERVERS\"] = \"cf_agent_mcp_servers\";\n\tMessageType$1[\"CF_MCP_AGENT_EVENT\"] = \"cf_mcp_agent_event\";\n\tMessageType$1[\"CF_AGENT_STATE\"] = \"cf_agent_state\";\n\tMessageType$1[\"RPC\"] = \"rpc\";\n\treturn MessageType$1;\n}({});\n\n//#endregion\nexport { MessageType as t };\n//# sourceMappingURL=ai-types-B3aQaFv3.js.map","import { t as MessageType } from \"./ai-types-B3aQaFv3.js\";\nimport { PartySocket } from \"partysocket\";\n\n//#region src/client.ts\n/**\n* Convert a camelCase string to a kebab-case string\n* @param str The string to convert\n* @returns The kebab-case string\n*/\nfunction camelCaseToKebabCase(str) {\n\tif (str === str.toUpperCase() && str !== str.toLowerCase()) return str.toLowerCase().replace(/_/g, \"-\");\n\tlet kebabified = str.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n\tkebabified = kebabified.startsWith(\"-\") ? kebabified.slice(1) : kebabified;\n\treturn kebabified.replace(/_/g, \"-\").replace(/-$/, \"\");\n}\n/**\n* WebSocket client for connecting to an Agent\n*/\nvar AgentClient = class extends PartySocket {\n\t/**\n\t* @deprecated Use agentFetch instead\n\t*/\n\tstatic fetch(_opts) {\n\t\tthrow new Error(\"AgentClient.fetch is not implemented, use agentFetch instead\");\n\t}\n\tconstructor(options) {\n\t\tconst agentNamespace = camelCaseToKebabCase(options.agent);\n\t\tsuper({\n\t\t\tparty: agentNamespace,\n\t\t\tprefix: \"agents\",\n\t\t\troom: options.name || \"default\",\n\t\t\t...options\n\t\t});\n\t\tthis._pendingCalls = /* @__PURE__ */ new Map();\n\t\tthis.agent = agentNamespace;\n\t\tthis.name = options.name || \"default\";\n\t\tthis.options = options;\n\t\tthis.addEventListener(\"message\", (event) => {\n\t\t\tif (typeof event.data === \"string\") {\n\t\t\t\tlet parsedMessage;\n\t\t\t\ttry {\n\t\t\t\t\tparsedMessage = JSON.parse(event.data);\n\t\t\t\t} catch (_error) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (parsedMessage.type === MessageType.CF_AGENT_STATE) {\n\t\t\t\t\tthis.options.onStateUpdate?.(parsedMessage.state, \"server\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (parsedMessage.type === MessageType.RPC) {\n\t\t\t\t\tconst response = parsedMessage;\n\t\t\t\t\tconst pending = this._pendingCalls.get(response.id);\n\t\t\t\t\tif (!pending) return;\n\t\t\t\t\tif (!response.success) {\n\t\t\t\t\t\tpending.reject(new Error(response.error));\n\t\t\t\t\t\tthis._pendingCalls.delete(response.id);\n\t\t\t\t\t\tpending.stream?.onError?.(response.error);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (\"done\" in response) if (response.done) {\n\t\t\t\t\t\tpending.resolve(response.result);\n\t\t\t\t\t\tthis._pendingCalls.delete(response.id);\n\t\t\t\t\t\tpending.stream?.onDone?.(response.result);\n\t\t\t\t\t} else pending.stream?.onChunk?.(response.result);\n\t\t\t\t\telse {\n\t\t\t\t\t\tpending.resolve(response.result);\n\t\t\t\t\t\tthis._pendingCalls.delete(response.id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\tsetState(state) {\n\t\tthis.send(JSON.stringify({\n\t\t\tstate,\n\t\t\ttype: MessageType.CF_AGENT_STATE\n\t\t}));\n\t\tthis.options.onStateUpdate?.(state, \"client\");\n\t}\n\tasync call(method, args = [], streamOptions) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst id = Math.random().toString(36).slice(2);\n\t\t\tthis._pendingCalls.set(id, {\n\t\t\t\treject,\n\t\t\t\tresolve: (value) => resolve(value),\n\t\t\t\tstream: streamOptions,\n\t\t\t\ttype: null\n\t\t\t});\n\t\t\tconst request = {\n\t\t\t\targs,\n\t\t\t\tid,\n\t\t\t\tmethod,\n\t\t\t\ttype: MessageType.RPC\n\t\t\t};\n\t\t\tthis.send(JSON.stringify(request));\n\t\t});\n\t}\n};\n/**\n* Make an HTTP request to an Agent\n* @param opts Connection options\n* @param init Request initialization options\n* @returns Promise resolving to a Response\n*/\nfunction agentFetch(opts, init) {\n\tconst agentNamespace = camelCaseToKebabCase(opts.agent);\n\treturn PartySocket.fetch({\n\t\tparty: agentNamespace,\n\t\tprefix: \"agents\",\n\t\troom: opts.name || \"default\",\n\t\t...opts\n\t}, init);\n}\n\n//#endregion\nexport { agentFetch as n, camelCaseToKebabCase as r, AgentClient as t };\n//# sourceMappingURL=client-BfiZ3HQd.js.map","import { nanoid } from \"nanoid\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { ElicitRequestSchema, PromptListChangedNotificationSchema, ResourceListChangedNotificationSchema, ToolListChangedNotificationSchema } from \"@modelcontextprotocol/sdk/types.js\";\nimport { SSEClientTransport } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\n\n//#region src/core/events.ts\nfunction toDisposable(fn) {\n\treturn { dispose: fn };\n}\nvar DisposableStore = class {\n\tconstructor() {\n\t\tthis._items = [];\n\t}\n\tadd(d) {\n\t\tthis._items.push(d);\n\t\treturn d;\n\t}\n\tdispose() {\n\t\twhile (this._items.length) try {\n\t\t\tthis._items.pop().dispose();\n\t\t} catch {}\n\t}\n};\nvar Emitter = class {\n\tconstructor() {\n\t\tthis._listeners = /* @__PURE__ */ new Set();\n\t\tthis.event = (listener) => {\n\t\t\tthis._listeners.add(listener);\n\t\t\treturn toDisposable(() => this._listeners.delete(listener));\n\t\t};\n\t}\n\tfire(data) {\n\t\tfor (const listener of [...this._listeners]) try {\n\t\t\tlistener(data);\n\t\t} catch (err) {\n\t\t\tconsole.error(\"Emitter listener error:\", err);\n\t\t}\n\t}\n\tdispose() {\n\t\tthis._listeners.clear();\n\t}\n};\n\n//#endregion\n//#region src/mcp/errors.ts\nfunction toErrorMessage(error) {\n\treturn error instanceof Error ? error.message : String(error);\n}\nfunction isUnauthorized(error) {\n\tconst msg = toErrorMessage(error);\n\treturn msg.includes(\"Unauthorized\") || msg.includes(\"401\");\n}\nfunction isTransportNotImplemented(error) {\n\tconst msg = toErrorMessage(error);\n\treturn msg.includes(\"404\") || msg.includes(\"405\") || msg.includes(\"Not Implemented\") || msg.includes(\"not implemented\");\n}\n\n//#endregion\n//#region src/mcp/sse-edge.ts\nvar SSEEdgeClientTransport = class extends SSEClientTransport {\n\t/**\n\t* Creates a new EdgeSSEClientTransport, which overrides fetch to be compatible with the CF workers environment\n\t*/\n\tconstructor(url, options) {\n\t\tconst fetchOverride = async (fetchUrl, fetchInit = {}) => {\n\t\t\tconst headers = await this.authHeaders();\n\t\t\tconst workerOptions = {\n\t\t\t\t...fetchInit,\n\t\t\t\theaders: {\n\t\t\t\t\t...options.requestInit?.headers,\n\t\t\t\t\t...fetchInit?.headers,\n\t\t\t\t\t...headers\n\t\t\t\t}\n\t\t\t};\n\t\t\tdelete workerOptions.mode;\n\t\t\treturn options.eventSourceInit?.fetch?.(fetchUrl, workerOptions) || fetch(fetchUrl, workerOptions);\n\t\t};\n\t\tsuper(url, {\n\t\t\t...options,\n\t\t\teventSourceInit: {\n\t\t\t\t...options.eventSourceInit,\n\t\t\t\tfetch: fetchOverride\n\t\t\t}\n\t\t});\n\t\tthis.authProvider = options.authProvider;\n\t}\n\tasync authHeaders() {\n\t\tif (this.authProvider) {\n\t\t\tconst tokens = await this.authProvider.tokens();\n\t\t\tif (tokens) return { Authorization: `Bearer ${tokens.access_token}` };\n\t\t}\n\t}\n};\n\n//#endregion\n//#region src/mcp/streamable-http-edge.ts\nvar StreamableHTTPEdgeClientTransport = class extends StreamableHTTPClientTransport {\n\t/**\n\t* Creates a new StreamableHTTPEdgeClientTransport, which overrides fetch to be compatible with the CF workers environment\n\t*/\n\tconstructor(url, options) {\n\t\tconst fetchOverride = async (fetchUrl, fetchInit = {}) => {\n\t\t\tconst headers = await this.authHeaders();\n\t\t\tconst workerOptions = {\n\t\t\t\t...fetchInit,\n\t\t\t\theaders: {\n\t\t\t\t\t...options.requestInit?.headers,\n\t\t\t\t\t...fetchInit?.headers,\n\t\t\t\t\t...headers\n\t\t\t\t}\n\t\t\t};\n\t\t\tdelete workerOptions.mode;\n\t\t\treturn options.requestInit?.fetch?.(fetchUrl, workerOptions) || fetch(fetchUrl, workerOptions);\n\t\t};\n\t\tsuper(url, {\n\t\t\t...options,\n\t\t\trequestInit: {\n\t\t\t\t...options.requestInit,\n\t\t\t\tfetch: fetchOverride\n\t\t\t}\n\t\t});\n\t\tthis.authProvider = options.authProvider;\n\t}\n\tasync authHeaders() {\n\t\tif (this.authProvider) {\n\t\t\tconst tokens = await this.authProvider.tokens();\n\t\t\tif (tokens) return { Authorization: `Bearer ${tokens.access_token}` };\n\t\t}\n\t}\n};\n\n//#endregion\n//#region src/mcp/client-connection.ts\nvar MCPClientConnection = class {\n\tconstructor(url, info, options = {\n\t\tclient: {},\n\t\ttransport: {}\n\t}) {\n\t\tthis.url = url;\n\t\tthis.options = options;\n\t\tthis.connectionState = \"connecting\";\n\t\tthis.tools = [];\n\t\tthis.prompts = [];\n\t\tthis.resources = [];\n\t\tthis.resourceTemplates = [];\n\t\tthis._onObservabilityEvent = new Emitter();\n\t\tthis.onObservabilityEvent = this._onObservabilityEvent.event;\n\t\tthis.client = new Client(info, {\n\t\t\t...options.client,\n\t\t\tcapabilities: {\n\t\t\t\t...options.client?.capabilities,\n\t\t\t\telicitation: {}\n\t\t\t}\n\t\t});\n\t}\n\t/**\n\t* Initialize a client connection\n\t*\n\t* @returns\n\t*/\n\tasync init() {\n\t\tconst transportType = this.options.transport.type;\n\t\tif (!transportType) throw new Error(\"Transport type must be specified\");\n\t\ttry {\n\t\t\tawait this.tryConnect(transportType);\n\t\t} catch (e) {\n\t\t\tif (isUnauthorized(e)) {\n\t\t\t\tthis.connectionState = \"authenticating\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\ttype: \"mcp:client:connect\",\n\t\t\t\tdisplayMessage: `Connection initialization failed for ${this.url.toString()}`,\n\t\t\t\tpayload: {\n\t\t\t\t\turl: this.url.toString(),\n\t\t\t\t\ttransport: transportType,\n\t\t\t\t\tstate: this.connectionState,\n\t\t\t\t\terror: toErrorMessage(e)\n\t\t\t\t},\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tid: nanoid()\n\t\t\t});\n\t\t\tthis.connectionState = \"failed\";\n\t\t\treturn;\n\t\t}\n\t\tawait this.discoverAndRegister();\n\t}\n\t/**\n\t* Finish OAuth by probing transports based on configured type.\n\t* - Explicit: finish on that transport\n\t* - Auto: try streamable-http, then sse on 404/405/Not Implemented\n\t*/\n\tasync finishAuthProbe(code) {\n\t\tif (!this.options.transport.authProvider) throw new Error(\"No auth provider configured\");\n\t\tconst configuredType = this.options.transport.type;\n\t\tif (!configuredType) throw new Error(\"Transport type must be specified\");\n\t\tconst finishAuth = async (base) => {\n\t\t\tawait this.getTransport(base).finishAuth(code);\n\t\t};\n\t\tif (configuredType === \"sse\" || configuredType === \"streamable-http\") {\n\t\t\tawait finishAuth(configuredType);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tawait finishAuth(\"streamable-http\");\n\t\t} catch (e) {\n\t\t\tif (isTransportNotImplemented(e)) {\n\t\t\t\tawait finishAuth(\"sse\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\t}\n\t/**\n\t* Complete OAuth authorization\n\t*/\n\tasync completeAuthorization(code) {\n\t\tif (this.connectionState !== \"authenticating\") throw new Error(\"Connection must be in authenticating state to complete authorization\");\n\t\ttry {\n\t\t\tawait this.finishAuthProbe(code);\n\t\t\tthis.connectionState = \"connecting\";\n\t\t} catch (error) {\n\t\t\tthis.connectionState = \"failed\";\n\t\t\tthrow error;\n\t\t}\n\t}\n\t/**\n\t* Establish connection after successful authorization\n\t*/\n\tasync establishConnection() {\n\t\tif (this.connectionState !== \"connecting\") throw new Error(\"Connection must be in connecting state to establish connection\");\n\t\ttry {\n\t\t\tconst transportType = this.options.transport.type;\n\t\t\tif (!transportType) throw new Error(\"Transport type must be specified\");\n\t\t\tawait this.tryConnect(transportType);\n\t\t\tawait this.discoverAndRegister();\n\t\t} catch (error) {\n\t\t\tthis.connectionState = \"failed\";\n\t\t\tthrow error;\n\t\t}\n\t}\n\t/**\n\t* Discover server capabilities and register tools, resources, prompts, and templates\n\t*/\n\tasync discoverAndRegister() {\n\t\tthis.connectionState = \"discovering\";\n\t\tthis.serverCapabilities = this.client.getServerCapabilities();\n\t\tif (!this.serverCapabilities) throw new Error(\"The MCP Server failed to return server capabilities\");\n\t\tconst [instructionsResult, toolsResult, resourcesResult, promptsResult, resourceTemplatesResult] = await Promise.allSettled([\n\t\t\tthis.client.getInstructions(),\n\t\t\tthis.registerTools(),\n\t\t\tthis.registerResources(),\n\t\t\tthis.registerPrompts(),\n\t\t\tthis.registerResourceTemplates()\n\t\t]);\n\t\tconst operations = [\n\t\t\t{\n\t\t\t\tname: \"instructions\",\n\t\t\t\tresult: instructionsResult\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"tools\",\n\t\t\t\tresult: toolsResult\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"resources\",\n\t\t\t\tresult: resourcesResult\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"prompts\",\n\t\t\t\tresult: promptsResult\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"resource templates\",\n\t\t\t\tresult: resourceTemplatesResult\n\t\t\t}\n\t\t];\n\t\tfor (const { name, result } of operations) if (result.status === \"rejected\") {\n\t\t\tconst url = this.url.toString();\n\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\ttype: \"mcp:client:discover\",\n\t\t\t\tdisplayMessage: `Failed to discover ${name} for ${url}`,\n\t\t\t\tpayload: {\n\t\t\t\t\turl,\n\t\t\t\t\tcapability: name,\n\t\t\t\t\terror: result.reason\n\t\t\t\t},\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tid: nanoid()\n\t\t\t});\n\t\t}\n\t\tthis.instructions = instructionsResult.status === \"fulfilled\" ? instructionsResult.value : void 0;\n\t\tthis.tools = toolsResult.status === \"fulfilled\" ? toolsResult.value : [];\n\t\tthis.resources = resourcesResult.status === \"fulfilled\" ? resourcesResult.value : [];\n\t\tthis.prompts = promptsResult.status === \"fulfilled\" ? promptsResult.value : [];\n\t\tthis.resourceTemplates = resourceTemplatesResult.status === \"fulfilled\" ? resourceTemplatesResult.value : [];\n\t\tthis.connectionState = \"ready\";\n\t}\n\t/**\n\t* Notification handler registration\n\t*/\n\tasync registerTools() {\n\t\tif (!this.serverCapabilities || !this.serverCapabilities.tools) return [];\n\t\tif (this.serverCapabilities.tools.listChanged) this.client.setNotificationHandler(ToolListChangedNotificationSchema, async (_notification) => {\n\t\t\tthis.tools = await this.fetchTools();\n\t\t});\n\t\treturn this.fetchTools();\n\t}\n\tasync registerResources() {\n\t\tif (!this.serverCapabilities || !this.serverCapabilities.resources) return [];\n\t\tif (this.serverCapabilities.resources.listChanged) this.client.setNotificationHandler(ResourceListChangedNotificationSchema, async (_notification) => {\n\t\t\tthis.resources = await this.fetchResources();\n\t\t});\n\t\treturn this.fetchResources();\n\t}\n\tasync registerPrompts() {\n\t\tif (!this.serverCapabilities || !this.serverCapabilities.prompts) return [];\n\t\tif (this.serverCapabilities.prompts.listChanged) this.client.setNotificationHandler(PromptListChangedNotificationSchema, async (_notification) => {\n\t\t\tthis.prompts = await this.fetchPrompts();\n\t\t});\n\t\treturn this.fetchPrompts();\n\t}\n\tasync registerResourceTemplates() {\n\t\tif (!this.serverCapabilities || !this.serverCapabilities.resources) return [];\n\t\treturn this.fetchResourceTemplates();\n\t}\n\tasync fetchTools() {\n\t\tlet toolsAgg = [];\n\t\tlet toolsResult = { tools: [] };\n\t\tdo {\n\t\t\ttoolsResult = await this.client.listTools({ cursor: toolsResult.nextCursor }).catch(this._capabilityErrorHandler({ tools: [] }, \"tools/list\"));\n\t\t\ttoolsAgg = toolsAgg.concat(toolsResult.tools);\n\t\t} while (toolsResult.nextCursor);\n\t\treturn toolsAgg;\n\t}\n\tasync fetchResources() {\n\t\tlet resourcesAgg = [];\n\t\tlet resourcesResult = { resources: [] };\n\t\tdo {\n\t\t\tresourcesResult = await this.client.listResources({ cursor: resourcesResult.nextCursor }).catch(this._capabilityErrorHandler({ resources: [] }, \"resources/list\"));\n\t\t\tresourcesAgg = resourcesAgg.concat(resourcesResult.resources);\n\t\t} while (resourcesResult.nextCursor);\n\t\treturn resourcesAgg;\n\t}\n\tasync fetchPrompts() {\n\t\tlet promptsAgg = [];\n\t\tlet promptsResult = { prompts: [] };\n\t\tdo {\n\t\t\tpromptsResult = await this.client.listPrompts({ cursor: promptsResult.nextCursor }).catch(this._capabilityErrorHandler({ prompts: [] }, \"prompts/list\"));\n\t\t\tpromptsAgg = promptsAgg.concat(promptsResult.prompts);\n\t\t} while (promptsResult.nextCursor);\n\t\treturn promptsAgg;\n\t}\n\tasync fetchResourceTemplates() {\n\t\tlet templatesAgg = [];\n\t\tlet templatesResult = { resourceTemplates: [] };\n\t\tdo {\n\t\t\ttemplatesResult = await this.client.listResourceTemplates({ cursor: templatesResult.nextCursor }).catch(this._capabilityErrorHandler({ resourceTemplates: [] }, \"resources/templates/list\"));\n\t\t\ttemplatesAgg = templatesAgg.concat(templatesResult.resourceTemplates);\n\t\t} while (templatesResult.nextCursor);\n\t\treturn templatesAgg;\n\t}\n\t/**\n\t* Handle elicitation request from server\n\t* Automatically uses the Agent's built-in elicitation handling if available\n\t*/\n\tasync handleElicitationRequest(_request) {\n\t\tthrow new Error(\"Elicitation handler must be implemented for your platform. Override handleElicitationRequest method.\");\n\t}\n\t/**\n\t* Get the transport for the client\n\t* @param transportType - The transport type to get\n\t* @returns The transport for the client\n\t*/\n\tgetTransport(transportType) {\n\t\tswitch (transportType) {\n\t\t\tcase \"streamable-http\": return new StreamableHTTPEdgeClientTransport(this.url, this.options.transport);\n\t\t\tcase \"sse\": return new SSEEdgeClientTransport(this.url, this.options.transport);\n\t\t\tdefault: throw new Error(`Unsupported transport type: ${transportType}`);\n\t\t}\n\t}\n\tasync tryConnect(transportType) {\n\t\tconst transports = transportType === \"auto\" ? [\"streamable-http\", \"sse\"] : [transportType];\n\t\tfor (const currentTransportType of transports) {\n\t\t\tconst isLastTransport = currentTransportType === transports[transports.length - 1];\n\t\t\tconst hasFallback = transportType === \"auto\" && currentTransportType === \"streamable-http\" && !isLastTransport;\n\t\t\tconst transport = this.getTransport(currentTransportType);\n\t\t\ttry {\n\t\t\t\tawait this.client.connect(transport);\n\t\t\t\tthis.lastConnectedTransport = currentTransportType;\n\t\t\t\tconst url = this.url.toString();\n\t\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\t\ttype: \"mcp:client:connect\",\n\t\t\t\t\tdisplayMessage: `Connected successfully using ${currentTransportType} transport for ${url}`,\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\turl,\n\t\t\t\t\t\ttransport: currentTransportType,\n\t\t\t\t\t\tstate: this.connectionState\n\t\t\t\t\t},\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\tid: nanoid()\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t} catch (e) {\n\t\t\t\tconst error = e instanceof Error ? e : new Error(String(e));\n\t\t\t\tif (isUnauthorized(error)) throw e;\n\t\t\t\tif (hasFallback && isTransportNotImplemented(error)) {\n\t\t\t\t\tconst url = this.url.toString();\n\t\t\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\t\t\ttype: \"mcp:client:connect\",\n\t\t\t\t\t\tdisplayMessage: `${currentTransportType} transport not available, trying ${transports[transports.indexOf(currentTransportType) + 1]} for ${url}`,\n\t\t\t\t\t\tpayload: {\n\t\t\t\t\t\t\turl,\n\t\t\t\t\t\t\ttransport: currentTransportType,\n\t\t\t\t\t\t\tstate: this.connectionState\n\t\t\t\t\t\t},\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\tid: nanoid()\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t\tthis.client.setRequestHandler(ElicitRequestSchema, async (request) => {\n\t\t\treturn await this.handleElicitationRequest(request);\n\t\t});\n\t}\n\t_capabilityErrorHandler(empty, method) {\n\t\treturn (e) => {\n\t\t\tif (e.code === -32601) {\n\t\t\t\tconst url = this.url.toString();\n\t\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\t\ttype: \"mcp:client:discover\",\n\t\t\t\t\tdisplayMessage: `The server advertised support for the capability ${method.split(\"/\")[0]}, but returned \"Method not found\" for '${method}' for ${url}`,\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\turl,\n\t\t\t\t\t\tcapability: method.split(\"/\")[0],\n\t\t\t\t\t\terror: toErrorMessage(e)\n\t\t\t\t\t},\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\tid: nanoid()\n\t\t\t\t});\n\t\t\t\treturn empty;\n\t\t\t}\n\t\t\tthrow e;\n\t\t};\n\t}\n};\n\n//#endregion\n//#region src/mcp/client.ts\n/**\n* Utility class that aggregates multiple MCP clients into one\n*/\nvar MCPClientManager = class {\n\t/**\n\t* @param _name Name of the MCP client\n\t* @param _version Version of the MCP Client\n\t* @param auth Auth paramters if being used to create a DurableObjectOAuthClientProvider\n\t*/\n\tconstructor(_name, _version) {\n\t\tthis._name = _name;\n\t\tthis._version = _version;\n\t\tthis.mcpConnections = {};\n\t\tthis._callbackUrls = [];\n\t\tthis._didWarnAboutUnstableGetAITools = false;\n\t\tthis._connectionDisposables = /* @__PURE__ */ new Map();\n\t\tthis._onObservabilityEvent = new Emitter();\n\t\tthis.onObservabilityEvent = this._onObservabilityEvent.event;\n\t\tthis._onConnected = new Emitter();\n\t\tthis.onConnected = this._onConnected.event;\n\t}\n\t/**\n\t* Connect to and register an MCP server\n\t*\n\t* @param transportConfig Transport config\n\t* @param clientConfig Client config\n\t* @param capabilities Client capabilities (i.e. if the client supports roots/sampling)\n\t*/\n\tasync connect(url, options = {}) {\n\t\t/**\n\t\t* We need to delay loading ai sdk, because putting it in module scope is\n\t\t* causing issues with startup time.\n\t\t* The only place it's used is in getAITools, which only matters after\n\t\t* .connect() is called on at least one server.\n\t\t* So it's safe to delay loading it until .connect() is called.\n\t\t*/\n\t\tif (!this.jsonSchema) {\n\t\t\tconst { jsonSchema } = await import(\"ai\");\n\t\t\tthis.jsonSchema = jsonSchema;\n\t\t}\n\t\tconst id = options.reconnect?.id ?? nanoid(8);\n\t\tif (options.transport?.authProvider) {\n\t\t\toptions.transport.authProvider.serverId = id;\n\t\t\tif (options.reconnect?.oauthClientId) options.transport.authProvider.clientId = options.reconnect?.oauthClientId;\n\t\t}\n\t\tif (!options.reconnect?.oauthCode || !this.mcpConnections[id]) {\n\t\t\tconst normalizedTransport = {\n\t\t\t\t...options.transport,\n\t\t\t\ttype: options.transport?.type ?? \"auto\"\n\t\t\t};\n\t\t\tthis.mcpConnections[id] = new MCPClientConnection(new URL(url), {\n\t\t\t\tname: this._name,\n\t\t\t\tversion: this._version\n\t\t\t}, {\n\t\t\t\tclient: options.client ?? {},\n\t\t\t\ttransport: normalizedTransport\n\t\t\t});\n\t\t\tconst store = new DisposableStore();\n\t\t\tconst existing = this._connectionDisposables.get(id);\n\t\t\tif (existing) existing.dispose();\n\t\t\tthis._connectionDisposables.set(id, store);\n\t\t\tstore.add(this.mcpConnections[id].onObservabilityEvent((event) => {\n\t\t\t\tthis._onObservabilityEvent.fire(event);\n\t\t\t}));\n\t\t}\n\t\tawait this.mcpConnections[id].init();\n\t\tif (options.reconnect?.oauthCode) try {\n\t\t\tawait this.mcpConnections[id].completeAuthorization(options.reconnect.oauthCode);\n\t\t\tawait this.mcpConnections[id].establishConnection();\n\t\t} catch (error) {\n\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\ttype: \"mcp:client:connect\",\n\t\t\t\tdisplayMessage: `Failed to complete OAuth reconnection for ${id} for ${url}`,\n\t\t\t\tpayload: {\n\t\t\t\t\turl,\n\t\t\t\t\ttransport: options.transport?.type ?? \"auto\",\n\t\t\t\t\tstate: this.mcpConnections[id].connectionState,\n\t\t\t\t\terror: toErrorMessage(error)\n\t\t\t\t},\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tid\n\t\t\t});\n\t\t\tthrow error;\n\t\t}\n\t\tconst authUrl = options.transport?.authProvider?.authUrl;\n\t\tif (this.mcpConnections[id].connectionState === \"authenticating\" && authUrl && options.transport?.authProvider?.redirectUrl) {\n\t\t\tthis._callbackUrls.push(options.transport.authProvider.redirectUrl.toString());\n\t\t\treturn {\n\t\t\t\tauthUrl,\n\t\t\t\tclientId: options.transport?.authProvider?.clientId,\n\t\t\t\tid\n\t\t\t};\n\t\t}\n\t\treturn { id };\n\t}\n\tisCallbackRequest(req) {\n\t\treturn req.method === \"GET\" && !!this._callbackUrls.find((url) => {\n\t\t\treturn req.url.startsWith(url);\n\t\t});\n\t}\n\tasync handleCallbackRequest(req) {\n\t\tconst url = new URL(req.url);\n\t\tconst urlMatch = this._callbackUrls.find((url$1) => {\n\t\t\treturn req.url.startsWith(url$1);\n\t\t});\n\t\tif (!urlMatch) throw new Error(`No callback URI match found for the request url: ${req.url}. Was the request matched with \\`isCallbackRequest()\\`?`);\n\t\tconst code = url.searchParams.get(\"code\");\n\t\tconst state = url.searchParams.get(\"state\");\n\t\tconst urlParams = urlMatch.split(\"/\");\n\t\tconst serverId = urlParams[urlParams.length - 1];\n\t\tif (!code) throw new Error(\"Unauthorized: no code provided\");\n\t\tif (!state) throw new Error(\"Unauthorized: no state provided\");\n\t\tif (this.mcpConnections[serverId] === void 0) throw new Error(`Could not find serverId: ${serverId}`);\n\t\tif (this.mcpConnections[serverId].connectionState !== \"authenticating\") throw new Error(\"Failed to authenticate: the client isn't in the `authenticating` state\");\n\t\tconst conn = this.mcpConnections[serverId];\n\t\tif (!conn.options.transport.authProvider) throw new Error(\"Trying to finalize authentication for a server connection without an authProvider\");\n\t\tconst clientId = conn.options.transport.authProvider.clientId || state;\n\t\tconn.options.transport.authProvider.clientId = clientId;\n\t\tconn.options.transport.authProvider.serverId = serverId;\n\t\ttry {\n\t\t\tawait conn.completeAuthorization(code);\n\t\t\treturn {\n\t\t\t\tserverId,\n\t\t\t\tauthSuccess: true\n\t\t\t};\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tserverId,\n\t\t\t\tauthSuccess: false,\n\t\t\t\tauthError: error instanceof Error ? error.message : String(error)\n\t\t\t};\n\t\t}\n\t}\n\t/**\n\t* Establish connection in the background after OAuth completion\n\t* This method is called asynchronously and doesn't block the OAuth callback response\n\t* @param serverId The server ID to establish connection for\n\t*/\n\tasync establishConnection(serverId) {\n\t\tconst conn = this.mcpConnections[serverId];\n\t\tif (!conn) {\n\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\ttype: \"mcp:client:preconnect\",\n\t\t\t\tdisplayMessage: `Connection not found for serverId: ${serverId}`,\n\t\t\t\tpayload: { serverId },\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tid: nanoid()\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tawait conn.establishConnection();\n\t\t\tthis._onConnected.fire(serverId);\n\t\t} catch (error) {\n\t\t\tconst url = conn.url.toString();\n\t\t\tthis._onObservabilityEvent.fire({\n\t\t\t\ttype: \"mcp:client:connect\",\n\t\t\t\tdisplayMessage: `Failed to establish connection to server ${serverId} with url ${url}`,\n\t\t\t\tpayload: {\n\t\t\t\t\turl,\n\t\t\t\t\ttransport: conn.options.transport.type ?? \"auto\",\n\t\t\t\t\tstate: conn.connectionState,\n\t\t\t\t\terror: toErrorMessage(error)\n\t\t\t\t},\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t\tid: nanoid()\n\t\t\t});\n\t\t}\n\t}\n\t/**\n\t* Register a callback URL for OAuth handling\n\t* @param url The callback URL to register\n\t*/\n\tregisterCallbackUrl(url) {\n\t\tif (!this._callbackUrls.includes(url)) this._callbackUrls.push(url);\n\t}\n\t/**\n\t* Unregister a callback URL\n\t* @param serverId The server ID whose callback URL should be removed\n\t*/\n\tunregisterCallbackUrl(serverId) {\n\t\tthis._callbackUrls = this._callbackUrls.filter((url) => !url.endsWith(`/${serverId}`));\n\t}\n\t/**\n\t* Configure OAuth callback handling\n\t* @param config OAuth callback configuration\n\t*/\n\tconfigureOAuthCallback(config) {\n\t\tthis._oauthCallbackConfig = config;\n\t}\n\t/**\n\t* Get the current OAuth callback configuration\n\t* @returns The current OAuth callback configuration\n\t*/\n\tgetOAuthCallbackConfig() {\n\t\treturn this._oauthCallbackConfig;\n\t}\n\t/**\n\t* @returns namespaced list of tools\n\t*/\n\tlistTools() {\n\t\treturn getNamespacedData(this.mcpConnections, \"tools\");\n\t}\n\t/**\n\t* @returns a set of tools that you can use with the AI SDK\n\t*/\n\tgetAITools() {\n\t\treturn Object.fromEntries(getNamespacedData(this.mcpConnections, \"tools\").map((tool) => {\n\t\t\treturn [`tool_${tool.serverId.replace(/-/g, \"\")}_${tool.name}`, {\n\t\t\t\tdescription: tool.description,\n\t\t\t\texecute: async (args) => {\n\t\t\t\t\tconst result = await this.callTool({\n\t\t\t\t\t\targuments: args,\n\t\t\t\t\t\tname: tool.name,\n\t\t\t\t\t\tserverId: tool.serverId\n\t\t\t\t\t});\n\t\t\t\t\tif (result.isError) throw new Error(result.content[0].text);\n\t\t\t\t\treturn result;\n\t\t\t\t},\n\t\t\t\tinputSchema: this.jsonSchema(tool.inputSchema),\n\t\t\t\toutputSchema: tool.outputSchema ? this.jsonSchema(tool.outputSchema) : void 0\n\t\t\t}];\n\t\t}));\n\t}\n\t/**\n\t* @deprecated this has been renamed to getAITools(), and unstable_getAITools will be removed in the next major version\n\t* @returns a set of tools that you can use with the AI SDK\n\t*/\n\tunstable_getAITools() {\n\t\tif (!this._didWarnAboutUnstableGetAITools) {\n\t\t\tthis._didWarnAboutUnstableGetAITools = true;\n\t\t\tconsole.warn(\"unstable_getAITools is deprecated, use getAITools instead. unstable_getAITools will be removed in the next major version.\");\n\t\t}\n\t\treturn this.getAITools();\n\t}\n\t/**\n\t* Closes all connections to MCP servers\n\t*/\n\tasync closeAllConnections() {\n\t\tconst ids = Object.keys(this.mcpConnections);\n\t\tawait Promise.all(ids.map(async (id) => {\n\t\t\tawait this.mcpConnections[id].client.close();\n\t\t}));\n\t\tfor (const id of ids) {\n\t\t\tconst store = this._connectionDisposables.get(id);\n\t\t\tif (store) store.dispose();\n\t\t\tthis._connectionDisposables.delete(id);\n\t\t\tdelete this.mcpConnections[id];\n\t\t}\n\t}\n\t/**\n\t* Closes a connection to an MCP server\n\t* @param id The id of the connection to close\n\t*/\n\tasync closeConnection(id) {\n\t\tif (!this.mcpConnections[id]) throw new Error(`Connection with id \"${id}\" does not exist.`);\n\t\tawait this.mcpConnections[id].client.close();\n\t\tdelete this.mcpConnections[id];\n\t\tconst store = this._connectionDisposables.get(id);\n\t\tif (store) store.dispose();\n\t\tthis._connectionDisposables.delete(id);\n\t}\n\t/**\n\t* Dispose the manager and all resources.\n\t*/\n\tasync dispose() {\n\t\ttry {\n\t\t\tawait this.closeAllConnections();\n\t\t} finally {\n\t\t\tthis._onConnected.dispose();\n\t\t\tthis._onObservabilityEvent.dispose();\n\t\t}\n\t}\n\t/**\n\t* @returns namespaced list of prompts\n\t*/\n\tlistPrompts() {\n\t\treturn getNamespacedData(this.mcpConnections, \"prompts\");\n\t}\n\t/**\n\t* @returns namespaced list of tools\n\t*/\n\tlistResources() {\n\t\treturn getNamespacedData(this.mcpConnections, \"resources\");\n\t}\n\t/**\n\t* @returns namespaced list of resource templates\n\t*/\n\tlistResourceTemplates() {\n\t\treturn getNamespacedData(this.mcpConnections, \"resourceTemplates\");\n\t}\n\t/**\n\t* Namespaced version of callTool\n\t*/\n\tasync callTool(params, resultSchema, options) {\n\t\tconst unqualifiedName = params.name.replace(`${params.serverId}.`, \"\");\n\t\treturn this.mcpConnections[params.serverId].client.callTool({\n\t\t\t...params,\n\t\t\tname: unqualifiedName\n\t\t}, resultSchema, options);\n\t}\n\t/**\n\t* Namespaced version of readResource\n\t*/\n\treadResource(params, options) {\n\t\treturn this.mcpConnections[params.serverId].client.readResource(params, options);\n\t}\n\t/**\n\t* Namespaced version of getPrompt\n\t*/\n\tgetPrompt(params, options) {\n\t\treturn this.mcpConnections[params.serverId].client.getPrompt(params, options);\n\t}\n};\nfunction getNamespacedData(mcpClients, type) {\n\treturn Object.entries(mcpClients).map(([name, conn]) => {\n\t\treturn {\n\t\t\tdata: conn[type],\n\t\t\tname\n\t\t};\n\t}).flatMap(({ name: serverId, data }) => {\n\t\treturn data.map((item) => {\n\t\t\treturn {\n\t\t\t\t...item,\n\t\t\t\tserverId\n\t\t\t};\n\t\t});\n\t});\n}\n\n//#endregion\nexport { DisposableStore as a, SSEEdgeClientTransport as i, getNamespacedData as n, StreamableHTTPEdgeClientTransport as r, MCPClientManager as t };\n//# sourceMappingURL=client-CIvp_OWw.js.map","import { nanoid } from \"nanoid\";\n\n//#region src/mcp/do-oauth-client-provider.ts\nvar DurableObjectOAuthClientProvider = class {\n\tconstructor(storage, clientName, baseRedirectUrl) {\n\t\tthis.storage = storage;\n\t\tthis.clientName = clientName;\n\t\tthis.baseRedirectUrl = baseRedirectUrl;\n\t}\n\tget clientMetadata() {\n\t\treturn {\n\t\t\tclient_name: this.clientName,\n\t\t\tclient_uri: this.clientUri,\n\t\t\tgrant_types: [\"authorization_code\", \"refresh_token\"],\n\t\t\tredirect_uris: [this.redirectUrl],\n\t\t\tresponse_types: [\"code\"],\n\t\t\ttoken_endpoint_auth_method: \"none\"\n\t\t};\n\t}\n\tget clientUri() {\n\t\treturn new URL(this.redirectUrl).origin;\n\t}\n\tget redirectUrl() {\n\t\treturn `${this.baseRedirectUrl}/${this.serverId}`;\n\t}\n\tget clientId() {\n\t\tif (!this._clientId_) throw new Error(\"Trying to access clientId before it was set\");\n\t\treturn this._clientId_;\n\t}\n\tset clientId(clientId_) {\n\t\tthis._clientId_ = clientId_;\n\t}\n\tget serverId() {\n\t\tif (!this._serverId_) throw new Error(\"Trying to access serverId before it was set\");\n\t\treturn this._serverId_;\n\t}\n\tset serverId(serverId_) {\n\t\tthis._serverId_ = serverId_;\n\t}\n\tkeyPrefix(clientId) {\n\t\treturn `/${this.clientName}/${this.serverId}/${clientId}`;\n\t}\n\tclientInfoKey(clientId) {\n\t\treturn `${this.keyPrefix(clientId)}/client_info/`;\n\t}\n\tasync clientInformation() {\n\t\tif (!this._clientId_) return;\n\t\treturn await this.storage.get(this.clientInfoKey(this.clientId)) ?? void 0;\n\t}\n\tasync saveClientInformation(clientInformation) {\n\t\tawait this.storage.put(this.clientInfoKey(clientInformation.client_id), clientInformation);\n\t\tthis.clientId = clientInformation.client_id;\n\t}\n\ttokenKey(clientId) {\n\t\treturn `${this.keyPrefix(clientId)}/token`;\n\t}\n\tasync tokens() {\n\t\tif (!this._clientId_) return;\n\t\treturn await this.storage.get(this.tokenKey(this.clientId)) ?? void 0;\n\t}\n\tasync saveTokens(tokens) {\n\t\tawait this.storage.put(this.tokenKey(this.clientId), tokens);\n\t}\n\tget authUrl() {\n\t\treturn this._authUrl_;\n\t}\n\t/**\n\t* Because this operates on the server side (but we need browser auth), we send this url back to the user\n\t* and require user interact to initiate the redirect flow\n\t*/\n\tasync redirectToAuthorization(authUrl) {\n\t\tconst stateToken = nanoid();\n\t\tauthUrl.searchParams.set(\"state\", stateToken);\n\t\tthis._authUrl_ = authUrl.toString();\n\t}\n\tcodeVerifierKey(clientId) {\n\t\treturn `${this.keyPrefix(clientId)}/code_verifier`;\n\t}\n\tasync saveCodeVerifier(verifier) {\n\t\tconst key = this.codeVerifierKey(this.clientId);\n\t\tif (await this.storage.get(key)) return;\n\t\tawait this.storage.put(key, verifier);\n\t}\n\tasync codeVerifier() {\n\t\tconst codeVerifier = await this.storage.get(this.codeVerifierKey(this.clientId));\n\t\tif (!codeVerifier) throw new Error(\"No code verifier found\");\n\t\treturn codeVerifier;\n\t}\n};\n\n//#endregion\nexport { DurableObjectOAuthClientProvider as t };\n//# sourceMappingURL=do-oauth-client-provider-CswoD5Lu.js.map","import { t as MessageType } from \"./ai-types-B3aQaFv3.js\";\nimport { r as camelCaseToKebabCase } from \"./client-BfiZ3HQd.js\";\nimport { a as DisposableStore, t as MCPClientManager } from \"./client-CIvp_OWw.js\";\nimport { t as DurableObjectOAuthClientProvider } from \"./do-oauth-client-provider-CswoD5Lu.js\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { parseCronExpression } from \"cron-schedule\";\nimport { nanoid } from \"nanoid\";\nimport { EmailMessage } from \"cloudflare:email\";\nimport { Server, getServerByName, routePartykitRequest } from \"partyserver\";\n\n//#region src/observability/index.ts\n/**\n* A generic observability implementation that logs events to the console.\n*/\nconst genericObservability = { emit(event) {\n\tif (isLocalMode()) {\n\t\tconsole.log(event.displayMessage);\n\t\treturn;\n\t}\n\tconsole.log(event);\n} };\nlet localMode = false;\nfunction isLocalMode() {\n\tif (localMode) return true;\n\tconst { request } = getCurrentAgent();\n\tif (!request) return false;\n\tlocalMode = new URL(request.url).hostname === \"localhost\";\n\treturn localMode;\n}\n\n//#endregion\n//#region src/index.ts\n/**\n* Type guard for RPC request messages\n*/\nfunction isRPCRequest(msg) {\n\treturn 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);\n}\n/**\n* Type guard for state update messages\n*/\nfunction isStateUpdateMessage(msg) {\n\treturn typeof msg === \"object\" && msg !== null && \"type\" in msg && msg.type === MessageType.CF_AGENT_STATE && \"state\" in msg;\n}\nconst callableMetadata = /* @__PURE__ */ new Map();\n/**\n* Decorator that marks a method as callable by clients\n* @param metadata Optional metadata about the callable method\n*/\nfunction callable(metadata = {}) {\n\treturn function callableDecorator(target, context) {\n\t\tif (!callableMetadata.has(target)) callableMetadata.set(target, metadata);\n\t\treturn target;\n\t};\n}\nlet didWarnAboutUnstableCallable = false;\n/**\n* Decorator that marks a method as callable by clients\n* @deprecated this has been renamed to callable, and unstable_callable will be removed in the next major version\n* @param metadata Optional metadata about the callable method\n*/\nconst unstable_callable = (metadata = {}) => {\n\tif (!didWarnAboutUnstableCallable) {\n\t\tdidWarnAboutUnstableCallable = true;\n\t\tconsole.warn(\"unstable_callable is deprecated, use callable instead. unstable_callable will be removed in the next major version.\");\n\t}\n\tcallable(metadata);\n};\nfunction getNextCronTime(cron) {\n\treturn parseCronExpression(cron).getNextDate();\n}\nconst STATE_ROW_ID = \"cf_state_row_id\";\nconst STATE_WAS_CHANGED = \"cf_state_was_changed\";\nconst DEFAULT_STATE = {};\nconst agentContext = new AsyncLocalStorage();\nfunction getCurrentAgent() {\n\tconst store = agentContext.getStore();\n\tif (!store) return {\n\t\tagent: void 0,\n\t\tconnection: void 0,\n\t\trequest: void 0,\n\t\temail: void 0\n\t};\n\treturn store;\n}\n/**\n* Wraps a method to run within the agent context, ensuring getCurrentAgent() works properly\n* @param agent The agent instance\n* @param method The method to wrap\n* @returns A wrapped method that runs within the agent context\n*/\nfunction withAgentContext(method) {\n\treturn function(...args) {\n\t\tconst { connection, request, email, agent } = getCurrentAgent();\n\t\tif (agent === this) return method.apply(this, args);\n\t\treturn agentContext.run({\n\t\t\tagent: this,\n\t\t\tconnection,\n\t\t\trequest,\n\t\t\temail\n\t\t}, () => {\n\t\t\treturn method.apply(this, args);\n\t\t});\n\t};\n}\n/**\n* Base class for creating Agent implementations\n* @template Env Environment type containing bindings\n* @template State State type to store within the Agent\n*/\nvar Agent = class Agent extends Server {\n\t/**\n\t* Current state of the Agent\n\t*/\n\tget state() {\n\t\tif (this._state !== DEFAULT_STATE) return this._state;\n\t\tconst wasChanged = this.sql`\n SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}\n `;\n\t\tconst result = this.sql`\n SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}\n `;\n\t\tif (wasChanged[0]?.state === \"true\" || result[0]?.state) {\n\t\t\tconst state = result[0]?.state;\n\t\t\tthis._state = JSON.parse(state);\n\t\t\treturn this._state;\n\t\t}\n\t\tif (this.initialState === DEFAULT_STATE) return;\n\t\tthis.setState(this.initialState);\n\t\treturn this.initialState;\n\t}\n\tstatic {\n\t\tthis.options = { hibernate: true };\n\t}\n\t/**\n\t* Execute SQL queries against the Agent's database\n\t* @template T Type of the returned rows\n\t* @param strings SQL query template strings\n\t* @param values Values to be inserted into the query\n\t* @returns Array of query results\n\t*/\n\tsql(strings, ...values) {\n\t\tlet query = \"\";\n\t\ttry {\n\t\t\tquery = strings.reduce((acc, str, i) => acc + str + (i < values.length ? \"?\" : \"\"), \"\");\n\t\t\treturn [...this.ctx.storage.sql.exec(query, ...values)];\n\t\t} catch (e) {\n\t\t\tconsole.error(`failed to execute sql query: ${query}`, e);\n\t\t\tthrow this.onError(e);\n\t\t}\n\t}\n\tconstructor(ctx, env) {\n\t\tsuper(ctx, env);\n\t\tthis._state = DEFAULT_STATE;\n\t\tthis._disposables = new DisposableStore();\n\t\tthis._ParentClass = Object.getPrototypeOf(this).constructor;\n\t\tthis.mcp = new MCPClientManager(this._ParentClass.name, \"0.0.1\");\n\t\tthis.initialState = DEFAULT_STATE;\n\t\tthis.observability = genericObservability;\n\t\tthis._flushingQueue = false;\n\t\tthis.alarm = async () => {\n\t\t\tconst now = Math.floor(Date.now() / 1e3);\n\t\t\tconst result = this.sql`\n SELECT * FROM cf_agents_schedules WHERE time <= ${now}\n `;\n\t\t\tif (result && Array.isArray(result)) for (const row of result) {\n\t\t\t\tconst callback = this[row.callback];\n\t\t\t\tif (!callback) {\n\t\t\t\t\tconsole.error(`callback ${row.callback} not found`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tawait agentContext.run({\n\t\t\t\t\tagent: this,\n\t\t\t\t\tconnection: void 0,\n\t\t\t\t\trequest: void 0,\n\t\t\t\t\temail: void 0\n\t\t\t\t}, async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tthis.observability?.emit({\n\t\t\t\t\t\t\tdisplayMessage: `Schedule ${row.id} executed`,\n\t\t\t\t\t\t\tid: nanoid(),\n\t\t\t\t\t\t\tpayload: {\n\t\t\t\t\t\t\t\tcallback: row.callback,\n\t\t\t\t\t\t\t\tid: row.id\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\t\ttype: \"schedule:execute\"\n\t\t\t\t\t\t}, this.ctx);\n\t\t\t\t\t\tawait callback.bind(this)(JSON.parse(row.payload), row);\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tconsole.error(`error executing callback \"${row.callback}\"`, e);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tif (row.type === \"cron\") {\n\t\t\t\t\tconst nextExecutionTime = getNextCronTime(row.cron);\n\t\t\t\t\tconst nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);\n\t\t\t\t\tthis.sql`\n UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}\n `;\n\t\t\t\t} else this.sql`\n DELETE FROM cf_agents_schedules WHERE id = ${row.id}\n `;\n\t\t\t}\n\t\t\tawait this._scheduleNextAlarm();\n\t\t};\n\t\tif (!wrappedClasses.has(this.constructor)) {\n\t\t\tthis._autoWrapCustomMethods();\n\t\t\twrappedClasses.add(this.constructor);\n\t\t}\n\t\tthis._disposables.add(this.mcp.onConnected(async () => {\n\t\t\tthis.broadcastMcpServers();\n\t\t}));\n\t\tthis._disposables.add(this.mcp.onObservabilityEvent((event) => {\n\t\t\tthis.observability?.emit(event);\n\t\t}));\n\t\tthis.sql`\n CREATE TABLE IF NOT EXISTS cf_agents_state (\n id TEXT PRIMARY KEY NOT NULL,\n state TEXT\n )\n `;\n\t\tthis.sql`\n CREATE TABLE IF NOT EXISTS cf_agents_queues (\n id TEXT PRIMARY KEY NOT NULL,\n payload TEXT,\n callback TEXT,\n created_at INTEGER DEFAULT (unixepoch())\n )\n `;\n\t\tthis.ctx.blockConcurrencyWhile(async () => {\n\t\t\treturn this._tryCatch(async () => {\n\t\t\t\tthis.sql`\n CREATE TABLE IF NOT EXISTS cf_agents_schedules (\n id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),\n callback TEXT,\n payload TEXT,\n type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),\n time INTEGER,\n delayInSeconds INTEGER,\n cron TEXT,\n created_at INTEGER DEFAULT (unixepoch())\n )\n `;\n\t\t\t\tawait this.alarm();\n\t\t\t});\n\t\t});\n\t\tthis.sql`\n CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (\n id TEXT PRIMARY KEY NOT NULL,\n name TEXT NOT NULL,\n server_url TEXT NOT NULL,\n callback_url TEXT NOT NULL,\n client_id TEXT,\n auth_url TEXT,\n server_options TEXT\n )\n `;\n\t\tconst _onRequest = this.onRequest.bind(this);\n\t\tthis.onRequest = (request) => {\n\t\t\treturn agentContext.run({\n\t\t\t\tagent: this,\n\t\t\t\tconnection: void 0,\n\t\t\t\trequest,\n\t\t\t\temail: void 0\n\t\t\t}, async () => {\n\t\t\t\tconst callbackResult = await this._handlePotentialOAuthCallback(request);\n\t\t\t\tif (callbackResult) return callbackResult;\n\t\t\t\treturn this._tryCatch(() => _onRequest(request));\n\t\t\t});\n\t\t};\n\t\tconst _onMessage = this.onMessage.bind(this);\n\t\tthis.onMessage = async (connection, message) => {\n\t\t\treturn agentContext.run({\n\t\t\t\tagent: this,\n\t\t\t\tconnection,\n\t\t\t\trequest: void 0,\n\t\t\t\temail: void 0\n\t\t\t}, async () => {\n\t\t\t\tif (typeof message !== \"string\") return this._tryCatch(() => _onMessage(connection, message));\n\t\t\t\tlet parsed;\n\t\t\t\ttry {\n\t\t\t\t\tparsed = JSON.parse(message);\n\t\t\t\t} catch (_e) {\n\t\t\t\t\treturn this._tryCatch(() => _onMessage(connection, message));\n\t\t\t\t}\n\t\t\t\tif (isStateUpdateMessage(parsed)) {\n\t\t\t\t\tthis._setStateInternal(parsed.state, connection);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (isRPCRequest(parsed)) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst { id, method, args } = parsed;\n\t\t\t\t\t\tconst methodFn = this[method];\n\t\t\t\t\t\tif (typeof methodFn !== \"function\") throw new Error(`Method ${method} does not exist`);\n\t\t\t\t\t\tif (!this._isCallable(method)) throw new Error(`Method ${method} is not callable`);\n\t\t\t\t\t\tconst metadata = callableMetadata.get(methodFn);\n\t\t\t\t\t\tif (metadata?.streaming) {\n\t\t\t\t\t\t\tconst stream = new StreamingResponse(connection, id);\n\t\t\t\t\t\t\tawait methodFn.apply(this, [stream, ...args]);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst result = await methodFn.apply(this, args);\n\t\t\t\t\t\tthis.observability?.emit({\n\t\t\t\t\t\t\tdisplayMessage: `RPC call to ${method}`,\n\t\t\t\t\t\t\tid: nanoid(),\n\t\t\t\t\t\t\tpayload: {\n\t\t\t\t\t\t\t\tmethod,\n\t\t\t\t\t\t\t\tstreaming: metadata?.streaming\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\t\ttype: \"rpc\"\n\t\t\t\t\t\t}, this.ctx);\n\t\t\t\t\t\tconst response = {\n\t\t\t\t\t\t\tdone: true,\n\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\tresult,\n\t\t\t\t\t\t\tsuccess: true,\n\t\t\t\t\t\t\ttype: MessageType.RPC\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconnection.send(JSON.stringify(response));\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tconst response = {\n\t\t\t\t\t\t\terror: e instanceof Error ? e.message : \"Unknown error occurred\",\n\t\t\t\t\t\t\tid: parsed.id,\n\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\ttype: MessageType.RPC\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconnection.send(JSON.stringify(response));\n\t\t\t\t\t\tconsole.error(\"RPC error:\", e);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treturn this._tryCatch(() => _onMessage(connection, message));\n\t\t\t});\n\t\t};\n\t\tconst _onConnect = this.onConnect.bind(this);\n\t\tthis.onConnect = (connection, ctx$1) => {\n\t\t\treturn agentContext.run({\n\t\t\t\tagent: this,\n\t\t\t\tconnection,\n\t\t\t\trequest: ctx$1.request,\n\t\t\t\temail: void 0\n\t\t\t}, () => {\n\t\t\t\tif (this.state) connection.send(JSON.stringify({\n\t\t\t\t\tstate: this.state,\n\t\t\t\t\ttype: MessageType.CF_AGENT_STATE\n\t\t\t\t}));\n\t\t\t\tconnection.send(JSON.stringify({\n\t\t\t\t\tmcp: this.getMcpServers(),\n\t\t\t\t\ttype: MessageType.CF_AGENT_MCP_SERVERS\n\t\t\t\t}));\n\t\t\t\tthis.observability?.emit({\n\t\t\t\t\tdisplayMessage: \"Connection established\",\n\t\t\t\t\tid: nanoid(),\n\t\t\t\t\tpayload: { connectionId: connection.id },\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\ttype: \"connect\"\n\t\t\t\t}, this.ctx);\n\t\t\t\treturn this._tryCatch(() => _onConnect(connection, ctx$1));\n\t\t\t});\n\t\t};\n\t\tconst _onStart = this.onStart.bind(this);\n\t\tthis.onStart = async (props) => {\n\t\t\treturn agentContext.run({\n\t\t\t\tagent: this,\n\t\t\t\tconnection: void 0,\n\t\t\t\trequest: void 0,\n\t\t\t\temail: void 0\n\t\t\t}, async () => {\n\t\t\t\tawait this._tryCatch(() => {\n\t\t\t\t\tconst servers = this.sql`\n SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;\n `;\n\t\t\t\t\tthis.broadcastMcpServers();\n\t\t\t\t\tif (servers && Array.isArray(servers) && servers.length > 0) {\n\t\t\t\t\t\tservers.forEach((server) => {\n\t\t\t\t\t\t\tif (server.callback_url) this.mcp.registerCallbackUrl(`${server.callback_url}/${server.id}`);\n\t\t\t\t\t\t});\n\t\t\t\t\t\tservers.forEach((server) => {\n\t\t\t\t\t\t\tthis._connectToMcpServerInternal(server.name, server.server_url, server.callback_url, server.server_options ? JSON.parse(server.server_options) : void 0, {\n\t\t\t\t\t\t\t\tid: server.id,\n\t\t\t\t\t\t\t\toauthClientId: server.client_id ?? void 0\n\t\t\t\t\t\t\t}).then(() => {\n\t\t\t\t\t\t\t\tthis.broadcastMcpServers();\n\t\t\t\t\t\t\t}).catch((error) => {\n\t\t\t\t\t\t\t\tconsole.error(`Error connecting to MCP server: ${server.name} (${server.server_url})`, error);\n\t\t\t\t\t\t\t\tthis.broadcastMcpServers();\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\treturn _onStart(props);\n\t\t\t\t});\n\t\t\t});\n\t\t};\n\t}\n\t_setStateInternal(state, source = \"server\") {\n\t\tthis._state = state;\n\t\tthis.sql`\n INSERT OR REPLACE INTO cf_agents_state (id, state)\n VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})\n `;\n\t\tthis.sql`\n INSERT OR REPLACE INTO cf_agents_state (id, state)\n VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})\n `;\n\t\tthis.broadcast(JSON.stringify({\n\t\t\tstate,\n\t\t\ttype: MessageType.CF_AGENT_STATE\n\t\t}), source !== \"server\" ? [source.id] : []);\n\t\treturn this._tryCatch(() => {\n\t\t\tconst { connection, request, email } = agentContext.getStore() || {};\n\t\t\treturn agentContext.run({\n\t\t\t\tagent: this,\n\t\t\t\tconnection,\n\t\t\t\trequest,\n\t\t\t\temail\n\t\t\t}, async () => {\n\t\t\t\tthis.observability?.emit({\n\t\t\t\t\tdisplayMessage: \"State updated\",\n\t\t\t\t\tid: nanoid(),\n\t\t\t\t\tpayload: {},\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\ttype: \"state:update\"\n\t\t\t\t}, this.ctx);\n\t\t\t\treturn this.onStateUpdate(state, source);\n\t\t\t});\n\t\t});\n\t}\n\t/**\n\t* Update the Agent's state\n\t* @param state New state to set\n\t*/\n\tsetState(state) {\n\t\tthis._setStateInternal(state, \"server\");\n\t}\n\t/**\n\t* Called when the Agent's state is updated\n\t* @param state Updated state\n\t* @param source Source of the state update (\"server\" or a client connection)\n\t*/\n\tonStateUpdate(state, source) {}\n\t/**\n\t* Called when the Agent receives an email via routeAgentEmail()\n\t* Override this method to handle incoming emails\n\t* @param email Email message to process\n\t*/\n\tasync _onEmail(email) {\n\t\treturn agentContext.run({\n\t\t\tagent: this,\n\t\t\tconnection: void 0,\n\t\t\trequest: void 0,\n\t\t\temail\n\t\t}, async () => {\n\t\t\tif (\"onEmail\" in this && typeof this.onEmail === \"function\") return this._tryCatch(() => this.onEmail(email));\n\t\t\telse {\n\t\t\t\tconsole.log(\"Received email from:\", email.from, \"to:\", email.to);\n\t\t\t\tconsole.log(\"Subject:\", email.headers.get(\"subject\"));\n\t\t\t\tconsole.log(\"Implement onEmail(email: AgentEmail): Promise<void> in your agent to process emails\");\n\t\t\t}\n\t\t});\n\t}\n\t/**\n\t* Reply to an email\n\t* @param email The email to reply to\n\t* @param options Options for the reply\n\t* @returns void\n\t*/\n\tasync replyToEmail(email, options) {\n\t\treturn this._tryCatch(async () => {\n\t\t\tconst agentName = camelCaseToKebabCase(this._ParentClass.name);\n\t\t\tconst agentId = this.name;\n\t\t\tconst { createMimeMessage } = await import(\"mimetext\");\n\t\t\tconst msg = createMimeMessage();\n\t\t\tmsg.setSender({\n\t\t\t\taddr: email.to,\n\t\t\t\tname: options.fromName\n\t\t\t});\n\t\t\tmsg.setRecipient(email.from);\n\t\t\tmsg.setSubject(options.subject || `Re: ${email.headers.get(\"subject\")}` || \"No subject\");\n\t\t\tmsg.addMessage({\n\t\t\t\tcontentType: options.contentType || \"text/plain\",\n\t\t\t\tdata: options.body\n\t\t\t});\n\t\t\tconst messageId = `<${agentId}@${email.from.split(\"@\")[1]}>`;\n\t\t\tmsg.setHeader(\"In-Reply-To\", email.headers.get(\"Message-ID\"));\n\t\t\tmsg.setHeader(\"Message-ID\", messageId);\n\t\t\tmsg.setHeader(\"X-Agent-Name\", agentName);\n\t\t\tmsg.setHeader(\"X-Agent-ID\", agentId);\n\t\t\tif (options.headers) for (const [key, value] of Object.entries(options.headers)) msg.setHeader(key, value);\n\t\t\tawait email.reply({\n\t\t\t\tfrom: email.to,\n\t\t\t\traw: msg.asRaw(),\n\t\t\t\tto: email.from\n\t\t\t});\n\t\t});\n\t}\n\tasync _tryCatch(fn) {\n\t\ttry {\n\t\t\treturn await fn();\n\t\t} catch (e) {\n\t\t\tthrow this.onError(e);\n\t\t}\n\t}\n\t/**\n\t* Automatically wrap custom methods with agent context\n\t* This ensures getCurrentAgent() works in all custom methods without decorators\n\t*/\n\t_autoWrapCustomMethods() {\n\t\tconst basePrototypes = [Agent.prototype, Server.prototype];\n\t\tconst baseMethods = /* @__PURE__ */ new Set();\n\t\tfor (const baseProto of basePrototypes) {\n\t\t\tlet proto$1 = baseProto;\n\t\t\twhile (proto$1 && proto$1 !== Object.prototype) {\n\t\t\t\tconst methodNames = Object.getOwnPropertyNames(proto$1);\n\t\t\t\tfor (const methodName of methodNames) baseMethods.add(methodName);\n\t\t\t\tproto$1 = Object.getPrototypeOf(proto$1);\n\t\t\t}\n\t\t}\n\t\tlet proto = Object.getPrototypeOf(this);\n\t\tlet depth = 0;\n\t\twhile (proto && proto !== Object.prototype && depth < 10) {\n\t\t\tconst methodNames = Object.getOwnPropertyNames(proto);\n\t\t\tfor (const methodName of methodNames) {\n\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(proto, methodName);\n\t\t\t\tif (baseMethods.has(methodName) || methodName.startsWith(\"_\") || !descriptor || !!descriptor.get || typeof descriptor.value !== \"function\") continue;\n\t\t\t\tconst wrappedFunction = withAgentContext(this[methodName]);\n\t\t\t\tif (this._isCallable(methodName)) callableMetadata.set(wrappedFunction, callableMetadata.get(this[methodName]));\n\t\t\t\tthis.constructor.prototype[methodName] = wrappedFunction;\n\t\t\t}\n\t\t\tproto = Object.getPrototypeOf(proto);\n\t\t\tdepth++;\n\t\t}\n\t}\n\tonError(connectionOrError, error) {\n\t\tlet theError;\n\t\tif (connectionOrError && error) {\n\t\t\ttheError = error;\n\t\t\tconsole.error(\"Error on websocket connection:\", connectionOrError.id, theError);\n\t\t\tconsole.error(\"Override onError(connection, error) to handle websocket connection errors\");\n\t\t} else {\n\t\t\ttheError = connectionOrError;\n\t\t\tconsole.error(\"Error on server:\", theError);\n\t\t\tconsole.error(\"Override onError(error) to handle server errors\");\n\t\t}\n\t\tthrow theError;\n\t}\n\t/**\n\t* Render content (not implemented in base class)\n\t*/\n\trender() {\n\t\tthrow new Error(\"Not implemented\");\n\t}\n\t/**\n\t* Queue a task to be executed in the future\n\t* @param payload Payload to pass to the callback\n\t* @param callback Name of the method to call\n\t* @returns The ID of the queued task\n\t*/\n\tasync queue(callback, payload) {\n\t\tconst id = nanoid(9);\n\t\tif (typeof callback !== \"string\") throw new Error(\"Callback must be a string\");\n\t\tif (typeof this[callback] !== \"function\") throw new Error(`this.${callback} is not a function`);\n\t\tthis.sql`\n INSERT OR REPLACE INTO cf_agents_queues (id, payload, callback)\n VALUES (${id}, ${JSON.stringify(payload)}, ${callback})\n `;\n\t\tthis._flushQueue().catch((e) => {\n\t\t\tconsole.error(\"Error flushing queue:\", e);\n\t\t});\n\t\treturn id;\n\t}\n\tasync _flushQueue() {\n\t\tif (this._flushingQueue) return;\n\t\tthis._flushingQueue = true;\n\t\twhile (true) {\n\t\t\tconst result = this.sql`\n SELECT * FROM cf_agents_queues\n ORDER BY created_at ASC\n `;\n\t\t\tif (!result || result.length === 0) break;\n\t\t\tfor (const row of result || []) {\n\t\t\t\tconst callback = this[row.callback];\n\t\t\t\tif (!callback) {\n\t\t\t\t\tconsole.error(`callback ${row.callback} not found`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst { connection, request, email } = agentContext.getStore() || {};\n\t\t\t\tawait agentContext.run({\n\t\t\t\t\tagent: this,\n\t\t\t\t\tconnection,\n\t\t\t\t\trequest,\n\t\t\t\t\temail\n\t\t\t\t}, async () => {\n\t\t\t\t\tawait callback.bind(this)(JSON.parse(row.payload), row);\n\t\t\t\t\tawait this.dequeue(row.id);\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tthis._flushingQueue = false;\n\t}\n\t/**\n\t* Dequeue a task by ID\n\t* @param id ID of the task to dequeue\n\t*/\n\tasync dequeue(id) {\n\t\tthis.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;\n\t}\n\t/**\n\t* Dequeue all tasks\n\t*/\n\tasync dequeueAll() {\n\t\tthis.sql`DELETE FROM cf_agents_queues`;\n\t}\n\t/**\n\t* Dequeue all tasks by callback\n\t* @param callback Name of the callback to dequeue\n\t*/\n\tasync dequeueAllByCallback(callback) {\n\t\tthis.sql`DELETE FROM cf_agents_queues WHERE callback = ${callback}`;\n\t}\n\t/**\n\t* Get a queued task by ID\n\t* @param id ID of the task to get\n\t* @returns The task or undefined if not found\n\t*/\n\tasync getQueue(id) {\n\t\tconst result = this.sql`\n SELECT * FROM cf_agents_queues WHERE id = ${id}\n `;\n\t\treturn result ? {\n\t\t\t...result[0],\n\t\t\tpayload: JSON.parse(result[0].payload)\n\t\t} : void 0;\n\t}\n\t/**\n\t* Get all queues by key and value\n\t* @param key Key to filter by\n\t* @param value Value to filter by\n\t* @returns Array of matching QueueItem objects\n\t*/\n\tasync getQueues(key, value) {\n\t\treturn this.sql`\n SELECT * FROM cf_agents_queues\n `.filter((row) => JSON.parse(row.payload)[key] === value);\n\t}\n\t/**\n\t* Schedule a task to be executed in the future\n\t* @template T Type of the payload data\n\t* @param when When to execute the task (Date, seconds delay, or cron expression)\n\t* @param callback Name of the method to call\n\t* @param payload Data to pass to the callback\n\t* @returns Schedule object representing the scheduled task\n\t*/\n\tasync schedule(when, callback, payload) {\n\t\tconst id = nanoid(9);\n\t\tconst emitScheduleCreate = (schedule) => this.observability?.emit({\n\t\t\tdisplayMessage: `Schedule ${schedule.id} created`,\n\t\t\tid: nanoid(),\n\t\t\tpayload: {\n\t\t\t\tcallback,\n\t\t\t\tid\n\t\t\t},\n\t\t\ttimestamp: Date.now(),\n\t\t\ttype: \"schedule:create\"\n\t\t}, this.ctx);\n\t\tif (typeof callback !== \"string\") throw new Error(\"Callback must be a string\");\n\t\tif (typeof this[callback] !== \"function\") throw new Error(`this.${callback} is not a function`);\n\t\tif (when instanceof Date) {\n\t\t\tconst timestamp = Math.floor(when.getTime() / 1e3);\n\t\t\tthis.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)\n VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'scheduled', ${timestamp})\n `;\n\t\t\tawait this._scheduleNextAlarm();\n\t\t\tconst schedule = {\n\t\t\t\tcallback,\n\t\t\t\tid,\n\t\t\t\tpayload,\n\t\t\t\ttime: timestamp,\n\t\t\t\ttype: \"scheduled\"\n\t\t\t};\n\t\t\temitScheduleCreate(schedule);\n\t\t\treturn schedule;\n\t\t}\n\t\tif (typeof when === \"number\") {\n\t\t\tconst time = new Date(Date.now() + when * 1e3);\n\t\t\tconst timestamp = Math.floor(time.getTime() / 1e3);\n\t\t\tthis.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)\n VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'delayed', ${when}, ${timestamp})\n `;\n\t\t\tawait this._scheduleNextAlarm();\n\t\t\tconst schedule = {\n\t\t\t\tcallback,\n\t\t\t\tdelayInSeconds: when,\n\t\t\t\tid,\n\t\t\t\tpayload,\n\t\t\t\ttime: timestamp,\n\t\t\t\ttype: \"delayed\"\n\t\t\t};\n\t\t\temitScheduleCreate(schedule);\n\t\t\treturn schedule;\n\t\t}\n\t\tif (typeof when === \"string\") {\n\t\t\tconst nextExecutionTime = getNextCronTime(when);\n\t\t\tconst timestamp = Math.floor(nextExecutionTime.getTime() / 1e3);\n\t\t\tthis.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)\n VALUES (${id}, ${callback}, ${JSON.stringify(payload)}, 'cron', ${when}, ${timestamp})\n `;\n\t\t\tawait this._scheduleNextAlarm();\n\t\t\tconst schedule = {\n\t\t\t\tcallback,\n\t\t\t\tcron: when,\n\t\t\t\tid,\n\t\t\t\tpayload,\n\t\t\t\ttime: timestamp,\n\t\t\t\ttype: \"cron\"\n\t\t\t};\n\t\t\temitScheduleCreate(schedule);\n\t\t\treturn schedule;\n\t\t}\n\t\tthrow new Error(\"Invalid schedule type\");\n\t}\n\t/**\n\t* Get a scheduled task by ID\n\t* @template T Type of the payload data\n\t* @param id ID of the scheduled task\n\t* @returns The Schedule object or undefined if not found\n\t*/\n\tasync getSchedule(id) {\n\t\tconst result = this.sql`\n SELECT * FROM cf_agents_schedules WHERE id = ${id}\n `;\n\t\tif (!result) {\n\t\t\tconsole.error(`schedule ${id} not found`);\n\t\t\treturn;\n\t\t}\n\t\treturn {\n\t\t\t...result[0],\n\t\t\tpayload: JSON.parse(result[0].payload)\n\t\t};\n\t}\n\t/**\n\t* Get scheduled tasks matching the given criteria\n\t* @template T Type of the payload data\n\t* @param criteria Criteria to filter schedules\n\t* @returns Array of matching Schedule objects\n\t*/\n\tgetSchedules(criteria = {}) {\n\t\tlet query = \"SELECT * FROM cf_agents_schedules WHERE 1=1\";\n\t\tconst params = [];\n\t\tif (criteria.id) {\n\t\t\tquery += \" AND id = ?\";\n\t\t\tparams.push(criteria.id);\n\t\t}\n\t\tif (criteria.type) {\n\t\t\tquery += \" AND type = ?\";\n\t\t\tparams.push(criteria.type);\n\t\t}\n\t\tif (criteria.timeRange) {\n\t\t\tquery += \" AND time >= ? AND time <= ?\";\n\t\t\tconst start = criteria.timeRange.start || /* @__PURE__ */ new Date(0);\n\t\t\tconst end = criteria.timeRange.end || /* @__PURE__ */ new Date(999999999999999);\n\t\t\tparams.push(Math.floor(start.getTime() / 1e3), Math.floor(end.getTime() / 1e3));\n\t\t}\n\t\treturn this.ctx.storage.sql.exec(query, ...params).toArray().map((row) => ({\n\t\t\t...row,\n\t\t\tpayload: JSON.parse(row.payload)\n\t\t}));\n\t}\n\t/**\n\t* Cancel a scheduled task\n\t* @param id ID of the task to cancel\n\t* @returns true if the task was cancelled, false otherwise\n\t*/\n\tasync cancelSchedule(id) {\n\t\tconst schedule = await this.getSchedule(id);\n\t\tif (schedule) this.observability?.emit({\n\t\t\tdisplayMessage: `Schedule ${id} cancelled`,\n\t\t\tid: nanoid(),\n\t\t\tpayload: {\n\t\t\t\tcallback: schedule.callback,\n\t\t\t\tid: schedule.id\n\t\t\t},\n\t\t\ttimestamp: Date.now(),\n\t\t\ttype: \"schedule:cancel\"\n\t\t}, this.ctx);\n\t\tthis.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;\n\t\tawait this._scheduleNextAlarm();\n\t\treturn true;\n\t}\n\tasync _scheduleNextAlarm() {\n\t\tconst result = this.sql`\n SELECT time FROM cf_agents_schedules\n WHERE time > ${Math.floor(Date.now() / 1e3)}\n ORDER BY time ASC\n LIMIT 1\n `;\n\t\tif (!result) return;\n\t\tif (result.length > 0 && \"time\" in result[0]) {\n\t\t\tconst nextTime = result[0].time * 1e3;\n\t\t\tawait this.ctx.storage.setAlarm(nextTime);\n\t\t}\n\t}\n\t/**\n\t* Destroy the Agent, removing all state and scheduled tasks\n\t*/\n\tasync destroy() {\n\t\tthis.sql`DROP TABLE IF EXISTS cf_agents_state`;\n\t\tthis.sql`DROP TABLE IF EXISTS cf_agents_schedules`;\n\t\tthis.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;\n\t\tthis.sql`DROP TABLE IF EXISTS cf_agents_queues`;\n\t\tawait this.ctx.storage.deleteAlarm();\n\t\tawait this.ctx.storage.deleteAll();\n\t\tthis._disposables.dispose();\n\t\tawait this.mcp.dispose?.();\n\t\tthis.ctx.abort(\"destroyed\");\n\t\tthis.observability?.emit({\n\t\t\tdisplayMessage: \"Agent destroyed\",\n\t\t\tid: nanoid(),\n\t\t\tpayload: {},\n\t\t\ttimestamp: Date.now(),\n\t\t\ttype: \"destroy\"\n\t\t}, this.ctx);\n\t}\n\t/**\n\t* Get all methods marked as callable on this Agent\n\t* @returns A map of method names to their metadata\n\t*/\n\t_isCallable(method) {\n\t\treturn callableMetadata.has(this[method]);\n\t}\n\t/**\n\t* Connect to a new MCP Server\n\t*\n\t* @param serverName Name of the MCP server\n\t* @param url MCP Server SSE URL\n\t* @param callbackHost Base host for the agent, used for the redirect URI. If not provided, will be derived from the current request.\n\t* @param agentsPrefix agents routing prefix if not using `agents`\n\t* @param options MCP client and transport options\n\t* @returns authUrl\n\t*/\n\tasync addMcpServer(serverName, url, callbackHost, agentsPrefix = \"agents\", options) {\n\t\tlet resolvedCallbackHost = callbackHost;\n\t\tif (!resolvedCallbackHost) {\n\t\t\tconst { request } = getCurrentAgent();\n\t\t\tif (!request) throw new Error(\"callbackHost is required when not called within a request context\");\n\t\t\tconst requestUrl = new URL(request.url);\n\t\t\tresolvedCallbackHost = `${requestUrl.protocol}//${requestUrl.host}`;\n\t\t}\n\t\tconst callbackUrl = `${resolvedCallbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;\n\t\tconst serverId = nanoid(8);\n\t\tthis.sql`\n INSERT OR REPLACE INTO cf_agents_mcp_servers (id, name, server_url, client_id, auth_url, callback_url, server_options)\n VALUES (\n ${serverId},\n ${serverName},\n ${url},\n ${null},\n ${null},\n ${callbackUrl},\n ${options ? JSON.stringify(options) : null}\n );\n `;\n\t\tconst result = await this._connectToMcpServerInternal(serverName, url, callbackUrl, options, { id: serverId });\n\t\tif (result.clientId || result.authUrl) this.sql`\n UPDATE cf_agents_mcp_servers\n SET client_id = ${result.clientId ?? null}, auth_url = ${result.authUrl ?? null}\n WHERE id = ${serverId}\n `;\n\t\tthis.broadcastMcpServers();\n\t\treturn result;\n\t}\n\t/**\n\t* Handle potential OAuth callback requests after DO hibernation.\n\t* Detects OAuth callbacks, restores state from database, and processes the callback.\n\t* Returns a Response if this was an OAuth callback, otherwise returns undefined.\n\t*/\n\tasync _handlePotentialOAuthCallback(request) {\n\t\tif (request.method !== \"GET\") return;\n\t\tconst url = new URL(request.url);\n\t\tif (!(url.pathname.includes(\"/callback/\") && url.searchParams.has(\"code\"))) return;\n\t\tconst pathParts = url.pathname.split(\"/\");\n\t\tconst callbackIndex = pathParts.indexOf(\"callback\");\n\t\tconst serverId = callbackIndex !== -1 ? pathParts[callbackIndex + 1] : null;\n\t\tif (!serverId) return new Response(\"Invalid callback URL: missing serverId\", { status: 400 });\n\t\tif (this.mcp.isCallbackRequest(request) && this.mcp.mcpConnections[serverId]) return this._processOAuthCallback(request);\n\t\ttry {\n\t\t\tconst server = this.sql`\n SELECT id, name, server_url, client_id, auth_url, callback_url, server_options\n FROM cf_agents_mcp_servers\n WHERE id = ${serverId}\n `.find((s) => s.id === serverId);\n\t\t\tif (!server) return new Response(`OAuth callback failed: Server ${serverId} not found in database`, { status: 404 });\n\t\t\tif (!server.callback_url) return new Response(`OAuth callback failed: No callback URL stored for server ${serverId}`, { status: 500 });\n\t\t\tthis.mcp.registerCallbackUrl(`${server.callback_url}/${server.id}`);\n\t\t\tif (!this.mcp.mcpConnections[serverId]) {\n\t\t\t\tlet parsedOptions;\n\t\t\t\ttry {\n\t\t\t\t\tparsedOptions = server.server_options ? JSON.parse(server.server_options) : void 0;\n\t\t\t\t} catch {\n\t\t\t\t\treturn new Response(`OAuth callback failed: Invalid server options in database for ${serverId}`, { status: 500 });\n\t\t\t\t}\n\t\t\t\tawait this._connectToMcpServerInternal(server.name, server.server_url, server.callback_url, parsedOptions, {\n\t\t\t\t\tid: server.id,\n\t\t\t\t\toauthClientId: server.client_id ?? void 0\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn this._processOAuthCallback(request);\n\t\t} catch (error) {\n\t\t\tconst errorMsg = error instanceof Error ? error.message : \"Unknown error\";\n\t\t\tconsole.error(`Failed to restore MCP state for ${serverId}:`, error);\n\t\t\treturn new Response(`OAuth callback failed during state restoration: ${errorMsg}`, { status: 500 });\n\t\t}\n\t}\n\t/**\n\t* Process an OAuth callback request (assumes state is already restored)\n\t*/\n\tasync _processOAuthCallback(request) {\n\t\tconst result = await this.mcp.handleCallbackRequest(request);\n\t\tthis.broadcastMcpServers();\n\t\tif (result.authSuccess) this.mcp.establishConnection(result.serverId).catch((error) => {\n\t\t\tconsole.error(\"Background connection failed:\", error);\n\t\t}).finally(() => {\n\t\t\tthis.broadcastMcpServers();\n\t\t});\n\t\treturn this.handleOAuthCallbackResponse(result, request);\n\t}\n\tasync _connectToMcpServerInternal(_serverName, url, callbackUrl, options, reconnect) {\n\t\tconst authProvider = new DurableObjectOAuthClientProvider(this.ctx.storage, this.name, callbackUrl);\n\t\tif (reconnect) {\n\t\t\tauthProvider.serverId = reconnect.id;\n\t\t\tif (reconnect.oauthClientId) authProvider.clientId = reconnect.oauthClientId;\n\t\t}\n\t\tconst transportType = options?.transport?.type ?? \"auto\";\n\t\tlet headerTransportOpts = {};\n\t\tif (options?.transport?.headers) headerTransportOpts = {\n\t\t\teventSourceInit: { fetch: (url$1, init) => fetch(url$1, {\n\t\t\t\t...init,\n\t\t\t\theaders: options?.transport?.headers\n\t\t\t}) },\n\t\t\trequestInit: { headers: options?.transport?.headers }\n\t\t};\n\t\tconst { id, authUrl, clientId } = await this.mcp.connect(url, {\n\t\t\tclient: options?.client,\n\t\t\treconnect,\n\t\t\ttransport: {\n\t\t\t\t...headerTransportOpts,\n\t\t\t\tauthProvider,\n\t\t\t\ttype: transportType\n\t\t\t}\n\t\t});\n\t\treturn {\n\t\t\tauthUrl,\n\t\t\tclientId,\n\t\t\tid\n\t\t};\n\t}\n\tasync removeMcpServer(id) {\n\t\tthis.mcp.closeConnection(id);\n\t\tthis.mcp.unregisterCallbackUrl(id);\n\t\tthis.sql`\n DELETE FROM cf_agents_mcp_servers WHERE id = ${id};\n `;\n\t\tthis.broadcastMcpServers();\n\t}\n\tgetMcpServers() {\n\t\tconst mcpState = {\n\t\t\tprompts: this.mcp.listPrompts(),\n\t\t\tresources: this.mcp.listResources(),\n\t\t\tservers: {},\n\t\t\ttools: this.mcp.listTools()\n\t\t};\n\t\tconst servers = this.sql`\n SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;\n `;\n\t\tif (servers && Array.isArray(servers) && servers.length > 0) for (const server of servers) {\n\t\t\tconst serverConn = this.mcp.mcpConnections[server.id];\n\t\t\tmcpState.servers[server.id] = {\n\t\t\t\tauth_url: server.auth_url,\n\t\t\t\tcapabilities: serverConn?.serverCapabilities ?? null,\n\t\t\t\tinstructions: serverConn?.instructions ?? null,\n\t\t\t\tname: server.name,\n\t\t\t\tserver_url: server.server_url,\n\t\t\t\tstate: serverConn?.connectionState ?? \"authenticating\"\n\t\t\t};\n\t\t}\n\t\treturn mcpState;\n\t}\n\tbroadcastMcpServers() {\n\t\tthis.broadcast(JSON.stringify({\n\t\t\tmcp: this.getMcpServers(),\n\t\t\ttype: MessageType.CF_AGENT_MCP_SERVERS\n\t\t}));\n\t}\n\t/**\n\t* Handle OAuth callback response using MCPClientManager configuration\n\t* @param result OAuth callback result\n\t* @param request The original request (needed for base URL)\n\t* @returns Response for the OAuth callback\n\t*/\n\thandleOAuthCallbackResponse(result, request) {\n\t\tconst config = this.mcp.getOAuthCallbackConfig();\n\t\tif (config?.customHandler) return config.customHandler(result);\n\t\tif (config?.successRedirect && result.authSuccess) return Response.redirect(config.successRedirect);\n\t\tif (config?.errorRedirect && !result.authSuccess) return Response.redirect(`${config.errorRedirect}?error=${encodeURIComponent(result.authError || \"Unknown error\")}`);\n\t\tconst baseUrl = new URL(request.url).origin;\n\t\treturn Response.redirect(baseUrl);\n\t}\n};\nconst wrappedClasses = /* @__PURE__ */ new Set();\n/**\n* Route a request to the appropriate Agent\n* @param request Request to route\n* @param env Environment containing Agent bindings\n* @param options Routing options\n* @returns Response from the Agent or undefined if no route matched\n*/\nasync function routeAgentRequest(request, env, options) {\n\tconst corsHeaders = options?.cors === true ? {\n\t\t\"Access-Control-Allow-Credentials\": \"true\",\n\t\t\"Access-Control-Allow-Methods\": \"GET, POST, HEAD, OPTIONS\",\n\t\t\"Access-Control-Allow-Origin\": \"*\",\n\t\t\"Access-Control-Max-Age\": \"86400\"\n\t} : options?.cors;\n\tif (request.method === \"OPTIONS\") {\n\t\tif (corsHeaders) return new Response(null, { headers: corsHeaders });\n\t\tconsole.warn(\"Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS.\");\n\t}\n\tlet response = await routePartykitRequest(request, env, {\n\t\tprefix: \"agents\",\n\t\t...options\n\t});\n\tif (response && corsHeaders && request.headers.get(\"upgrade\")?.toLowerCase() !== \"websocket\" && request.headers.get(\"Upgrade\")?.toLowerCase() !== \"websocket\") response = new Response(response.body, { headers: {\n\t\t...response.headers,\n\t\t...corsHeaders\n\t} });\n\treturn response;\n}\n/**\n* Create a resolver that uses the message-id header to determine the agent to route the email to\n* @returns A function that resolves the agent to route the email to\n*/\nfunction createHeaderBasedEmailResolver() {\n\treturn async (email, _env) => {\n\t\tconst messageId = email.headers.get(\"message-id\");\n\t\tif (messageId) {\n\t\t\tconst messageIdMatch = messageId.match(/<([^@]+)@([^>]+)>/);\n\t\t\tif (messageIdMatch) {\n\t\t\t\tconst [, agentId$1, domain] = messageIdMatch;\n\t\t\t\treturn {\n\t\t\t\t\tagentName: domain.split(\".\")[0],\n\t\t\t\t\tagentId: agentId$1\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\tconst references = email.headers.get(\"references\");\n\t\tif (references) {\n\t\t\tconst referencesMatch = references.match(/<([A-Za-z0-9+/]{43}=)@([^>]+)>/);\n\t\t\tif (referencesMatch) {\n\t\t\t\tconst [, base64Id, domain] = referencesMatch;\n\t\t\t\tconst agentId$1 = Buffer.from(base64Id, \"base64\").toString(\"hex\");\n\t\t\t\treturn {\n\t\t\t\t\tagentName: domain.split(\".\")[0],\n\t\t\t\t\tagentId: agentId$1\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\tconst agentName = email.headers.get(\"x-agent-name\");\n\t\tconst agentId = email.headers.get(\"x-agent-id\");\n\t\tif (agentName && agentId) return {\n\t\t\tagentName,\n\t\t\tagentId\n\t\t};\n\t\treturn null;\n\t};\n}\n/**\n* Create a resolver that uses the email address to determine the agent to route the email to\n* @param defaultAgentName The default agent name to use if the email address does not contain a sub-address\n* @returns A function that resolves the agent to route the email to\n*/\nfunction createAddressBasedEmailResolver(defaultAgentName) {\n\treturn async (email, _env) => {\n\t\tconst emailMatch = email.to.match(/^([^+@]+)(?:\\+([^@]+))?@(.+)$/);\n\t\tif (!emailMatch) return null;\n\t\tconst [, localPart, subAddress] = emailMatch;\n\t\tif (subAddress) return {\n\t\t\tagentName: localPart,\n\t\t\tagentId: subAddress\n\t\t};\n\t\treturn {\n\t\t\tagentName: defaultAgentName,\n\t\t\tagentId: localPart\n\t\t};\n\t};\n}\n/**\n* Create a resolver that uses the agentName and agentId to determine the agent to route the email to\n* @param agentName The name of the agent to route the email to\n* @param agentId The id of the agent to route the email to\n* @returns A function that resolves the agent to route the email to\n*/\nfunction createCatchAllEmailResolver(agentName, agentId) {\n\treturn async () => ({\n\t\tagentName,\n\t\tagentId\n\t});\n}\nconst agentMapCache = /* @__PURE__ */ new WeakMap();\n/**\n* Route an email to the appropriate Agent\n* @param email The email to route\n* @param env The environment containing the Agent bindings\n* @param options The options for routing the email\n* @returns A promise that resolves when the email has been routed\n*/\nasync function routeAgentEmail(email, env, options) {\n\tconst routingInfo = await options.resolver(email, env);\n\tif (!routingInfo) {\n\t\tconsole.warn(\"No routing information found for email, dropping message\");\n\t\treturn;\n\t}\n\tif (!agentMapCache.has(env)) {\n\t\tconst map = {};\n\t\tfor (const [key, value] of Object.entries(env)) if (value && typeof value === \"object\" && \"idFromName\" in value && typeof value.idFromName === \"function\") {\n\t\t\tmap[key] = value;\n\t\t\tmap[camelCaseToKebabCase(key)] = value;\n\t\t}\n\t\tagentMapCache.set(env, map);\n\t}\n\tconst agentMap = agentMapCache.get(env);\n\tconst namespace = agentMap[routingInfo.agentName];\n\tif (!namespace) {\n\t\tconst availableAgents = Object.keys(agentMap).filter((key) => !key.includes(\"-\")).join(\", \");\n\t\tthrow new Error(`Agent namespace '${routingInfo.agentName}' not found in environment. Available agents: ${availableAgents}`);\n\t}\n\tconst agent = await getAgentByName(namespace, routingInfo.agentId);\n\tconst serialisableEmail = {\n\t\tgetRaw: async () => {\n\t\t\tconst reader = email.raw.getReader();\n\t\t\tconst chunks = [];\n\t\t\tlet done = false;\n\t\t\twhile (!done) {\n\t\t\t\tconst { value, done: readerDone } = await reader.read();\n\t\t\t\tdone = readerDone;\n\t\t\t\tif (value) chunks.push(value);\n\t\t\t}\n\t\t\tconst totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);\n\t\t\tconst combined = new Uint8Array(totalLength);\n\t\t\tlet offset = 0;\n\t\t\tfor (const chunk of chunks) {\n\t\t\t\tcombined.set(chunk, offset);\n\t\t\t\toffset += chunk.length;\n\t\t\t}\n\t\t\treturn combined;\n\t\t},\n\t\theaders: email.headers,\n\t\trawSize: email.rawSize,\n\t\tsetReject: (reason) => {\n\t\t\temail.setReject(reason);\n\t\t},\n\t\tforward: (rcptTo, headers) => {\n\t\t\treturn email.forward(rcptTo, headers);\n\t\t},\n\t\treply: (options$1) => {\n\t\t\treturn email.reply(new EmailMessage(options$1.from, options$1.to, options$1.raw));\n\t\t},\n\t\tfrom: email.from,\n\t\tto: email.to\n\t};\n\tawait agent._onEmail(serialisableEmail);\n}\n/**\n* Get or create an Agent by name\n* @template Env Environment type containing bindings\n* @template T Type of the Agent class\n* @param namespace Agent namespace\n* @param name Name of the Agent instance\n* @param options Options for Agent creation\n* @returns Promise resolving to an Agent instance stub\n*/\nasync function getAgentByName(namespace, name, options) {\n\treturn getServerByName(namespace, name, options);\n}\n/**\n* A wrapper for streaming responses in callable methods\n*/\nvar StreamingResponse = class {\n\tconstructor(connection, id) {\n\t\tthis._closed = false;\n\t\tthis._connection = connection;\n\t\tthis._id = id;\n\t}\n\t/**\n\t* Send a chunk of data to the client\n\t* @param chunk The data to send\n\t*/\n\tsend(chunk) {\n\t\tif (this._closed) throw new Error(\"StreamingResponse is already closed\");\n\t\tconst response = {\n\t\t\tdone: false,\n\t\t\tid: this._id,\n\t\t\tresult: chunk,\n\t\t\tsuccess: true,\n\t\t\ttype: MessageType.RPC\n\t\t};\n\t\tthis._connection.send(JSON.stringify(response));\n\t}\n\t/**\n\t* End the stream and send the final chunk (if any)\n\t* @param finalChunk Optional final chunk of data to send\n\t*/\n\tend(finalChunk) {\n\t\tif (this._closed) throw new Error(\"StreamingResponse is already closed\");\n\t\tthis._closed = true;\n\t\tconst response = {\n\t\t\tdone: true,\n\t\t\tid: this._id,\n\t\t\tresult: finalChunk,\n\t\t\tsuccess: true,\n\t\t\ttype: MessageType.RPC\n\t\t};\n\t\tthis._connection.send(JSON.stringify(response));\n\t}\n};\n\n//#endregion\nexport { createCatchAllEmailResolver as a, getCurrentAgent as c, unstable_callable as d, genericObservability as f, createAddressBasedEmailResolver as i, routeAgentEmail as l, StreamingResponse as n, createHeaderBasedEmailResolver as o, callable as r, getAgentByName as s, Agent as t, routeAgentRequest as u };\n//# sourceMappingURL=src-CTtjSFyX.js.map","import type { AgentOptions } from \"agents\";\nimport { routeAgentRequest } from \"agents\";\nimport type { Context, Env } from \"hono\";\nimport { env } from \"hono/adapter\";\nimport { createMiddleware } from \"hono/factory\";\n\n/**\n * Configuration options for the Cloudflare Agents middleware\n */\ntype AgentMiddlewareContext<E extends Env> = {\n /** Cloudflare Agents-specific configuration options */\n options?: AgentOptions<E>;\n /** Optional error handler for caught errors */\n onError?: (error: Error) => void;\n};\n\n/**\n * Creates a middleware for handling Cloudflare Agents WebSocket and HTTP requests\n * Processes both WebSocket upgrades and standard HTTP requests, delegating them to Cloudflare Agents\n */\nexport function agentsMiddleware<E extends Env = Env>(\n ctx?: AgentMiddlewareContext<E>\n) {\n return createMiddleware<Env>(async (c, next) => {\n try {\n const handler = isWebSocketUpgrade(c)\n ? handleWebSocketUpgrade\n : handleHttpRequest;\n\n const response = await handler(c, ctx?.options);\n\n return response === null ? await next() : response;\n } catch (error) {\n if (ctx?.onError) {\n ctx.onError(error as Error);\n return next();\n }\n throw error;\n }\n });\n}\n\n/**\n * Checks if the incoming request is a WebSocket upgrade request\n * Looks for the 'upgrade' header with a value of 'websocket' (case-insensitive)\n */\nfunction isWebSocketUpgrade(c: Context): boolean {\n return c.req.header(\"upgrade\")?.toLowerCase() === \"websocket\";\n}\n\n/**\n * Handles WebSocket upgrade requests\n * Returns a WebSocket upgrade response if successful, null otherwise\n */\nasync function handleWebSocketUpgrade<E extends Env>(\n c: Context<E>,\n options?: AgentOptions<E>\n) {\n const response = await routeAgentRequest(\n c.req.raw,\n env(c) satisfies Env,\n options\n );\n\n if (!response?.webSocket) {\n return null;\n }\n\n return new Response(null, {\n status: 101,\n webSocket: response.webSocket\n });\n}\n\n/**\n * Handles standard HTTP requests\n * Forwards the request to Cloudflare Agents and returns the response\n */\nasync function handleHttpRequest<E extends Env>(\n c: Context<E>,\n options?: AgentOptions<E>\n) {\n return routeAgentRequest(c.req.raw, env(c) satisfies Env, options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAIA,IAAI,cAA8B,yBAAS,eAAe;AACzD,eAAc,4BAA4B;AAC1C,eAAc,+BAA+B;AAC7C,eAAc,gCAAgC;AAC9C,eAAc,yBAAyB;AACvC,eAAc,kCAAkC;AAChD,eAAc,0BAA0B;AACxC,eAAc,wBAAwB;AACtC,eAAc,oBAAoB;AAClC,eAAc,SAAS;AACvB,QAAO;EACN,EAAE,CAAC;;;;;;;;;ACNL,SAAS,qBAAqB,KAAK;AAClC,KAAI,QAAQ,IAAI,aAAa,IAAI,QAAQ,IAAI,aAAa,CAAE,QAAO,IAAI,aAAa,CAAC,QAAQ,MAAM,IAAI;CACvG,IAAI,aAAa,IAAI,QAAQ,WAAW,WAAW,IAAI,OAAO,aAAa,GAAG;AAC9E,cAAa,WAAW,WAAW,IAAI,GAAG,WAAW,MAAM,EAAE,GAAG;AAChE,QAAO,WAAW,QAAQ,MAAM,IAAI,CAAC,QAAQ,MAAM,GAAG;;;;;ACNvD,SAAS,aAAa,IAAI;AACzB,QAAO,EAAE,SAAS,IAAI;;AAEvB,IAAI,kBAAkB,MAAM;CAC3B,cAAc;AACb,OAAK,SAAS,EAAE;;CAEjB,IAAI,GAAG;AACN,OAAK,OAAO,KAAK,EAAE;AACnB,SAAO;;CAER,UAAU;AACT,SAAO,KAAK,OAAO,OAAQ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AS;EACrB,CAAC;;;;;;AAOJ,eAAe,kBACb,GACA,SACA;AACA,QAAO,kBAAkB,EAAE,IAAI,KAAK,IAAI,EAAE,EAAgB,QAAQ"}
|
package/package.json
CHANGED
|
@@ -5,8 +5,8 @@
|
|
|
5
5
|
},
|
|
6
6
|
"description": "Add Cloudflare Agents to your Hono app",
|
|
7
7
|
"devDependencies": {
|
|
8
|
-
"agents": "^0.2.
|
|
9
|
-
"hono": "^4.
|
|
8
|
+
"agents": "^0.2.16",
|
|
9
|
+
"hono": "^4.10.3"
|
|
10
10
|
},
|
|
11
11
|
"publishConfig": {
|
|
12
12
|
"access": "public"
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
"main": "src/index.ts",
|
|
32
32
|
"name": "hono-agents",
|
|
33
33
|
"peerDependencies": {
|
|
34
|
-
"agents": "^0.2.
|
|
34
|
+
"agents": "^0.2.16",
|
|
35
35
|
"hono": "^4.6.17"
|
|
36
36
|
},
|
|
37
37
|
"repository": {
|
|
@@ -45,5 +45,5 @@
|
|
|
45
45
|
},
|
|
46
46
|
"type": "module",
|
|
47
47
|
"types": "dist/index.d.ts",
|
|
48
|
-
"version": "2.0.
|
|
48
|
+
"version": "2.0.5"
|
|
49
49
|
}
|