agents 0.0.0-e777fdd → 0.0.0-e7d0d4d
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/ai-chat-agent.d.ts +16 -17
- package/dist/ai-chat-agent.js +532 -352
- package/dist/ai-chat-agent.js.map +1 -1
- package/dist/ai-chat-v5-migration-DBHGW4Hv.js +155 -0
- package/dist/ai-chat-v5-migration-DBHGW4Hv.js.map +1 -0
- package/dist/ai-chat-v5-migration.d.ts +7 -4
- package/dist/ai-chat-v5-migration.js +3 -20
- package/dist/ai-react.d.ts +14 -23
- package/dist/ai-react.js +258 -349
- package/dist/ai-react.js.map +1 -1
- package/dist/ai-types-B3aQaFv3.js +20 -0
- package/dist/ai-types-B3aQaFv3.js.map +1 -0
- package/dist/ai-types-D5YoPrBZ.d.ts +95 -0
- package/dist/ai-types.d.ts +6 -92
- package/dist/ai-types.js +3 -8
- package/dist/client-9Ld2_lnt.js +786 -0
- package/dist/client-9Ld2_lnt.js.map +1 -0
- package/dist/client-BfiZ3HQd.js +117 -0
- package/dist/client-BfiZ3HQd.js.map +1 -0
- package/dist/client-CbWe9FBd.d.ts +104 -0
- package/dist/client-Csp_m13H.d.ts +5315 -0
- package/dist/client.d.ts +11 -92
- package/dist/client.js +4 -13
- package/dist/codemode/ai.d.ts +27 -0
- package/dist/codemode/ai.js +151 -0
- package/dist/codemode/ai.js.map +1 -0
- package/dist/do-oauth-client-provider-CswoD5Lu.js +93 -0
- package/dist/do-oauth-client-provider-CswoD5Lu.js.map +1 -0
- package/dist/do-oauth-client-provider-DGc5pP0l.d.ts +55 -0
- package/dist/index-DFqsR7mb.d.ts +560 -0
- package/dist/index-DhJCaDWd.d.ts +58 -0
- package/dist/index.d.ts +55 -556
- package/dist/index.js +7 -32
- package/dist/mcp/client.d.ts +4 -11
- package/dist/mcp/client.js +3 -10
- package/dist/mcp/do-oauth-client-provider.d.ts +2 -50
- package/dist/mcp/do-oauth-client-provider.js +3 -8
- package/dist/mcp/index.d.ts +151 -75
- package/dist/mcp/index.js +1355 -1081
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/x402.d.ts +22 -27
- package/dist/mcp/x402.js +186 -3187
- package/dist/mcp/x402.js.map +1 -1
- package/dist/mcp-Dw5vDrY8.d.ts +61 -0
- package/dist/observability/index.d.ts +3 -46
- package/dist/observability/index.js +7 -12
- package/dist/react-NCPvtyCY.d.ts +115 -0
- package/dist/react.d.ts +10 -123
- package/dist/react.js +183 -113
- package/dist/react.js.map +1 -1
- package/dist/schedule.d.ts +13 -10
- package/dist/schedule.js +43 -33
- package/dist/schedule.js.map +1 -1
- package/dist/serializable-CymX8ovI.d.ts +39 -0
- package/dist/serializable.d.ts +7 -32
- package/dist/serializable.js +1 -1
- package/dist/src-Dz0H9hSU.js +1200 -0
- package/dist/src-Dz0H9hSU.js.map +1 -0
- package/package.json +30 -12
- package/dist/_esm-LV5FJ3HK.js +0 -3922
- package/dist/_esm-LV5FJ3HK.js.map +0 -1
- package/dist/ai-chat-v5-migration.js.map +0 -1
- package/dist/ai-types.js.map +0 -1
- package/dist/ccip-CMBYN64O.js +0 -15
- package/dist/ccip-CMBYN64O.js.map +0 -1
- package/dist/chunk-5Y6BEZDY.js +0 -276
- package/dist/chunk-5Y6BEZDY.js.map +0 -1
- package/dist/chunk-BER7KXUJ.js +0 -18
- package/dist/chunk-BER7KXUJ.js.map +0 -1
- package/dist/chunk-JJBFIGUC.js +0 -5202
- package/dist/chunk-JJBFIGUC.js.map +0 -1
- package/dist/chunk-PR4QN5HX.js +0 -43
- package/dist/chunk-PR4QN5HX.js.map +0 -1
- package/dist/chunk-QEPGNUG6.js +0 -650
- package/dist/chunk-QEPGNUG6.js.map +0 -1
- package/dist/chunk-QEVM4BVL.js +0 -116
- package/dist/chunk-QEVM4BVL.js.map +0 -1
- package/dist/chunk-RS5OCNEQ.js +0 -1323
- package/dist/chunk-RS5OCNEQ.js.map +0 -1
- package/dist/chunk-TYAY6AU6.js +0 -159
- package/dist/chunk-TYAY6AU6.js.map +0 -1
- package/dist/chunk-UJVEAURM.js +0 -150
- package/dist/chunk-UJVEAURM.js.map +0 -1
- package/dist/chunk-XFS5ERG3.js +0 -127
- package/dist/chunk-XFS5ERG3.js.map +0 -1
- package/dist/client-BohGLma8.d.ts +0 -5041
- package/dist/client.js.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/mcp/client.js.map +0 -1
- package/dist/mcp/do-oauth-client-provider.js.map +0 -1
- package/dist/observability/index.js.map +0 -1
- package/dist/secp256k1-M22GZP2U.js +0 -2193
- package/dist/secp256k1-M22GZP2U.js.map +0 -1
- package/dist/serializable.js.map +0 -1
- package/src/index.ts +0 -1987
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/observability/index.ts"],"sourcesContent":["import type { env } from \"cloudflare:workers\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { SSEClientTransportOptions } from \"@modelcontextprotocol/sdk/client/sse.js\";\n\nimport type {\n Prompt,\n Resource,\n ServerCapabilities,\n Tool\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { parseCronExpression } from \"cron-schedule\";\nimport { nanoid } from \"nanoid\";\nimport { EmailMessage } from \"cloudflare:email\";\nimport {\n type Connection,\n type ConnectionContext,\n type PartyServerOptions,\n Server,\n type WSMessage,\n getServerByName,\n routePartykitRequest\n} from \"partyserver\";\nimport { camelCaseToKebabCase } from \"./client\";\nimport { MCPClientManager } from \"./mcp/client\";\nimport { DurableObjectOAuthClientProvider } from \"./mcp/do-oauth-client-provider\";\nimport type { TransportType } from \"./mcp/types\";\nimport { genericObservability, type Observability } from \"./observability\";\nimport { MessageType } from \"./ai-types\";\n\nexport type { Connection, ConnectionContext, WSMessage } from \"partyserver\";\n\n/**\n * RPC request message from client\n */\nexport type RPCRequest = {\n type: \"rpc\";\n id: string;\n method: string;\n args: unknown[];\n};\n\n/**\n * State update message from client\n */\nexport type StateUpdateMessage = {\n type: MessageType.CF_AGENT_STATE;\n state: unknown;\n};\n\n/**\n * RPC response message to client\n */\nexport type RPCResponse = {\n type: MessageType.RPC;\n id: string;\n} & (\n | {\n success: true;\n result: unknown;\n done?: false;\n }\n | {\n success: true;\n result: unknown;\n done: true;\n }\n | {\n success: false;\n error: string;\n }\n);\n\n/**\n * Type guard for RPC request messages\n */\nfunction isRPCRequest(msg: unknown): msg is RPCRequest {\n return (\n typeof msg === \"object\" &&\n msg !== null &&\n \"type\" in msg &&\n msg.type === MessageType.RPC &&\n \"id\" in msg &&\n typeof msg.id === \"string\" &&\n \"method\" in msg &&\n typeof msg.method === \"string\" &&\n \"args\" in msg &&\n Array.isArray((msg as RPCRequest).args)\n );\n}\n\n/**\n * Type guard for state update messages\n */\nfunction isStateUpdateMessage(msg: unknown): msg is StateUpdateMessage {\n return (\n typeof msg === \"object\" &&\n msg !== null &&\n \"type\" in msg &&\n msg.type === MessageType.CF_AGENT_STATE &&\n \"state\" in msg\n );\n}\n\n/**\n * Metadata for a callable method\n */\nexport type CallableMetadata = {\n /** Optional description of what the method does */\n description?: string;\n /** Whether the method supports streaming responses */\n streaming?: boolean;\n};\n\nconst callableMetadata = new Map<Function, CallableMetadata>();\n\n/**\n * Decorator that marks a method as callable by clients\n * @param metadata Optional metadata about the callable method\n */\nexport function callable(metadata: CallableMetadata = {}) {\n return function callableDecorator<This, Args extends unknown[], Return>(\n target: (this: This, ...args: Args) => Return,\n // biome-ignore lint/correctness/noUnusedFunctionParameters: later\n context: ClassMethodDecoratorContext\n ) {\n if (!callableMetadata.has(target)) {\n callableMetadata.set(target, metadata);\n }\n\n return target;\n };\n}\n\nlet didWarnAboutUnstableCallable = false;\n\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 */\nexport const unstable_callable = (metadata: CallableMetadata = {}) => {\n if (!didWarnAboutUnstableCallable) {\n didWarnAboutUnstableCallable = true;\n console.warn(\n \"unstable_callable is deprecated, use callable instead. unstable_callable will be removed in the next major version.\"\n );\n }\n callable(metadata);\n};\n\nexport type QueueItem<T = string> = {\n id: string;\n payload: T;\n callback: keyof Agent<unknown>;\n created_at: number;\n};\n\n/**\n * Represents a scheduled task within an Agent\n * @template T Type of the payload data\n */\nexport type Schedule<T = string> = {\n /** Unique identifier for the schedule */\n id: string;\n /** Name of the method to be called */\n callback: string;\n /** Data to be passed to the callback */\n payload: T;\n} & (\n | {\n /** Type of schedule for one-time execution at a specific time */\n type: \"scheduled\";\n /** Timestamp when the task should execute */\n time: number;\n }\n | {\n /** Type of schedule for delayed execution */\n type: \"delayed\";\n /** Timestamp when the task should execute */\n time: number;\n /** Number of seconds to delay execution */\n delayInSeconds: number;\n }\n | {\n /** Type of schedule for recurring execution based on cron expression */\n type: \"cron\";\n /** Timestamp for the next execution */\n time: number;\n /** Cron expression defining the schedule */\n cron: string;\n }\n);\n\nfunction getNextCronTime(cron: string) {\n const interval = parseCronExpression(cron);\n return interval.getNextDate();\n}\n\nexport type { TransportType } from \"./mcp/types\";\n\n/**\n * MCP Server state update message from server -> Client\n */\nexport type MCPServerMessage = {\n type: MessageType.CF_AGENT_MCP_SERVERS;\n mcp: MCPServersState;\n};\n\nexport type MCPServersState = {\n servers: {\n [id: string]: MCPServer;\n };\n tools: Tool[];\n prompts: Prompt[];\n resources: Resource[];\n};\n\nexport type MCPServer = {\n name: string;\n server_url: string;\n auth_url: string | null;\n // This state is specifically about the temporary process of getting a token (if needed).\n // Scope outside of that can't be relied upon because when the DO sleeps, there's no way\n // to communicate a change to a non-ready state.\n state: \"authenticating\" | \"connecting\" | \"ready\" | \"discovering\" | \"failed\";\n instructions: string | null;\n capabilities: ServerCapabilities | null;\n};\n\n/**\n * MCP Server data stored in DO SQL for resuming MCP Server connections\n */\ntype MCPServerRow = {\n id: string;\n name: string;\n server_url: string;\n client_id: string | null;\n auth_url: string | null;\n callback_url: string;\n server_options: string;\n};\n\nconst STATE_ROW_ID = \"cf_state_row_id\";\nconst STATE_WAS_CHANGED = \"cf_state_was_changed\";\n\nconst DEFAULT_STATE = {} as unknown;\n\nconst agentContext = new AsyncLocalStorage<{\n agent: Agent<unknown, unknown>;\n connection: Connection | undefined;\n request: Request | undefined;\n email: AgentEmail | undefined;\n}>();\n\nexport function getCurrentAgent<\n T extends Agent<unknown, unknown> = Agent<unknown, unknown>\n>(): {\n agent: T | undefined;\n connection: Connection | undefined;\n request: Request | undefined;\n email: AgentEmail | undefined;\n} {\n const store = agentContext.getStore() as\n | {\n agent: T;\n connection: Connection | undefined;\n request: Request | undefined;\n email: AgentEmail | undefined;\n }\n | undefined;\n if (!store) {\n return {\n agent: undefined,\n connection: undefined,\n request: undefined,\n email: undefined\n };\n }\n return store;\n}\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 */\n\n// biome-ignore lint/suspicious/noExplicitAny: I can't typescript\nfunction withAgentContext<T extends (...args: any[]) => any>(\n method: T\n): (this: Agent<unknown, unknown>, ...args: Parameters<T>) => ReturnType<T> {\n return function (...args: Parameters<T>): ReturnType<T> {\n const { connection, request, email, agent } = getCurrentAgent();\n\n if (agent === this) {\n // already wrapped, so we can just call the method\n return method.apply(this, args);\n }\n // not wrapped, so we need to wrap it\n return agentContext.run({ agent: this, connection, request, email }, () => {\n return method.apply(this, args);\n });\n };\n}\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 */\nexport class Agent<\n Env = typeof env,\n State = unknown,\n Props extends Record<string, unknown> = Record<string, unknown>\n> extends Server<Env, Props> {\n private _state = DEFAULT_STATE as State;\n\n private _ParentClass: typeof Agent<Env, State> =\n Object.getPrototypeOf(this).constructor;\n\n readonly mcp: MCPClientManager = new MCPClientManager(\n this._ParentClass.name,\n \"0.0.1\"\n );\n\n /**\n * Initial state for the Agent\n * Override to provide default state values\n */\n initialState: State = DEFAULT_STATE as State;\n\n /**\n * Current state of the Agent\n */\n get state(): State {\n if (this._state !== DEFAULT_STATE) {\n // state was previously set, and populated internal state\n return this._state;\n }\n // looks like this is the first time the state is being accessed\n // check if the state was set in a previous life\n const wasChanged = this.sql<{ state: \"true\" | undefined }>`\n SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}\n `;\n\n // ok, let's pick up the actual state from the db\n const result = this.sql<{ state: State | undefined }>`\n SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}\n `;\n\n if (\n wasChanged[0]?.state === \"true\" ||\n // we do this check for people who updated their code before we shipped wasChanged\n result[0]?.state\n ) {\n const state = result[0]?.state as string; // could be null?\n\n this._state = JSON.parse(state);\n return this._state;\n }\n\n // ok, this is the first time the state is being accessed\n // and the state was not set in a previous life\n // so we need to set the initial state (if provided)\n if (this.initialState === DEFAULT_STATE) {\n // no initial state provided, so we return undefined\n return undefined as State;\n }\n // initial state provided, so we set the state,\n // update db and return the initial state\n this.setState(this.initialState);\n return this.initialState;\n }\n\n /**\n * Agent configuration options\n */\n static options = {\n /** Whether the Agent should hibernate when inactive */\n hibernate: true // default to hibernate\n };\n\n /**\n * The observability implementation to use for the Agent\n */\n observability?: Observability = genericObservability;\n\n /**\n * Execute SQL queries against the Agent's database\n * @template T Type of the returned rows\n * @param strings SQL query template strings\n * @param values Values to be inserted into the query\n * @returns Array of query results\n */\n sql<T = Record<string, string | number | boolean | null>>(\n strings: TemplateStringsArray,\n ...values: (string | number | boolean | null)[]\n ) {\n let query = \"\";\n try {\n // Construct the SQL query with placeholders\n query = strings.reduce(\n (acc, str, i) => acc + str + (i < values.length ? \"?\" : \"\"),\n \"\"\n );\n\n // Execute the SQL query with the provided values\n return [...this.ctx.storage.sql.exec(query, ...values)] as T[];\n } catch (e) {\n console.error(`failed to execute sql query: ${query}`, e);\n throw this.onError(e);\n }\n }\n constructor(ctx: AgentContext, env: Env) {\n super(ctx, env);\n\n if (!wrappedClasses.has(this.constructor)) {\n // Auto-wrap custom methods with agent context\n this._autoWrapCustomMethods();\n wrappedClasses.add(this.constructor);\n }\n\n this.sql`\n CREATE TABLE IF NOT EXISTS cf_agents_state (\n id TEXT PRIMARY KEY NOT NULL,\n state TEXT\n )\n `;\n\n this.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\n void this.ctx.blockConcurrencyWhile(async () => {\n return this._tryCatch(async () => {\n // Create alarms table if it doesn't exist\n this.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\n // execute any pending alarms and schedule the next alarm\n await this.alarm();\n });\n });\n\n this.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\n const _onRequest = this.onRequest.bind(this);\n this.onRequest = (request: Request) => {\n return agentContext.run(\n { agent: this, connection: undefined, request, email: undefined },\n async () => {\n if (this.mcp.isCallbackRequest(request)) {\n await this.mcp.handleCallbackRequest(request);\n\n // after the MCP connection handshake, we can send updated mcp state\n this.broadcast(\n JSON.stringify({\n mcp: this.getMcpServers(),\n type: MessageType.CF_AGENT_MCP_SERVERS\n })\n );\n\n // We probably should let the user configure this response/redirect, but this is fine for now.\n return new Response(\"<script>window.close();</script>\", {\n headers: { \"content-type\": \"text/html\" },\n status: 200\n });\n }\n\n return this._tryCatch(() => _onRequest(request));\n }\n );\n };\n\n const _onMessage = this.onMessage.bind(this);\n this.onMessage = async (connection: Connection, message: WSMessage) => {\n return agentContext.run(\n { agent: this, connection, request: undefined, email: undefined },\n async () => {\n if (typeof message !== \"string\") {\n return this._tryCatch(() => _onMessage(connection, message));\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(message);\n } catch (_e) {\n // silently fail and let the onMessage handler handle it\n return this._tryCatch(() => _onMessage(connection, message));\n }\n\n if (isStateUpdateMessage(parsed)) {\n this._setStateInternal(parsed.state as State, connection);\n return;\n }\n\n if (isRPCRequest(parsed)) {\n try {\n const { id, method, args } = parsed;\n\n // Check if method exists and is callable\n const methodFn = this[method as keyof this];\n if (typeof methodFn !== \"function\") {\n throw new Error(`Method ${method} does not exist`);\n }\n\n if (!this._isCallable(method)) {\n throw new Error(`Method ${method} is not callable`);\n }\n\n const metadata = callableMetadata.get(methodFn as Function);\n\n // For streaming methods, pass a StreamingResponse object\n if (metadata?.streaming) {\n const stream = new StreamingResponse(connection, id);\n await methodFn.apply(this, [stream, ...args]);\n return;\n }\n\n // For regular methods, execute and send response\n const result = await methodFn.apply(this, args);\n\n this.observability?.emit(\n {\n displayMessage: `RPC call to ${method}`,\n id: nanoid(),\n payload: {\n method,\n streaming: metadata?.streaming\n },\n timestamp: Date.now(),\n type: \"rpc\"\n },\n this.ctx\n );\n\n const response: RPCResponse = {\n done: true,\n id,\n result,\n success: true,\n type: MessageType.RPC\n };\n connection.send(JSON.stringify(response));\n } catch (e) {\n // Send error response\n const response: RPCResponse = {\n error:\n e instanceof Error ? e.message : \"Unknown error occurred\",\n id: parsed.id,\n success: false,\n type: MessageType.RPC\n };\n connection.send(JSON.stringify(response));\n console.error(\"RPC error:\", e);\n }\n return;\n }\n\n return this._tryCatch(() => _onMessage(connection, message));\n }\n );\n };\n\n const _onConnect = this.onConnect.bind(this);\n this.onConnect = (connection: Connection, ctx: ConnectionContext) => {\n // TODO: This is a hack to ensure the state is sent after the connection is established\n // must fix this\n return agentContext.run(\n { agent: this, connection, request: ctx.request, email: undefined },\n () => {\n if (this.state) {\n connection.send(\n JSON.stringify({\n state: this.state,\n type: MessageType.CF_AGENT_STATE\n })\n );\n }\n\n connection.send(\n JSON.stringify({\n mcp: this.getMcpServers(),\n type: MessageType.CF_AGENT_MCP_SERVERS\n })\n );\n\n this.observability?.emit(\n {\n displayMessage: \"Connection established\",\n id: nanoid(),\n payload: {\n connectionId: connection.id\n },\n timestamp: Date.now(),\n type: \"connect\"\n },\n this.ctx\n );\n return this._tryCatch(() => _onConnect(connection, ctx));\n }\n );\n };\n\n const _onStart = this.onStart.bind(this);\n this.onStart = async (props?: Props) => {\n return agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n async () => {\n await this._tryCatch(() => {\n const servers = this.sql<MCPServerRow>`\n SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;\n `;\n\n this.broadcast(\n JSON.stringify({\n mcp: this.getMcpServers(),\n type: MessageType.CF_AGENT_MCP_SERVERS\n })\n );\n\n // from DO storage, reconnect to all servers not currently in the oauth flow using our saved auth information\n if (servers && Array.isArray(servers) && servers.length > 0) {\n // Restore callback URLs for OAuth-enabled servers\n servers.forEach((server) => {\n if (server.callback_url) {\n this.mcp.registerCallbackUrl(server.callback_url);\n }\n });\n\n servers.forEach((server) => {\n this._connectToMcpServerInternal(\n server.name,\n server.server_url,\n server.callback_url,\n server.server_options\n ? JSON.parse(server.server_options)\n : undefined,\n {\n id: server.id,\n oauthClientId: server.client_id ?? undefined\n }\n )\n .then(() => {\n // Broadcast updated MCP servers state after each server connects\n this.broadcast(\n JSON.stringify({\n mcp: this.getMcpServers(),\n type: MessageType.CF_AGENT_MCP_SERVERS\n })\n );\n })\n .catch((error) => {\n console.error(\n `Error connecting to MCP server: ${server.name} (${server.server_url})`,\n error\n );\n // Still broadcast even if connection fails, so clients know about the failure\n this.broadcast(\n JSON.stringify({\n mcp: this.getMcpServers(),\n type: MessageType.CF_AGENT_MCP_SERVERS\n })\n );\n });\n });\n }\n return _onStart(props);\n });\n }\n );\n };\n }\n\n private _setStateInternal(\n state: State,\n source: Connection | \"server\" = \"server\"\n ) {\n this._state = state;\n this.sql`\n INSERT OR REPLACE INTO cf_agents_state (id, state)\n VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})\n `;\n this.sql`\n INSERT OR REPLACE INTO cf_agents_state (id, state)\n VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})\n `;\n this.broadcast(\n JSON.stringify({\n state: state,\n type: MessageType.CF_AGENT_STATE\n }),\n source !== \"server\" ? [source.id] : []\n );\n return this._tryCatch(() => {\n const { connection, request, email } = agentContext.getStore() || {};\n return agentContext.run(\n { agent: this, connection, request, email },\n async () => {\n this.observability?.emit(\n {\n displayMessage: \"State updated\",\n id: nanoid(),\n payload: {},\n timestamp: Date.now(),\n type: \"state:update\"\n },\n this.ctx\n );\n return this.onStateUpdate(state, source);\n }\n );\n });\n }\n\n /**\n * Update the Agent's state\n * @param state New state to set\n */\n setState(state: State) {\n this._setStateInternal(state, \"server\");\n }\n\n /**\n * Called when the Agent's state is updated\n * @param state Updated state\n * @param source Source of the state update (\"server\" or a client connection)\n */\n // biome-ignore lint/correctness/noUnusedFunctionParameters: overridden later\n onStateUpdate(state: State | undefined, source: Connection | \"server\") {\n // override this to handle state updates\n }\n\n /**\n * Called when the Agent receives an email via routeAgentEmail()\n * Override this method to handle incoming emails\n * @param email Email message to process\n */\n async _onEmail(email: AgentEmail) {\n // nb: we use this roundabout way of getting to onEmail\n // because of https://github.com/cloudflare/workerd/issues/4499\n return agentContext.run(\n { agent: this, connection: undefined, request: undefined, email: email },\n async () => {\n if (\"onEmail\" in this && typeof this.onEmail === \"function\") {\n return this._tryCatch(() =>\n (this.onEmail as (email: AgentEmail) => Promise<void>)(email)\n );\n } else {\n console.log(\"Received email from:\", email.from, \"to:\", email.to);\n console.log(\"Subject:\", email.headers.get(\"subject\"));\n console.log(\n \"Implement onEmail(email: AgentEmail): Promise<void> in your agent to process emails\"\n );\n }\n }\n );\n }\n\n /**\n * Reply to an email\n * @param email The email to reply to\n * @param options Options for the reply\n * @returns void\n */\n async replyToEmail(\n email: AgentEmail,\n options: {\n fromName: string;\n subject?: string | undefined;\n body: string;\n contentType?: string;\n headers?: Record<string, string>;\n }\n ): Promise<void> {\n return this._tryCatch(async () => {\n const agentName = camelCaseToKebabCase(this._ParentClass.name);\n const agentId = this.name;\n\n const { createMimeMessage } = await import(\"mimetext\");\n const msg = createMimeMessage();\n msg.setSender({ addr: email.to, name: options.fromName });\n msg.setRecipient(email.from);\n msg.setSubject(\n options.subject || `Re: ${email.headers.get(\"subject\")}` || \"No subject\"\n );\n msg.addMessage({\n contentType: options.contentType || \"text/plain\",\n data: options.body\n });\n\n const domain = email.from.split(\"@\")[1];\n const messageId = `<${agentId}@${domain}>`;\n msg.setHeader(\"In-Reply-To\", email.headers.get(\"Message-ID\")!);\n msg.setHeader(\"Message-ID\", messageId);\n msg.setHeader(\"X-Agent-Name\", agentName);\n msg.setHeader(\"X-Agent-ID\", agentId);\n\n if (options.headers) {\n for (const [key, value] of Object.entries(options.headers)) {\n msg.setHeader(key, value);\n }\n }\n await email.reply({\n from: email.to,\n raw: msg.asRaw(),\n to: email.from\n });\n });\n }\n\n private async _tryCatch<T>(fn: () => T | Promise<T>) {\n try {\n return await fn();\n } catch (e) {\n throw this.onError(e);\n }\n }\n\n /**\n * Automatically wrap custom methods with agent context\n * This ensures getCurrentAgent() works in all custom methods without decorators\n */\n private _autoWrapCustomMethods() {\n // Collect all methods from base prototypes (Agent and Server)\n const basePrototypes = [Agent.prototype, Server.prototype];\n const baseMethods = new Set<string>();\n for (const baseProto of basePrototypes) {\n let proto = baseProto;\n while (proto && proto !== Object.prototype) {\n const methodNames = Object.getOwnPropertyNames(proto);\n for (const methodName of methodNames) {\n baseMethods.add(methodName);\n }\n proto = Object.getPrototypeOf(proto);\n }\n }\n // Get all methods from the current instance's prototype chain\n let proto = Object.getPrototypeOf(this);\n let depth = 0;\n while (proto && proto !== Object.prototype && depth < 10) {\n const methodNames = Object.getOwnPropertyNames(proto);\n for (const methodName of methodNames) {\n const descriptor = Object.getOwnPropertyDescriptor(proto, methodName);\n\n // Skip if it's a private method, a base method, a getter, or not a function,\n if (\n baseMethods.has(methodName) ||\n methodName.startsWith(\"_\") ||\n !descriptor ||\n !!descriptor.get ||\n typeof descriptor.value !== \"function\"\n ) {\n continue;\n }\n\n // Now, methodName is confirmed to be a custom method/function\n // Wrap the custom method with context\n const wrappedFunction = withAgentContext(\n // biome-ignore lint/suspicious/noExplicitAny: I can't typescript\n this[methodName as keyof this] as (...args: any[]) => any\n // biome-ignore lint/suspicious/noExplicitAny: I can't typescript\n ) as any;\n\n // if the method is callable, copy the metadata from the original method\n if (this._isCallable(methodName)) {\n callableMetadata.set(\n wrappedFunction,\n callableMetadata.get(this[methodName as keyof this] as Function)!\n );\n }\n\n // set the wrapped function on the prototype\n this.constructor.prototype[methodName as keyof this] = wrappedFunction;\n }\n\n proto = Object.getPrototypeOf(proto);\n depth++;\n }\n }\n\n override onError(\n connection: Connection,\n error: unknown\n ): void | Promise<void>;\n override onError(error: unknown): void | Promise<void>;\n override onError(connectionOrError: Connection | unknown, error?: unknown) {\n let theError: unknown;\n if (connectionOrError && error) {\n theError = error;\n // this is a websocket connection error\n console.error(\n \"Error on websocket connection:\",\n (connectionOrError as Connection).id,\n theError\n );\n console.error(\n \"Override onError(connection, error) to handle websocket connection errors\"\n );\n } else {\n theError = connectionOrError;\n // this is a server error\n console.error(\"Error on server:\", theError);\n console.error(\"Override onError(error) to handle server errors\");\n }\n throw theError;\n }\n\n /**\n * Render content (not implemented in base class)\n */\n render() {\n throw new Error(\"Not implemented\");\n }\n\n /**\n * Queue a task to be executed in the future\n * @param payload Payload to pass to the callback\n * @param callback Name of the method to call\n * @returns The ID of the queued task\n */\n async queue<T = unknown>(callback: keyof this, payload: T): Promise<string> {\n const id = nanoid(9);\n if (typeof callback !== \"string\") {\n throw new Error(\"Callback must be a string\");\n }\n\n if (typeof this[callback] !== \"function\") {\n throw new Error(`this.${callback} is not a function`);\n }\n\n this.sql`\n INSERT OR REPLACE INTO cf_agents_queues (id, payload, callback)\n VALUES (${id}, ${JSON.stringify(payload)}, ${callback})\n `;\n\n void this._flushQueue().catch((e) => {\n console.error(\"Error flushing queue:\", e);\n });\n\n return id;\n }\n\n private _flushingQueue = false;\n\n private async _flushQueue() {\n if (this._flushingQueue) {\n return;\n }\n this._flushingQueue = true;\n while (true) {\n const result = this.sql<QueueItem<string>>`\n SELECT * FROM cf_agents_queues\n ORDER BY created_at ASC\n `;\n\n if (!result || result.length === 0) {\n break;\n }\n\n for (const row of result || []) {\n const callback = this[row.callback as keyof Agent<Env>];\n if (!callback) {\n console.error(`callback ${row.callback} not found`);\n continue;\n }\n const { connection, request, email } = agentContext.getStore() || {};\n await agentContext.run(\n {\n agent: this,\n connection,\n request,\n email\n },\n async () => {\n // TODO: add retries and backoff\n await (\n callback as (\n payload: unknown,\n queueItem: QueueItem<string>\n ) => Promise<void>\n ).bind(this)(JSON.parse(row.payload as string), row);\n await this.dequeue(row.id);\n }\n );\n }\n }\n this._flushingQueue = false;\n }\n\n /**\n * Dequeue a task by ID\n * @param id ID of the task to dequeue\n */\n async dequeue(id: string) {\n this.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;\n }\n\n /**\n * Dequeue all tasks\n */\n async dequeueAll() {\n this.sql`DELETE FROM cf_agents_queues`;\n }\n\n /**\n * Dequeue all tasks by callback\n * @param callback Name of the callback to dequeue\n */\n async dequeueAllByCallback(callback: string) {\n this.sql`DELETE FROM cf_agents_queues WHERE callback = ${callback}`;\n }\n\n /**\n * Get a queued task by ID\n * @param id ID of the task to get\n * @returns The task or undefined if not found\n */\n async getQueue(id: string): Promise<QueueItem<string> | undefined> {\n const result = this.sql<QueueItem<string>>`\n SELECT * FROM cf_agents_queues WHERE id = ${id}\n `;\n return result\n ? { ...result[0], payload: JSON.parse(result[0].payload) }\n : undefined;\n }\n\n /**\n * Get all queues by key and value\n * @param key Key to filter by\n * @param value Value to filter by\n * @returns Array of matching QueueItem objects\n */\n async getQueues(key: string, value: string): Promise<QueueItem<string>[]> {\n const result = this.sql<QueueItem<string>>`\n SELECT * FROM cf_agents_queues\n `;\n return result.filter((row) => JSON.parse(row.payload)[key] === value);\n }\n\n /**\n * Schedule a task to be executed in the future\n * @template T Type of the payload data\n * @param when When to execute the task (Date, seconds delay, or cron expression)\n * @param callback Name of the method to call\n * @param payload Data to pass to the callback\n * @returns Schedule object representing the scheduled task\n */\n async schedule<T = string>(\n when: Date | string | number,\n callback: keyof this,\n payload?: T\n ): Promise<Schedule<T>> {\n const id = nanoid(9);\n\n const emitScheduleCreate = (schedule: Schedule<T>) =>\n this.observability?.emit(\n {\n displayMessage: `Schedule ${schedule.id} created`,\n id: nanoid(),\n payload: {\n callback: callback as string,\n id: id\n },\n timestamp: Date.now(),\n type: \"schedule:create\"\n },\n this.ctx\n );\n\n if (typeof callback !== \"string\") {\n throw new Error(\"Callback must be a string\");\n }\n\n if (typeof this[callback] !== \"function\") {\n throw new Error(`this.${callback} is not a function`);\n }\n\n if (when instanceof Date) {\n const timestamp = Math.floor(when.getTime() / 1000);\n this.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)\n VALUES (${id}, ${callback}, ${JSON.stringify(\n payload\n )}, 'scheduled', ${timestamp})\n `;\n\n await this._scheduleNextAlarm();\n\n const schedule: Schedule<T> = {\n callback: callback,\n id,\n payload: payload as T,\n time: timestamp,\n type: \"scheduled\"\n };\n\n emitScheduleCreate(schedule);\n\n return schedule;\n }\n if (typeof when === \"number\") {\n const time = new Date(Date.now() + when * 1000);\n const timestamp = Math.floor(time.getTime() / 1000);\n\n this.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)\n VALUES (${id}, ${callback}, ${JSON.stringify(\n payload\n )}, 'delayed', ${when}, ${timestamp})\n `;\n\n await this._scheduleNextAlarm();\n\n const schedule: Schedule<T> = {\n callback: callback,\n delayInSeconds: when,\n id,\n payload: payload as T,\n time: timestamp,\n type: \"delayed\"\n };\n\n emitScheduleCreate(schedule);\n\n return schedule;\n }\n if (typeof when === \"string\") {\n const nextExecutionTime = getNextCronTime(when);\n const timestamp = Math.floor(nextExecutionTime.getTime() / 1000);\n\n this.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)\n VALUES (${id}, ${callback}, ${JSON.stringify(\n payload\n )}, 'cron', ${when}, ${timestamp})\n `;\n\n await this._scheduleNextAlarm();\n\n const schedule: Schedule<T> = {\n callback: callback,\n cron: when,\n id,\n payload: payload as T,\n time: timestamp,\n type: \"cron\"\n };\n\n emitScheduleCreate(schedule);\n\n return schedule;\n }\n throw new Error(\"Invalid schedule type\");\n }\n\n /**\n * Get a scheduled task by ID\n * @template T Type of the payload data\n * @param id ID of the scheduled task\n * @returns The Schedule object or undefined if not found\n */\n async getSchedule<T = string>(id: string): Promise<Schedule<T> | undefined> {\n const result = this.sql<Schedule<string>>`\n SELECT * FROM cf_agents_schedules WHERE id = ${id}\n `;\n if (!result) {\n console.error(`schedule ${id} not found`);\n return undefined;\n }\n\n return { ...result[0], payload: JSON.parse(result[0].payload) as T };\n }\n\n /**\n * Get scheduled tasks matching the given criteria\n * @template T Type of the payload data\n * @param criteria Criteria to filter schedules\n * @returns Array of matching Schedule objects\n */\n getSchedules<T = string>(\n criteria: {\n id?: string;\n type?: \"scheduled\" | \"delayed\" | \"cron\";\n timeRange?: { start?: Date; end?: Date };\n } = {}\n ): Schedule<T>[] {\n let query = \"SELECT * FROM cf_agents_schedules WHERE 1=1\";\n const params = [];\n\n if (criteria.id) {\n query += \" AND id = ?\";\n params.push(criteria.id);\n }\n\n if (criteria.type) {\n query += \" AND type = ?\";\n params.push(criteria.type);\n }\n\n if (criteria.timeRange) {\n query += \" AND time >= ? AND time <= ?\";\n const start = criteria.timeRange.start || new Date(0);\n const end = criteria.timeRange.end || new Date(999999999999999);\n params.push(\n Math.floor(start.getTime() / 1000),\n Math.floor(end.getTime() / 1000)\n );\n }\n\n const result = this.ctx.storage.sql\n .exec(query, ...params)\n .toArray()\n .map((row) => ({\n ...row,\n payload: JSON.parse(row.payload as string) as T\n })) as Schedule<T>[];\n\n return result;\n }\n\n /**\n * Cancel a scheduled task\n * @param id ID of the task to cancel\n * @returns true if the task was cancelled, false otherwise\n */\n async cancelSchedule(id: string): Promise<boolean> {\n const schedule = await this.getSchedule(id);\n if (schedule) {\n this.observability?.emit(\n {\n displayMessage: `Schedule ${id} cancelled`,\n id: nanoid(),\n payload: {\n callback: schedule.callback,\n id: schedule.id\n },\n timestamp: Date.now(),\n type: \"schedule:cancel\"\n },\n this.ctx\n );\n }\n this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;\n\n await this._scheduleNextAlarm();\n return true;\n }\n\n private async _scheduleNextAlarm() {\n // Find the next schedule that needs to be executed\n const result = this.sql`\n SELECT time FROM cf_agents_schedules\n WHERE time > ${Math.floor(Date.now() / 1000)}\n ORDER BY time ASC\n LIMIT 1\n `;\n if (!result) return;\n\n if (result.length > 0 && \"time\" in result[0]) {\n const nextTime = (result[0].time as number) * 1000;\n await this.ctx.storage.setAlarm(nextTime);\n }\n }\n\n /**\n * Method called when an alarm fires.\n * Executes any scheduled tasks that are due.\n *\n * @remarks\n * To schedule a task, please use the `this.schedule` method instead.\n * See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}\n */\n public readonly alarm = async () => {\n const now = Math.floor(Date.now() / 1000);\n\n // Get all schedules that should be executed now\n const result = this.sql<Schedule<string>>`\n SELECT * FROM cf_agents_schedules WHERE time <= ${now}\n `;\n\n if (result && Array.isArray(result)) {\n for (const row of result) {\n const callback = this[row.callback as keyof Agent<Env>];\n if (!callback) {\n console.error(`callback ${row.callback} not found`);\n continue;\n }\n await agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n async () => {\n try {\n this.observability?.emit(\n {\n displayMessage: `Schedule ${row.id} executed`,\n id: nanoid(),\n payload: {\n callback: row.callback,\n id: row.id\n },\n timestamp: Date.now(),\n type: \"schedule:execute\"\n },\n this.ctx\n );\n\n await (\n callback as (\n payload: unknown,\n schedule: Schedule<unknown>\n ) => Promise<void>\n ).bind(this)(JSON.parse(row.payload as string), row);\n } catch (e) {\n console.error(`error executing callback \"${row.callback}\"`, e);\n }\n }\n );\n if (row.type === \"cron\") {\n // Update next execution time for cron schedules\n const nextExecutionTime = getNextCronTime(row.cron);\n const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1000);\n\n this.sql`\n UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}\n `;\n } else {\n // Delete one-time schedules after execution\n this.sql`\n DELETE FROM cf_agents_schedules WHERE id = ${row.id}\n `;\n }\n }\n }\n\n // Schedule the next alarm\n await this._scheduleNextAlarm();\n };\n\n /**\n * Destroy the Agent, removing all state and scheduled tasks\n */\n async destroy() {\n // drop all tables\n this.sql`DROP TABLE IF EXISTS cf_agents_state`;\n this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;\n this.sql`DROP TABLE IF EXISTS cf_agents_mcp_servers`;\n this.sql`DROP TABLE IF EXISTS cf_agents_queues`;\n\n // delete all alarms\n await this.ctx.storage.deleteAlarm();\n await this.ctx.storage.deleteAll();\n this.ctx.abort(\"destroyed\"); // enforce that the agent is evicted\n\n this.observability?.emit(\n {\n displayMessage: \"Agent destroyed\",\n id: nanoid(),\n payload: {},\n timestamp: Date.now(),\n type: \"destroy\"\n },\n this.ctx\n );\n }\n\n /**\n * Get all methods marked as callable on this Agent\n * @returns A map of method names to their metadata\n */\n private _isCallable(method: string): boolean {\n return callableMetadata.has(this[method as keyof this] as Function);\n }\n\n /**\n * Connect to a new MCP Server\n *\n * @param serverName Name of the MCP server\n * @param url MCP Server SSE URL\n * @param callbackHost Base host for the agent, used for the redirect URI. If not provided, will be derived from the current request.\n * @param agentsPrefix agents routing prefix if not using `agents`\n * @param options MCP client and transport (header) options\n * @returns authUrl\n */\n async addMcpServer(\n serverName: string,\n url: string,\n callbackHost?: string,\n agentsPrefix = \"agents\",\n options?: {\n client?: ConstructorParameters<typeof Client>[1];\n transport?: {\n headers: HeadersInit;\n };\n }\n ): Promise<{ id: string; authUrl: string | undefined }> {\n // If callbackHost is not provided, derive it from the current request\n let resolvedCallbackHost = callbackHost;\n if (!resolvedCallbackHost) {\n const { request } = getCurrentAgent();\n if (!request) {\n throw new Error(\n \"callbackHost is required when not called within a request context\"\n );\n }\n\n // Extract the origin from the request\n const requestUrl = new URL(request.url);\n resolvedCallbackHost = `${requestUrl.protocol}//${requestUrl.host}`;\n }\n\n const callbackUrl = `${resolvedCallbackHost}/${agentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;\n\n const result = await this._connectToMcpServerInternal(\n serverName,\n url,\n callbackUrl,\n options\n );\n this.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\n this.broadcast(\n JSON.stringify({\n mcp: this.getMcpServers(),\n type: MessageType.CF_AGENT_MCP_SERVERS\n })\n );\n\n return result;\n }\n\n async _connectToMcpServerInternal(\n _serverName: string,\n url: string,\n callbackUrl: string,\n // it's important that any options here are serializable because we put them into our sqlite DB for reconnection purposes\n options?: {\n client?: ConstructorParameters<typeof Client>[1];\n /**\n * We don't expose the normal set of transport options because:\n * 1) we can't serialize things like the auth provider or a fetch function into the DB for reconnection purposes\n * 2) We probably want these options to be agnostic to the transport type (SSE vs Streamable)\n *\n * This has the limitation that you can't override fetch, but I think headers should handle nearly all cases needed (i.e. non-standard bearer auth).\n */\n transport?: {\n headers?: HeadersInit;\n type?: TransportType;\n };\n },\n reconnect?: {\n id: string;\n oauthClientId?: string;\n }\n ): Promise<{\n id: string;\n authUrl: string | undefined;\n clientId: string | undefined;\n }> {\n const authProvider = new DurableObjectOAuthClientProvider(\n this.ctx.storage,\n this.name,\n callbackUrl\n );\n\n if (reconnect) {\n authProvider.serverId = reconnect.id;\n if (reconnect.oauthClientId) {\n authProvider.clientId = reconnect.oauthClientId;\n }\n }\n\n // allows passing through transport headers if necessary\n // this handles some non-standard bearer auth setups (i.e. MCP server behind CF access instead of OAuth)\n let headerTransportOpts: SSEClientTransportOptions = {};\n if (options?.transport?.headers) {\n headerTransportOpts = {\n eventSourceInit: {\n fetch: (url, init) =>\n fetch(url, {\n ...init,\n headers: options?.transport?.headers\n })\n },\n requestInit: {\n headers: options?.transport?.headers\n }\n };\n }\n\n // Use the transport type specified in options, or default to \"auto\"\n const transportType = options?.transport?.type || \"auto\";\n\n const { id, authUrl, clientId } = await this.mcp.connect(url, {\n client: options?.client,\n reconnect,\n transport: {\n ...headerTransportOpts,\n authProvider,\n type: transportType\n }\n });\n\n return {\n authUrl,\n clientId,\n id\n };\n }\n\n async removeMcpServer(id: string) {\n this.mcp.closeConnection(id);\n this.mcp.unregisterCallbackUrl(id);\n this.sql`\n DELETE FROM cf_agents_mcp_servers WHERE id = ${id};\n `;\n this.broadcast(\n JSON.stringify({\n mcp: this.getMcpServers(),\n type: MessageType.CF_AGENT_MCP_SERVERS\n })\n );\n }\n\n getMcpServers(): MCPServersState {\n const mcpState: MCPServersState = {\n prompts: this.mcp.listPrompts(),\n resources: this.mcp.listResources(),\n servers: {},\n tools: this.mcp.listTools()\n };\n\n const servers = this.sql<MCPServerRow>`\n SELECT id, name, server_url, client_id, auth_url, callback_url, server_options FROM cf_agents_mcp_servers;\n `;\n\n if (servers && Array.isArray(servers) && servers.length > 0) {\n for (const server of servers) {\n const serverConn = this.mcp.mcpConnections[server.id];\n mcpState.servers[server.id] = {\n auth_url: server.auth_url,\n capabilities: serverConn?.serverCapabilities ?? null,\n instructions: serverConn?.instructions ?? null,\n name: server.name,\n server_url: server.server_url,\n // mark as \"authenticating\" because the server isn't automatically connected, so it's pending authenticating\n state: serverConn?.connectionState ?? \"authenticating\"\n };\n }\n }\n\n return mcpState;\n }\n}\n\n// A set of classes that have been wrapped with agent context\nconst wrappedClasses = new Set<typeof Agent.prototype.constructor>();\n\n/**\n * Namespace for creating Agent instances\n * @template Agentic Type of the Agent class\n */\nexport type AgentNamespace<Agentic extends Agent<unknown>> =\n DurableObjectNamespace<Agentic>;\n\n/**\n * Agent's durable context\n */\nexport type AgentContext = DurableObjectState;\n\n/**\n * Configuration options for Agent routing\n */\nexport type AgentOptions<Env> = PartyServerOptions<Env> & {\n /**\n * Whether to enable CORS for the Agent\n */\n cors?: boolean | HeadersInit | undefined;\n};\n\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 */\nexport async function routeAgentRequest<Env>(\n request: Request,\n env: Env,\n options?: AgentOptions<Env>\n) {\n const corsHeaders =\n options?.cors === true\n ? {\n \"Access-Control-Allow-Credentials\": \"true\",\n \"Access-Control-Allow-Methods\": \"GET, POST, HEAD, OPTIONS\",\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Max-Age\": \"86400\"\n }\n : options?.cors;\n\n if (request.method === \"OPTIONS\") {\n if (corsHeaders) {\n return new Response(null, {\n headers: corsHeaders\n });\n }\n console.warn(\n \"Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS.\"\n );\n }\n\n let response = await routePartykitRequest(\n request,\n env as Record<string, unknown>,\n {\n prefix: \"agents\",\n ...(options as PartyServerOptions<Record<string, unknown>>)\n }\n );\n\n if (\n response &&\n corsHeaders &&\n request.headers.get(\"upgrade\")?.toLowerCase() !== \"websocket\" &&\n request.headers.get(\"Upgrade\")?.toLowerCase() !== \"websocket\"\n ) {\n response = new Response(response.body, {\n headers: {\n ...response.headers,\n ...corsHeaders\n }\n });\n }\n return response;\n}\n\nexport type EmailResolver<Env> = (\n email: ForwardableEmailMessage,\n env: Env\n) => Promise<{\n agentName: string;\n agentId: string;\n} | null>;\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 */\nexport function createHeaderBasedEmailResolver<Env>(): EmailResolver<Env> {\n return async (email: ForwardableEmailMessage, _env: Env) => {\n const messageId = email.headers.get(\"message-id\");\n if (messageId) {\n const messageIdMatch = messageId.match(/<([^@]+)@([^>]+)>/);\n if (messageIdMatch) {\n const [, agentId, domain] = messageIdMatch;\n const agentName = domain.split(\".\")[0];\n return { agentName, agentId };\n }\n }\n\n const references = email.headers.get(\"references\");\n if (references) {\n const referencesMatch = references.match(\n /<([A-Za-z0-9+/]{43}=)@([^>]+)>/\n );\n if (referencesMatch) {\n const [, base64Id, domain] = referencesMatch;\n const agentId = Buffer.from(base64Id, \"base64\").toString(\"hex\");\n const agentName = domain.split(\".\")[0];\n return { agentName, agentId };\n }\n }\n\n const agentName = email.headers.get(\"x-agent-name\");\n const agentId = email.headers.get(\"x-agent-id\");\n if (agentName && agentId) {\n return { agentName, agentId };\n }\n\n return null;\n };\n}\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 */\nexport function createAddressBasedEmailResolver<Env>(\n defaultAgentName: string\n): EmailResolver<Env> {\n return async (email: ForwardableEmailMessage, _env: Env) => {\n const emailMatch = email.to.match(/^([^+@]+)(?:\\+([^@]+))?@(.+)$/);\n if (!emailMatch) {\n return null;\n }\n\n const [, localPart, subAddress] = emailMatch;\n\n if (subAddress) {\n return {\n agentName: localPart,\n agentId: subAddress\n };\n }\n\n // Option 2: Use defaultAgentName namespace, localPart as agentId\n // Common for catch-all email routing to a single EmailAgent namespace\n return {\n agentName: defaultAgentName,\n agentId: localPart\n };\n };\n}\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 */\nexport function createCatchAllEmailResolver<Env>(\n agentName: string,\n agentId: string\n): EmailResolver<Env> {\n return async () => ({ agentName, agentId });\n}\n\nexport type EmailRoutingOptions<Env> = AgentOptions<Env> & {\n resolver: EmailResolver<Env>;\n};\n\n// Cache the agent namespace map for email routing\n// This maps both kebab-case and original names to namespaces\nconst agentMapCache = new WeakMap<\n Record<string, unknown>,\n Record<string, unknown>\n>();\n\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 */\nexport async function routeAgentEmail<Env>(\n email: ForwardableEmailMessage,\n env: Env,\n options: EmailRoutingOptions<Env>\n): Promise<void> {\n const routingInfo = await options.resolver(email, env);\n\n if (!routingInfo) {\n console.warn(\"No routing information found for email, dropping message\");\n return;\n }\n\n // Build a map that includes both original names and kebab-case versions\n if (!agentMapCache.has(env as Record<string, unknown>)) {\n const map: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(env as Record<string, unknown>)) {\n if (\n value &&\n typeof value === \"object\" &&\n \"idFromName\" in value &&\n typeof value.idFromName === \"function\"\n ) {\n // Add both the original name and kebab-case version\n map[key] = value;\n map[camelCaseToKebabCase(key)] = value;\n }\n }\n agentMapCache.set(env as Record<string, unknown>, map);\n }\n\n const agentMap = agentMapCache.get(env as Record<string, unknown>)!;\n const namespace = agentMap[routingInfo.agentName];\n\n if (!namespace) {\n // Provide helpful error message listing available agents\n const availableAgents = Object.keys(agentMap)\n .filter((key) => !key.includes(\"-\")) // Show only original names, not kebab-case duplicates\n .join(\", \");\n throw new Error(\n `Agent namespace '${routingInfo.agentName}' not found in environment. Available agents: ${availableAgents}`\n );\n }\n\n const agent = await getAgentByName(\n namespace as unknown as AgentNamespace<Agent<Env>>,\n routingInfo.agentId\n );\n\n // let's make a serialisable version of the email\n const serialisableEmail: AgentEmail = {\n getRaw: async () => {\n const reader = email.raw.getReader();\n const chunks: Uint8Array[] = [];\n\n let done = false;\n while (!done) {\n const { value, done: readerDone } = await reader.read();\n done = readerDone;\n if (value) {\n chunks.push(value);\n }\n }\n\n const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);\n const combined = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n combined.set(chunk, offset);\n offset += chunk.length;\n }\n\n return combined;\n },\n headers: email.headers,\n rawSize: email.rawSize,\n setReject: (reason: string) => {\n email.setReject(reason);\n },\n forward: (rcptTo: string, headers?: Headers) => {\n return email.forward(rcptTo, headers);\n },\n reply: (options: { from: string; to: string; raw: string }) => {\n return email.reply(\n new EmailMessage(options.from, options.to, options.raw)\n );\n },\n from: email.from,\n to: email.to\n };\n\n await agent._onEmail(serialisableEmail);\n}\n\nexport type AgentEmail = {\n from: string;\n to: string;\n getRaw: () => Promise<Uint8Array>;\n headers: Headers;\n rawSize: number;\n setReject: (reason: string) => void;\n forward: (rcptTo: string, headers?: Headers) => Promise<void>;\n reply: (options: { from: string; to: string; raw: string }) => Promise<void>;\n};\n\nexport type EmailSendOptions = {\n to: string;\n subject: string;\n body: string;\n contentType?: string;\n headers?: Record<string, string>;\n includeRoutingHeaders?: boolean;\n agentName?: string;\n agentId?: string;\n domain?: string;\n};\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 */\nexport async function getAgentByName<\n Env,\n T extends Agent<Env>,\n Props extends Record<string, unknown> = Record<string, unknown>\n>(\n namespace: AgentNamespace<T>,\n name: string,\n options?: {\n jurisdiction?: DurableObjectJurisdiction;\n locationHint?: DurableObjectLocationHint;\n props?: Props;\n }\n) {\n return getServerByName<Env, T>(namespace, name, options);\n}\n\n/**\n * A wrapper for streaming responses in callable methods\n */\nexport class StreamingResponse {\n private _connection: Connection;\n private _id: string;\n private _closed = false;\n\n constructor(connection: Connection, id: string) {\n this._connection = connection;\n this._id = id;\n }\n\n /**\n * Send a chunk of data to the client\n * @param chunk The data to send\n */\n send(chunk: unknown) {\n if (this._closed) {\n throw new Error(\"StreamingResponse is already closed\");\n }\n const response: RPCResponse = {\n done: false,\n id: this._id,\n result: chunk,\n success: true,\n type: MessageType.RPC\n };\n this._connection.send(JSON.stringify(response));\n }\n\n /**\n * End the stream and send the final chunk (if any)\n * @param finalChunk Optional final chunk of data to send\n */\n end(finalChunk?: unknown) {\n if (this._closed) {\n throw new Error(\"StreamingResponse is already closed\");\n }\n this._closed = true;\n const response: RPCResponse = {\n done: true,\n id: this._id,\n result: finalChunk,\n success: true,\n type: MessageType.RPC\n };\n this._connection.send(JSON.stringify(response));\n }\n}\n","import { getCurrentAgent } from \"../index\";\n\ntype BaseEvent<\n T extends string,\n Payload extends Record<string, unknown> = {}\n> = {\n type: T;\n /**\n * The unique identifier for the event\n */\n id: string;\n /**\n * The message to display in the logs for this event, should the implementation choose to display\n * a human-readable message.\n */\n displayMessage: string;\n /**\n * The payload of the event\n */\n payload: Payload;\n /**\n * The timestamp of the event in milliseconds since epoch\n */\n timestamp: number;\n};\n\n/**\n * The type of events that can be emitted by an Agent\n */\nexport type ObservabilityEvent =\n | BaseEvent<\"state:update\", {}>\n | BaseEvent<\n \"rpc\",\n {\n method: string;\n streaming?: boolean;\n }\n >\n | BaseEvent<\"message:request\" | \"message:response\", {}>\n | BaseEvent<\"message:clear\">\n | BaseEvent<\n \"schedule:create\" | \"schedule:execute\" | \"schedule:cancel\",\n {\n callback: string;\n id: string;\n }\n >\n | BaseEvent<\"destroy\">\n | BaseEvent<\n \"connect\",\n {\n connectionId: string;\n }\n >;\n\nexport interface Observability {\n /**\n * Emit an event for the Agent's observability implementation to handle.\n * @param event - The event to emit\n * @param ctx - The execution context of the invocation\n */\n emit(event: ObservabilityEvent, ctx: DurableObjectState): void;\n}\n\n/**\n * A generic observability implementation that logs events to the console.\n */\nexport const genericObservability: Observability = {\n emit(event) {\n // In local mode, we display a pretty-print version of the event for easier debugging.\n if (isLocalMode()) {\n console.log(event.displayMessage);\n return;\n }\n\n console.log(event);\n }\n};\n\nlet localMode = false;\n\nfunction isLocalMode() {\n if (localMode) {\n return true;\n }\n const { request } = getCurrentAgent();\n if (!request) {\n return false;\n }\n\n const url = new URL(request.url);\n localMode = url.hostname === \"localhost\";\n return localMode;\n}\n"],"mappings":";;;;;;;;;;;AACA,SAAS,yBAAyB;AAUlC,SAAS,2BAA2B;AACpC,SAAS,cAAc;AACvB,SAAS,oBAAoB;AAC7B;AAAA,EAIE;AAAA,EAEA;AAAA,EACA;AAAA,OACK;AAsDP,SAAS,aAAa,KAAiC;AACrD,SACE,OAAO,QAAQ,YACf,QAAQ,QACR,UAAU,OACV,IAAI,4BACJ,QAAQ,OACR,OAAO,IAAI,OAAO,YAClB,YAAY,OACZ,OAAO,IAAI,WAAW,YACtB,UAAU,OACV,MAAM,QAAS,IAAmB,IAAI;AAE1C;AAKA,SAAS,qBAAqB,KAAyC;AACrE,SACE,OAAO,QAAQ,YACf,QAAQ,QACR,UAAU,OACV,IAAI,kDACJ,WAAW;AAEf;AAYA,IAAM,mBAAmB,oBAAI,IAAgC;AAMtD,SAAS,SAAS,WAA6B,CAAC,GAAG;AACxD,SAAO,SAAS,kBACd,QAEA,SACA;AACA,QAAI,CAAC,iBAAiB,IAAI,MAAM,GAAG;AACjC,uBAAiB,IAAI,QAAQ,QAAQ;AAAA,IACvC;AAEA,WAAO;AAAA,EACT;AACF;AAEA,IAAI,+BAA+B;AAO5B,IAAM,oBAAoB,CAAC,WAA6B,CAAC,MAAM;AACpE,MAAI,CAAC,8BAA8B;AACjC,mCAA+B;AAC/B,YAAQ;AAAA,MACN;AAAA,IACF;AAAA,EACF;AACA,WAAS,QAAQ;AACnB;AA6CA,SAAS,gBAAgB,M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3DO,IAAM,uBAAsC;AAAA,EACjD,KAAK,OAAO;AAEV,QAAI,YAAY,GAAG;AACjB,cAAQ,IAAI,MAAM,cAAc;AAChC;AAAA,IACF;AAEA,YAAQ,IAAI,KAAK;AAAA,EACnB;AACF;AAEA,IAAI,YAAY;AAEhB,SAAS,cAAc;AACrB,MAAI,WAAW;AACb,WAAO;AAAA,EACT;AACA,QAAM,EAAE,QAAQ,IAAI,gBAAgB;AACpC,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,EACT;AAEA,QAAM,MAAM,IAAI,IAAI,QAAQ,GAAG;AAC/B,cAAY,IAAI,aAAa;AAC7B,SAAO;AACT;","names":["ctx","proto","url","agentId","agentName","options"]}
|
package/dist/chunk-TYAY6AU6.js
DELETED
|
@@ -1,159 +0,0 @@
|
|
|
1
|
-
// ../../node_modules/@noble/hashes/esm/cryptoNode.js
|
|
2
|
-
import * as nc from "crypto";
|
|
3
|
-
var crypto = nc && typeof nc === "object" && "webcrypto" in nc ? nc.webcrypto : nc && typeof nc === "object" && "randomBytes" in nc ? nc : void 0;
|
|
4
|
-
|
|
5
|
-
// ../../node_modules/@noble/hashes/esm/utils.js
|
|
6
|
-
function isBytes(a) {
|
|
7
|
-
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
|
|
8
|
-
}
|
|
9
|
-
function anumber(n) {
|
|
10
|
-
if (!Number.isSafeInteger(n) || n < 0)
|
|
11
|
-
throw new Error("positive integer expected, got " + n);
|
|
12
|
-
}
|
|
13
|
-
function abytes(b, ...lengths) {
|
|
14
|
-
if (!isBytes(b))
|
|
15
|
-
throw new Error("Uint8Array expected");
|
|
16
|
-
if (lengths.length > 0 && !lengths.includes(b.length))
|
|
17
|
-
throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
|
|
18
|
-
}
|
|
19
|
-
function ahash(h) {
|
|
20
|
-
if (typeof h !== "function" || typeof h.create !== "function")
|
|
21
|
-
throw new Error("Hash should be wrapped by utils.createHasher");
|
|
22
|
-
anumber(h.outputLen);
|
|
23
|
-
anumber(h.blockLen);
|
|
24
|
-
}
|
|
25
|
-
function aexists(instance, checkFinished = true) {
|
|
26
|
-
if (instance.destroyed)
|
|
27
|
-
throw new Error("Hash instance has been destroyed");
|
|
28
|
-
if (checkFinished && instance.finished)
|
|
29
|
-
throw new Error("Hash#digest() has already been called");
|
|
30
|
-
}
|
|
31
|
-
function aoutput(out, instance) {
|
|
32
|
-
abytes(out);
|
|
33
|
-
const min = instance.outputLen;
|
|
34
|
-
if (out.length < min) {
|
|
35
|
-
throw new Error("digestInto() expects output buffer of length at least " + min);
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
function u32(arr) {
|
|
39
|
-
return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
|
|
40
|
-
}
|
|
41
|
-
function clean(...arrays) {
|
|
42
|
-
for (let i = 0; i < arrays.length; i++) {
|
|
43
|
-
arrays[i].fill(0);
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
function createView(arr) {
|
|
47
|
-
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
48
|
-
}
|
|
49
|
-
function rotr(word, shift) {
|
|
50
|
-
return word << 32 - shift | word >>> shift;
|
|
51
|
-
}
|
|
52
|
-
var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
|
|
53
|
-
function byteSwap(word) {
|
|
54
|
-
return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
|
|
55
|
-
}
|
|
56
|
-
function byteSwap32(arr) {
|
|
57
|
-
for (let i = 0; i < arr.length; i++) {
|
|
58
|
-
arr[i] = byteSwap(arr[i]);
|
|
59
|
-
}
|
|
60
|
-
return arr;
|
|
61
|
-
}
|
|
62
|
-
var swap32IfBE = isLE ? (u) => u : byteSwap32;
|
|
63
|
-
function utf8ToBytes(str) {
|
|
64
|
-
if (typeof str !== "string")
|
|
65
|
-
throw new Error("string expected");
|
|
66
|
-
return new Uint8Array(new TextEncoder().encode(str));
|
|
67
|
-
}
|
|
68
|
-
function toBytes(data) {
|
|
69
|
-
if (typeof data === "string")
|
|
70
|
-
data = utf8ToBytes(data);
|
|
71
|
-
abytes(data);
|
|
72
|
-
return data;
|
|
73
|
-
}
|
|
74
|
-
function concatBytes(...arrays) {
|
|
75
|
-
let sum = 0;
|
|
76
|
-
for (let i = 0; i < arrays.length; i++) {
|
|
77
|
-
const a = arrays[i];
|
|
78
|
-
abytes(a);
|
|
79
|
-
sum += a.length;
|
|
80
|
-
}
|
|
81
|
-
const res = new Uint8Array(sum);
|
|
82
|
-
for (let i = 0, pad = 0; i < arrays.length; i++) {
|
|
83
|
-
const a = arrays[i];
|
|
84
|
-
res.set(a, pad);
|
|
85
|
-
pad += a.length;
|
|
86
|
-
}
|
|
87
|
-
return res;
|
|
88
|
-
}
|
|
89
|
-
var Hash = class {
|
|
90
|
-
};
|
|
91
|
-
function createHasher(hashCons) {
|
|
92
|
-
const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
|
|
93
|
-
const tmp = hashCons();
|
|
94
|
-
hashC.outputLen = tmp.outputLen;
|
|
95
|
-
hashC.blockLen = tmp.blockLen;
|
|
96
|
-
hashC.create = () => hashCons();
|
|
97
|
-
return hashC;
|
|
98
|
-
}
|
|
99
|
-
function randomBytes(bytesLength = 32) {
|
|
100
|
-
if (crypto && typeof crypto.getRandomValues === "function") {
|
|
101
|
-
return crypto.getRandomValues(new Uint8Array(bytesLength));
|
|
102
|
-
}
|
|
103
|
-
if (crypto && typeof crypto.randomBytes === "function") {
|
|
104
|
-
return Uint8Array.from(crypto.randomBytes(bytesLength));
|
|
105
|
-
}
|
|
106
|
-
throw new Error("crypto.getRandomValues must be defined");
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
// ../../node_modules/@noble/hashes/esm/_u64.js
|
|
110
|
-
var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
|
|
111
|
-
var _32n = /* @__PURE__ */ BigInt(32);
|
|
112
|
-
function fromBig(n, le = false) {
|
|
113
|
-
if (le)
|
|
114
|
-
return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
|
|
115
|
-
return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
|
|
116
|
-
}
|
|
117
|
-
function split(lst, le = false) {
|
|
118
|
-
const len = lst.length;
|
|
119
|
-
let Ah = new Uint32Array(len);
|
|
120
|
-
let Al = new Uint32Array(len);
|
|
121
|
-
for (let i = 0; i < len; i++) {
|
|
122
|
-
const { h, l } = fromBig(lst[i], le);
|
|
123
|
-
[Ah[i], Al[i]] = [h, l];
|
|
124
|
-
}
|
|
125
|
-
return [Ah, Al];
|
|
126
|
-
}
|
|
127
|
-
var rotlSH = (h, l, s) => h << s | l >>> 32 - s;
|
|
128
|
-
var rotlSL = (h, l, s) => l << s | h >>> 32 - s;
|
|
129
|
-
var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
|
|
130
|
-
var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
|
|
131
|
-
|
|
132
|
-
export {
|
|
133
|
-
anumber,
|
|
134
|
-
abytes,
|
|
135
|
-
ahash,
|
|
136
|
-
aexists,
|
|
137
|
-
aoutput,
|
|
138
|
-
u32,
|
|
139
|
-
clean,
|
|
140
|
-
createView,
|
|
141
|
-
rotr,
|
|
142
|
-
swap32IfBE,
|
|
143
|
-
toBytes,
|
|
144
|
-
concatBytes,
|
|
145
|
-
Hash,
|
|
146
|
-
createHasher,
|
|
147
|
-
randomBytes,
|
|
148
|
-
split,
|
|
149
|
-
rotlSH,
|
|
150
|
-
rotlSL,
|
|
151
|
-
rotlBH,
|
|
152
|
-
rotlBL
|
|
153
|
-
};
|
|
154
|
-
/*! Bundled license information:
|
|
155
|
-
|
|
156
|
-
@noble/hashes/esm/utils.js:
|
|
157
|
-
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
158
|
-
*/
|
|
159
|
-
//# sourceMappingURL=chunk-TYAY6AU6.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../node_modules/@noble/hashes/src/cryptoNode.ts","../../../node_modules/@noble/hashes/src/utils.ts","../../../node_modules/@noble/hashes/src/_u64.ts"],"sourcesContent":["/**\n * Internal webcrypto alias.\n * We prefer WebCrypto aka globalThis.crypto, which exists in node.js 16+.\n * Falls back to Node.js built-in crypto for Node.js <=v14.\n * See utils.ts for details.\n * @module\n */\n// @ts-ignore\nimport * as nc from 'node:crypto';\nexport const crypto: any =\n nc && typeof nc === 'object' && 'webcrypto' in nc\n ? (nc.webcrypto as any)\n : nc && typeof nc === 'object' && 'randomBytes' in nc\n ? nc\n : undefined;\n","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a: unknown): a is Uint8Array {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n\n/** Asserts something is positive integer. */\nexport function anumber(n: number): void {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n);\n}\n\n/** Asserts something is Uint8Array. */\nexport function abytes(b: Uint8Array | undefined, ...lengths: number[]): void {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n\n/** Asserts something is hash */\nexport function ahash(h: IHash): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance: any, checkFinished = true): void {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out: any, instance: any): void {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n\n/** Generic type encompassing 8/16/32-byte arrays - but not 64-byte. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr: TypedArray): Uint8Array {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr: TypedArray): Uint32Array {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays: TypedArray[]): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr: TypedArray): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/** The byte swap operation for uint32 */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n);\n\n/** @deprecated */\nexport const byteSwapIfBE: typeof swap8IfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr: Uint32Array): Uint32Array {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n\nexport const swap32IfBE: (u: Uint32Array) => Uint32Array = isLE\n ? (u: Uint32Array) => u\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin) return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async (): Promise<void> => {};\n\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise<void> {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n/** Accepted input of hash functions. Strings are converted to byte arrays. */\nexport type Input = string | Uint8Array;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data: KDFInput): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Hash interface. */\nexport type IHash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\n\n/** For runtime check if class implements interface */\nexport abstract class Hash<T extends Hash<T>> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n /**\n * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n * when no options are passed.\n * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n * There are no guarantees for clean-up because it's impossible in JS.\n */\n abstract _cloneInto(to?: T): T;\n // Safe version that clones internal state\n abstract clone(): T;\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF<T extends Hash<T>> = Hash<T> & {\n xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\n/** Hash function */\nexport type CHash = ReturnType<typeof createHasher>;\n/** Hash function with output */\nexport type CHashO = ReturnType<typeof createOptHasher>;\n/** XOF with output */\nexport type CHashXO = ReturnType<typeof createXOFer>;\n\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher<T extends Hash<T>>(\n hashCons: () => Hash<T>\n): {\n (msg: Input): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(): Hash<T>;\n} {\n const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\n\nexport function createOptHasher<H extends Hash<H>, T extends Object>(\n hashCons: (opts?: T) => Hash<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): Hash<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\n\nexport function createXOFer<H extends HashXOF<H>, T extends Object>(\n hashCons: (opts?: T) => HashXOF<H>\n): {\n (msg: Input, opts?: T): Uint8Array;\n outputLen: number;\n blockLen: number;\n create(opts?: T): HashXOF<H>;\n} {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts?: T) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor: typeof createHasher = createHasher;\nexport const wrapConstructorWithOpts: typeof createOptHasher = createOptHasher;\nexport const wrapXOFConstructorWithOpts: typeof createXOFer = createXOFer;\n\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\nfunction fromBig(\n n: bigint,\n le = false\n): {\n h: number;\n l: number;\n} {\n if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n\nfunction split(lst: bigint[], le = false): Uint32Array[] {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n\nconst toBig = (h: number, l: number): bigint => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number): number => h >>> s;\nconst shrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number): number => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h: number, l: number, s: number): number => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number): number => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number): number => l;\nconst rotr32L = (h: number, _l: number): number => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number): number => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number): number => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h: number, l: number, s: number): number => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number): number => (h << (s - 32)) | (l >>> (64 - s));\n\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(\n Ah: number,\n Al: number,\n Bh: number,\n Bl: number\n): {\n h: number;\n l: number;\n} {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al: number, Bl: number, Cl: number): number => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number): number =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number): number =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number): number =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig\n};\n// prettier-ignore\nconst u64: { fromBig: typeof fromBig; split: typeof split; toBig: (h: number, l: number) => bigint; shrSH: (h: number, _l: number, s: number) => number; shrSL: (h: number, l: number, s: number) => number; rotrSH: (h: number, l: number, s: number) => number; rotrSL: (h: number, l: number, s: number) => number; rotrBH: (h: number, l: number, s: number) => number; rotrBL: (h: number, l: number, s: number) => number; rotr32H: (_h: number, l: number) => number; rotr32L: (h: number, _l: number) => number; rotlSH: (h: number, l: number, s: number) => number; rotlSL: (h: number, l: number, s: number) => number; rotlBH: (h: number, l: number, s: number) => number; rotlBL: (h: number, l: number, s: number) => number; add: typeof add; add3L: (Al: number, Bl: number, Cl: number) => number; add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; } = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n"],"mappings":";AAQA,YAAY,QAAQ;AACb,IAAM,SACX,MAAM,OAAO,OAAO,YAAY,eAAe,KACvC,eACJ,MAAM,OAAO,OAAO,YAAY,iBAAiB,KAC/C,KACA;;;ACCF,SAAU,QAAQ,GAAU;AAChC,SAAO,aAAa,cAAe,YAAY,OAAO,CAAC,KAAK,EAAE,YAAY,SAAS;AACrF;AAGM,SAAU,QAAQ,GAAS;AAC/B,MAAI,CAAC,OAAO,cAAc,CAAC,KAAK,IAAI;AAAG,UAAM,IAAI,MAAM,oCAAoC,CAAC;AAC9F;AAGM,SAAU,OAAO,MAA8B,SAAiB;AACpE,MAAI,CAAC,QAAQ,CAAC;AAAG,UAAM,IAAI,MAAM,qBAAqB;AACtD,MAAI,QAAQ,SAAS,KAAK,CAAC,QAAQ,SAAS,EAAE,MAAM;AAClD,UAAM,IAAI,MAAM,mCAAmC,UAAU,kBAAkB,EAAE,MAAM;AAC3F;AAGM,SAAU,MAAM,GAAQ;AAC5B,MAAI,OAAO,MAAM,cAAc,OAAO,EAAE,WAAW;AACjD,UAAM,IAAI,MAAM,8CAA8C;AAChE,UAAQ,EAAE,SAAS;AACnB,UAAQ,EAAE,QAAQ;AACpB;AAGM,SAAU,QAAQ,UAAe,gBAAgB,MAAI;AACzD,MAAI,SAAS;AAAW,UAAM,IAAI,MAAM,kCAAkC;A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AO,IAAI,UAAU,IAAI,EAAC;AACjF;AAEA,SAAS,MAAM,KAAe,KAAK,OAAK;AACtC,QAAM,MAAM,IAAI;AAChB,MAAI,KAAK,IAAI,YAAY,GAAG;AAC5B,MAAI,KAAK,IAAI,YAAY,GAAG;AAC5B,WAAS,IAAI,GAAG,IAAI,KAAK,KAAK;AAC5B,UAAM,EAAE,GAAG,EAAC,IAAK,QAAQ,IAAI,CAAC,GAAG,EAAE;AACnC,KAAC,GAAG,CAAC,GAAG,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC;EACxB;AACA,SAAO,CAAC,IAAI,EAAE;AAChB;AAgBA,IAAM,SAAS,CAAC,GAAW,GAAW,MAAuB,KAAK,IAAM,MAAO,KAAK;AACpF,IAAM,SAAS,CAAC,GAAW,GAAW,MAAuB,KAAK,IAAM,MAAO,KAAK;AAEpF,IAAM,SAAS,CAAC,GAAW,GAAW,MAAuB,KAAM,IAAI,KAAQ,MAAO,KAAK;AAC3F,IAAM,SAAS,CAAC,GAAW,GAAW,MAAuB,KAAM,IAAI,KAAQ,MAAO,KAAK;","names":[]}
|
package/dist/chunk-UJVEAURM.js
DELETED
|
@@ -1,150 +0,0 @@
|
|
|
1
|
-
// src/ai-chat-v5-migration.ts
|
|
2
|
-
var STATE_MAP = {
|
|
3
|
-
"partial-call": "input-streaming",
|
|
4
|
-
call: "input-available",
|
|
5
|
-
result: "output-available",
|
|
6
|
-
error: "output-error"
|
|
7
|
-
};
|
|
8
|
-
function isUIMessage(message) {
|
|
9
|
-
return typeof message === "object" && message !== null && "parts" in message && Array.isArray(message.parts);
|
|
10
|
-
}
|
|
11
|
-
function isLegacyMessage(message) {
|
|
12
|
-
return typeof message === "object" && message !== null && "role" in message && "content" in message && typeof message.role === "string" && typeof message.content === "string";
|
|
13
|
-
}
|
|
14
|
-
function isCorruptArrayMessage(message) {
|
|
15
|
-
return typeof message === "object" && message !== null && "role" in message && "content" in message && typeof message.role === "string" && Array.isArray(message.content) && !("parts" in message);
|
|
16
|
-
}
|
|
17
|
-
function autoTransformMessage(message, index = 0) {
|
|
18
|
-
if (isUIMessage(message)) {
|
|
19
|
-
return message;
|
|
20
|
-
}
|
|
21
|
-
const parts = [];
|
|
22
|
-
if (message.reasoning) {
|
|
23
|
-
parts.push({
|
|
24
|
-
type: "reasoning",
|
|
25
|
-
text: message.reasoning
|
|
26
|
-
});
|
|
27
|
-
}
|
|
28
|
-
if (message.toolInvocations && Array.isArray(message.toolInvocations)) {
|
|
29
|
-
message.toolInvocations.forEach((inv) => {
|
|
30
|
-
if (typeof inv === "object" && inv !== null && "toolName" in inv) {
|
|
31
|
-
const invObj = inv;
|
|
32
|
-
parts.push({
|
|
33
|
-
type: `tool-${invObj.toolName}`,
|
|
34
|
-
toolCallId: invObj.toolCallId,
|
|
35
|
-
state: STATE_MAP[invObj.state] || "input-available",
|
|
36
|
-
input: invObj.args,
|
|
37
|
-
output: invObj.result !== void 0 ? invObj.result : null
|
|
38
|
-
});
|
|
39
|
-
}
|
|
40
|
-
});
|
|
41
|
-
}
|
|
42
|
-
if (message.parts && Array.isArray(message.parts)) {
|
|
43
|
-
message.parts.forEach((part) => {
|
|
44
|
-
if (typeof part === "object" && part !== null && "type" in part) {
|
|
45
|
-
const partObj = part;
|
|
46
|
-
if (partObj.type === "file") {
|
|
47
|
-
parts.push({
|
|
48
|
-
type: "file",
|
|
49
|
-
url: partObj.url || (partObj.data ? `data:${partObj.mimeType || partObj.mediaType};base64,${partObj.data}` : void 0),
|
|
50
|
-
mediaType: partObj.mediaType || partObj.mimeType,
|
|
51
|
-
filename: partObj.filename
|
|
52
|
-
});
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
});
|
|
56
|
-
}
|
|
57
|
-
if (Array.isArray(message.content)) {
|
|
58
|
-
message.content.forEach((item) => {
|
|
59
|
-
if (typeof item === "object" && item !== null && "text" in item) {
|
|
60
|
-
const itemObj = item;
|
|
61
|
-
parts.push({
|
|
62
|
-
type: itemObj.type || "text",
|
|
63
|
-
text: itemObj.text || ""
|
|
64
|
-
});
|
|
65
|
-
}
|
|
66
|
-
});
|
|
67
|
-
}
|
|
68
|
-
if (!parts.length && message.content !== void 0) {
|
|
69
|
-
parts.push({
|
|
70
|
-
type: "text",
|
|
71
|
-
text: typeof message.content === "string" ? message.content : JSON.stringify(message.content)
|
|
72
|
-
});
|
|
73
|
-
}
|
|
74
|
-
if (!parts.length) {
|
|
75
|
-
parts.push({
|
|
76
|
-
type: "text",
|
|
77
|
-
text: typeof message === "string" ? message : JSON.stringify(message)
|
|
78
|
-
});
|
|
79
|
-
}
|
|
80
|
-
return {
|
|
81
|
-
id: message.id || `msg-${index}`,
|
|
82
|
-
role: message.role === "data" ? "system" : message.role || "user",
|
|
83
|
-
parts
|
|
84
|
-
};
|
|
85
|
-
}
|
|
86
|
-
function migrateToUIMessage(message) {
|
|
87
|
-
return autoTransformMessage(message);
|
|
88
|
-
}
|
|
89
|
-
function autoTransformMessages(messages) {
|
|
90
|
-
return messages.map((msg, i) => autoTransformMessage(msg, i));
|
|
91
|
-
}
|
|
92
|
-
function migrateMessagesToUIFormat(messages) {
|
|
93
|
-
return autoTransformMessages(messages);
|
|
94
|
-
}
|
|
95
|
-
function needsMigration(messages) {
|
|
96
|
-
return messages.some((message) => {
|
|
97
|
-
if (isUIMessage(message)) {
|
|
98
|
-
return false;
|
|
99
|
-
}
|
|
100
|
-
if (isCorruptArrayMessage(message)) {
|
|
101
|
-
return true;
|
|
102
|
-
}
|
|
103
|
-
if (isLegacyMessage(message)) {
|
|
104
|
-
return true;
|
|
105
|
-
}
|
|
106
|
-
return true;
|
|
107
|
-
});
|
|
108
|
-
}
|
|
109
|
-
function analyzeCorruption(messages) {
|
|
110
|
-
const stats = {
|
|
111
|
-
total: messages.length,
|
|
112
|
-
clean: 0,
|
|
113
|
-
legacyString: 0,
|
|
114
|
-
corruptArray: 0,
|
|
115
|
-
unknown: 0,
|
|
116
|
-
examples: {}
|
|
117
|
-
};
|
|
118
|
-
for (const message of messages) {
|
|
119
|
-
if (isUIMessage(message)) {
|
|
120
|
-
stats.clean++;
|
|
121
|
-
} else if (isCorruptArrayMessage(message)) {
|
|
122
|
-
stats.corruptArray++;
|
|
123
|
-
if (!stats.examples.corruptArray) {
|
|
124
|
-
stats.examples.corruptArray = message;
|
|
125
|
-
}
|
|
126
|
-
} else if (isLegacyMessage(message)) {
|
|
127
|
-
stats.legacyString++;
|
|
128
|
-
if (!stats.examples.legacyString) {
|
|
129
|
-
stats.examples.legacyString = message;
|
|
130
|
-
}
|
|
131
|
-
} else {
|
|
132
|
-
stats.unknown++;
|
|
133
|
-
if (!stats.examples.unknown) {
|
|
134
|
-
stats.examples.unknown = message;
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
return stats;
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
export {
|
|
142
|
-
isUIMessage,
|
|
143
|
-
autoTransformMessage,
|
|
144
|
-
migrateToUIMessage,
|
|
145
|
-
autoTransformMessages,
|
|
146
|
-
migrateMessagesToUIFormat,
|
|
147
|
-
needsMigration,
|
|
148
|
-
analyzeCorruption
|
|
149
|
-
};
|
|
150
|
-
//# sourceMappingURL=chunk-UJVEAURM.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/ai-chat-v5-migration.ts"],"sourcesContent":["import type { UIMessage } from \"ai\";\n\n/**\n * AI SDK v5 Migration following https://jhak.im/blog/ai-sdk-migration-handling-previously-saved-messages\n * Using exact types from the official AI SDK documentation\n */\n\n/**\n * AI SDK v5 Message Part types reference (from official AI SDK documentation)\n *\n * The migration logic below transforms legacy messages to match these official AI SDK v5 formats:\n * - TextUIPart: { type: \"text\", text: string, state?: \"streaming\" | \"done\" }\n * - ReasoningUIPart: { type: \"reasoning\", text: string, state?: \"streaming\" | \"done\", providerMetadata?: Record<string, unknown> }\n * - FileUIPart: { type: \"file\", mediaType: string, filename?: string, url: string }\n * - ToolUIPart: { type: `tool-${string}`, toolCallId: string, state: \"input-streaming\" | \"input-available\" | \"output-available\" | \"output-error\", input?: Record<string, unknown>, output?: unknown, errorText?: string, providerExecuted?: boolean }\n */\n\n/**\n * Tool invocation from v4 format\n */\ntype ToolInvocation = {\n toolCallId: string;\n toolName: string;\n args: Record<string, unknown>;\n result?: unknown;\n state: \"partial-call\" | \"call\" | \"result\" | \"error\";\n};\n\n/**\n * Legacy part from v4 format\n */\ntype LegacyPart = {\n type: string;\n text?: string;\n url?: string;\n data?: string;\n mimeType?: string;\n mediaType?: string;\n filename?: string;\n};\n\n/**\n * Legacy message format from AI SDK v4\n */\nexport type LegacyMessage = {\n id?: string;\n role: string;\n content: string;\n reasoning?: string;\n toolInvocations?: ToolInvocation[];\n parts?: LegacyPart[];\n [key: string]: unknown;\n};\n\n/**\n * Corrupt content item\n */\ntype CorruptContentItem = {\n type: string;\n text: string;\n};\n\n/**\n * Corrupted message format - has content as array instead of parts\n */\nexport type CorruptArrayMessage = {\n id?: string;\n role: string;\n content: CorruptContentItem[];\n reasoning?: string;\n toolInvocations?: ToolInvocation[];\n [key: string]: unknown;\n};\n\n/**\n * Union type for messages that could be in any format\n */\nexport type MigratableMessage = LegacyMessage | CorruptArrayMessage | UIMessage;\n\n/**\n * Tool call state mapping for v4 to v5 migration\n */\nconst STATE_MAP = {\n \"partial-call\": \"input-streaming\",\n call: \"input-available\",\n result: \"output-available\",\n error: \"output-error\"\n} as const;\n\n/**\n * Checks if a message is already in the UIMessage format (has parts array)\n */\nexport function isUIMessage(message: unknown): message is UIMessage {\n return (\n typeof message === \"object\" &&\n message !== null &&\n \"parts\" in message &&\n Array.isArray((message as { parts: unknown }).parts)\n );\n}\n\n/**\n * Type guard to check if a message is in legacy format (content as string)\n */\nfunction isLegacyMessage(message: unknown): message is LegacyMessage {\n return (\n typeof message === \"object\" &&\n message !== null &&\n \"role\" in message &&\n \"content\" in message &&\n typeof (message as { role: unknown }).role === \"string\" &&\n typeof (message as { content: unknown }).content === \"string\"\n );\n}\n\n/**\n * Type guard to check if a message has corrupted array content format\n * Detects: {role: \"user\", content: [{type: \"text\", text: \"...\"}]}\n */\nfunction isCorruptArrayMessage(\n message: unknown\n): message is CorruptArrayMessage {\n return (\n typeof message === \"object\" &&\n message !== null &&\n \"role\" in message &&\n \"content\" in message &&\n typeof (message as { role: unknown }).role === \"string\" &&\n Array.isArray((message as { content: unknown }).content) &&\n !(\"parts\" in message) // Ensure it's not already a UIMessage\n );\n}\n\n/**\n * Internal message part type for transformation\n */\ntype TransformMessagePart = {\n type: string;\n text?: string;\n toolCallId?: string;\n state?: string;\n input?: Record<string, unknown>;\n output?: unknown;\n url?: string;\n mediaType?: string;\n errorText?: string;\n filename?: string;\n};\n\n/**\n * Input message that could be in any format - using unknown for flexibility\n */\ntype InputMessage = {\n id?: string;\n role?: string;\n content?: unknown;\n reasoning?: string;\n toolInvocations?: unknown[];\n parts?: unknown[];\n [key: string]: unknown;\n};\n\n/**\n * Automatic message transformer following the blog post pattern\n * Handles comprehensive migration from AI SDK v4 to v5 format\n * @param message - Message in any legacy format\n * @param index - Index for ID generation fallback\n * @returns UIMessage in v5 format\n */\nexport function autoTransformMessage(\n message: InputMessage,\n index = 0\n): UIMessage {\n // Already in v5 format\n if (isUIMessage(message)) {\n return message;\n }\n\n const parts: TransformMessagePart[] = [];\n\n // Handle reasoning transformation\n if (message.reasoning) {\n parts.push({\n type: \"reasoning\",\n text: message.reasoning\n });\n }\n\n // Handle tool invocations transformation\n if (message.toolInvocations && Array.isArray(message.toolInvocations)) {\n message.toolInvocations.forEach((inv: unknown) => {\n if (typeof inv === \"object\" && inv !== null && \"toolName\" in inv) {\n const invObj = inv as ToolInvocation;\n parts.push({\n type: `tool-${invObj.toolName}`,\n toolCallId: invObj.toolCallId,\n state:\n STATE_MAP[invObj.state as keyof typeof STATE_MAP] ||\n \"input-available\",\n input: invObj.args,\n output: invObj.result !== undefined ? invObj.result : null\n });\n }\n });\n }\n\n // Handle file parts transformation\n if (message.parts && Array.isArray(message.parts)) {\n message.parts.forEach((part: unknown) => {\n if (typeof part === \"object\" && part !== null && \"type\" in part) {\n const partObj = part as LegacyPart;\n if (partObj.type === \"file\") {\n parts.push({\n type: \"file\",\n url:\n partObj.url ||\n (partObj.data\n ? `data:${partObj.mimeType || partObj.mediaType};base64,${partObj.data}`\n : undefined),\n mediaType: partObj.mediaType || partObj.mimeType,\n filename: partObj.filename\n });\n }\n }\n });\n }\n\n // Handle corrupt array format: {role: \"user\", content: [{type: \"text\", text: \"...\"}]}\n if (Array.isArray(message.content)) {\n message.content.forEach((item: unknown) => {\n if (typeof item === \"object\" && item !== null && \"text\" in item) {\n const itemObj = item as CorruptContentItem;\n parts.push({\n type: itemObj.type || \"text\",\n text: itemObj.text || \"\"\n });\n }\n });\n }\n\n // Fallback: convert plain content to text part\n if (!parts.length && message.content !== undefined) {\n parts.push({\n type: \"text\",\n text:\n typeof message.content === \"string\"\n ? message.content\n : JSON.stringify(message.content)\n });\n }\n\n // If still no parts, create a default text part\n if (!parts.length) {\n parts.push({\n type: \"text\",\n text: typeof message === \"string\" ? message : JSON.stringify(message)\n });\n }\n\n return {\n id: message.id || `msg-${index}`,\n role:\n message.role === \"data\"\n ? \"system\"\n : (message.role as \"user\" | \"assistant\" | \"system\") || \"user\",\n parts: parts as UIMessage[\"parts\"]\n };\n}\n\n/**\n * Legacy single message migration for backward compatibility\n */\nexport function migrateToUIMessage(message: MigratableMessage): UIMessage {\n return autoTransformMessage(message as InputMessage);\n}\n\n/**\n * Automatic message transformer for arrays following the blog post pattern\n * @param messages - Array of messages in any format\n * @returns Array of UIMessages in v5 format\n */\nexport function autoTransformMessages(messages: unknown[]): UIMessage[] {\n return messages.map((msg, i) => autoTransformMessage(msg as InputMessage, i));\n}\n\n/**\n * Migrates an array of messages to UIMessage format (legacy compatibility)\n * @param messages - Array of messages in old or new format\n * @returns Array of UIMessages in the new format\n */\nexport function migrateMessagesToUIFormat(\n messages: MigratableMessage[]\n): UIMessage[] {\n return autoTransformMessages(messages as InputMessage[]);\n}\n\n/**\n * Checks if any messages in an array need migration\n * @param messages - Array of messages to check\n * @returns true if any messages are not in proper UIMessage format\n */\nexport function needsMigration(messages: unknown[]): boolean {\n return messages.some((message) => {\n // If it's already a UIMessage, no migration needed\n if (isUIMessage(message)) {\n return false;\n }\n\n // Check for corrupt array format specifically\n if (isCorruptArrayMessage(message)) {\n return true;\n }\n\n // Check for legacy string format\n if (isLegacyMessage(message)) {\n return true;\n }\n\n // Any other format needs migration\n return true;\n });\n}\n\n/**\n * Analyzes the corruption types in a message array for debugging\n * @param messages - Array of messages to analyze\n * @returns Statistics about corruption types found\n */\nexport function analyzeCorruption(messages: unknown[]): {\n total: number;\n clean: number;\n legacyString: number;\n corruptArray: number;\n unknown: number;\n examples: {\n legacyString?: unknown;\n corruptArray?: unknown;\n unknown?: unknown;\n };\n} {\n const stats = {\n total: messages.length,\n clean: 0,\n legacyString: 0,\n corruptArray: 0,\n unknown: 0,\n examples: {} as {\n legacyString?: unknown;\n corruptArray?: unknown;\n unknown?: unknown;\n }\n };\n\n for (const message of messages) {\n if (isUIMessage(message)) {\n stats.clean++;\n } else if (isCorruptArrayMessage(message)) {\n stats.corruptArray++;\n if (!stats.examples.corruptArray) {\n stats.examples.corruptArray = message;\n }\n } else if (isLegacyMessage(message)) {\n stats.legacyString++;\n if (!stats.examples.legacyString) {\n stats.examples.legacyString = message;\n }\n } else {\n stats.unknown++;\n if (!stats.examples.unknown) {\n stats.examples.unknown = message;\n }\n }\n }\n\n return stats;\n}\n"],"mappings":";AAkFA,IAAM,YAAY;AAAA,EAChB,gBAAgB;AAAA,EAChB,MAAM;AAAA,EACN,QAAQ;AAAA,EACR,OAAO;AACT;AAKO,SAAS,YAAY,SAAwC;AAClE,SACE,OAAO,YAAY,YACnB,YAAY,QACZ,WAAW,WACX,MAAM,QAAS,QAA+B,KAAK;AAEvD;AAKA,SAAS,gBAAgB,SAA4C;AACnE,SACE,OAAO,YAAY,YACnB,YAAY,QACZ,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