agents 0.0.0-c552d8b → 0.0.0-c5e3a32
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/README.md +22 -22
- package/dist/ai-chat-agent.d.ts +32 -5
- package/dist/ai-chat-agent.js +149 -115
- package/dist/ai-chat-agent.js.map +1 -1
- package/dist/ai-react.d.ts +18 -5
- package/dist/ai-react.js +28 -29
- package/dist/ai-react.js.map +1 -1
- package/dist/chunk-EDUDXISR.js +1148 -0
- package/dist/chunk-EDUDXISR.js.map +1 -0
- package/dist/chunk-KUH345EY.js +116 -0
- package/dist/chunk-KUH345EY.js.map +1 -0
- package/dist/{chunk-Q5ZBHY4Z.js → chunk-MW5BQ2FW.js} +49 -36
- package/dist/chunk-MW5BQ2FW.js.map +1 -0
- package/dist/chunk-PVQZBKN7.js +106 -0
- package/dist/chunk-PVQZBKN7.js.map +1 -0
- package/dist/client.d.ts +16 -2
- package/dist/client.js +6 -126
- package/dist/client.js.map +1 -1
- package/dist/index-DukU3sIa.d.ts +571 -0
- package/dist/index.d.ts +32 -308
- package/dist/index.js +10 -3
- package/dist/mcp/client.d.ts +301 -23
- package/dist/mcp/client.js +1 -2
- package/dist/mcp/do-oauth-client-provider.d.ts +3 -3
- package/dist/mcp/do-oauth-client-provider.js +3 -103
- package/dist/mcp/do-oauth-client-provider.js.map +1 -1
- package/dist/mcp/index.d.ts +23 -13
- package/dist/mcp/index.js +150 -175
- package/dist/mcp/index.js.map +1 -1
- package/dist/observability/index.d.ts +12 -0
- package/dist/observability/index.js +10 -0
- package/dist/react.d.ts +85 -5
- package/dist/react.js +20 -8
- package/dist/react.js.map +1 -1
- package/dist/schedule.d.ts +6 -6
- package/dist/schedule.js +4 -6
- package/dist/schedule.js.map +1 -1
- package/dist/serializable.d.ts +32 -0
- package/dist/serializable.js +1 -0
- package/dist/serializable.js.map +1 -0
- package/package.json +76 -68
- package/src/index.ts +926 -136
- package/dist/chunk-HMLY7DHA.js +0 -16
- package/dist/chunk-Q5ZBHY4Z.js.map +0 -1
- package/dist/chunk-WNIGPPNB.js +0 -608
- package/dist/chunk-WNIGPPNB.js.map +0 -1
- /package/dist/{chunk-HMLY7DHA.js.map → observability/index.js.map} +0 -0
package/dist/chunk-HMLY7DHA.js
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
var __typeError = (msg) => {
|
|
2
|
-
throw TypeError(msg);
|
|
3
|
-
};
|
|
4
|
-
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
|
|
5
|
-
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
|
|
6
|
-
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
7
|
-
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
|
|
8
|
-
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
|
|
9
|
-
|
|
10
|
-
export {
|
|
11
|
-
__privateGet,
|
|
12
|
-
__privateAdd,
|
|
13
|
-
__privateSet,
|
|
14
|
-
__privateMethod
|
|
15
|
-
};
|
|
16
|
-
//# sourceMappingURL=chunk-HMLY7DHA.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/mcp/sse-edge.ts","../src/mcp/client-connection.ts","../src/mcp/client.ts"],"sourcesContent":["import {\n SSEClientTransport,\n type SSEClientTransportOptions,\n} from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport type { OAuthClientProvider } from \"@modelcontextprotocol/sdk/client/auth.js\";\n\nexport class SSEEdgeClientTransport extends SSEClientTransport {\n private authProvider: OAuthClientProvider | undefined;\n /**\n * Creates a new EdgeSSEClientTransport, which overrides fetch to be compatible with the CF workers environment\n */\n constructor(url: URL, options: SSEClientTransportOptions) {\n const fetchOverride: typeof fetch = async (\n fetchUrl: RequestInfo | URL,\n fetchInit: RequestInit = {}\n ) => {\n // add auth headers\n const headers = await this.authHeaders();\n const workerOptions = {\n ...fetchInit,\n headers: {\n ...fetchInit?.headers,\n ...headers,\n },\n };\n\n // Remove unsupported properties\n // biome-ignore lint/performance/noDelete: workaround for workers environment\n delete workerOptions.mode;\n\n // Call the original fetch with fixed options\n return fetch(fetchUrl, workerOptions);\n };\n\n super(url, {\n ...options,\n eventSourceInit: {\n fetch: fetchOverride,\n },\n });\n this.authProvider = options.authProvider;\n }\n\n async authHeaders() {\n if (this.authProvider) {\n const tokens = await this.authProvider.tokens();\n if (tokens) {\n return {\n Authorization: `Bearer ${tokens.access_token}`,\n };\n }\n }\n }\n}\n","import { SSEEdgeClientTransport } from \"./sse-edge\";\n\nimport {\n ToolListChangedNotificationSchema,\n type ClientCapabilities,\n type Resource,\n type Tool,\n type Prompt,\n ResourceListChangedNotificationSchema,\n PromptListChangedNotificationSchema,\n type ListToolsResult,\n type ListResourcesResult,\n type ListPromptsResult,\n type ServerCapabilities,\n type ResourceTemplate,\n type ListResourceTemplatesResult,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { SSEClientTransportOptions } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport type { AgentsOAuthProvider } from \"./do-oauth-client-provider\";\n\nexport class MCPClientConnection {\n client: Client;\n connectionState:\n | \"authenticating\"\n | \"connecting\"\n | \"ready\"\n | \"discovering\"\n | \"failed\" = \"connecting\";\n instructions?: string;\n tools: Tool[] = [];\n prompts: Prompt[] = [];\n resources: Resource[] = [];\n resourceTemplates: ResourceTemplate[] = [];\n serverCapabilities: ServerCapabilities | undefined;\n\n constructor(\n public url: URL,\n info: ConstructorParameters<typeof Client>[0],\n public options: {\n transport: SSEClientTransportOptions & {\n authProvider?: AgentsOAuthProvider;\n };\n client: ConstructorParameters<typeof Client>[1];\n capabilities: ClientCapabilities;\n } = { transport: {}, client: {}, capabilities: {} }\n ) {\n this.client = new Client(info, options.client);\n this.client.registerCapabilities(options.capabilities);\n }\n\n /**\n * Initialize a client connection\n *\n * @param code Optional OAuth code to initialize the connection with if auth hasn't been initialized\n * @returns\n */\n async init(code?: string, clientId?: string) {\n try {\n const transport = new SSEEdgeClientTransport(\n this.url,\n this.options.transport\n );\n if (code) {\n await transport.finishAuth(code);\n }\n\n await this.client.connect(transport);\n // biome-ignore lint/suspicious/noExplicitAny: allow for the error check here\n } catch (e: any) {\n if (e.toString().includes(\"Unauthorized\")) {\n // unauthorized, we should wait for the user to authenticate\n this.connectionState = \"authenticating\";\n return;\n }\n this.connectionState = \"failed\";\n throw e;\n }\n\n this.connectionState = \"discovering\";\n\n this.serverCapabilities = await this.client.getServerCapabilities();\n if (!this.serverCapabilities) {\n throw new Error(\"The MCP Server failed to return server capabilities\");\n }\n\n const [instructions, tools, resources, prompts, resourceTemplates] =\n await Promise.all([\n this.client.getInstructions(),\n this.registerTools(),\n this.registerResources(),\n this.registerPrompts(),\n this.registerResourceTemplates(),\n ]);\n\n this.instructions = instructions;\n this.tools = tools;\n this.resources = resources;\n this.prompts = prompts;\n this.resourceTemplates = resourceTemplates;\n\n this.connectionState = \"ready\";\n }\n\n /**\n * Notification handler registration\n */\n async registerTools(): Promise<Tool[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.tools) {\n return [];\n }\n\n if (this.serverCapabilities.tools.listChanged) {\n this.client.setNotificationHandler(\n ToolListChangedNotificationSchema,\n async (_notification) => {\n this.tools = await this.fetchTools();\n }\n );\n }\n\n return this.fetchTools();\n }\n\n async registerResources(): Promise<Resource[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.resources) {\n return [];\n }\n\n if (this.serverCapabilities.resources.listChanged) {\n this.client.setNotificationHandler(\n ResourceListChangedNotificationSchema,\n async (_notification) => {\n this.resources = await this.fetchResources();\n }\n );\n }\n\n return this.fetchResources();\n }\n\n async registerPrompts(): Promise<Prompt[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.prompts) {\n return [];\n }\n\n if (this.serverCapabilities.prompts.listChanged) {\n this.client.setNotificationHandler(\n PromptListChangedNotificationSchema,\n async (_notification) => {\n this.prompts = await this.fetchPrompts();\n }\n );\n }\n\n return this.fetchPrompts();\n }\n\n async registerResourceTemplates(): Promise<ResourceTemplate[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.resources) {\n return [];\n }\n\n return this.fetchResourceTemplates();\n }\n\n async fetchTools() {\n let toolsAgg: Tool[] = [];\n let toolsResult: ListToolsResult = { tools: [] };\n do {\n toolsResult = await this.client\n .listTools({\n cursor: toolsResult.nextCursor,\n })\n .catch(capabilityErrorHandler({ tools: [] }, \"tools/list\"));\n toolsAgg = toolsAgg.concat(toolsResult.tools);\n } while (toolsResult.nextCursor);\n return toolsAgg;\n }\n\n async fetchResources() {\n let resourcesAgg: Resource[] = [];\n let resourcesResult: ListResourcesResult = { resources: [] };\n do {\n resourcesResult = await this.client\n .listResources({\n cursor: resourcesResult.nextCursor,\n })\n .catch(capabilityErrorHandler({ resources: [] }, \"resources/list\"));\n resourcesAgg = resourcesAgg.concat(resourcesResult.resources);\n } while (resourcesResult.nextCursor);\n return resourcesAgg;\n }\n\n async fetchPrompts() {\n let promptsAgg: Prompt[] = [];\n let promptsResult: ListPromptsResult = { prompts: [] };\n do {\n promptsResult = await this.client\n .listPrompts({\n cursor: promptsResult.nextCursor,\n })\n .catch(capabilityErrorHandler({ prompts: [] }, \"prompts/list\"));\n promptsAgg = promptsAgg.concat(promptsResult.prompts);\n } while (promptsResult.nextCursor);\n return promptsAgg;\n }\n\n async fetchResourceTemplates() {\n let templatesAgg: ResourceTemplate[] = [];\n let templatesResult: ListResourceTemplatesResult = {\n resourceTemplates: [],\n };\n do {\n templatesResult = await this.client\n .listResourceTemplates({\n cursor: templatesResult.nextCursor,\n })\n .catch(\n capabilityErrorHandler(\n { resourceTemplates: [] },\n \"resources/templates/list\"\n )\n );\n templatesAgg = templatesAgg.concat(templatesResult.resourceTemplates);\n } while (templatesResult.nextCursor);\n return templatesAgg;\n }\n}\n\nfunction capabilityErrorHandler<T>(empty: T, method: string) {\n return (e: { code: number }) => {\n // server is badly behaved and returning invalid capabilities. This commonly occurs for resource templates\n if (e.code === -32601) {\n console.error(\n `The server advertised support for the capability ${method.split(\"/\")[0]}, but returned \"Method not found\" for '${method}'.`\n );\n return empty;\n }\n throw e;\n };\n}\n","import { MCPClientConnection } from \"./client-connection\";\n\nimport type {\n ClientCapabilities,\n CallToolRequest,\n CallToolResultSchema,\n CompatibilityCallToolResultSchema,\n ReadResourceRequest,\n GetPromptRequest,\n Tool,\n Resource,\n Prompt,\n ResourceTemplate,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { SSEClientTransportOptions } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport type { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { RequestOptions } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\nimport type { AgentsOAuthProvider } from \"./do-oauth-client-provider\";\nimport { jsonSchema, type ToolSet } from \"ai\";\nimport { nanoid } from \"nanoid\";\n\n/**\n * Utility class that aggregates multiple MCP clients into one\n */\nexport class MCPClientManager {\n public mcpConnections: Record<string, MCPClientConnection> = {};\n private callbackUrls: string[] = [];\n\n /**\n * @param name Name of the MCP client\n * @param version Version of the MCP Client\n * @param auth Auth paramters if being used to create a DurableObjectOAuthClientProvider\n */\n constructor(\n private name: string,\n private version: string\n ) {}\n\n /**\n * Connect to and register an MCP server\n *\n * @param transportConfig Transport config\n * @param clientConfig Client config\n * @param capabilities Client capabilities (i.e. if the client supports roots/sampling)\n */\n async connect(\n url: string,\n options: {\n // Allows you to reconnect to a server (in the case of a auth reconnect)\n // Doesn't handle session reconnection\n reconnect?: {\n id: string;\n oauthClientId?: string;\n oauthCode?: string;\n };\n // we're overriding authProvider here because we want to be able to access the auth URL\n transport?: SSEClientTransportOptions & {\n authProvider?: AgentsOAuthProvider;\n };\n client?: ConstructorParameters<typeof Client>[1];\n capabilities?: ClientCapabilities;\n } = {}\n ): Promise<{ id: string; authUrl: string | undefined }> {\n const id = options.reconnect?.id ?? nanoid(8);\n\n if (!options.transport?.authProvider) {\n console.warn(\n \"No authProvider provided in the transport options. This client will only support unauthenticated remote MCP Servers\"\n );\n } else {\n options.transport.authProvider.serverId = id;\n }\n\n this.mcpConnections[id] = new MCPClientConnection(\n new URL(url),\n {\n name: this.name,\n version: this.version,\n },\n {\n transport: options.transport ?? {},\n client: options.client ?? {},\n capabilities: options.client ?? {},\n }\n );\n\n await this.mcpConnections[id].init(\n options.reconnect?.oauthCode,\n options.reconnect?.oauthClientId\n );\n\n const authUrl = options.transport?.authProvider?.authUrl;\n if (authUrl && options.transport?.authProvider?.redirectUrl) {\n this.callbackUrls.push(\n options.transport.authProvider.redirectUrl.toString()\n );\n }\n\n return {\n id,\n authUrl,\n };\n }\n\n isCallbackRequest(req: Request): boolean {\n return (\n req.method === \"GET\" &&\n !!this.callbackUrls.find((url) => {\n return req.url.startsWith(url);\n })\n );\n }\n\n async handleCallbackRequest(req: Request) {\n const url = new URL(req.url);\n const urlMatch = this.callbackUrls.find((url) => {\n return req.url.startsWith(url);\n });\n if (!urlMatch) {\n throw new Error(\n `No callback URI match found for the request url: ${req.url}. Was the request matched with \\`isCallbackRequest()\\`?`\n );\n }\n const code = url.searchParams.get(\"code\");\n const clientId = url.searchParams.get(\"state\");\n const urlParams = urlMatch.split(\"/\");\n const serverId = urlParams[urlParams.length - 1];\n if (!code) {\n throw new Error(\"Unauthorized: no code provided\");\n }\n if (!clientId) {\n throw new Error(\"Unauthorized: no state provided\");\n }\n\n if (this.mcpConnections[serverId] === undefined) {\n throw new Error(`Could not find serverId: ${serverId}`);\n }\n\n if (this.mcpConnections[serverId].connectionState !== \"authenticating\") {\n throw new Error(\n \"Failed to authenticate: the client isn't in the `authenticating` state\"\n );\n }\n\n const conn = this.mcpConnections[serverId];\n if (!conn.options.transport.authProvider) {\n throw new Error(\n \"Trying to finalize authentication for a server connection without an authProvider\"\n );\n }\n\n conn.options.transport.authProvider.clientId = clientId;\n conn.options.transport.authProvider.serverId = serverId;\n\n // reconnect to server with authorization\n const serverUrl = conn.url.toString();\n await this.connect(serverUrl, {\n reconnect: {\n id: serverId,\n oauthClientId: clientId,\n oauthCode: code,\n },\n ...conn.options,\n });\n\n if (this.mcpConnections[serverId].connectionState === \"authenticating\") {\n throw new Error(\"Failed to authenticate: client failed to initialize\");\n }\n\n return { serverId };\n }\n\n /**\n * @returns namespaced list of tools\n */\n listTools(): NamespacedData[\"tools\"] {\n return getNamespacedData(this.mcpConnections, \"tools\");\n }\n\n /**\n * @returns a set of tools that you can use with the AI SDK\n */\n unstable_getAITools(): ToolSet {\n return Object.fromEntries(\n getNamespacedData(this.mcpConnections, \"tools\").map((tool) => {\n return [\n `${tool.serverId}_${tool.name}`,\n {\n parameters: jsonSchema(tool.inputSchema),\n description: tool.description,\n execute: async (args) => {\n const result = await this.callTool({\n name: tool.name,\n arguments: args,\n serverId: tool.serverId,\n });\n if (result.isError) {\n // @ts-expect-error TODO we should fix this\n throw new Error(result.content[0].text);\n }\n return result;\n },\n },\n ];\n })\n );\n }\n\n /**\n * Closes all connections to MCP servers\n */\n async closeAllConnections() {\n return Promise.all(\n Object.values(this.mcpConnections).map(async (connection) => {\n await connection.client.close();\n })\n );\n }\n\n /**\n * Closes a connection to an MCP server\n * @param id The id of the connection to close\n */\n async closeConnection(id: string) {\n if (!this.mcpConnections[id]) {\n throw new Error(`Connection with id \"${id}\" does not exist.`);\n }\n await this.mcpConnections[id].client.close();\n }\n\n /**\n * @returns namespaced list of prompts\n */\n listPrompts(): NamespacedData[\"prompts\"] {\n return getNamespacedData(this.mcpConnections, \"prompts\");\n }\n\n /**\n * @returns namespaced list of tools\n */\n listResources(): NamespacedData[\"resources\"] {\n return getNamespacedData(this.mcpConnections, \"resources\");\n }\n\n /**\n * @returns namespaced list of resource templates\n */\n listResourceTemplates(): NamespacedData[\"resourceTemplates\"] {\n return getNamespacedData(this.mcpConnections, \"resourceTemplates\");\n }\n\n /**\n * Namespaced version of callTool\n */\n callTool(\n params: CallToolRequest[\"params\"] & { serverId: string },\n resultSchema?:\n | typeof CallToolResultSchema\n | typeof CompatibilityCallToolResultSchema,\n options?: RequestOptions\n ) {\n const unqualifiedName = params.name.replace(`${params.serverId}.`, \"\");\n return this.mcpConnections[params.serverId].client.callTool(\n {\n ...params,\n name: unqualifiedName,\n },\n resultSchema,\n options\n );\n }\n\n /**\n * Namespaced version of readResource\n */\n readResource(\n params: ReadResourceRequest[\"params\"] & { serverId: string },\n options: RequestOptions\n ) {\n return this.mcpConnections[params.serverId].client.readResource(\n params,\n options\n );\n }\n\n /**\n * Namespaced version of getPrompt\n */\n getPrompt(\n params: GetPromptRequest[\"params\"] & { serverId: string },\n options: RequestOptions\n ) {\n return this.mcpConnections[params.serverId].client.getPrompt(\n params,\n options\n );\n }\n}\n\ntype NamespacedData = {\n tools: (Tool & { serverId: string })[];\n prompts: (Prompt & { serverId: string })[];\n resources: (Resource & { serverId: string })[];\n resourceTemplates: (ResourceTemplate & { serverId: string })[];\n};\n\nexport function getNamespacedData<T extends keyof NamespacedData>(\n mcpClients: Record<string, MCPClientConnection>,\n type: T\n): NamespacedData[T] {\n const sets = Object.entries(mcpClients).map(([name, conn]) => {\n return { name, data: conn[type] };\n });\n\n const namespacedData = sets.flatMap(({ name: serverId, data }) => {\n return data.map((item) => {\n return {\n ...item,\n // we add a serverId so we can easily pull it out and send the tool call to the right server\n serverId,\n };\n });\n });\n\n return namespacedData as NamespacedData[T]; // Type assertion needed due to TS limitations with conditional return types\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,OAEK;AAGA,IAAM,yBAAN,cAAqC,mBAAmB;AAAA;AAAA;AAAA;AAAA,EAK7D,YAAY,KAAU,SAAoC;AACxD,UAAM,gBAA8B,OAClC,UACA,YAAyB,CAAC,MACvB;AAEH,YAAM,UAAU,MAAM,KAAK,YAA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AAQ,GAAG,OAAO,QAAQ,KAAK,EAAE;AACrE,WAAO,KAAK,eAAe,OAAO,QAAQ,EAAE,OAAO;AAAA,MACjD;AAAA,QACE,GAAG;AAAA,QACH,MAAM;AAAA,MACR;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,aACE,QACA,SACA;AACA,WAAO,KAAK,eAAe,OAAO,QAAQ,EAAE,OAAO;AAAA,MACjD;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,UACE,QACA,SACA;AACA,WAAO,KAAK,eAAe,OAAO,QAAQ,EAAE,OAAO;AAAA,MACjD;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;AASO,SAAS,kBACd,YACA,MACmB;AACnB,QAAM,OAAO,OAAO,QAAQ,UAAU,EAAE,IAAI,CAAC,CAAC,MAAM,IAAI,MAAM;AAC5D,WAAO,EAAE,MAAM,MAAM,KAAK,IAAI,EAAE;AAAA,EAClC,CAAC;AAED,QAAM,iBAAiB,KAAK,QAAQ,CAAC,EAAE,MAAM,UAAU,KAAK,MAAM;AAChE,WAAO,KAAK,IAAI,CAAC,SAAS;AACxB,aAAO;AAAA,QACL,GAAG;AAAA;AAAA,QAEH;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AAED,SAAO;AACT;","names":["url"]}
|
package/dist/chunk-WNIGPPNB.js
DELETED
|
@@ -1,608 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
MCPClientManager
|
|
3
|
-
} from "./chunk-Q5ZBHY4Z.js";
|
|
4
|
-
import {
|
|
5
|
-
__privateAdd,
|
|
6
|
-
__privateGet,
|
|
7
|
-
__privateMethod,
|
|
8
|
-
__privateSet
|
|
9
|
-
} from "./chunk-HMLY7DHA.js";
|
|
10
|
-
|
|
11
|
-
// src/index.ts
|
|
12
|
-
import {
|
|
13
|
-
Server,
|
|
14
|
-
routePartykitRequest,
|
|
15
|
-
getServerByName
|
|
16
|
-
} from "partyserver";
|
|
17
|
-
import { parseCronExpression } from "cron-schedule";
|
|
18
|
-
import { nanoid } from "nanoid";
|
|
19
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
20
|
-
function isRPCRequest(msg) {
|
|
21
|
-
return typeof msg === "object" && msg !== null && "type" in msg && msg.type === "rpc" && "id" in msg && typeof msg.id === "string" && "method" in msg && typeof msg.method === "string" && "args" in msg && Array.isArray(msg.args);
|
|
22
|
-
}
|
|
23
|
-
function isStateUpdateMessage(msg) {
|
|
24
|
-
return typeof msg === "object" && msg !== null && "type" in msg && msg.type === "cf_agent_state" && "state" in msg;
|
|
25
|
-
}
|
|
26
|
-
var callableMetadata = /* @__PURE__ */ new Map();
|
|
27
|
-
function unstable_callable(metadata = {}) {
|
|
28
|
-
return function callableDecorator(target, context) {
|
|
29
|
-
if (!callableMetadata.has(target)) {
|
|
30
|
-
callableMetadata.set(target, metadata);
|
|
31
|
-
}
|
|
32
|
-
return target;
|
|
33
|
-
};
|
|
34
|
-
}
|
|
35
|
-
function getNextCronTime(cron) {
|
|
36
|
-
const interval = parseCronExpression(cron);
|
|
37
|
-
return interval.getNextDate();
|
|
38
|
-
}
|
|
39
|
-
var STATE_ROW_ID = "cf_state_row_id";
|
|
40
|
-
var STATE_WAS_CHANGED = "cf_state_was_changed";
|
|
41
|
-
var DEFAULT_STATE = {};
|
|
42
|
-
var agentContext = new AsyncLocalStorage();
|
|
43
|
-
function getCurrentAgent() {
|
|
44
|
-
const store = agentContext.getStore();
|
|
45
|
-
if (!store) {
|
|
46
|
-
return {
|
|
47
|
-
agent: void 0,
|
|
48
|
-
connection: void 0,
|
|
49
|
-
request: void 0
|
|
50
|
-
};
|
|
51
|
-
}
|
|
52
|
-
return store;
|
|
53
|
-
}
|
|
54
|
-
var _state, _ParentClass, _Agent_instances, setStateInternal_fn, tryCatch_fn, scheduleNextAlarm_fn, isCallable_fn;
|
|
55
|
-
var Agent = class extends Server {
|
|
56
|
-
constructor(ctx, env) {
|
|
57
|
-
super(ctx, env);
|
|
58
|
-
__privateAdd(this, _Agent_instances);
|
|
59
|
-
__privateAdd(this, _state, DEFAULT_STATE);
|
|
60
|
-
__privateAdd(this, _ParentClass, Object.getPrototypeOf(this).constructor);
|
|
61
|
-
this.mcp = new MCPClientManager(__privateGet(this, _ParentClass).name, "0.0.1");
|
|
62
|
-
/**
|
|
63
|
-
* Initial state for the Agent
|
|
64
|
-
* Override to provide default state values
|
|
65
|
-
*/
|
|
66
|
-
this.initialState = DEFAULT_STATE;
|
|
67
|
-
this.sql`
|
|
68
|
-
CREATE TABLE IF NOT EXISTS cf_agents_state (
|
|
69
|
-
id TEXT PRIMARY KEY NOT NULL,
|
|
70
|
-
state TEXT
|
|
71
|
-
)
|
|
72
|
-
`;
|
|
73
|
-
void this.ctx.blockConcurrencyWhile(async () => {
|
|
74
|
-
return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, async () => {
|
|
75
|
-
this.sql`
|
|
76
|
-
CREATE TABLE IF NOT EXISTS cf_agents_schedules (
|
|
77
|
-
id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
|
|
78
|
-
callback TEXT,
|
|
79
|
-
payload TEXT,
|
|
80
|
-
type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),
|
|
81
|
-
time INTEGER,
|
|
82
|
-
delayInSeconds INTEGER,
|
|
83
|
-
cron TEXT,
|
|
84
|
-
created_at INTEGER DEFAULT (unixepoch())
|
|
85
|
-
)
|
|
86
|
-
`;
|
|
87
|
-
await this.alarm();
|
|
88
|
-
});
|
|
89
|
-
});
|
|
90
|
-
const _onMessage = this.onMessage.bind(this);
|
|
91
|
-
this.onMessage = async (connection, message) => {
|
|
92
|
-
return agentContext.run(
|
|
93
|
-
{ agent: this, connection, request: void 0 },
|
|
94
|
-
async () => {
|
|
95
|
-
if (typeof message !== "string") {
|
|
96
|
-
return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onMessage(connection, message));
|
|
97
|
-
}
|
|
98
|
-
let parsed;
|
|
99
|
-
try {
|
|
100
|
-
parsed = JSON.parse(message);
|
|
101
|
-
} catch (e) {
|
|
102
|
-
return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onMessage(connection, message));
|
|
103
|
-
}
|
|
104
|
-
if (isStateUpdateMessage(parsed)) {
|
|
105
|
-
__privateMethod(this, _Agent_instances, setStateInternal_fn).call(this, parsed.state, connection);
|
|
106
|
-
return;
|
|
107
|
-
}
|
|
108
|
-
if (isRPCRequest(parsed)) {
|
|
109
|
-
try {
|
|
110
|
-
const { id, method, args } = parsed;
|
|
111
|
-
const methodFn = this[method];
|
|
112
|
-
if (typeof methodFn !== "function") {
|
|
113
|
-
throw new Error(`Method ${method} does not exist`);
|
|
114
|
-
}
|
|
115
|
-
if (!__privateMethod(this, _Agent_instances, isCallable_fn).call(this, method)) {
|
|
116
|
-
throw new Error(`Method ${method} is not callable`);
|
|
117
|
-
}
|
|
118
|
-
const metadata = callableMetadata.get(methodFn);
|
|
119
|
-
if (metadata?.streaming) {
|
|
120
|
-
const stream = new StreamingResponse(connection, id);
|
|
121
|
-
await methodFn.apply(this, [stream, ...args]);
|
|
122
|
-
return;
|
|
123
|
-
}
|
|
124
|
-
const result = await methodFn.apply(this, args);
|
|
125
|
-
const response = {
|
|
126
|
-
type: "rpc",
|
|
127
|
-
id,
|
|
128
|
-
success: true,
|
|
129
|
-
result,
|
|
130
|
-
done: true
|
|
131
|
-
};
|
|
132
|
-
connection.send(JSON.stringify(response));
|
|
133
|
-
} catch (e) {
|
|
134
|
-
const response = {
|
|
135
|
-
type: "rpc",
|
|
136
|
-
id: parsed.id,
|
|
137
|
-
success: false,
|
|
138
|
-
error: e instanceof Error ? e.message : "Unknown error occurred"
|
|
139
|
-
};
|
|
140
|
-
connection.send(JSON.stringify(response));
|
|
141
|
-
console.error("RPC error:", e);
|
|
142
|
-
}
|
|
143
|
-
return;
|
|
144
|
-
}
|
|
145
|
-
return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onMessage(connection, message));
|
|
146
|
-
}
|
|
147
|
-
);
|
|
148
|
-
};
|
|
149
|
-
const _onConnect = this.onConnect.bind(this);
|
|
150
|
-
this.onConnect = (connection, ctx2) => {
|
|
151
|
-
return agentContext.run(
|
|
152
|
-
{ agent: this, connection, request: ctx2.request },
|
|
153
|
-
async () => {
|
|
154
|
-
setTimeout(() => {
|
|
155
|
-
if (this.state) {
|
|
156
|
-
connection.send(
|
|
157
|
-
JSON.stringify({
|
|
158
|
-
type: "cf_agent_state",
|
|
159
|
-
state: this.state
|
|
160
|
-
})
|
|
161
|
-
);
|
|
162
|
-
}
|
|
163
|
-
return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onConnect(connection, ctx2));
|
|
164
|
-
}, 20);
|
|
165
|
-
}
|
|
166
|
-
);
|
|
167
|
-
};
|
|
168
|
-
}
|
|
169
|
-
/**
|
|
170
|
-
* Current state of the Agent
|
|
171
|
-
*/
|
|
172
|
-
get state() {
|
|
173
|
-
if (__privateGet(this, _state) !== DEFAULT_STATE) {
|
|
174
|
-
return __privateGet(this, _state);
|
|
175
|
-
}
|
|
176
|
-
const wasChanged = this.sql`
|
|
177
|
-
SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}
|
|
178
|
-
`;
|
|
179
|
-
const result = this.sql`
|
|
180
|
-
SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}
|
|
181
|
-
`;
|
|
182
|
-
if (wasChanged[0]?.state === "true" || // we do this check for people who updated their code before we shipped wasChanged
|
|
183
|
-
result[0]?.state) {
|
|
184
|
-
const state = result[0]?.state;
|
|
185
|
-
__privateSet(this, _state, JSON.parse(state));
|
|
186
|
-
return __privateGet(this, _state);
|
|
187
|
-
}
|
|
188
|
-
if (this.initialState === DEFAULT_STATE) {
|
|
189
|
-
return void 0;
|
|
190
|
-
}
|
|
191
|
-
this.setState(this.initialState);
|
|
192
|
-
return this.initialState;
|
|
193
|
-
}
|
|
194
|
-
/**
|
|
195
|
-
* Execute SQL queries against the Agent's database
|
|
196
|
-
* @template T Type of the returned rows
|
|
197
|
-
* @param strings SQL query template strings
|
|
198
|
-
* @param values Values to be inserted into the query
|
|
199
|
-
* @returns Array of query results
|
|
200
|
-
*/
|
|
201
|
-
sql(strings, ...values) {
|
|
202
|
-
let query = "";
|
|
203
|
-
try {
|
|
204
|
-
query = strings.reduce(
|
|
205
|
-
(acc, str, i) => acc + str + (i < values.length ? "?" : ""),
|
|
206
|
-
""
|
|
207
|
-
);
|
|
208
|
-
return [...this.ctx.storage.sql.exec(query, ...values)];
|
|
209
|
-
} catch (e) {
|
|
210
|
-
console.error(`failed to execute sql query: ${query}`, e);
|
|
211
|
-
throw this.onError(e);
|
|
212
|
-
}
|
|
213
|
-
}
|
|
214
|
-
/**
|
|
215
|
-
* Update the Agent's state
|
|
216
|
-
* @param state New state to set
|
|
217
|
-
*/
|
|
218
|
-
setState(state) {
|
|
219
|
-
__privateMethod(this, _Agent_instances, setStateInternal_fn).call(this, state, "server");
|
|
220
|
-
}
|
|
221
|
-
/**
|
|
222
|
-
* Called when the Agent's state is updated
|
|
223
|
-
* @param state Updated state
|
|
224
|
-
* @param source Source of the state update ("server" or a client connection)
|
|
225
|
-
*/
|
|
226
|
-
onStateUpdate(state, source) {
|
|
227
|
-
}
|
|
228
|
-
/**
|
|
229
|
-
* Called when the Agent receives an email
|
|
230
|
-
* @param email Email message to process
|
|
231
|
-
*/
|
|
232
|
-
onEmail(email) {
|
|
233
|
-
return agentContext.run(
|
|
234
|
-
{ agent: this, connection: void 0, request: void 0 },
|
|
235
|
-
async () => {
|
|
236
|
-
console.error("onEmail not implemented");
|
|
237
|
-
}
|
|
238
|
-
);
|
|
239
|
-
}
|
|
240
|
-
onError(connectionOrError, error) {
|
|
241
|
-
let theError;
|
|
242
|
-
if (connectionOrError && error) {
|
|
243
|
-
theError = error;
|
|
244
|
-
console.error(
|
|
245
|
-
"Error on websocket connection:",
|
|
246
|
-
connectionOrError.id,
|
|
247
|
-
theError
|
|
248
|
-
);
|
|
249
|
-
console.error(
|
|
250
|
-
"Override onError(connection, error) to handle websocket connection errors"
|
|
251
|
-
);
|
|
252
|
-
} else {
|
|
253
|
-
theError = connectionOrError;
|
|
254
|
-
console.error("Error on server:", theError);
|
|
255
|
-
console.error("Override onError(error) to handle server errors");
|
|
256
|
-
}
|
|
257
|
-
throw theError;
|
|
258
|
-
}
|
|
259
|
-
/**
|
|
260
|
-
* Render content (not implemented in base class)
|
|
261
|
-
*/
|
|
262
|
-
render() {
|
|
263
|
-
throw new Error("Not implemented");
|
|
264
|
-
}
|
|
265
|
-
/**
|
|
266
|
-
* Schedule a task to be executed in the future
|
|
267
|
-
* @template T Type of the payload data
|
|
268
|
-
* @param when When to execute the task (Date, seconds delay, or cron expression)
|
|
269
|
-
* @param callback Name of the method to call
|
|
270
|
-
* @param payload Data to pass to the callback
|
|
271
|
-
* @returns Schedule object representing the scheduled task
|
|
272
|
-
*/
|
|
273
|
-
async schedule(when, callback, payload) {
|
|
274
|
-
const id = nanoid(9);
|
|
275
|
-
if (typeof callback !== "string") {
|
|
276
|
-
throw new Error("Callback must be a string");
|
|
277
|
-
}
|
|
278
|
-
if (typeof this[callback] !== "function") {
|
|
279
|
-
throw new Error(`this.${callback} is not a function`);
|
|
280
|
-
}
|
|
281
|
-
if (when instanceof Date) {
|
|
282
|
-
const timestamp = Math.floor(when.getTime() / 1e3);
|
|
283
|
-
this.sql`
|
|
284
|
-
INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)
|
|
285
|
-
VALUES (${id}, ${callback}, ${JSON.stringify(
|
|
286
|
-
payload
|
|
287
|
-
)}, 'scheduled', ${timestamp})
|
|
288
|
-
`;
|
|
289
|
-
await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
|
|
290
|
-
return {
|
|
291
|
-
id,
|
|
292
|
-
callback,
|
|
293
|
-
payload,
|
|
294
|
-
time: timestamp,
|
|
295
|
-
type: "scheduled"
|
|
296
|
-
};
|
|
297
|
-
}
|
|
298
|
-
if (typeof when === "number") {
|
|
299
|
-
const time = new Date(Date.now() + when * 1e3);
|
|
300
|
-
const timestamp = Math.floor(time.getTime() / 1e3);
|
|
301
|
-
this.sql`
|
|
302
|
-
INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)
|
|
303
|
-
VALUES (${id}, ${callback}, ${JSON.stringify(
|
|
304
|
-
payload
|
|
305
|
-
)}, 'delayed', ${when}, ${timestamp})
|
|
306
|
-
`;
|
|
307
|
-
await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
|
|
308
|
-
return {
|
|
309
|
-
id,
|
|
310
|
-
callback,
|
|
311
|
-
payload,
|
|
312
|
-
delayInSeconds: when,
|
|
313
|
-
time: timestamp,
|
|
314
|
-
type: "delayed"
|
|
315
|
-
};
|
|
316
|
-
}
|
|
317
|
-
if (typeof when === "string") {
|
|
318
|
-
const nextExecutionTime = getNextCronTime(when);
|
|
319
|
-
const timestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
|
|
320
|
-
this.sql`
|
|
321
|
-
INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)
|
|
322
|
-
VALUES (${id}, ${callback}, ${JSON.stringify(
|
|
323
|
-
payload
|
|
324
|
-
)}, 'cron', ${when}, ${timestamp})
|
|
325
|
-
`;
|
|
326
|
-
await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
|
|
327
|
-
return {
|
|
328
|
-
id,
|
|
329
|
-
callback,
|
|
330
|
-
payload,
|
|
331
|
-
cron: when,
|
|
332
|
-
time: timestamp,
|
|
333
|
-
type: "cron"
|
|
334
|
-
};
|
|
335
|
-
}
|
|
336
|
-
throw new Error("Invalid schedule type");
|
|
337
|
-
}
|
|
338
|
-
/**
|
|
339
|
-
* Get a scheduled task by ID
|
|
340
|
-
* @template T Type of the payload data
|
|
341
|
-
* @param id ID of the scheduled task
|
|
342
|
-
* @returns The Schedule object or undefined if not found
|
|
343
|
-
*/
|
|
344
|
-
async getSchedule(id) {
|
|
345
|
-
const result = this.sql`
|
|
346
|
-
SELECT * FROM cf_agents_schedules WHERE id = ${id}
|
|
347
|
-
`;
|
|
348
|
-
if (!result) {
|
|
349
|
-
console.error(`schedule ${id} not found`);
|
|
350
|
-
return void 0;
|
|
351
|
-
}
|
|
352
|
-
return { ...result[0], payload: JSON.parse(result[0].payload) };
|
|
353
|
-
}
|
|
354
|
-
/**
|
|
355
|
-
* Get scheduled tasks matching the given criteria
|
|
356
|
-
* @template T Type of the payload data
|
|
357
|
-
* @param criteria Criteria to filter schedules
|
|
358
|
-
* @returns Array of matching Schedule objects
|
|
359
|
-
*/
|
|
360
|
-
getSchedules(criteria = {}) {
|
|
361
|
-
let query = "SELECT * FROM cf_agents_schedules WHERE 1=1";
|
|
362
|
-
const params = [];
|
|
363
|
-
if (criteria.id) {
|
|
364
|
-
query += " AND id = ?";
|
|
365
|
-
params.push(criteria.id);
|
|
366
|
-
}
|
|
367
|
-
if (criteria.type) {
|
|
368
|
-
query += " AND type = ?";
|
|
369
|
-
params.push(criteria.type);
|
|
370
|
-
}
|
|
371
|
-
if (criteria.timeRange) {
|
|
372
|
-
query += " AND time >= ? AND time <= ?";
|
|
373
|
-
const start = criteria.timeRange.start || /* @__PURE__ */ new Date(0);
|
|
374
|
-
const end = criteria.timeRange.end || /* @__PURE__ */ new Date(999999999999999);
|
|
375
|
-
params.push(
|
|
376
|
-
Math.floor(start.getTime() / 1e3),
|
|
377
|
-
Math.floor(end.getTime() / 1e3)
|
|
378
|
-
);
|
|
379
|
-
}
|
|
380
|
-
const result = this.ctx.storage.sql.exec(query, ...params).toArray().map((row) => ({
|
|
381
|
-
...row,
|
|
382
|
-
payload: JSON.parse(row.payload)
|
|
383
|
-
}));
|
|
384
|
-
return result;
|
|
385
|
-
}
|
|
386
|
-
/**
|
|
387
|
-
* Cancel a scheduled task
|
|
388
|
-
* @param id ID of the task to cancel
|
|
389
|
-
* @returns true if the task was cancelled, false otherwise
|
|
390
|
-
*/
|
|
391
|
-
async cancelSchedule(id) {
|
|
392
|
-
this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;
|
|
393
|
-
await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
|
|
394
|
-
return true;
|
|
395
|
-
}
|
|
396
|
-
/**
|
|
397
|
-
* Method called when an alarm fires
|
|
398
|
-
* Executes any scheduled tasks that are due
|
|
399
|
-
*/
|
|
400
|
-
async alarm() {
|
|
401
|
-
const now = Math.floor(Date.now() / 1e3);
|
|
402
|
-
const result = this.sql`
|
|
403
|
-
SELECT * FROM cf_agents_schedules WHERE time <= ${now}
|
|
404
|
-
`;
|
|
405
|
-
for (const row of result || []) {
|
|
406
|
-
const callback = this[row.callback];
|
|
407
|
-
if (!callback) {
|
|
408
|
-
console.error(`callback ${row.callback} not found`);
|
|
409
|
-
continue;
|
|
410
|
-
}
|
|
411
|
-
await agentContext.run(
|
|
412
|
-
{ agent: this, connection: void 0, request: void 0 },
|
|
413
|
-
async () => {
|
|
414
|
-
try {
|
|
415
|
-
await callback.bind(this)(JSON.parse(row.payload), row);
|
|
416
|
-
} catch (e) {
|
|
417
|
-
console.error(`error executing callback "${row.callback}"`, e);
|
|
418
|
-
}
|
|
419
|
-
}
|
|
420
|
-
);
|
|
421
|
-
if (row.type === "cron") {
|
|
422
|
-
const nextExecutionTime = getNextCronTime(row.cron);
|
|
423
|
-
const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
|
|
424
|
-
this.sql`
|
|
425
|
-
UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
|
|
426
|
-
`;
|
|
427
|
-
} else {
|
|
428
|
-
this.sql`
|
|
429
|
-
DELETE FROM cf_agents_schedules WHERE id = ${row.id}
|
|
430
|
-
`;
|
|
431
|
-
}
|
|
432
|
-
}
|
|
433
|
-
await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
|
|
434
|
-
}
|
|
435
|
-
/**
|
|
436
|
-
* Destroy the Agent, removing all state and scheduled tasks
|
|
437
|
-
*/
|
|
438
|
-
async destroy() {
|
|
439
|
-
this.sql`DROP TABLE IF EXISTS cf_agents_state`;
|
|
440
|
-
this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;
|
|
441
|
-
await this.ctx.storage.deleteAlarm();
|
|
442
|
-
await this.ctx.storage.deleteAll();
|
|
443
|
-
}
|
|
444
|
-
};
|
|
445
|
-
_state = new WeakMap();
|
|
446
|
-
_ParentClass = new WeakMap();
|
|
447
|
-
_Agent_instances = new WeakSet();
|
|
448
|
-
setStateInternal_fn = function(state, source = "server") {
|
|
449
|
-
__privateSet(this, _state, state);
|
|
450
|
-
this.sql`
|
|
451
|
-
INSERT OR REPLACE INTO cf_agents_state (id, state)
|
|
452
|
-
VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})
|
|
453
|
-
`;
|
|
454
|
-
this.sql`
|
|
455
|
-
INSERT OR REPLACE INTO cf_agents_state (id, state)
|
|
456
|
-
VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})
|
|
457
|
-
`;
|
|
458
|
-
this.broadcast(
|
|
459
|
-
JSON.stringify({
|
|
460
|
-
type: "cf_agent_state",
|
|
461
|
-
state
|
|
462
|
-
}),
|
|
463
|
-
source !== "server" ? [source.id] : []
|
|
464
|
-
);
|
|
465
|
-
return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => {
|
|
466
|
-
const { connection, request } = agentContext.getStore() || {};
|
|
467
|
-
return agentContext.run(
|
|
468
|
-
{ agent: this, connection, request },
|
|
469
|
-
async () => {
|
|
470
|
-
return this.onStateUpdate(state, source);
|
|
471
|
-
}
|
|
472
|
-
);
|
|
473
|
-
});
|
|
474
|
-
};
|
|
475
|
-
tryCatch_fn = async function(fn) {
|
|
476
|
-
try {
|
|
477
|
-
return await fn();
|
|
478
|
-
} catch (e) {
|
|
479
|
-
throw this.onError(e);
|
|
480
|
-
}
|
|
481
|
-
};
|
|
482
|
-
scheduleNextAlarm_fn = async function() {
|
|
483
|
-
const result = this.sql`
|
|
484
|
-
SELECT time FROM cf_agents_schedules
|
|
485
|
-
WHERE time > ${Math.floor(Date.now() / 1e3)}
|
|
486
|
-
ORDER BY time ASC
|
|
487
|
-
LIMIT 1
|
|
488
|
-
`;
|
|
489
|
-
if (!result) return;
|
|
490
|
-
if (result.length > 0 && "time" in result[0]) {
|
|
491
|
-
const nextTime = result[0].time * 1e3;
|
|
492
|
-
await this.ctx.storage.setAlarm(nextTime);
|
|
493
|
-
}
|
|
494
|
-
};
|
|
495
|
-
/**
|
|
496
|
-
* Get all methods marked as callable on this Agent
|
|
497
|
-
* @returns A map of method names to their metadata
|
|
498
|
-
*/
|
|
499
|
-
isCallable_fn = function(method) {
|
|
500
|
-
return callableMetadata.has(this[method]);
|
|
501
|
-
};
|
|
502
|
-
/**
|
|
503
|
-
* Agent configuration options
|
|
504
|
-
*/
|
|
505
|
-
Agent.options = {
|
|
506
|
-
/** Whether the Agent should hibernate when inactive */
|
|
507
|
-
hibernate: true
|
|
508
|
-
// default to hibernate
|
|
509
|
-
};
|
|
510
|
-
async function routeAgentRequest(request, env, options) {
|
|
511
|
-
const corsHeaders = options?.cors === true ? {
|
|
512
|
-
"Access-Control-Allow-Origin": "*",
|
|
513
|
-
"Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS",
|
|
514
|
-
"Access-Control-Allow-Credentials": "true",
|
|
515
|
-
"Access-Control-Max-Age": "86400"
|
|
516
|
-
} : options?.cors;
|
|
517
|
-
if (request.method === "OPTIONS") {
|
|
518
|
-
if (corsHeaders) {
|
|
519
|
-
return new Response(null, {
|
|
520
|
-
headers: corsHeaders
|
|
521
|
-
});
|
|
522
|
-
}
|
|
523
|
-
console.warn(
|
|
524
|
-
"Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS."
|
|
525
|
-
);
|
|
526
|
-
}
|
|
527
|
-
let response = await routePartykitRequest(
|
|
528
|
-
request,
|
|
529
|
-
env,
|
|
530
|
-
{
|
|
531
|
-
prefix: "agents",
|
|
532
|
-
...options
|
|
533
|
-
}
|
|
534
|
-
);
|
|
535
|
-
if (response && corsHeaders && request.headers.get("upgrade")?.toLowerCase() !== "websocket" && request.headers.get("Upgrade")?.toLowerCase() !== "websocket") {
|
|
536
|
-
response = new Response(response.body, {
|
|
537
|
-
headers: {
|
|
538
|
-
...response.headers,
|
|
539
|
-
...corsHeaders
|
|
540
|
-
}
|
|
541
|
-
});
|
|
542
|
-
}
|
|
543
|
-
return response;
|
|
544
|
-
}
|
|
545
|
-
async function routeAgentEmail(email, env, options) {
|
|
546
|
-
}
|
|
547
|
-
function getAgentByName(namespace, name, options) {
|
|
548
|
-
return getServerByName(namespace, name, options);
|
|
549
|
-
}
|
|
550
|
-
var _connection, _id, _closed;
|
|
551
|
-
var StreamingResponse = class {
|
|
552
|
-
constructor(connection, id) {
|
|
553
|
-
__privateAdd(this, _connection);
|
|
554
|
-
__privateAdd(this, _id);
|
|
555
|
-
__privateAdd(this, _closed, false);
|
|
556
|
-
__privateSet(this, _connection, connection);
|
|
557
|
-
__privateSet(this, _id, id);
|
|
558
|
-
}
|
|
559
|
-
/**
|
|
560
|
-
* Send a chunk of data to the client
|
|
561
|
-
* @param chunk The data to send
|
|
562
|
-
*/
|
|
563
|
-
send(chunk) {
|
|
564
|
-
if (__privateGet(this, _closed)) {
|
|
565
|
-
throw new Error("StreamingResponse is already closed");
|
|
566
|
-
}
|
|
567
|
-
const response = {
|
|
568
|
-
type: "rpc",
|
|
569
|
-
id: __privateGet(this, _id),
|
|
570
|
-
success: true,
|
|
571
|
-
result: chunk,
|
|
572
|
-
done: false
|
|
573
|
-
};
|
|
574
|
-
__privateGet(this, _connection).send(JSON.stringify(response));
|
|
575
|
-
}
|
|
576
|
-
/**
|
|
577
|
-
* End the stream and send the final chunk (if any)
|
|
578
|
-
* @param finalChunk Optional final chunk of data to send
|
|
579
|
-
*/
|
|
580
|
-
end(finalChunk) {
|
|
581
|
-
if (__privateGet(this, _closed)) {
|
|
582
|
-
throw new Error("StreamingResponse is already closed");
|
|
583
|
-
}
|
|
584
|
-
__privateSet(this, _closed, true);
|
|
585
|
-
const response = {
|
|
586
|
-
type: "rpc",
|
|
587
|
-
id: __privateGet(this, _id),
|
|
588
|
-
success: true,
|
|
589
|
-
result: finalChunk,
|
|
590
|
-
done: true
|
|
591
|
-
};
|
|
592
|
-
__privateGet(this, _connection).send(JSON.stringify(response));
|
|
593
|
-
}
|
|
594
|
-
};
|
|
595
|
-
_connection = new WeakMap();
|
|
596
|
-
_id = new WeakMap();
|
|
597
|
-
_closed = new WeakMap();
|
|
598
|
-
|
|
599
|
-
export {
|
|
600
|
-
unstable_callable,
|
|
601
|
-
getCurrentAgent,
|
|
602
|
-
Agent,
|
|
603
|
-
routeAgentRequest,
|
|
604
|
-
routeAgentEmail,
|
|
605
|
-
getAgentByName,
|
|
606
|
-
StreamingResponse
|
|
607
|
-
};
|
|
608
|
-
//# sourceMappingURL=chunk-WNIGPPNB.js.map
|