agents 0.7.3 → 0.7.4
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/{client-storage-yDVwzgfF.d.ts → client-storage-BPjfP_is.d.ts} +2 -2
- package/dist/experimental/forever.d.ts +2 -2
- package/dist/index.d.ts +1 -1
- package/dist/index.js +37 -1
- package/dist/index.js.map +1 -1
- package/dist/mcp/client.d.ts +1 -1
- package/dist/mcp/index.d.ts +1 -1
- package/dist/react.d.ts +1 -1
- package/dist/workflows.d.ts +1 -1
- package/package.json +1 -1
|
@@ -554,7 +554,7 @@ declare class MCPClientConnection {
|
|
|
554
554
|
*/
|
|
555
555
|
getTransport(
|
|
556
556
|
transportType: BaseTransportType
|
|
557
|
-
):
|
|
557
|
+
): StreamableHTTPClientTransport | SSEClientTransport | RPCClientTransport;
|
|
558
558
|
private tryConnect;
|
|
559
559
|
private _capabilityErrorHandler;
|
|
560
560
|
}
|
|
@@ -601,4 +601,4 @@ export {
|
|
|
601
601
|
MaybePromise as x,
|
|
602
602
|
StreamableHTTPEdgeClientTransport as y
|
|
603
603
|
};
|
|
604
|
-
//# sourceMappingURL=client-storage-
|
|
604
|
+
//# sourceMappingURL=client-storage-BPjfP_is.d.ts.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { RetryOptions } from "../retries.js";
|
|
2
|
-
import "../client-storage-
|
|
2
|
+
import "../client-storage-BPjfP_is.js";
|
|
3
3
|
import { Agent, Schedule } from "../index.js";
|
|
4
4
|
|
|
5
5
|
//#region src/experimental/forever.d.ts
|
|
@@ -92,13 +92,13 @@ declare function withFibers<TBase extends AgentLike>(Base: TBase, options?: {
|
|
|
92
92
|
_checkInterruptedFibers(): Promise<void>; /** @internal */
|
|
93
93
|
_cleanupOrphanedHeartbeats(): void; /** @internal */
|
|
94
94
|
_maybeCleanupFibers(): void;
|
|
95
|
-
alarm: () => Promise<void>;
|
|
96
95
|
sql: <T = Record<string, string | number | boolean | null>>(strings: TemplateStringsArray, ...values: (string | number | boolean | null)[]) => T[];
|
|
97
96
|
scheduleEvery: <T = string>(intervalSeconds: number, callback: keyof Agent<Cloudflare.Env, unknown, Record<string, unknown>>, payload?: T | undefined, options?: {
|
|
98
97
|
retry?: RetryOptions;
|
|
99
98
|
_idempotent?: boolean;
|
|
100
99
|
}) => Promise<Schedule<T>>;
|
|
101
100
|
cancelSchedule: (id: string) => Promise<boolean>;
|
|
101
|
+
alarm: () => Promise<void>;
|
|
102
102
|
keepAlive: () => Promise<() => void>;
|
|
103
103
|
keepAliveWhile: <T>(fn: () => Promise<T>) => Promise<T>;
|
|
104
104
|
};
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -333,7 +333,9 @@ var Agent = class Agent extends Server {
|
|
|
333
333
|
cron TEXT,
|
|
334
334
|
intervalSeconds INTEGER,
|
|
335
335
|
running INTEGER DEFAULT 0,
|
|
336
|
-
created_at INTEGER DEFAULT (unixepoch())
|
|
336
|
+
created_at INTEGER DEFAULT (unixepoch()),
|
|
337
|
+
execution_started_at INTEGER,
|
|
338
|
+
retry_options TEXT
|
|
337
339
|
)
|
|
338
340
|
`;
|
|
339
341
|
const addColumnIfNotExists = (sql) => {
|
|
@@ -348,6 +350,40 @@ var Agent = class Agent extends Server {
|
|
|
348
350
|
addColumnIfNotExists("ALTER TABLE cf_agents_schedules ADD COLUMN execution_started_at INTEGER");
|
|
349
351
|
addColumnIfNotExists("ALTER TABLE cf_agents_schedules ADD COLUMN retry_options TEXT");
|
|
350
352
|
addColumnIfNotExists("ALTER TABLE cf_agents_queues ADD COLUMN retry_options TEXT");
|
|
353
|
+
{
|
|
354
|
+
const rows = this.ctx.storage.sql.exec("SELECT sql FROM sqlite_master WHERE type='table' AND name='cf_agents_schedules'").toArray();
|
|
355
|
+
if (rows.length > 0) {
|
|
356
|
+
if (!String(rows[0].sql).includes("'interval'")) {
|
|
357
|
+
this.ctx.storage.sql.exec("DROP TABLE IF EXISTS cf_agents_schedules_new");
|
|
358
|
+
this.ctx.storage.sql.exec(`
|
|
359
|
+
CREATE TABLE cf_agents_schedules_new (
|
|
360
|
+
id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
|
|
361
|
+
callback TEXT,
|
|
362
|
+
payload TEXT,
|
|
363
|
+
type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron', 'interval')),
|
|
364
|
+
time INTEGER,
|
|
365
|
+
delayInSeconds INTEGER,
|
|
366
|
+
cron TEXT,
|
|
367
|
+
intervalSeconds INTEGER,
|
|
368
|
+
running INTEGER DEFAULT 0,
|
|
369
|
+
created_at INTEGER DEFAULT (unixepoch()),
|
|
370
|
+
execution_started_at INTEGER,
|
|
371
|
+
retry_options TEXT
|
|
372
|
+
)
|
|
373
|
+
`);
|
|
374
|
+
this.ctx.storage.sql.exec(`
|
|
375
|
+
INSERT INTO cf_agents_schedules_new
|
|
376
|
+
(id, callback, payload, type, time, delayInSeconds, cron,
|
|
377
|
+
intervalSeconds, running, created_at, execution_started_at, retry_options)
|
|
378
|
+
SELECT id, callback, payload, type, time, delayInSeconds, cron,
|
|
379
|
+
intervalSeconds, running, created_at, execution_started_at, retry_options
|
|
380
|
+
FROM cf_agents_schedules
|
|
381
|
+
`);
|
|
382
|
+
this.ctx.storage.sql.exec("DROP TABLE cf_agents_schedules");
|
|
383
|
+
this.ctx.storage.sql.exec("ALTER TABLE cf_agents_schedules_new RENAME TO cf_agents_schedules");
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
}
|
|
351
387
|
this.sql`
|
|
352
388
|
CREATE TABLE IF NOT EXISTS cf_agents_workflows (
|
|
353
389
|
id TEXT PRIMARY KEY NOT NULL,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["agentContext"],"sources":["../src/index.ts"],"sourcesContent":["import type { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport {\n __DO_NOT_USE_WILL_BREAK__agentContext as agentContext,\n type AgentEmail\n} from \"./internal_context\";\nexport { __DO_NOT_USE_WILL_BREAK__agentContext } from \"./internal_context\";\nimport type { SSEClientTransportOptions } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport { signAgentHeaders } from \"./email\";\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 \"./utils\";\nimport {\n type RetryOptions,\n tryN,\n isErrorRetryable,\n validateRetryOptions\n} from \"./retries\";\nimport { MCPClientManager, type MCPClientOAuthResult } from \"./mcp/client\";\nimport type {\n WorkflowCallback,\n WorkflowTrackingRow,\n WorkflowStatus,\n RunWorkflowOptions,\n WorkflowEventPayload,\n WorkflowInfo,\n WorkflowQueryCriteria,\n WorkflowPage\n} from \"./workflow-types\";\nimport { MCPConnectionState } from \"./mcp/client-connection\";\nimport {\n DurableObjectOAuthClientProvider,\n type AgentMcpOAuthProvider\n} from \"./mcp/do-oauth-client-provider\";\nimport type { TransportType } from \"./mcp/types\";\nimport {\n genericObservability,\n type Observability,\n type ObservabilityEvent\n} from \"./observability\";\nimport { DisposableStore } from \"./core/events\";\nimport { MessageType } from \"./types\";\nimport { RPC_DO_PREFIX } from \"./mcp/rpc\";\nimport type { McpAgent } from \"./mcp\";\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 WeakMap<Function, CallableMetadata>();\n\n/**\n * Error class for SQL execution failures, containing the query that failed\n */\nexport class SqlError extends Error {\n /** The SQL query that failed */\n readonly query: string;\n\n constructor(query: string, cause: unknown) {\n const message = cause instanceof Error ? cause.message : String(cause);\n super(`SQL query failed: ${message}`, { cause });\n this.name = \"SqlError\";\n this.query = query;\n }\n}\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 _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 return callable(metadata);\n};\n\nexport type QueueItem<T = string> = {\n id: string;\n payload: T;\n callback: keyof Agent<Cloudflare.Env>;\n created_at: number;\n retry?: RetryOptions;\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 /** Retry options for callback execution */\n retry?: RetryOptions;\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 /** Type of schedule for recurring execution at fixed intervals */\n type: \"interval\";\n /** Timestamp for the next execution */\n time: number;\n /** Number of seconds between executions */\n intervalSeconds: number;\n }\n);\n\n/**\n * Represents the public state of a fiber.\n */\nfunction getNextCronTime(cron: string) {\n const interval = parseCronExpression(cron);\n return interval.getNextDate();\n}\n\nexport type { TransportType } from \"./mcp/types\";\nexport type { RetryOptions } from \"./retries\";\nexport {\n DurableObjectOAuthClientProvider,\n type AgentMcpOAuthProvider,\n /** @deprecated Use {@link AgentMcpOAuthProvider} instead. */\n type AgentsOAuthProvider\n} from \"./mcp/do-oauth-client-provider\";\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 & { serverId: string })[];\n prompts: (Prompt & { serverId: string })[];\n resources: (Resource & { serverId: string })[];\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: MCPConnectionState;\n /** May contain untrusted content from external OAuth providers. Escape appropriately for your output context. */\n error: string | null;\n instructions: string | null;\n capabilities: ServerCapabilities | null;\n};\n\n/**\n * Options for adding an MCP server\n */\nexport type AddMcpServerOptions = {\n /** OAuth callback host (auto-derived from request if omitted) */\n callbackHost?: string;\n /**\n * Custom callback URL path — bypasses the default `/agents/{class}/{name}/callback` construction.\n * Required when `sendIdentityOnConnect` is `false` to prevent leaking the instance name.\n * When set, the callback URL becomes `{callbackHost}/{callbackPath}`.\n * The developer must route this path to the agent instance via `getAgentByName`.\n * Should be a plain path (e.g., `/mcp-callback`) — do not include query strings or fragments.\n */\n callbackPath?: string;\n /** Agents routing prefix (default: \"agents\") */\n agentsPrefix?: string;\n /** MCP client options */\n client?: ConstructorParameters<typeof Client>[1];\n /** Transport options */\n transport?: {\n /** Custom headers for authentication (e.g., bearer tokens, CF Access) */\n headers?: HeadersInit;\n /** Transport type: \"sse\", \"streamable-http\", or \"auto\" (default) */\n type?: TransportType;\n };\n /** Retry options for connection and reconnection attempts */\n retry?: RetryOptions;\n};\n\n/**\n * Options for adding an MCP server via RPC (Durable Object binding)\n */\nexport type AddRpcMcpServerOptions = {\n /** Props to pass to the McpAgent instance */\n props?: Record<string, unknown>;\n};\n\nconst KEEP_ALIVE_INTERVAL_MS = 30_000;\n\nconst STATE_ROW_ID = \"cf_state_row_id\";\nconst STATE_WAS_CHANGED = \"cf_state_was_changed\";\n\nconst DEFAULT_STATE = {} as unknown;\n\n/**\n * Internal key used to store the readonly flag in connection state.\n * Prefixed with _cf_ to avoid collision with user state keys.\n */\nconst CF_READONLY_KEY = \"_cf_readonly\";\n\n/**\n * Internal key used to store the no-protocol flag in connection state.\n * When set, protocol messages (identity, state sync, MCP servers) are not\n * sent to this connection — neither on connect nor via broadcasts.\n */\nconst CF_NO_PROTOCOL_KEY = \"_cf_no_protocol\";\n\n/**\n * The set of all internal keys stored in connection state that must be\n * hidden from user code and preserved across setState calls.\n */\nconst CF_INTERNAL_KEYS: ReadonlySet<string> = new Set([\n CF_READONLY_KEY,\n CF_NO_PROTOCOL_KEY\n]);\n\n/** Check if a raw connection state object contains any internal keys. */\nfunction rawHasInternalKeys(raw: Record<string, unknown>): boolean {\n for (const key of Object.keys(raw)) {\n if (CF_INTERNAL_KEYS.has(key)) return true;\n }\n return false;\n}\n\n/** Return a copy of `raw` with all internal keys removed, or null if no user keys remain. */\nfunction stripInternalKeys(\n raw: Record<string, unknown>\n): Record<string, unknown> | null {\n const result: Record<string, unknown> = {};\n let hasUserKeys = false;\n for (const key of Object.keys(raw)) {\n if (!CF_INTERNAL_KEYS.has(key)) {\n result[key] = raw[key];\n hasUserKeys = true;\n }\n }\n return hasUserKeys ? result : null;\n}\n\n/** Return a copy containing only the internal keys present in `raw`. */\nfunction extractInternalFlags(\n raw: Record<string, unknown>\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(raw)) {\n if (CF_INTERNAL_KEYS.has(key)) {\n result[key] = raw[key];\n }\n }\n return result;\n}\n\n/** Max length for error strings broadcast to clients. */\nconst MAX_ERROR_STRING_LENGTH = 500;\n\n/**\n * Sanitize an error string before broadcasting to clients.\n * MCP error strings may contain untrusted content from external OAuth\n * providers — truncate and strip control characters to limit XSS risk.\n */\n// Regex to match C0 control characters (except \\t, \\n, \\r) and DEL.\nconst CONTROL_CHAR_RE = new RegExp(\n // oxlint-disable-next-line no-control-regex -- intentionally matching control chars for sanitization\n \"[\\\\u0000-\\\\u0008\\\\u000B\\\\u000C\\\\u000E-\\\\u001F\\\\u007F]\",\n \"g\"\n);\n\nfunction sanitizeErrorString(error: string | null): string | null {\n if (error === null) return null;\n // Strip control characters (keep printable ASCII + common unicode)\n let sanitized = error.replace(CONTROL_CHAR_RE, \"\");\n if (sanitized.length > MAX_ERROR_STRING_LENGTH) {\n sanitized = sanitized.substring(0, MAX_ERROR_STRING_LENGTH) + \"...\";\n }\n return sanitized;\n}\n\n/**\n * Tracks which agent constructors have already emitted the onStateUpdate\n * deprecation warning, so it fires at most once per class.\n */\nconst _onStateUpdateWarnedClasses = new WeakSet<Function>();\n\n/**\n * Tracks which agent constructors have already emitted the\n * sendIdentityOnConnect deprecation warning, so it fires at most once per class.\n */\nconst _sendIdentityWarnedClasses = new WeakSet<Function>();\n\n/**\n * Default options for Agent configuration.\n * Child classes can override specific options without spreading.\n */\nexport const DEFAULT_AGENT_STATIC_OPTIONS = {\n /** Whether the Agent should hibernate when inactive */\n hibernate: true,\n /** Whether to send identity (name, agent) to clients on connect */\n sendIdentityOnConnect: true,\n /**\n * Timeout in seconds before a running interval schedule is considered \"hung\"\n * and force-reset. Increase this if you have callbacks that legitimately\n * take longer than 30 seconds.\n */\n hungScheduleTimeoutSeconds: 30,\n /** Default retry options for schedule(), queue(), and this.retry() */\n retry: {\n maxAttempts: 3,\n baseDelayMs: 100,\n maxDelayMs: 3000\n } satisfies Required<RetryOptions>\n};\n\n/**\n * Fully resolved agent options — all fields are defined with concrete values.\n */\ninterface ResolvedAgentOptions {\n hibernate: boolean;\n sendIdentityOnConnect: boolean;\n hungScheduleTimeoutSeconds: number;\n retry: Required<RetryOptions>;\n}\n\n/**\n * Configuration options for the Agent.\n * Override in subclasses via `static options`.\n * All fields are optional - defaults are applied at runtime.\n * Note: `hibernate` defaults to `true` if not specified.\n */\nexport interface AgentStaticOptions {\n hibernate?: boolean;\n sendIdentityOnConnect?: boolean;\n hungScheduleTimeoutSeconds?: number;\n /** Default retry options for schedule(), queue(), and this.retry(). */\n retry?: RetryOptions;\n}\n\n/**\n * Parse the raw `retry_options` TEXT column from a SQLite row into a\n * typed `RetryOptions` object, or `undefined` if not set.\n */\nfunction parseRetryOptions(\n row: Record<string, unknown>\n): RetryOptions | undefined {\n const raw = row.retry_options;\n if (typeof raw !== \"string\") return undefined;\n return JSON.parse(raw) as RetryOptions;\n}\n\n/**\n * Resolve per-task retry options against class-level defaults and call\n * `tryN`. This is the shared retry-execution path used by both queue\n * flush and schedule alarm handlers.\n */\nfunction resolveRetryConfig(\n taskRetry: RetryOptions | undefined,\n defaults: Required<RetryOptions>\n): { maxAttempts: number; baseDelayMs: number; maxDelayMs: number } {\n return {\n maxAttempts: taskRetry?.maxAttempts ?? defaults.maxAttempts,\n baseDelayMs: taskRetry?.baseDelayMs ?? defaults.baseDelayMs,\n maxDelayMs: taskRetry?.maxDelayMs ?? defaults.maxDelayMs\n };\n}\n\nexport function getCurrentAgent<\n T extends Agent<Cloudflare.Env> = Agent<Cloudflare.Env>\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// oxlint-disable-next-line @typescript-eslint/no-explicit-any -- generic callable constraint\nfunction withAgentContext<T extends (...args: any[]) => any>(\n method: T\n): (\n this: Agent<Cloudflare.Env, unknown>,\n ...args: Parameters<T>\n) => 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 * Extract string keys from Env where the value is a Workflow binding.\n */\ntype WorkflowBinding<E> = {\n [K in keyof E & string]: E[K] extends Workflow ? K : never;\n}[keyof E & string];\n\n/**\n * Type for workflow name parameter.\n * When Env has typed Workflow bindings, provides autocomplete for those keys.\n * Also accepts any string for dynamic use cases and compatibility.\n * The `string & {}` trick preserves autocomplete while allowing any string.\n */\ntype WorkflowName<E> = WorkflowBinding<E> | (string & {});\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 extends Cloudflare.Env = Cloudflare.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 private _disposables = new DisposableStore();\n private _destroyed = false;\n\n /**\n * Stores raw state accessors for wrapped connections.\n * Used by internal flag methods (readonly, no-protocol) to read/write\n * _cf_-prefixed keys without going through the user-facing state/setState.\n */\n private _rawStateAccessors = new WeakMap<\n Connection,\n {\n getRaw: () => Record<string, unknown> | null;\n setRaw: (state: unknown) => unknown;\n }\n >();\n\n /**\n * Cached persistence-hook dispatch mode, computed once in the constructor.\n * - \"new\" → call onStateChanged\n * - \"old\" → call onStateUpdate (deprecated)\n * - \"none\" → neither hook is overridden, skip entirely\n */\n private _persistenceHookMode: \"new\" | \"old\" | \"none\" = \"none\";\n\n private _ParentClass: typeof Agent<Env, State> =\n Object.getPrototypeOf(this).constructor;\n\n readonly mcp: MCPClientManager;\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 try {\n this._state = JSON.parse(state);\n } catch (e) {\n console.error(\n \"Failed to parse stored state, falling back to initialState:\",\n e\n );\n if (this.initialState !== DEFAULT_STATE) {\n this._state = this.initialState;\n // Persist the fixed state to prevent future parse errors\n this._setStateInternal(this.initialState);\n } else {\n // No initialState defined - clear corrupted data to prevent infinite retry loop\n this.sql`DELETE FROM cf_agents_state WHERE id = ${STATE_ROW_ID}`;\n this.sql`DELETE FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}`;\n return undefined as State;\n }\n }\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._setStateInternal(this.initialState);\n return this.initialState;\n }\n\n /**\n * Agent configuration options.\n * Override in subclasses - only specify what you want to change.\n * @example\n * class SecureAgent extends Agent {\n * static options = { sendIdentityOnConnect: false };\n * }\n */\n static options: AgentStaticOptions = { hibernate: true };\n\n /**\n * Resolved options (merges defaults with subclass overrides).\n * Cached after first access — static options never change during the\n * lifetime of a Durable Object instance.\n */\n private _cachedOptions?: ResolvedAgentOptions;\n private get _resolvedOptions(): ResolvedAgentOptions {\n if (this._cachedOptions) return this._cachedOptions;\n const ctor = this.constructor as typeof Agent;\n const userRetry = ctor.options?.retry;\n this._cachedOptions = {\n hibernate:\n ctor.options?.hibernate ?? DEFAULT_AGENT_STATIC_OPTIONS.hibernate,\n sendIdentityOnConnect:\n ctor.options?.sendIdentityOnConnect ??\n DEFAULT_AGENT_STATIC_OPTIONS.sendIdentityOnConnect,\n hungScheduleTimeoutSeconds:\n ctor.options?.hungScheduleTimeoutSeconds ??\n DEFAULT_AGENT_STATIC_OPTIONS.hungScheduleTimeoutSeconds,\n retry: {\n maxAttempts:\n userRetry?.maxAttempts ??\n DEFAULT_AGENT_STATIC_OPTIONS.retry.maxAttempts,\n baseDelayMs:\n userRetry?.baseDelayMs ??\n DEFAULT_AGENT_STATIC_OPTIONS.retry.baseDelayMs,\n maxDelayMs:\n userRetry?.maxDelayMs ?? DEFAULT_AGENT_STATIC_OPTIONS.retry.maxDelayMs\n }\n };\n return this._cachedOptions;\n }\n\n /**\n * The observability implementation to use for the Agent\n */\n observability?: Observability = genericObservability;\n\n /**\n * Emit an observability event with auto-generated timestamp.\n * @internal\n */\n protected _emit(\n type: ObservabilityEvent[\"type\"],\n payload: Record<string, unknown> = {}\n ): void {\n this.observability?.emit({\n type,\n agent: this._ParentClass.name,\n name: this.name,\n payload,\n timestamp: Date.now()\n } as ObservabilityEvent);\n }\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 throw new SqlError(query, 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_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 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 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', 'interval')),\n time INTEGER,\n delayInSeconds INTEGER,\n cron TEXT,\n intervalSeconds INTEGER,\n running INTEGER DEFAULT 0,\n created_at INTEGER DEFAULT (unixepoch())\n )\n `;\n\n // Migration: Add columns for interval scheduling (for existing agents)\n // Use raw exec to avoid error logging through onError for expected failures\n const addColumnIfNotExists = (sql: string) => {\n try {\n this.ctx.storage.sql.exec(sql);\n } catch (e) {\n // Only ignore \"duplicate column\" errors, re-throw unexpected errors\n const message = e instanceof Error ? e.message : String(e);\n if (!message.toLowerCase().includes(\"duplicate column\")) {\n throw e;\n }\n }\n };\n\n addColumnIfNotExists(\n \"ALTER TABLE cf_agents_schedules ADD COLUMN intervalSeconds INTEGER\"\n );\n addColumnIfNotExists(\n \"ALTER TABLE cf_agents_schedules ADD COLUMN running INTEGER DEFAULT 0\"\n );\n addColumnIfNotExists(\n \"ALTER TABLE cf_agents_schedules ADD COLUMN execution_started_at INTEGER\"\n );\n addColumnIfNotExists(\n \"ALTER TABLE cf_agents_schedules ADD COLUMN retry_options TEXT\"\n );\n addColumnIfNotExists(\n \"ALTER TABLE cf_agents_queues ADD COLUMN retry_options TEXT\"\n );\n\n // Workflow tracking table for Agent-Workflow integration\n this.sql`\n CREATE TABLE IF NOT EXISTS cf_agents_workflows (\n id TEXT PRIMARY KEY NOT NULL,\n workflow_id TEXT NOT NULL UNIQUE,\n workflow_name TEXT NOT NULL,\n status TEXT NOT NULL CHECK(status IN (\n 'queued', 'running', 'paused', 'errored',\n 'terminated', 'complete', 'waiting',\n 'waitingForPause', 'unknown'\n )),\n metadata TEXT,\n error_name TEXT,\n error_message TEXT,\n created_at INTEGER NOT NULL DEFAULT (unixepoch()),\n updated_at INTEGER NOT NULL DEFAULT (unixepoch()),\n completed_at INTEGER\n )\n `;\n\n this.sql`\n CREATE INDEX IF NOT EXISTS idx_workflows_status ON cf_agents_workflows(status)\n `;\n\n this.sql`\n CREATE INDEX IF NOT EXISTS idx_workflows_name ON cf_agents_workflows(workflow_name)\n `;\n\n // Initialize MCPClientManager AFTER tables are created\n this.mcp = new MCPClientManager(this._ParentClass.name, \"0.0.1\", {\n storage: this.ctx.storage,\n createAuthProvider: (callbackUrl) =>\n this.createMcpOAuthProvider(callbackUrl)\n });\n\n // Broadcast server state whenever MCP state changes (register, connect, OAuth, remove, etc.)\n this._disposables.add(\n this.mcp.onServerStateChanged(async () => {\n this.broadcastMcpServers();\n })\n );\n\n // Emit MCP observability events\n this._disposables.add(\n this.mcp.onObservabilityEvent((event) => {\n this.observability?.emit({\n ...event,\n agent: this._ParentClass.name,\n name: this.name\n });\n })\n );\n // Compute persistence-hook dispatch mode once.\n // Throws immediately if both hooks are overridden on the same class.\n {\n const proto = Object.getPrototypeOf(this);\n const hasOwnNew = Object.prototype.hasOwnProperty.call(\n proto,\n \"onStateChanged\"\n );\n const hasOwnOld = Object.prototype.hasOwnProperty.call(\n proto,\n \"onStateUpdate\"\n );\n\n if (hasOwnNew && hasOwnOld) {\n throw new Error(\n `[Agent] Cannot override both onStateChanged and onStateUpdate. ` +\n `Remove onStateUpdate — it has been renamed to onStateChanged.`\n );\n }\n\n if (hasOwnOld) {\n const ctor = this.constructor;\n if (!_onStateUpdateWarnedClasses.has(ctor)) {\n _onStateUpdateWarnedClasses.add(ctor);\n console.warn(\n `[Agent] onStateUpdate is deprecated. Rename to onStateChanged — the behavior is identical.`\n );\n }\n }\n\n const base = Agent.prototype;\n if (proto.onStateChanged !== base.onStateChanged) {\n this._persistenceHookMode = \"new\";\n } else if (proto.onStateUpdate !== base.onStateUpdate) {\n this._persistenceHookMode = \"old\";\n }\n // default \"none\" already set in field initializer\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 // TODO: make zod/ai sdk more performant and remove this\n // Late initialization of jsonSchemaFn (needed for getAITools)\n await this.mcp.ensureJsonSchema();\n\n // Handle MCP OAuth callback if this is one\n const oauthResponse = await this.handleMcpOAuthCallback(request);\n if (oauthResponse) {\n return oauthResponse;\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 this._ensureConnectionWrapped(connection);\n return agentContext.run(\n { agent: this, connection, request: undefined, email: undefined },\n async () => {\n // TODO: make zod/ai sdk more performant and remove this\n // Late initialization of jsonSchemaFn (needed for getAITools)\n await this.mcp.ensureJsonSchema();\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 // Check if connection is readonly\n if (this.isConnectionReadonly(connection)) {\n // Send error response back to the connection\n connection.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_STATE_ERROR,\n error: \"Connection is readonly\"\n })\n );\n return;\n }\n try {\n this._setStateInternal(parsed.state as State, connection);\n } catch (e) {\n // validateStateChange (or another sync error) rejected the update.\n // Log the full error server-side, send a generic message to the client.\n console.error(\"[Agent] State update rejected:\", e);\n connection.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_STATE_ERROR,\n error: \"State update rejected\"\n })\n );\n }\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\n this._emit(\"rpc\", { method, streaming: true });\n\n try {\n await methodFn.apply(this, [stream, ...args]);\n } catch (err) {\n console.error(`Error in streaming method \"${method}\":`, err);\n this._emit(\"rpc:error\", {\n method,\n error: err instanceof Error ? err.message : String(err)\n });\n // Auto-close stream with error if method throws before closing\n if (!stream.isClosed) {\n stream.error(\n err instanceof Error ? err.message : String(err)\n );\n }\n }\n return;\n }\n\n // For regular methods, execute and send response\n const result = await methodFn.apply(this, args);\n\n this._emit(\"rpc\", { method, streaming: metadata?.streaming });\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 this._emit(\"rpc:error\", {\n method: parsed.method,\n error: e instanceof Error ? e.message : String(e)\n });\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 this._ensureConnectionWrapped(connection);\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 async () => {\n // Check if connection should be readonly before sending any messages\n // so that the flag is set before the client can respond\n if (this.shouldConnectionBeReadonly(connection, ctx)) {\n this.setConnectionReadonly(connection, true);\n }\n\n // Check if protocol messages should be suppressed for this\n // connection. When disabled, no identity/state/MCP text frames\n // are sent — useful for binary-only clients (e.g. MQTT devices).\n if (this.shouldSendProtocolMessages(connection, ctx)) {\n // Send agent identity first so client knows which instance it's connected to\n // Can be disabled via static options for security-sensitive instance names\n if (this._resolvedOptions.sendIdentityOnConnect) {\n const ctor = this.constructor as typeof Agent;\n if (\n ctor.options?.sendIdentityOnConnect === undefined &&\n !_sendIdentityWarnedClasses.has(ctor)\n ) {\n // Only warn when using custom routing — with default routing\n // the name is already visible in the URL path (/agents/{class}/{name})\n // so sendIdentityOnConnect leaks no additional information.\n const urlPath = new URL(ctx.request.url).pathname;\n if (!urlPath.includes(this.name)) {\n _sendIdentityWarnedClasses.add(ctor);\n console.warn(\n `[Agent] ${ctor.name}: sending instance name \"${this.name}\" to clients ` +\n `via sendIdentityOnConnect (the name is not visible in the URL with ` +\n `custom routing). If this name is sensitive, add ` +\n `\\`static options = { sendIdentityOnConnect: false }\\` to opt out. ` +\n `Set it to true to silence this message.`\n );\n }\n }\n connection.send(\n JSON.stringify({\n name: this.name,\n agent: camelCaseToKebabCase(this._ParentClass.name),\n type: MessageType.CF_AGENT_IDENTITY\n })\n );\n }\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 } else {\n this._setConnectionNoProtocol(connection);\n }\n\n this._emit(\"connect\", { connectionId: connection.id });\n return this._tryCatch(() => _onConnect(connection, ctx));\n }\n );\n };\n\n const _onClose = this.onClose.bind(this);\n this.onClose = (\n connection: Connection,\n code: number,\n reason: string,\n wasClean: boolean\n ) => {\n return agentContext.run(\n { agent: this, connection, request: undefined, email: undefined },\n () => {\n this._emit(\"disconnect\", {\n connectionId: connection.id,\n code,\n reason\n });\n return _onClose(connection, code, reason, wasClean);\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(async () => {\n await this.mcp.restoreConnectionsFromStorage(this.name);\n await this._restoreRpcMcpServers();\n this.broadcastMcpServers();\n\n this._checkOrphanedWorkflows();\n\n return _onStart(props);\n });\n }\n );\n };\n }\n\n /**\n * Check for workflows referencing unknown bindings and warn with migration suggestion.\n */\n private _checkOrphanedWorkflows(): void {\n // Get distinct workflow names with counts by active/completed status\n const distinctNames = this.sql<{\n workflow_name: string;\n total: number;\n active: number;\n completed: number;\n }>`\n SELECT \n workflow_name,\n COUNT(*) as total,\n SUM(CASE WHEN status NOT IN ('complete', 'errored', 'terminated') THEN 1 ELSE 0 END) as active,\n SUM(CASE WHEN status IN ('complete', 'errored', 'terminated') THEN 1 ELSE 0 END) as completed\n FROM cf_agents_workflows \n GROUP BY workflow_name\n `;\n\n const orphaned = distinctNames.filter(\n (row) => !this._findWorkflowBindingByName(row.workflow_name)\n );\n\n if (orphaned.length > 0) {\n const currentBindings = this._getWorkflowBindingNames();\n for (const {\n workflow_name: oldName,\n total,\n active,\n completed\n } of orphaned) {\n const suggestion =\n currentBindings.length === 1\n ? `this.migrateWorkflowBinding('${oldName}', '${currentBindings[0]}')`\n : `this.migrateWorkflowBinding('${oldName}', '<NEW_BINDING_NAME>')`;\n const breakdown =\n active > 0 && completed > 0\n ? ` (${active} active, ${completed} completed)`\n : active > 0\n ? ` (${active} active)`\n : ` (${completed} completed)`;\n console.warn(\n `[Agent] Found ${total} workflow(s) referencing unknown binding '${oldName}'${breakdown}. ` +\n `If you renamed the binding, call: ${suggestion}`\n );\n }\n }\n }\n\n /**\n * Broadcast a protocol message only to connections that have protocol\n * messages enabled. Connections where shouldSendProtocolMessages returned\n * false are excluded automatically.\n * @param msg The JSON-encoded protocol message\n * @param excludeIds Additional connection IDs to exclude (e.g. the source)\n */\n private _broadcastProtocol(msg: string, excludeIds: string[] = []) {\n const exclude = [...excludeIds];\n for (const conn of this.getConnections()) {\n if (!this.isConnectionProtocolEnabled(conn)) {\n exclude.push(conn.id);\n }\n }\n this.broadcast(msg, exclude);\n }\n\n private _setStateInternal(\n nextState: State,\n source: Connection | \"server\" = \"server\"\n ): void {\n // Validation/gating hook (sync only)\n this.validateStateChange(nextState, source);\n\n // Persist state\n this._state = nextState;\n this.sql`\n INSERT OR REPLACE INTO cf_agents_state (id, state)\n VALUES (${STATE_ROW_ID}, ${JSON.stringify(nextState)})\n `;\n this.sql`\n INSERT OR REPLACE INTO cf_agents_state (id, state)\n VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})\n `;\n\n // Broadcast state to protocol-enabled connections, excluding the source\n this._broadcastProtocol(\n JSON.stringify({\n state: nextState,\n type: MessageType.CF_AGENT_STATE\n }),\n source !== \"server\" ? [source.id] : []\n );\n\n // Notification hook (non-gating). Run after broadcast and do not block.\n // Use waitUntil for reliability after the handler returns.\n const { connection, request, email } = agentContext.getStore() || {};\n this.ctx.waitUntil(\n (async () => {\n try {\n await agentContext.run(\n { agent: this, connection, request, email },\n async () => {\n this._emit(\"state:update\");\n await this._callStatePersistenceHook(nextState, source);\n }\n );\n } catch (e) {\n // onStateChanged/onStateUpdate errors should not affect state or broadcasts\n try {\n await this.onError(e);\n } catch {\n // swallow\n }\n }\n })()\n );\n }\n\n /**\n * Update the Agent's state\n * @param state New state to set\n * @throws Error if called from a readonly connection context\n */\n setState(state: State): void {\n // Check if the current context has a readonly connection\n const store = agentContext.getStore();\n if (store?.connection && this.isConnectionReadonly(store.connection)) {\n throw new Error(\"Connection is readonly\");\n }\n this._setStateInternal(state, \"server\");\n }\n\n /**\n * Wraps connection.state and connection.setState so that internal\n * _cf_-prefixed flags (readonly, no-protocol) are hidden from user code\n * and cannot be accidentally overwritten.\n *\n * Idempotent — safe to call multiple times on the same connection.\n * After hibernation, the _rawStateAccessors WeakMap is empty but the\n * connection's state getter still reads from the persisted WebSocket\n * attachment. Calling this method re-captures the raw getter so that\n * predicate methods (isConnectionReadonly, isConnectionProtocolEnabled)\n * work correctly post-hibernation.\n */\n private _ensureConnectionWrapped(connection: Connection) {\n if (this._rawStateAccessors.has(connection)) return;\n\n // Determine whether `state` is an accessor (getter) or a data property.\n // partyserver always defines `state` as a getter via Object.defineProperties,\n // but we handle the data-property case to stay robust for hibernate: false\n // and any future connection implementations.\n const descriptor = Object.getOwnPropertyDescriptor(connection, \"state\");\n\n let getRaw: () => Record<string, unknown> | null;\n let setRaw: (state: unknown) => unknown;\n\n if (descriptor?.get) {\n // Accessor property — bind the original getter directly.\n // The getter reads from the serialized WebSocket attachment, so it\n // always returns the latest value even after setState updates it.\n getRaw = descriptor.get.bind(connection) as () => Record<\n string,\n unknown\n > | null;\n setRaw = connection.setState.bind(connection);\n } else {\n // Data property — track raw state in a closure variable.\n // Reading `connection.state` after our override would call our filtered\n // getter (circular), so we snapshot the value here and keep it in sync.\n let rawState = (connection.state ?? null) as Record<\n string,\n unknown\n > | null;\n getRaw = () => rawState;\n setRaw = (state: unknown) => {\n rawState = state as Record<string, unknown> | null;\n return rawState;\n };\n }\n\n this._rawStateAccessors.set(connection, { getRaw, setRaw });\n\n // Override state getter to hide all internal _cf_ flags from user code\n Object.defineProperty(connection, \"state\", {\n configurable: true,\n enumerable: true,\n get() {\n const raw = getRaw();\n if (raw != null && typeof raw === \"object\" && rawHasInternalKeys(raw)) {\n return stripInternalKeys(raw);\n }\n return raw;\n }\n });\n\n // Override setState to preserve internal flags when user sets state\n Object.defineProperty(connection, \"setState\", {\n configurable: true,\n writable: true,\n value(stateOrFn: unknown | ((prev: unknown) => unknown)) {\n const raw = getRaw();\n const flags =\n raw != null && typeof raw === \"object\"\n ? extractInternalFlags(raw as Record<string, unknown>)\n : {};\n const hasFlags = Object.keys(flags).length > 0;\n\n let newUserState: unknown;\n if (typeof stateOrFn === \"function\") {\n // Pass only the user-visible state (without internal flags) to the callback\n const userVisible = hasFlags\n ? stripInternalKeys(raw as Record<string, unknown>)\n : raw;\n newUserState = (stateOrFn as (prev: unknown) => unknown)(userVisible);\n } else {\n newUserState = stateOrFn;\n }\n\n // Merge back internal flags if any were set\n if (hasFlags) {\n if (newUserState != null && typeof newUserState === \"object\") {\n return setRaw({\n ...(newUserState as Record<string, unknown>),\n ...flags\n });\n }\n // User set null — store just the flags\n return setRaw(flags);\n }\n return setRaw(newUserState);\n }\n });\n }\n\n /**\n * Mark a connection as readonly or readwrite\n * @param connection The connection to mark\n * @param readonly Whether the connection should be readonly (default: true)\n */\n setConnectionReadonly(connection: Connection, readonly = true) {\n this._ensureConnectionWrapped(connection);\n const accessors = this._rawStateAccessors.get(connection)!;\n const raw = (accessors.getRaw() as Record<string, unknown> | null) ?? {};\n if (readonly) {\n accessors.setRaw({ ...raw, [CF_READONLY_KEY]: true });\n } else {\n // Remove the key entirely instead of storing false — avoids dead keys\n // accumulating in the connection attachment.\n const { [CF_READONLY_KEY]: _, ...rest } = raw;\n accessors.setRaw(Object.keys(rest).length > 0 ? rest : null);\n }\n }\n\n /**\n * Check if a connection is marked as readonly.\n *\n * Safe to call after hibernation — re-wraps the connection if the\n * in-memory accessor cache was cleared.\n * @param connection The connection to check\n * @returns True if the connection is readonly\n */\n isConnectionReadonly(connection: Connection): boolean {\n this._ensureConnectionWrapped(connection);\n const raw = this._rawStateAccessors.get(connection)!.getRaw() as Record<\n string,\n unknown\n > | null;\n return !!raw?.[CF_READONLY_KEY];\n }\n\n /**\n * Override this method to determine if a connection should be readonly on connect\n * @param _connection The connection that is being established\n * @param _ctx Connection context\n * @returns True if the connection should be readonly\n */\n shouldConnectionBeReadonly(\n _connection: Connection,\n _ctx: ConnectionContext\n ): boolean {\n return false;\n }\n\n /**\n * Override this method to control whether protocol messages are sent to a\n * connection. Protocol messages include identity (CF_AGENT_IDENTITY), state\n * sync (CF_AGENT_STATE), and MCP server lists (CF_AGENT_MCP_SERVERS).\n *\n * When this returns `false` for a connection, that connection will not\n * receive any protocol text frames — neither on connect nor via broadcasts.\n * This is useful for binary-only clients (e.g. MQTT devices) that cannot\n * handle JSON text frames.\n *\n * The connection can still send and receive regular messages, use RPC, and\n * participate in all non-protocol communication.\n *\n * @param _connection The connection that is being established\n * @param _ctx Connection context (includes the upgrade request)\n * @returns True if protocol messages should be sent (default), false to suppress them\n */\n shouldSendProtocolMessages(\n _connection: Connection,\n _ctx: ConnectionContext\n ): boolean {\n return true;\n }\n\n /**\n * Check if a connection has protocol messages enabled.\n * Protocol messages include identity, state sync, and MCP server lists.\n *\n * Safe to call after hibernation — re-wraps the connection if the\n * in-memory accessor cache was cleared.\n * @param connection The connection to check\n * @returns True if the connection receives protocol messages\n */\n isConnectionProtocolEnabled(connection: Connection): boolean {\n this._ensureConnectionWrapped(connection);\n const raw = this._rawStateAccessors.get(connection)!.getRaw() as Record<\n string,\n unknown\n > | null;\n return !raw?.[CF_NO_PROTOCOL_KEY];\n }\n\n /**\n * Mark a connection as having protocol messages disabled.\n * Called internally when shouldSendProtocolMessages returns false.\n */\n private _setConnectionNoProtocol(connection: Connection) {\n this._ensureConnectionWrapped(connection);\n const accessors = this._rawStateAccessors.get(connection)!;\n const raw = (accessors.getRaw() as Record<string, unknown> | null) ?? {};\n accessors.setRaw({ ...raw, [CF_NO_PROTOCOL_KEY]: true });\n }\n\n /**\n * Called before the Agent's state is persisted and broadcast.\n * Override to validate or reject an update by throwing an error.\n *\n * IMPORTANT: This hook must be synchronous.\n */\n // oxlint-disable-next-line eslint(no-unused-vars) -- params used by subclass overrides\n validateStateChange(nextState: State, source: Connection | \"server\") {\n // override this to validate state updates\n }\n\n /**\n * Called after the Agent's state has been persisted and broadcast to all clients.\n * This is a notification hook — errors here are routed to onError and do not\n * affect state persistence or client broadcasts.\n *\n * @param state Updated state\n * @param source Source of the state update (\"server\" or a client connection)\n */\n // oxlint-disable-next-line eslint(no-unused-vars) -- params used by subclass overrides\n onStateChanged(state: State | undefined, source: Connection | \"server\") {\n // override this to handle state updates after persist + broadcast\n }\n\n /**\n * @deprecated Renamed to `onStateChanged` — the behavior is identical.\n * `onStateUpdate` will be removed in the next major version.\n *\n * Called after the Agent's state has been persisted and broadcast to all clients.\n * This is a server-side notification hook. For the client-side state callback,\n * see the `onStateUpdate` option in `useAgent` / `AgentClient`.\n *\n * @param state Updated state\n * @param source Source of the state update (\"server\" or a client connection)\n */\n // oxlint-disable-next-line eslint(no-unused-vars) -- params used by subclass overrides\n onStateUpdate(state: State | undefined, source: Connection | \"server\") {\n // override this to handle state updates (deprecated — use onStateChanged)\n }\n\n /**\n * Dispatch to the appropriate persistence hook based on the mode\n * cached in the constructor. No prototype walks at call time.\n */\n private async _callStatePersistenceHook(\n state: State | undefined,\n source: Connection | \"server\"\n ): Promise<void> {\n switch (this._persistenceHookMode) {\n case \"new\":\n await this.onStateChanged(state, source);\n break;\n case \"old\":\n await this.onStateUpdate(state, source);\n break;\n // \"none\": neither hook overridden — skip\n }\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 this._emit(\"email:receive\", {\n from: email.from,\n to: email.to,\n subject: email.headers.get(\"subject\") ?? undefined\n });\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 * @param options.secret Secret for signing agent headers (enables secure reply routing).\n * Required if the email was routed via createSecureReplyEmailResolver.\n * Pass explicit `null` to opt-out of signing (not recommended for secure routing).\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 secret?: string | null;\n }\n ): Promise<void> {\n return this._tryCatch(async () => {\n // Enforce signing for emails routed via createSecureReplyEmailResolver\n if (email._secureRouted && options.secret === undefined) {\n throw new Error(\n \"This email was routed via createSecureReplyEmailResolver. \" +\n \"You must pass a secret to replyToEmail() to sign replies, \" +\n \"or pass explicit null to opt-out (not recommended).\"\n );\n }\n\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 // Sign headers if secret is provided (enables secure reply routing)\n if (typeof options.secret === \"string\") {\n const signedHeaders = await signAgentHeaders(\n options.secret,\n agentName,\n agentId\n );\n msg.setHeader(\"X-Agent-Sig\", signedHeaders[\"X-Agent-Sig\"]);\n msg.setHeader(\"X-Agent-Sig-Ts\", signedHeaders[\"X-Agent-Sig-Ts\"]);\n }\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 // Emit after the send succeeds — from/to are swapped because\n // this is a reply: the agent (email.to) is now the sender.\n const rawSubject = email.headers.get(\"subject\");\n this._emit(\"email:reply\", {\n from: email.to,\n to: email.from,\n subject:\n options.subject ?? (rawSubject ? `Re: ${rawSubject}` : undefined)\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 /* oxlint-disable @typescript-eslint/no-explicit-any -- dynamic method wrapping requires any */\n const wrappedFunction = withAgentContext(\n this[methodName as keyof this] as (...args: any[]) => any\n ) as any;\n /* oxlint-enable @typescript-eslint/no-explicit-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 * Retry an async operation with exponential backoff and jitter.\n * Retries on all errors by default. Use `shouldRetry` to bail early on non-retryable errors.\n *\n * @param fn The async function to retry. Receives the current attempt number (1-indexed).\n * @param options Retry configuration.\n * @param options.maxAttempts Maximum number of attempts (including the first). Falls back to static options, then 3.\n * @param options.baseDelayMs Base delay in ms for exponential backoff. Falls back to static options, then 100.\n * @param options.maxDelayMs Maximum delay cap in ms. Falls back to static options, then 3000.\n * @param options.shouldRetry Predicate called with the error and next attempt number. Return false to stop retrying immediately. Default: retry all errors.\n * @returns The result of fn on success.\n * @throws The last error if all attempts fail or shouldRetry returns false.\n */\n async retry<T>(\n fn: (attempt: number) => Promise<T>,\n options?: RetryOptions & {\n /** Return false to stop retrying a specific error. Receives the error and the next attempt number. Default: retry all errors. */\n shouldRetry?: (err: unknown, nextAttempt: number) => boolean;\n }\n ): Promise<T> {\n const defaults = this._resolvedOptions.retry;\n if (options) {\n validateRetryOptions(options, defaults);\n }\n return tryN(options?.maxAttempts ?? defaults.maxAttempts, fn, {\n baseDelayMs: options?.baseDelayMs ?? defaults.baseDelayMs,\n maxDelayMs: options?.maxDelayMs ?? defaults.maxDelayMs,\n shouldRetry: options?.shouldRetry\n });\n }\n\n /**\n * Queue a task to be executed in the future\n * @param callback Name of the method to call\n * @param payload Payload to pass to the callback\n * @param options Options for the queued task\n * @param options.retry Retry options for the callback execution\n * @returns The ID of the queued task\n */\n async queue<T = unknown>(\n callback: keyof this,\n payload: T,\n options?: { retry?: RetryOptions }\n ): 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 if (options?.retry) {\n validateRetryOptions(options.retry, this._resolvedOptions.retry);\n }\n\n const retryJson = options?.retry ? JSON.stringify(options.retry) : null;\n\n this.sql`\n INSERT OR REPLACE INTO cf_agents_queues (id, payload, callback, retry_options)\n VALUES (${id}, ${JSON.stringify(payload)}, ${callback}, ${retryJson})\n `;\n\n this._emit(\"queue:create\", { callback: callback as string, id });\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 try {\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 await this.dequeue(row.id);\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 const retryOpts = parseRetryOptions(\n row as unknown as Record<string, unknown>\n );\n const { maxAttempts, baseDelayMs, maxDelayMs } =\n resolveRetryConfig(retryOpts, this._resolvedOptions.retry);\n const parsedPayload = JSON.parse(row.payload as string);\n try {\n await tryN(\n maxAttempts,\n async (attempt) => {\n if (attempt > 1) {\n this._emit(\"queue:retry\", {\n callback: row.callback,\n id: row.id,\n attempt,\n maxAttempts\n });\n }\n await (\n callback as (\n payload: unknown,\n queueItem: QueueItem<string>\n ) => Promise<void>\n ).bind(this)(parsedPayload, row);\n },\n { baseDelayMs, maxDelayMs }\n );\n } catch (e) {\n console.error(\n `queue callback \"${row.callback}\" failed after ${maxAttempts} attempts`,\n e\n );\n this._emit(\"queue:error\", {\n callback: row.callback,\n id: row.id,\n error: e instanceof Error ? e.message : String(e),\n attempts: maxAttempts\n });\n try {\n await this.onError(e);\n } catch {\n // swallow onError errors\n }\n } finally {\n this.dequeue(row.id);\n }\n }\n );\n }\n }\n } finally {\n this._flushingQueue = false;\n }\n }\n\n /**\n * Dequeue a task by ID\n * @param id ID of the task to dequeue\n */\n dequeue(id: string) {\n this.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;\n }\n\n /**\n * Dequeue all tasks\n */\n 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 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 getQueue(id: string): QueueItem<string> | undefined {\n const result = this.sql<QueueItem<string>>`\n SELECT * FROM cf_agents_queues WHERE id = ${id}\n `;\n if (!result || result.length === 0) return undefined;\n const row = result[0];\n return {\n ...row,\n payload: JSON.parse(row.payload as unknown as string),\n retry: parseRetryOptions(row as unknown as Record<string, unknown>)\n };\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 getQueues(key: string, value: string): QueueItem<string>[] {\n const result = this.sql<QueueItem<string>>`\n SELECT * FROM cf_agents_queues\n `;\n return result\n .filter(\n (row) => JSON.parse(row.payload as unknown as string)[key] === value\n )\n .map((row) => ({\n ...row,\n payload: JSON.parse(row.payload as unknown as string),\n retry: parseRetryOptions(row as unknown as Record<string, unknown>)\n }));\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 * @param options Options for the scheduled task\n * @param options.retry Retry options for the callback execution\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 options?: { retry?: RetryOptions }\n ): Promise<Schedule<T>> {\n const id = nanoid(9);\n\n if (options?.retry) {\n validateRetryOptions(options.retry, this._resolvedOptions.retry);\n }\n\n const retryJson = options?.retry ? JSON.stringify(options.retry) : null;\n\n const emitScheduleCreate = () =>\n this._emit(\"schedule:create\", { callback: callback as string, id });\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, retry_options)\n VALUES (${id}, ${callback}, ${JSON.stringify(\n payload\n )}, 'scheduled', ${timestamp}, ${retryJson})\n `;\n\n await this._scheduleNextAlarm();\n\n const schedule: Schedule<T> = {\n callback: callback,\n id,\n payload: payload as T,\n retry: options?.retry,\n time: timestamp,\n type: \"scheduled\"\n };\n\n emitScheduleCreate();\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, retry_options)\n VALUES (${id}, ${callback}, ${JSON.stringify(\n payload\n )}, 'delayed', ${when}, ${timestamp}, ${retryJson})\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 retry: options?.retry,\n time: timestamp,\n type: \"delayed\"\n };\n\n emitScheduleCreate();\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, retry_options)\n VALUES (${id}, ${callback}, ${JSON.stringify(\n payload\n )}, 'cron', ${when}, ${timestamp}, ${retryJson})\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 retry: options?.retry,\n time: timestamp,\n type: \"cron\"\n };\n\n emitScheduleCreate();\n\n return schedule;\n }\n throw new Error(\n `Invalid schedule type: ${JSON.stringify(when)}(${typeof when}) trying to schedule ${callback}`\n );\n }\n\n /**\n * Schedule a task to run repeatedly at a fixed interval.\n *\n * This method is **idempotent** — calling it multiple times with the same\n * `callback`, `intervalSeconds`, and `payload` returns the existing schedule\n * instead of creating a duplicate. A different interval or payload is\n * treated as a distinct schedule and creates a new row.\n *\n * This makes it safe to call in `onStart()`, which runs on every Durable\n * Object wake:\n *\n * ```ts\n * async onStart() {\n * // Only one schedule is created, no matter how many times the DO wakes\n * await this.scheduleEvery(30, \"tick\");\n * }\n * ```\n *\n * @template T Type of the payload data\n * @param intervalSeconds Number of seconds between executions\n * @param callback Name of the method to call\n * @param payload Data to pass to the callback\n * @param options Options for the scheduled task\n * @param options.retry Retry options for the callback execution\n * @returns Schedule object representing the scheduled task\n */\n async scheduleEvery<T = string>(\n intervalSeconds: number,\n callback: keyof this,\n payload?: T,\n options?: { retry?: RetryOptions; _idempotent?: boolean }\n ): Promise<Schedule<T>> {\n // DO alarms have a max schedule time of 30 days\n const MAX_INTERVAL_SECONDS = 30 * 24 * 60 * 60; // 30 days in seconds\n\n if (typeof intervalSeconds !== \"number\" || intervalSeconds <= 0) {\n throw new Error(\"intervalSeconds must be a positive number\");\n }\n\n if (intervalSeconds > MAX_INTERVAL_SECONDS) {\n throw new Error(\n `intervalSeconds cannot exceed ${MAX_INTERVAL_SECONDS} seconds (30 days)`\n );\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 (options?.retry) {\n validateRetryOptions(options.retry, this._resolvedOptions.retry);\n }\n\n const idempotent = options?._idempotent !== false;\n const payloadJson = JSON.stringify(payload);\n\n // Idempotency: check for an existing interval schedule with the same\n // callback, interval, and payload. A different interval or payload is\n // treated as a distinct schedule and gets its own row.\n if (idempotent) {\n const existing = this.sql<{\n id: string;\n callback: string;\n payload: string;\n type: string;\n time: number;\n intervalSeconds: number;\n retry_options: string | null;\n }>`\n SELECT * FROM cf_agents_schedules\n WHERE type = 'interval'\n AND callback = ${callback}\n AND intervalSeconds = ${intervalSeconds}\n AND payload IS ${payloadJson}\n LIMIT 1\n `;\n\n if (existing.length > 0) {\n const row = existing[0];\n\n // Exact match — return existing schedule as-is (no-op)\n return {\n callback: row.callback,\n id: row.id,\n intervalSeconds: row.intervalSeconds,\n payload: JSON.parse(row.payload) as T,\n retry: parseRetryOptions(row as unknown as Record<string, unknown>),\n time: row.time,\n type: \"interval\"\n };\n }\n }\n\n const id = nanoid(9);\n const time = new Date(Date.now() + intervalSeconds * 1000);\n const timestamp = Math.floor(time.getTime() / 1000);\n\n const retryJson = options?.retry ? JSON.stringify(options.retry) : null;\n\n this.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, intervalSeconds, time, running, retry_options)\n VALUES (${id}, ${callback}, ${payloadJson}, 'interval', ${intervalSeconds}, ${timestamp}, 0, ${retryJson})\n `;\n\n await this._scheduleNextAlarm();\n\n const schedule: Schedule<T> = {\n callback: callback,\n id,\n intervalSeconds,\n payload: payload as T,\n retry: options?.retry,\n time: timestamp,\n type: \"interval\"\n };\n\n this._emit(\"schedule:create\", { callback: callback as string, id });\n\n return schedule;\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 getSchedule<T = string>(id: string): Schedule<T> | undefined {\n const result = this.sql<Schedule<string>>`\n SELECT * FROM cf_agents_schedules WHERE id = ${id}\n `;\n if (!result || result.length === 0) {\n return undefined;\n }\n const row = result[0];\n return {\n ...row,\n payload: JSON.parse(row.payload) as T,\n retry: parseRetryOptions(row as unknown as Record<string, unknown>)\n };\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\" | \"interval\";\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 retry: parseRetryOptions(row as unknown as Record<string, unknown>)\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 if the task was not found\n */\n async cancelSchedule(id: string): Promise<boolean> {\n const schedule = this.getSchedule(id);\n if (!schedule) {\n return false;\n }\n\n this._emit(\"schedule:cancel\", {\n callback: schedule.callback,\n id: schedule.id\n });\n\n this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;\n\n await this._scheduleNextAlarm();\n return true;\n }\n\n /**\n * Keep the Durable Object alive via alarm heartbeats.\n * Returns a disposer function that stops the heartbeat when called.\n *\n * Use this when you have long-running work and need to prevent the\n * DO from going idle (eviction after ~70-140s of inactivity).\n * The heartbeat fires every 30 seconds via the scheduling system.\n *\n * @experimental This API may change between releases.\n *\n * @example\n * ```ts\n * const dispose = await this.keepAlive();\n * try {\n * // ... long-running work ...\n * } finally {\n * dispose();\n * }\n * ```\n */\n async keepAlive(): Promise<() => void> {\n const heartbeatSeconds = Math.ceil(KEEP_ALIVE_INTERVAL_MS / 1000);\n const schedule = await this.scheduleEvery(\n heartbeatSeconds,\n \"_cf_keepAliveHeartbeat\" as keyof this,\n undefined,\n { _idempotent: false }\n );\n\n let disposed = false;\n return () => {\n if (disposed) return;\n disposed = true;\n void this.cancelSchedule(schedule.id);\n };\n }\n\n /**\n * Run an async function while keeping the Durable Object alive.\n * The heartbeat is automatically stopped when the function completes\n * (whether it succeeds or throws).\n *\n * This is the recommended way to use keepAlive — it guarantees cleanup\n * so you cannot forget to dispose the heartbeat.\n *\n * @experimental This API may change between releases.\n *\n * @example\n * ```ts\n * const result = await this.keepAliveWhile(async () => {\n * const data = await longRunningComputation();\n * return data;\n * });\n * ```\n */\n async keepAliveWhile<T>(fn: () => Promise<T>): Promise<T> {\n const dispose = await this.keepAlive();\n try {\n return await fn();\n } finally {\n dispose();\n }\n }\n\n /**\n * Internal no-op callback invoked by the keepAlive heartbeat schedule.\n * Its only purpose is to keep the DO alive — the alarm machinery\n * handles the rest.\n * @internal\n */\n async _cf_keepAliveHeartbeat(): Promise<void> {\n // intentionally empty — the alarm firing is what keeps the DO alive\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 * Override PartyServer's onAlarm hook as a no-op.\n * Agent handles alarm logic directly in the alarm() method override,\n * but super.alarm() calls onAlarm() after #ensureInitialized(),\n * so we suppress the default \"Implement onAlarm\" warning.\n */\n onAlarm(): void {}\n\n /**\n * Method called when an alarm fires.\n * Executes any scheduled tasks that are due.\n *\n * Calls super.alarm() first to ensure PartyServer's #ensureInitialized()\n * runs, which hydrates this.name from storage and calls onStart() if needed.\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 async alarm() {\n // Ensure PartyServer initialization (name hydration, onStart) runs\n // before processing any scheduled tasks.\n await super.alarm();\n\n const now = Math.floor(Date.now() / 1000);\n\n // Get all schedules that should be executed now\n const result = this.sql<\n Schedule<string> & { running?: number; intervalSeconds?: number }\n >`\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\n // Overlap prevention for interval schedules with hung callback detection\n if (row.type === \"interval\" && row.running === 1) {\n const executionStartedAt =\n (row as { execution_started_at?: number }).execution_started_at ??\n 0;\n const hungTimeoutSeconds =\n this._resolvedOptions.hungScheduleTimeoutSeconds;\n const elapsedSeconds = now - executionStartedAt;\n\n if (elapsedSeconds < hungTimeoutSeconds) {\n console.warn(\n `Skipping interval schedule ${row.id}: previous execution still running`\n );\n continue;\n }\n // Previous execution appears hung, force reset and re-execute\n console.warn(\n `Forcing reset of hung interval schedule ${row.id} (started ${elapsedSeconds}s ago)`\n );\n }\n\n // Mark interval as running before execution\n if (row.type === \"interval\") {\n this\n .sql`UPDATE cf_agents_schedules SET running = 1, execution_started_at = ${now} WHERE id = ${row.id}`;\n }\n\n await agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n async () => {\n const retryOpts = parseRetryOptions(\n row as unknown as Record<string, unknown>\n );\n const { maxAttempts, baseDelayMs, maxDelayMs } = resolveRetryConfig(\n retryOpts,\n this._resolvedOptions.retry\n );\n const parsedPayload = JSON.parse(row.payload as string);\n\n try {\n this._emit(\"schedule:execute\", {\n callback: row.callback,\n id: row.id\n });\n\n await tryN(\n maxAttempts,\n async (attempt) => {\n if (attempt > 1) {\n this._emit(\"schedule:retry\", {\n callback: row.callback,\n id: row.id,\n attempt,\n maxAttempts\n });\n }\n await (\n callback as (\n payload: unknown,\n schedule: Schedule<unknown>\n ) => Promise<void>\n ).bind(this)(parsedPayload, row);\n },\n { baseDelayMs, maxDelayMs }\n );\n } catch (e) {\n console.error(\n `error executing callback \"${row.callback}\" after ${maxAttempts} attempts`,\n e\n );\n this._emit(\"schedule:error\", {\n callback: row.callback,\n id: row.id,\n error: e instanceof Error ? e.message : String(e),\n attempts: maxAttempts\n });\n // Route schedule errors through onError for consistency\n try {\n await this.onError(e);\n } catch {\n // swallow onError errors\n }\n }\n }\n );\n\n if (this._destroyed) return;\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 if (row.type === \"interval\") {\n // Reset running flag and schedule next interval execution\n const nextTimestamp =\n Math.floor(Date.now() / 1000) + (row.intervalSeconds ?? 0);\n\n this.sql`\n UPDATE cf_agents_schedules SET running = 0, 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 if (this._destroyed) return;\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_mcp_servers`;\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_queues`;\n this.sql`DROP TABLE IF EXISTS cf_agents_workflows`;\n\n // delete all alarms\n await this.ctx.storage.deleteAlarm();\n await this.ctx.storage.deleteAll();\n\n this._disposables.dispose();\n await this.mcp.dispose();\n\n this._destroyed = true;\n\n // `ctx.abort` throws an uncatchable error, so we yield to the event loop\n // to avoid capturing it and let handlers finish cleaning up\n setTimeout(() => {\n this.ctx.abort(\"destroyed\");\n }, 0);\n\n this._emit(\"destroy\");\n }\n\n /**\n * Check if a method is callable\n * @param method The method name to check\n * @returns True if the method is marked as callable\n */\n private _isCallable(method: string): boolean {\n return callableMetadata.has(this[method as keyof this] as Function);\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 getCallableMethods(): Map<string, CallableMetadata> {\n const result = new Map<string, CallableMetadata>();\n\n // Walk the entire prototype chain to find callable methods from parent classes\n let prototype = Object.getPrototypeOf(this);\n while (prototype && prototype !== Object.prototype) {\n for (const name of Object.getOwnPropertyNames(prototype)) {\n if (name === \"constructor\") continue;\n // Don't override child class methods (first one wins)\n if (result.has(name)) continue;\n\n try {\n const fn = prototype[name];\n if (typeof fn === \"function\") {\n const meta = callableMetadata.get(fn as Function);\n if (meta) {\n result.set(name, meta);\n }\n }\n } catch (e) {\n if (!(e instanceof TypeError)) {\n throw e;\n }\n }\n }\n prototype = Object.getPrototypeOf(prototype);\n }\n\n return result;\n }\n\n // ==========================================\n // Workflow Integration Methods\n // ==========================================\n\n /**\n * Start a workflow and track it in this Agent's database.\n * Automatically injects agent identity into the workflow params.\n *\n * @template P - Type of params to pass to the workflow\n * @param workflowName - Name of the workflow binding in env (e.g., 'MY_WORKFLOW')\n * @param params - Params to pass to the workflow\n * @param options - Optional workflow options\n * @returns The workflow instance ID\n *\n * @example\n * ```typescript\n * const workflowId = await this.runWorkflow(\n * 'MY_WORKFLOW',\n * { taskId: '123', data: 'process this' }\n * );\n * ```\n */\n async runWorkflow<P = unknown>(\n workflowName: WorkflowName<Env>,\n params: P,\n options?: RunWorkflowOptions\n ): Promise<string> {\n // Look up the workflow binding by name\n const workflow = this._findWorkflowBindingByName(workflowName);\n if (!workflow) {\n throw new Error(\n `Workflow binding '${workflowName}' not found in environment`\n );\n }\n\n // Find the binding name for this Agent's namespace\n const agentBindingName =\n options?.agentBinding ?? this._findAgentBindingName();\n if (!agentBindingName) {\n throw new Error(\n \"Could not detect Agent binding name from class name. \" +\n \"Pass it explicitly via options.agentBinding\"\n );\n }\n\n // Generate workflow ID if not provided\n const workflowId = options?.id ?? nanoid();\n\n // Inject agent identity and workflow name into params\n const augmentedParams = {\n ...params,\n __agentName: this.name,\n __agentBinding: agentBindingName,\n __workflowName: workflowName\n };\n\n // Create the workflow instance\n const instance = await workflow.create({\n id: workflowId,\n params: augmentedParams\n });\n\n // Track the workflow in our database\n const id = nanoid();\n const metadataJson = options?.metadata\n ? JSON.stringify(options.metadata)\n : null;\n try {\n this.sql`\n INSERT INTO cf_agents_workflows (id, workflow_id, workflow_name, status, metadata)\n VALUES (${id}, ${instance.id}, ${workflowName}, 'queued', ${metadataJson})\n `;\n } catch (e) {\n if (\n e instanceof Error &&\n e.message.includes(\"UNIQUE constraint failed\")\n ) {\n throw new Error(\n `Workflow with ID \"${workflowId}\" is already being tracked`\n );\n }\n throw e;\n }\n\n this._emit(\"workflow:start\", { workflowId: instance.id, workflowName });\n\n return instance.id;\n }\n\n /**\n * Send an event to a running workflow.\n * The workflow can wait for this event using step.waitForEvent().\n *\n * @param workflowName - Name of the workflow binding in env (e.g., 'MY_WORKFLOW')\n * @param workflowId - ID of the workflow instance\n * @param event - Event to send\n *\n * @example\n * ```typescript\n * await this.sendWorkflowEvent(\n * 'MY_WORKFLOW',\n * workflowId,\n * { type: 'approval', payload: { approved: true } }\n * );\n * ```\n */\n async sendWorkflowEvent(\n workflowName: WorkflowName<Env>,\n workflowId: string,\n event: WorkflowEventPayload\n ): Promise<void> {\n const workflow = this._findWorkflowBindingByName(workflowName);\n if (!workflow) {\n throw new Error(\n `Workflow binding '${workflowName}' not found in environment`\n );\n }\n\n const instance = await workflow.get(workflowId);\n await tryN(3, async () => instance.sendEvent(event), {\n shouldRetry: isErrorRetryable,\n baseDelayMs: 200,\n maxDelayMs: 3000\n });\n\n this._emit(\"workflow:event\", { workflowId, eventType: event.type });\n }\n\n /**\n * Approve a waiting workflow.\n * Sends an approval event to the workflow that can be received by waitForApproval().\n *\n * @param workflowId - ID of the workflow to approve\n * @param data - Optional approval data (reason, metadata)\n *\n * @example\n * ```typescript\n * await this.approveWorkflow(workflowId, {\n * reason: 'Approved by admin',\n * metadata: { approvedBy: userId }\n * });\n * ```\n */\n async approveWorkflow(\n workflowId: string,\n data?: { reason?: string; metadata?: Record<string, unknown> }\n ): Promise<void> {\n const workflowInfo = this.getWorkflow(workflowId);\n if (!workflowInfo) {\n throw new Error(`Workflow ${workflowId} not found in tracking table`);\n }\n\n await this.sendWorkflowEvent(\n workflowInfo.workflowName as WorkflowName<Env>,\n workflowId,\n {\n type: \"approval\",\n payload: {\n approved: true,\n reason: data?.reason,\n metadata: data?.metadata\n }\n }\n );\n\n this._emit(\"workflow:approved\", { workflowId, reason: data?.reason });\n }\n\n /**\n * Reject a waiting workflow.\n * Sends a rejection event to the workflow that will cause waitForApproval() to throw.\n *\n * @param workflowId - ID of the workflow to reject\n * @param data - Optional rejection data (reason)\n *\n * @example\n * ```typescript\n * await this.rejectWorkflow(workflowId, {\n * reason: 'Request denied by admin'\n * });\n * ```\n */\n async rejectWorkflow(\n workflowId: string,\n data?: { reason?: string }\n ): Promise<void> {\n const workflowInfo = this.getWorkflow(workflowId);\n if (!workflowInfo) {\n throw new Error(`Workflow ${workflowId} not found in tracking table`);\n }\n\n await this.sendWorkflowEvent(\n workflowInfo.workflowName as WorkflowName<Env>,\n workflowId,\n {\n type: \"approval\",\n payload: {\n approved: false,\n reason: data?.reason\n }\n }\n );\n\n this._emit(\"workflow:rejected\", { workflowId, reason: data?.reason });\n }\n\n /**\n * Terminate a running workflow.\n * This immediately stops the workflow and sets its status to \"terminated\".\n *\n * @param workflowId - ID of the workflow to terminate (must be tracked via runWorkflow)\n * @throws Error if workflow not found in tracking table\n * @throws Error if workflow binding not found in environment\n * @throws Error if workflow is already completed/errored/terminated (from Cloudflare)\n *\n * @note `terminate()` is not yet supported in local development (wrangler dev).\n * It will throw an error locally but works when deployed to Cloudflare.\n *\n * @example\n * ```typescript\n * await this.terminateWorkflow(workflowId);\n * ```\n */\n async terminateWorkflow(workflowId: string): Promise<void> {\n const workflowInfo = this.getWorkflow(workflowId);\n if (!workflowInfo) {\n throw new Error(`Workflow ${workflowId} not found in tracking table`);\n }\n\n const workflow = this._findWorkflowBindingByName(\n workflowInfo.workflowName as WorkflowName<Env>\n );\n if (!workflow) {\n throw new Error(\n `Workflow binding '${workflowInfo.workflowName}' not found in environment`\n );\n }\n\n const instance = await workflow.get(workflowId);\n try {\n await tryN(3, async () => instance.terminate(), {\n shouldRetry: isErrorRetryable,\n baseDelayMs: 200,\n maxDelayMs: 3000\n });\n } catch (err) {\n if (err instanceof Error && err.message.includes(\"Not implemented\")) {\n throw new Error(\n \"terminateWorkflow() is not supported in local development. \" +\n \"Deploy to Cloudflare to use this feature. \" +\n \"Follow https://github.com/cloudflare/agents/issues/823 for details and updates.\"\n );\n }\n throw err;\n }\n\n // Update tracking table with new status\n const status = await instance.status();\n this._updateWorkflowTracking(workflowId, status);\n\n this._emit(\"workflow:terminated\", {\n workflowId,\n workflowName: workflowInfo.workflowName\n });\n }\n\n /**\n * Pause a running workflow.\n * The workflow can be resumed later with resumeWorkflow().\n *\n * @param workflowId - ID of the workflow to pause (must be tracked via runWorkflow)\n * @throws Error if workflow not found in tracking table\n * @throws Error if workflow binding not found in environment\n * @throws Error if workflow is not running (from Cloudflare)\n *\n * @note `pause()` is not yet supported in local development (wrangler dev).\n * It will throw an error locally but works when deployed to Cloudflare.\n *\n * @example\n * ```typescript\n * await this.pauseWorkflow(workflowId);\n * ```\n */\n async pauseWorkflow(workflowId: string): Promise<void> {\n const workflowInfo = this.getWorkflow(workflowId);\n if (!workflowInfo) {\n throw new Error(`Workflow ${workflowId} not found in tracking table`);\n }\n\n const workflow = this._findWorkflowBindingByName(\n workflowInfo.workflowName as WorkflowName<Env>\n );\n if (!workflow) {\n throw new Error(\n `Workflow binding '${workflowInfo.workflowName}' not found in environment`\n );\n }\n\n const instance = await workflow.get(workflowId);\n try {\n await tryN(3, async () => instance.pause(), {\n shouldRetry: isErrorRetryable,\n baseDelayMs: 200,\n maxDelayMs: 3000\n });\n } catch (err) {\n if (err instanceof Error && err.message.includes(\"Not implemented\")) {\n throw new Error(\n \"pauseWorkflow() is not supported in local development. \" +\n \"Deploy to Cloudflare to use this feature. \" +\n \"Follow https://github.com/cloudflare/agents/issues/823 for details and updates.\"\n );\n }\n throw err;\n }\n\n const status = await instance.status();\n this._updateWorkflowTracking(workflowId, status);\n\n this._emit(\"workflow:paused\", {\n workflowId,\n workflowName: workflowInfo.workflowName\n });\n }\n\n /**\n * Resume a paused workflow.\n *\n * @param workflowId - ID of the workflow to resume (must be tracked via runWorkflow)\n * @throws Error if workflow not found in tracking table\n * @throws Error if workflow binding not found in environment\n * @throws Error if workflow is not paused (from Cloudflare)\n *\n * @note `resume()` is not yet supported in local development (wrangler dev).\n * It will throw an error locally but works when deployed to Cloudflare.\n *\n * @example\n * ```typescript\n * await this.resumeWorkflow(workflowId);\n * ```\n */\n async resumeWorkflow(workflowId: string): Promise<void> {\n const workflowInfo = this.getWorkflow(workflowId);\n if (!workflowInfo) {\n throw new Error(`Workflow ${workflowId} not found in tracking table`);\n }\n\n const workflow = this._findWorkflowBindingByName(\n workflowInfo.workflowName as WorkflowName<Env>\n );\n if (!workflow) {\n throw new Error(\n `Workflow binding '${workflowInfo.workflowName}' not found in environment`\n );\n }\n\n const instance = await workflow.get(workflowId);\n try {\n await tryN(3, async () => instance.resume(), {\n shouldRetry: isErrorRetryable,\n baseDelayMs: 200,\n maxDelayMs: 3000\n });\n } catch (err) {\n if (err instanceof Error && err.message.includes(\"Not implemented\")) {\n throw new Error(\n \"resumeWorkflow() is not supported in local development. \" +\n \"Deploy to Cloudflare to use this feature. \" +\n \"Follow https://github.com/cloudflare/agents/issues/823 for details and updates.\"\n );\n }\n throw err;\n }\n\n const status = await instance.status();\n this._updateWorkflowTracking(workflowId, status);\n\n this._emit(\"workflow:resumed\", {\n workflowId,\n workflowName: workflowInfo.workflowName\n });\n }\n\n /**\n * Restart a workflow instance.\n * This re-runs the workflow from the beginning with the same ID.\n *\n * @param workflowId - ID of the workflow to restart (must be tracked via runWorkflow)\n * @param options - Optional settings\n * @param options.resetTracking - If true (default), resets created_at and clears error fields.\n * If false, preserves original timestamps.\n * @throws Error if workflow not found in tracking table\n * @throws Error if workflow binding not found in environment\n *\n * @note `restart()` is not yet supported in local development (wrangler dev).\n * It will throw an error locally but works when deployed to Cloudflare.\n *\n * @example\n * ```typescript\n * // Reset tracking (default)\n * await this.restartWorkflow(workflowId);\n *\n * // Preserve original timestamps\n * await this.restartWorkflow(workflowId, { resetTracking: false });\n * ```\n */\n async restartWorkflow(\n workflowId: string,\n options: { resetTracking?: boolean } = {}\n ): Promise<void> {\n const { resetTracking = true } = options;\n\n const workflowInfo = this.getWorkflow(workflowId);\n if (!workflowInfo) {\n throw new Error(`Workflow ${workflowId} not found in tracking table`);\n }\n\n const workflow = this._findWorkflowBindingByName(\n workflowInfo.workflowName as WorkflowName<Env>\n );\n if (!workflow) {\n throw new Error(\n `Workflow binding '${workflowInfo.workflowName}' not found in environment`\n );\n }\n\n const instance = await workflow.get(workflowId);\n try {\n await tryN(3, async () => instance.restart(), {\n shouldRetry: isErrorRetryable,\n baseDelayMs: 200,\n maxDelayMs: 3000\n });\n } catch (err) {\n if (err instanceof Error && err.message.includes(\"Not implemented\")) {\n throw new Error(\n \"restartWorkflow() is not supported in local development. \" +\n \"Deploy to Cloudflare to use this feature. \" +\n \"Follow https://github.com/cloudflare/agents/issues/823 for details and updates.\"\n );\n }\n throw err;\n }\n\n if (resetTracking) {\n // Reset tracking fields for fresh start\n const now = Math.floor(Date.now() / 1000);\n this.sql`\n UPDATE cf_agents_workflows\n SET status = 'queued',\n created_at = ${now},\n updated_at = ${now},\n completed_at = NULL,\n error_name = NULL,\n error_message = NULL\n WHERE workflow_id = ${workflowId}\n `;\n } else {\n // Just update status from Cloudflare\n const status = await instance.status();\n this._updateWorkflowTracking(workflowId, status);\n }\n\n this._emit(\"workflow:restarted\", {\n workflowId,\n workflowName: workflowInfo.workflowName\n });\n }\n\n /**\n * Find a workflow binding by its name.\n */\n private _findWorkflowBindingByName(\n workflowName: string\n ): Workflow | undefined {\n const binding = (this.env as Record<string, unknown>)[workflowName];\n if (\n binding &&\n typeof binding === \"object\" &&\n \"create\" in binding &&\n \"get\" in binding\n ) {\n return binding as Workflow;\n }\n return undefined;\n }\n\n /**\n * Get all workflow binding names from the environment.\n */\n private _getWorkflowBindingNames(): string[] {\n const names: string[] = [];\n for (const [key, value] of Object.entries(\n this.env as Record<string, unknown>\n )) {\n if (\n value &&\n typeof value === \"object\" &&\n \"create\" in value &&\n \"get\" in value\n ) {\n names.push(key);\n }\n }\n return names;\n }\n\n /**\n * Get the status of a workflow and update the tracking record.\n *\n * @param workflowName - Name of the workflow binding in env (e.g., 'MY_WORKFLOW')\n * @param workflowId - ID of the workflow instance\n * @returns The workflow status\n */\n async getWorkflowStatus(\n workflowName: WorkflowName<Env>,\n workflowId: string\n ): Promise<InstanceStatus> {\n const workflow = this._findWorkflowBindingByName(workflowName);\n if (!workflow) {\n throw new Error(\n `Workflow binding '${workflowName}' not found in environment`\n );\n }\n\n const instance = await workflow.get(workflowId);\n const status = await instance.status();\n\n // Update the tracking record\n this._updateWorkflowTracking(workflowId, status);\n\n return status;\n }\n\n /**\n * Get a tracked workflow by ID.\n *\n * @param workflowId - Workflow instance ID\n * @returns Workflow info or undefined if not found\n */\n getWorkflow(workflowId: string): WorkflowInfo | undefined {\n const rows = this.sql<WorkflowTrackingRow>`\n SELECT * FROM cf_agents_workflows WHERE workflow_id = ${workflowId}\n `;\n\n if (!rows || rows.length === 0) {\n return undefined;\n }\n\n return this._rowToWorkflowInfo(rows[0]);\n }\n\n /**\n * Query tracked workflows with cursor-based pagination.\n *\n * @param criteria - Query criteria including optional cursor for pagination\n * @returns WorkflowPage with workflows, total count, and next cursor\n *\n * @example\n * ```typescript\n * // First page\n * const page1 = this.getWorkflows({ status: 'running', limit: 20 });\n *\n * // Next page\n * if (page1.nextCursor) {\n * const page2 = this.getWorkflows({\n * status: 'running',\n * limit: 20,\n * cursor: page1.nextCursor\n * });\n * }\n * ```\n */\n getWorkflows(criteria: WorkflowQueryCriteria = {}): WorkflowPage {\n const limit = Math.min(criteria.limit ?? 50, 100);\n const isAsc = criteria.orderBy === \"asc\";\n\n // Get total count (ignores cursor and limit)\n const total = this._countWorkflows(criteria);\n\n // Build base query\n let query = \"SELECT * FROM cf_agents_workflows WHERE 1=1\";\n const params: (string | number | boolean)[] = [];\n\n if (criteria.status) {\n const statuses = Array.isArray(criteria.status)\n ? criteria.status\n : [criteria.status];\n const placeholders = statuses.map(() => \"?\").join(\", \");\n query += ` AND status IN (${placeholders})`;\n params.push(...statuses);\n }\n\n if (criteria.workflowName) {\n query += \" AND workflow_name = ?\";\n params.push(criteria.workflowName);\n }\n\n if (criteria.metadata) {\n for (const [key, value] of Object.entries(criteria.metadata)) {\n query += ` AND json_extract(metadata, '$.' || ?) = ?`;\n params.push(key, value);\n }\n }\n\n // Apply cursor for keyset pagination\n if (criteria.cursor) {\n const cursor = this._decodeCursor(criteria.cursor);\n if (isAsc) {\n // ASC: get items after cursor\n query +=\n \" AND (created_at > ? OR (created_at = ? AND workflow_id > ?))\";\n } else {\n // DESC: get items before cursor\n query +=\n \" AND (created_at < ? OR (created_at = ? AND workflow_id < ?))\";\n }\n params.push(cursor.createdAt, cursor.createdAt, cursor.workflowId);\n }\n\n // Order by created_at and workflow_id for consistent keyset pagination\n query += ` ORDER BY created_at ${isAsc ? \"ASC\" : \"DESC\"}, workflow_id ${isAsc ? \"ASC\" : \"DESC\"}`;\n\n // Fetch limit + 1 to detect if there are more pages\n query += \" LIMIT ?\";\n params.push(limit + 1);\n\n const rows = this.ctx.storage.sql\n .exec(query, ...params)\n .toArray() as WorkflowTrackingRow[];\n\n const hasMore = rows.length > limit;\n const resultRows = hasMore ? rows.slice(0, limit) : rows;\n const workflows = resultRows.map((row) => this._rowToWorkflowInfo(row));\n\n // Build next cursor from last item\n const nextCursor =\n hasMore && workflows.length > 0\n ? this._encodeCursor(workflows[workflows.length - 1])\n : null;\n\n return { workflows, total, nextCursor };\n }\n\n /**\n * Count workflows matching criteria (for pagination total).\n */\n private _countWorkflows(\n criteria: Omit<WorkflowQueryCriteria, \"limit\" | \"cursor\" | \"orderBy\"> & {\n createdBefore?: Date;\n }\n ): number {\n let query = \"SELECT COUNT(*) as count FROM cf_agents_workflows WHERE 1=1\";\n const params: (string | number | boolean)[] = [];\n\n if (criteria.status) {\n const statuses = Array.isArray(criteria.status)\n ? criteria.status\n : [criteria.status];\n const placeholders = statuses.map(() => \"?\").join(\", \");\n query += ` AND status IN (${placeholders})`;\n params.push(...statuses);\n }\n\n if (criteria.workflowName) {\n query += \" AND workflow_name = ?\";\n params.push(criteria.workflowName);\n }\n\n if (criteria.metadata) {\n for (const [key, value] of Object.entries(criteria.metadata)) {\n query += ` AND json_extract(metadata, '$.' || ?) = ?`;\n params.push(key, value);\n }\n }\n\n if (criteria.createdBefore) {\n query += \" AND created_at < ?\";\n params.push(Math.floor(criteria.createdBefore.getTime() / 1000));\n }\n\n const result = this.ctx.storage.sql.exec(query, ...params).toArray() as {\n count: number;\n }[];\n\n return result[0]?.count ?? 0;\n }\n\n /**\n * Encode a cursor from workflow info for pagination.\n * Stores createdAt as Unix timestamp in seconds (matching DB storage).\n */\n private _encodeCursor(workflow: WorkflowInfo): string {\n return btoa(\n JSON.stringify({\n c: Math.floor(workflow.createdAt.getTime() / 1000),\n i: workflow.workflowId\n })\n );\n }\n\n /**\n * Decode a pagination cursor.\n * Returns createdAt as Unix timestamp in seconds (matching DB storage).\n */\n private _decodeCursor(cursor: string): {\n createdAt: number;\n workflowId: string;\n } {\n try {\n const data = JSON.parse(atob(cursor));\n if (typeof data.c !== \"number\" || typeof data.i !== \"string\") {\n throw new Error(\"Invalid cursor structure\");\n }\n return { createdAt: data.c, workflowId: data.i };\n } catch {\n throw new Error(\n \"Invalid pagination cursor. The cursor may be malformed or corrupted.\"\n );\n }\n }\n\n /**\n * Delete a workflow tracking record.\n *\n * @param workflowId - ID of the workflow to delete\n * @returns true if a record was deleted, false if not found\n */\n deleteWorkflow(workflowId: string): boolean {\n // First check if workflow exists\n const existing = this.sql<{ count: number }>`\n SELECT COUNT(*) as count FROM cf_agents_workflows WHERE workflow_id = ${workflowId}\n `;\n if (!existing[0] || existing[0].count === 0) {\n return false;\n }\n this.sql`DELETE FROM cf_agents_workflows WHERE workflow_id = ${workflowId}`;\n return true;\n }\n\n /**\n * Delete workflow tracking records matching criteria.\n * Useful for cleaning up old completed/errored workflows.\n *\n * @param criteria - Criteria for which workflows to delete\n * @returns Number of records matching criteria (expected deleted count)\n *\n * @example\n * ```typescript\n * // Delete all completed workflows created more than 7 days ago\n * const deleted = this.deleteWorkflows({\n * status: 'complete',\n * createdBefore: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)\n * });\n *\n * // Delete all errored and terminated workflows\n * const deleted = this.deleteWorkflows({\n * status: ['errored', 'terminated']\n * });\n * ```\n */\n deleteWorkflows(\n criteria: Omit<WorkflowQueryCriteria, \"limit\" | \"orderBy\"> & {\n createdBefore?: Date;\n } = {}\n ): number {\n let query = \"DELETE FROM cf_agents_workflows WHERE 1=1\";\n const params: (string | number | boolean)[] = [];\n\n if (criteria.status) {\n const statuses = Array.isArray(criteria.status)\n ? criteria.status\n : [criteria.status];\n const placeholders = statuses.map(() => \"?\").join(\", \");\n query += ` AND status IN (${placeholders})`;\n params.push(...statuses);\n }\n\n if (criteria.workflowName) {\n query += \" AND workflow_name = ?\";\n params.push(criteria.workflowName);\n }\n\n if (criteria.metadata) {\n for (const [key, value] of Object.entries(criteria.metadata)) {\n query += ` AND json_extract(metadata, '$.' || ?) = ?`;\n params.push(key, value);\n }\n }\n\n if (criteria.createdBefore) {\n query += \" AND created_at < ?\";\n params.push(Math.floor(criteria.createdBefore.getTime() / 1000));\n }\n\n const cursor = this.ctx.storage.sql.exec(query, ...params);\n return cursor.rowsWritten;\n }\n\n /**\n * Migrate workflow tracking records from an old binding name to a new one.\n * Use this after renaming a workflow binding in wrangler.toml.\n *\n * @param oldName - Previous workflow binding name\n * @param newName - New workflow binding name\n * @returns Number of records migrated\n *\n * @example\n * ```typescript\n * // After renaming OLD_WORKFLOW to NEW_WORKFLOW in wrangler.toml\n * async onStart() {\n * const migrated = this.migrateWorkflowBinding('OLD_WORKFLOW', 'NEW_WORKFLOW');\n * }\n * ```\n */\n migrateWorkflowBinding(oldName: string, newName: string): number {\n // Validate new binding exists\n if (!this._findWorkflowBindingByName(newName)) {\n throw new Error(`Workflow binding '${newName}' not found in environment`);\n }\n\n const result = this.sql<{ count: number }>`\n SELECT COUNT(*) as count FROM cf_agents_workflows WHERE workflow_name = ${oldName}\n `;\n const count = result[0]?.count ?? 0;\n\n if (count > 0) {\n this\n .sql`UPDATE cf_agents_workflows SET workflow_name = ${newName} WHERE workflow_name = ${oldName}`;\n console.log(\n `[Agent] Migrated ${count} workflow(s) from '${oldName}' to '${newName}'`\n );\n }\n\n return count;\n }\n\n /**\n * Update workflow tracking record from InstanceStatus\n */\n private _updateWorkflowTracking(\n workflowId: string,\n status: InstanceStatus\n ): void {\n const statusName = status.status;\n const now = Math.floor(Date.now() / 1000);\n\n // Determine if workflow is complete\n const completedStatuses: WorkflowStatus[] = [\n \"complete\",\n \"errored\",\n \"terminated\"\n ];\n const completedAt = completedStatuses.includes(statusName) ? now : null;\n\n // Extract error info if present\n const errorName = status.error?.name ?? null;\n const errorMessage = status.error?.message ?? null;\n\n this.sql`\n UPDATE cf_agents_workflows\n SET status = ${statusName},\n error_name = ${errorName},\n error_message = ${errorMessage},\n updated_at = ${now},\n completed_at = ${completedAt}\n WHERE workflow_id = ${workflowId}\n `;\n }\n\n /**\n * Convert a database row to WorkflowInfo\n */\n private _rowToWorkflowInfo(row: WorkflowTrackingRow): WorkflowInfo {\n return {\n id: row.id,\n workflowId: row.workflow_id,\n workflowName: row.workflow_name,\n status: row.status,\n metadata: row.metadata ? JSON.parse(row.metadata) : null,\n error: row.error_name\n ? { name: row.error_name, message: row.error_message ?? \"\" }\n : null,\n createdAt: new Date(row.created_at * 1000),\n updatedAt: new Date(row.updated_at * 1000),\n completedAt: row.completed_at ? new Date(row.completed_at * 1000) : null\n };\n }\n\n /**\n * Find the binding name for this Agent's namespace by matching class name.\n * Returns undefined if no match found - use options.agentBinding as fallback.\n */\n private _findAgentBindingName(): string | undefined {\n const className = this._ParentClass.name;\n for (const [key, value] of Object.entries(\n this.env as Record<string, unknown>\n )) {\n if (\n value &&\n typeof value === \"object\" &&\n \"idFromName\" in value &&\n typeof value.idFromName === \"function\"\n ) {\n // Check if this namespace's binding name matches our class name\n if (\n key === className ||\n camelCaseToKebabCase(key) === camelCaseToKebabCase(className)\n ) {\n return key;\n }\n }\n }\n return undefined;\n }\n\n private _findBindingNameForNamespace(\n namespace: DurableObjectNamespace<McpAgent>\n ): string | undefined {\n for (const [key, value] of Object.entries(\n this.env as Record<string, unknown>\n )) {\n if (value === namespace) {\n return key;\n }\n }\n return undefined;\n }\n\n private async _restoreRpcMcpServers(): Promise<void> {\n const rpcServers = this.mcp.getRpcServersFromStorage();\n for (const server of rpcServers) {\n if (this.mcp.mcpConnections[server.id]) {\n continue;\n }\n\n const opts: { bindingName: string; props?: Record<string, unknown> } =\n server.server_options ? JSON.parse(server.server_options) : {};\n\n const namespace = (this.env as Record<string, unknown>)[\n opts.bindingName\n ] as DurableObjectNamespace<McpAgent> | undefined;\n if (!namespace) {\n console.warn(\n `[Agent] Cannot restore RPC MCP server \"${server.name}\": binding \"${opts.bindingName}\" not found in env`\n );\n continue;\n }\n\n const normalizedName = server.server_url.replace(RPC_DO_PREFIX, \"\");\n\n try {\n await this.mcp.connect(`${RPC_DO_PREFIX}${normalizedName}`, {\n reconnect: { id: server.id },\n transport: {\n type: \"rpc\" as TransportType,\n namespace,\n name: normalizedName,\n props: opts.props\n }\n });\n\n const conn = this.mcp.mcpConnections[server.id];\n if (conn && conn.connectionState === MCPConnectionState.CONNECTED) {\n await this.mcp.discoverIfConnected(server.id);\n }\n } catch (error) {\n console.error(\n `[Agent] Error restoring RPC MCP server \"${server.name}\":`,\n error\n );\n }\n }\n }\n\n // ==========================================\n // Workflow Lifecycle Callbacks\n // ==========================================\n\n /**\n * Handle a callback from a workflow.\n * Called when the Agent receives a callback at /_workflow/callback.\n * Override this to handle all callback types in one place.\n *\n * @param callback - The callback payload\n */\n async onWorkflowCallback(callback: WorkflowCallback): Promise<void> {\n const now = Math.floor(Date.now() / 1000);\n\n switch (callback.type) {\n case \"progress\":\n // Update tracking status to \"running\" when receiving progress\n // Only transition from queued/waiting to avoid overwriting terminal states\n this.sql`\n UPDATE cf_agents_workflows\n SET status = 'running', updated_at = ${now}\n WHERE workflow_id = ${callback.workflowId} AND status IN ('queued', 'waiting')\n `;\n await this.onWorkflowProgress(\n callback.workflowName,\n callback.workflowId,\n callback.progress\n );\n break;\n case \"complete\":\n // Update tracking status to \"complete\"\n // Don't overwrite if already terminated/paused (race condition protection)\n this.sql`\n UPDATE cf_agents_workflows\n SET status = 'complete', updated_at = ${now}, completed_at = ${now}\n WHERE workflow_id = ${callback.workflowId}\n AND status NOT IN ('terminated', 'paused')\n `;\n await this.onWorkflowComplete(\n callback.workflowName,\n callback.workflowId,\n callback.result\n );\n break;\n case \"error\":\n // Update tracking status to \"errored\"\n // Don't overwrite if already terminated/paused (race condition protection)\n this.sql`\n UPDATE cf_agents_workflows\n SET status = 'errored', updated_at = ${now}, completed_at = ${now},\n error_name = 'WorkflowError', error_message = ${callback.error}\n WHERE workflow_id = ${callback.workflowId}\n AND status NOT IN ('terminated', 'paused')\n `;\n await this.onWorkflowError(\n callback.workflowName,\n callback.workflowId,\n callback.error\n );\n break;\n case \"event\":\n // No status change for events - they can occur at any stage\n await this.onWorkflowEvent(\n callback.workflowName,\n callback.workflowId,\n callback.event\n );\n break;\n }\n }\n\n /**\n * Called when a workflow reports progress.\n * Override to handle progress updates.\n *\n * @param workflowName - Workflow binding name\n * @param workflowId - ID of the workflow\n * @param progress - Typed progress data (default: DefaultProgress)\n */\n async onWorkflowProgress(\n _workflowName: string,\n _workflowId: string,\n _progress: unknown\n ): Promise<void> {\n // Override to handle progress updates\n }\n\n /**\n * Called when a workflow completes successfully.\n * Override to handle completion.\n *\n * @param workflowName - Workflow binding name\n * @param workflowId - ID of the workflow\n * @param result - Optional result data\n */\n async onWorkflowComplete(\n _workflowName: string,\n _workflowId: string,\n _result?: unknown\n ): Promise<void> {\n // Override to handle completion\n }\n\n /**\n * Called when a workflow encounters an error.\n * Override to handle errors.\n *\n * @param workflowName - Workflow binding name\n * @param workflowId - ID of the workflow\n * @param error - Error message\n */\n async onWorkflowError(\n _workflowName: string,\n _workflowId: string,\n _error: string\n ): Promise<void> {\n // Override to handle errors\n }\n\n /**\n * Called when a workflow sends a custom event.\n * Override to handle custom events.\n *\n * @param workflowName - Workflow binding name\n * @param workflowId - ID of the workflow\n * @param event - Custom event payload\n */\n async onWorkflowEvent(\n _workflowName: string,\n _workflowId: string,\n _event: unknown\n ): Promise<void> {\n // Override to handle custom events\n }\n\n // ============================================================\n // Internal RPC methods for AgentWorkflow communication\n // These are called via DO RPC, not exposed via HTTP\n // ============================================================\n\n /**\n * Handle a workflow callback via RPC.\n * @internal - Called by AgentWorkflow, do not call directly\n */\n async _workflow_handleCallback(callback: WorkflowCallback): Promise<void> {\n await this.__unsafe_ensureInitialized();\n await this.onWorkflowCallback(callback);\n }\n\n /**\n * Broadcast a message to all connected clients via RPC.\n * @internal - Called by AgentWorkflow, do not call directly\n */\n async _workflow_broadcast(message: unknown): Promise<void> {\n await this.__unsafe_ensureInitialized();\n this.broadcast(JSON.stringify(message));\n }\n\n /**\n * Update agent state via RPC.\n * @internal - Called by AgentWorkflow, do not call directly\n */\n async _workflow_updateState(\n action: \"set\" | \"merge\" | \"reset\",\n state?: unknown\n ): Promise<void> {\n await this.__unsafe_ensureInitialized();\n if (action === \"set\") {\n this.setState(state as State);\n } else if (action === \"merge\") {\n const currentState = this.state ?? ({} as State);\n this.setState({\n ...currentState,\n ...(state as Record<string, unknown>)\n } as State);\n } else if (action === \"reset\") {\n this.setState(this.initialState);\n }\n }\n\n /**\n * Connect to a new MCP Server via RPC (Durable Object binding)\n *\n * The binding name and props are persisted to storage so the connection\n * is automatically restored after Durable Object hibernation.\n *\n * @example\n * await this.addMcpServer(\"counter\", env.MY_MCP);\n * await this.addMcpServer(\"counter\", env.MY_MCP, { props: { userId: \"123\" } });\n */\n async addMcpServer<T extends McpAgent>(\n serverName: string,\n binding: DurableObjectNamespace<T>,\n options?: AddRpcMcpServerOptions\n ): Promise<{ id: string; state: typeof MCPConnectionState.READY }>;\n\n /**\n * Connect to a new MCP Server via HTTP (SSE or Streamable HTTP)\n *\n * @example\n * await this.addMcpServer(\"github\", \"https://mcp.github.com\");\n * await this.addMcpServer(\"github\", \"https://mcp.github.com\", { transport: { type: \"sse\" } });\n * await this.addMcpServer(\"github\", url, callbackHost, agentsPrefix, options); // legacy\n */\n async addMcpServer(\n serverName: string,\n url: string,\n callbackHostOrOptions?: string | AddMcpServerOptions,\n agentsPrefix?: string,\n options?: {\n client?: ConstructorParameters<typeof Client>[1];\n transport?: { headers?: HeadersInit; type?: TransportType };\n }\n ): Promise<\n | {\n id: string;\n state: typeof MCPConnectionState.AUTHENTICATING;\n authUrl: string;\n }\n | { id: string; state: typeof MCPConnectionState.READY }\n >;\n\n async addMcpServer<T extends McpAgent>(\n serverName: string,\n urlOrBinding: string | DurableObjectNamespace<T>,\n callbackHostOrOptions?:\n | string\n | AddMcpServerOptions\n | AddRpcMcpServerOptions,\n agentsPrefix?: string,\n options?: {\n client?: ConstructorParameters<typeof Client>[1];\n transport?: {\n headers?: HeadersInit;\n type?: TransportType;\n };\n }\n ): Promise<\n | {\n id: string;\n state: typeof MCPConnectionState.AUTHENTICATING;\n authUrl: string;\n }\n | {\n id: string;\n state: typeof MCPConnectionState.READY;\n authUrl?: undefined;\n }\n > {\n const isHttpTransport = typeof urlOrBinding === \"string\";\n const normalizedUrl = isHttpTransport\n ? new URL(urlOrBinding).href\n : undefined;\n const existingServer = this.mcp\n .listServers()\n .find(\n (s) =>\n s.name === serverName &&\n (!isHttpTransport || new URL(s.server_url).href === normalizedUrl)\n );\n if (existingServer && this.mcp.mcpConnections[existingServer.id]) {\n const conn = this.mcp.mcpConnections[existingServer.id];\n if (\n conn.connectionState === MCPConnectionState.AUTHENTICATING &&\n conn.options.transport.authProvider?.authUrl\n ) {\n return {\n id: existingServer.id,\n state: MCPConnectionState.AUTHENTICATING,\n authUrl: conn.options.transport.authProvider.authUrl\n };\n }\n if (conn.connectionState === MCPConnectionState.FAILED) {\n throw new Error(\n `MCP server \"${serverName}\" is in failed state: ${conn.connectionError}`\n );\n }\n return { id: existingServer.id, state: MCPConnectionState.READY };\n }\n\n // RPC transport path: second argument is a DurableObjectNamespace\n if (typeof urlOrBinding !== \"string\") {\n const rpcOpts = callbackHostOrOptions as\n | AddRpcMcpServerOptions\n | undefined;\n\n const normalizedName = serverName.toLowerCase().replace(/\\s+/g, \"-\");\n\n const reconnectId = existingServer?.id;\n const { id } = await this.mcp.connect(\n `${RPC_DO_PREFIX}${normalizedName}`,\n {\n reconnect: reconnectId ? { id: reconnectId } : undefined,\n transport: {\n type: \"rpc\" as TransportType,\n namespace:\n urlOrBinding as unknown as DurableObjectNamespace<McpAgent>,\n name: normalizedName,\n props: rpcOpts?.props\n }\n }\n );\n\n const conn = this.mcp.mcpConnections[id];\n if (conn && conn.connectionState === MCPConnectionState.CONNECTED) {\n const discoverResult = await this.mcp.discoverIfConnected(id);\n if (discoverResult && !discoverResult.success) {\n throw new Error(\n `Failed to discover MCP server capabilities: ${discoverResult.error}`\n );\n }\n } else if (conn && conn.connectionState === MCPConnectionState.FAILED) {\n throw new Error(\n `Failed to connect to MCP server \"${serverName}\" via RPC: ${conn.connectionError}`\n );\n }\n\n const bindingName = this._findBindingNameForNamespace(\n urlOrBinding as unknown as DurableObjectNamespace<McpAgent>\n );\n if (bindingName) {\n this.mcp.saveRpcServerToStorage(\n id,\n serverName,\n normalizedName,\n bindingName,\n rpcOpts?.props\n );\n }\n\n return { id, state: MCPConnectionState.READY };\n }\n\n // HTTP transport path\n const httpOptions = callbackHostOrOptions as\n | string\n | AddMcpServerOptions\n | undefined;\n\n let resolvedCallbackHost: string | undefined;\n let resolvedAgentsPrefix: string;\n let resolvedOptions:\n | {\n client?: ConstructorParameters<typeof Client>[1];\n transport?: {\n headers?: HeadersInit;\n type?: TransportType;\n };\n retry?: RetryOptions;\n }\n | undefined;\n\n let resolvedCallbackPath: string | undefined;\n\n if (typeof httpOptions === \"object\" && httpOptions !== null) {\n resolvedCallbackHost = httpOptions.callbackHost;\n resolvedCallbackPath = httpOptions.callbackPath;\n resolvedAgentsPrefix = httpOptions.agentsPrefix ?? \"agents\";\n resolvedOptions = {\n client: httpOptions.client,\n transport: httpOptions.transport,\n retry: httpOptions.retry\n };\n } else {\n resolvedCallbackHost = httpOptions;\n resolvedAgentsPrefix = agentsPrefix ?? \"agents\";\n resolvedOptions = options;\n }\n\n // Enforce callbackPath when sendIdentityOnConnect is false and callbackHost is provided\n if (\n !this._resolvedOptions.sendIdentityOnConnect &&\n resolvedCallbackHost &&\n !resolvedCallbackPath\n ) {\n throw new Error(\n \"callbackPath is required in addMcpServer options when sendIdentityOnConnect is false — \" +\n \"the default callback URL would expose the instance name. \" +\n \"Provide a callbackPath and route the callback request to this agent via getAgentByName.\"\n );\n }\n\n // Try to derive callbackHost from the current request if not explicitly provided\n if (!resolvedCallbackHost) {\n const { request } = getCurrentAgent();\n if (request) {\n const requestUrl = new URL(request.url);\n resolvedCallbackHost = `${requestUrl.protocol}//${requestUrl.host}`;\n }\n }\n\n // Build the callback URL if we have a host (needed for OAuth, optional for non-OAuth servers)\n let callbackUrl: string | undefined;\n if (resolvedCallbackHost) {\n const normalizedHost = resolvedCallbackHost.replace(/\\/$/, \"\");\n callbackUrl = resolvedCallbackPath\n ? `${normalizedHost}/${resolvedCallbackPath.replace(/^\\//, \"\")}`\n : `${normalizedHost}/${resolvedAgentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;\n }\n\n await this.mcp.ensureJsonSchema();\n\n const id = nanoid(8);\n\n // Only create authProvider if we have a callbackUrl (needed for OAuth servers)\n let authProvider:\n | ReturnType<typeof this.createMcpOAuthProvider>\n | undefined;\n if (callbackUrl) {\n authProvider = this.createMcpOAuthProvider(callbackUrl);\n authProvider.serverId = id;\n }\n\n // Use the transport type specified in options, or default to \"auto\"\n const transportType: TransportType =\n resolvedOptions?.transport?.type ?? \"auto\";\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 (resolvedOptions?.transport?.headers) {\n headerTransportOpts = {\n eventSourceInit: {\n fetch: (url, init) =>\n fetch(url, {\n ...init,\n headers: resolvedOptions?.transport?.headers\n })\n },\n requestInit: {\n headers: resolvedOptions?.transport?.headers\n }\n };\n }\n\n // Register server (also saves to storage)\n await this.mcp.registerServer(id, {\n url: normalizedUrl!,\n name: serverName,\n callbackUrl,\n client: resolvedOptions?.client,\n transport: {\n ...headerTransportOpts,\n authProvider,\n type: transportType\n },\n retry: resolvedOptions?.retry\n });\n\n const result = await this.mcp.connectToServer(id);\n\n if (result.state === MCPConnectionState.FAILED) {\n // Server stays in storage so user can retry via connectToServer(id)\n throw new Error(\n `Failed to connect to MCP server at ${normalizedUrl}: ${result.error}`\n );\n }\n\n if (result.state === MCPConnectionState.AUTHENTICATING) {\n if (!callbackUrl) {\n throw new Error(\n \"This MCP server requires OAuth authentication. \" +\n \"Provide callbackHost in addMcpServer options to enable the OAuth flow.\"\n );\n }\n return { id, state: result.state, authUrl: result.authUrl };\n }\n\n // State is CONNECTED - discover capabilities\n const discoverResult = await this.mcp.discoverIfConnected(id);\n\n if (discoverResult && !discoverResult.success) {\n // Server stays in storage - connection is still valid, user can retry discovery\n throw new Error(\n `Failed to discover MCP server capabilities: ${discoverResult.error}`\n );\n }\n\n return { id, state: MCPConnectionState.READY };\n }\n\n async removeMcpServer(id: string) {\n await this.mcp.removeServer(id);\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.mcp.listServers();\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\n // Determine the default state when no connection exists\n let defaultState: \"authenticating\" | \"not-connected\" = \"not-connected\";\n if (!serverConn && server.auth_url) {\n // If there's an auth_url but no connection, it's waiting for OAuth\n defaultState = \"authenticating\";\n }\n\n mcpState.servers[server.id] = {\n auth_url: server.auth_url,\n capabilities: serverConn?.serverCapabilities ?? null,\n error: sanitizeErrorString(serverConn?.connectionError ?? null),\n instructions: serverConn?.instructions ?? null,\n name: server.name,\n server_url: server.server_url,\n state: serverConn?.connectionState ?? defaultState\n };\n }\n }\n\n return mcpState;\n }\n\n /**\n * Create the OAuth provider used when connecting to MCP servers that require authentication.\n *\n * Override this method in a subclass to supply a custom OAuth provider implementation,\n * for example to use pre-registered client credentials, mTLS-based authentication,\n * or any other OAuth flow beyond dynamic client registration.\n *\n * @example\n * // Custom OAuth provider\n * class MyAgent extends Agent {\n * createMcpOAuthProvider(callbackUrl: string): AgentMcpOAuthProvider {\n * return new MyCustomOAuthProvider(\n * this.ctx.storage,\n * this.name,\n * callbackUrl\n * );\n * }\n * }\n *\n * @param callbackUrl The OAuth callback URL for the authorization flow\n * @returns An {@link AgentMcpOAuthProvider} instance used by {@link addMcpServer}\n */\n createMcpOAuthProvider(callbackUrl: string): AgentMcpOAuthProvider {\n return new DurableObjectOAuthClientProvider(\n this.ctx.storage,\n this.name,\n callbackUrl\n );\n }\n\n private broadcastMcpServers() {\n this._broadcastProtocol(\n JSON.stringify({\n mcp: this.getMcpServers(),\n type: MessageType.CF_AGENT_MCP_SERVERS\n })\n );\n }\n\n /**\n * Handle MCP OAuth callback request if it's an OAuth callback.\n *\n * This method encapsulates the entire OAuth callback flow:\n * 1. Checks if the request is an MCP OAuth callback\n * 2. Processes the OAuth code exchange\n * 3. Establishes the connection if successful\n * 4. Broadcasts MCP server state updates\n * 5. Returns the appropriate HTTP response\n *\n * @param request The incoming HTTP request\n * @returns Response if this was an OAuth callback, null otherwise\n */\n private async handleMcpOAuthCallback(\n request: Request\n ): Promise<Response | null> {\n // Check if this is an OAuth callback request\n const isCallback = this.mcp.isCallbackRequest(request);\n if (!isCallback) {\n return null;\n }\n\n // Handle the OAuth callback (exchanges code for token, clears OAuth credentials from storage)\n // This fires onServerStateChanged event which triggers broadcast\n const result = await this.mcp.handleCallbackRequest(request);\n\n // If auth was successful, establish the connection in the background\n // (establishConnection handles retries internally using per-server retry config)\n if (result.authSuccess) {\n this.mcp.establishConnection(result.serverId).catch((error) => {\n console.error(\n \"[Agent handleMcpOAuthCallback] Connection establishment failed:\",\n error\n );\n });\n }\n\n this.broadcastMcpServers();\n\n // Return the HTTP response for the OAuth callback\n return this.handleOAuthCallbackResponse(result, request);\n }\n\n /**\n * Handle OAuth callback response using MCPClientManager configuration\n * @param result OAuth callback result\n * @param request The original request (needed for base URL)\n * @returns Response for the OAuth callback\n */\n private handleOAuthCallbackResponse(\n result: MCPClientOAuthResult,\n request: Request\n ): Response {\n const config = this.mcp.getOAuthCallbackConfig();\n\n // Use custom handler if configured\n if (config?.customHandler) {\n return config.customHandler(result);\n }\n\n const baseOrigin = new URL(request.url).origin;\n\n // Redirect to success URL if configured\n if (config?.successRedirect && result.authSuccess) {\n try {\n return Response.redirect(\n new URL(config.successRedirect, baseOrigin).href\n );\n } catch (e) {\n console.error(\n \"Invalid successRedirect URL:\",\n config.successRedirect,\n e\n );\n return Response.redirect(baseOrigin);\n }\n }\n\n // Redirect to error URL if configured\n if (config?.errorRedirect && !result.authSuccess) {\n try {\n const errorUrl = `${config.errorRedirect}?error=${encodeURIComponent(\n result.authError || \"Unknown error\"\n )}`;\n return Response.redirect(new URL(errorUrl, baseOrigin).href);\n } catch (e) {\n console.error(\"Invalid errorRedirect URL:\", config.errorRedirect, e);\n return Response.redirect(baseOrigin);\n }\n }\n\n return Response.redirect(baseOrigin);\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 * @deprecated Use DurableObjectNamespace instead\n */\nexport type AgentNamespace<Agentic extends Agent<Cloudflare.Env>> =\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/**\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 return routePartykitRequest(request, env as Record<string, unknown>, {\n prefix: \"agents\",\n ...(options as PartyServerOptions<Record<string, unknown>>)\n });\n}\n\n// Email routing - deprecated resolver kept in root for upgrade discoverability\n// Other email utilities moved to agents/email subpath\nexport { createHeaderBasedEmailResolver } from \"./email\";\n\nimport type { EmailResolver } from \"./email\";\n\nexport type EmailRoutingOptions<Env> = AgentOptions<Env> & {\n resolver: EmailResolver<Env>;\n /**\n * Callback invoked when no routing information is found for an email.\n * Use this to reject the email or perform custom handling.\n * If not provided, a warning is logged and the email is dropped.\n */\n onNoRoute?: (email: ForwardableEmailMessage) => void | Promise<void>;\n};\n\n// Cache the agent namespace map for email routing\n// This maps original names, kebab-case, and lowercase versions to namespaces\nconst agentMapCache = new WeakMap<\n Record<string, unknown>,\n { map: Record<string, unknown>; originalNames: string[] }\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<\n Env extends Cloudflare.Env = Cloudflare.Env\n>(\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 if (options.onNoRoute) {\n await options.onNoRoute(email);\n } else {\n console.warn(\"No routing information found for email, dropping message\");\n }\n return;\n }\n\n // Build a map that includes original names, kebab-case, and lowercase versions\n if (!agentMapCache.has(env as Record<string, unknown>)) {\n const map: Record<string, unknown> = {};\n const originalNames: string[] = [];\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 the original name, kebab-case version, and lowercase version\n map[key] = value;\n map[camelCaseToKebabCase(key)] = value;\n map[key.toLowerCase()] = value;\n originalNames.push(key);\n }\n }\n agentMapCache.set(env as Record<string, unknown>, {\n map,\n originalNames\n });\n }\n\n const cached = agentMapCache.get(env as Record<string, unknown>)!;\n const namespace = cached.map[routingInfo.agentName];\n\n if (!namespace) {\n // Provide helpful error message listing available agents\n const availableAgents = cached.originalNames.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 DurableObjectNamespace<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: (replyOptions: { from: string; to: string; raw: string }) => {\n return email.reply(\n new EmailMessage(replyOptions.from, replyOptions.to, replyOptions.raw)\n );\n },\n from: email.from,\n to: email.to,\n _secureRouted: routingInfo._secureRouted\n };\n\n await agent._onEmail(serialisableEmail);\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 extends Cloudflare.Env = Cloudflare.Env,\n T extends Agent<Env> = Agent<Env>,\n Props extends Record<string, unknown> = Record<string, unknown>\n>(\n namespace: DurableObjectNamespace<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 * Whether the stream has been closed (via end() or error())\n */\n get isClosed(): boolean {\n return this._closed;\n }\n\n /**\n * Send a chunk of data to the client\n * @param chunk The data to send\n * @returns false if stream is already closed (no-op), true if sent\n */\n send(chunk: unknown): boolean {\n if (this._closed) {\n console.warn(\n \"StreamingResponse.send() called after stream was closed - data not sent\"\n );\n return false;\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 return true;\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 * @returns false if stream is already closed (no-op), true if sent\n */\n end(finalChunk?: unknown): boolean {\n if (this._closed) {\n return false;\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 return true;\n }\n\n /**\n * Send an error to the client and close the stream\n * @param message Error message to send\n * @returns false if stream is already closed (no-op), true if sent\n */\n error(message: string): boolean {\n if (this._closed) {\n return false;\n }\n this._closed = true;\n const response: RPCResponse = {\n error: message,\n id: this._id,\n success: false,\n type: MessageType.RPC\n };\n this._connection.send(JSON.stringify(response));\n return true;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2GA,SAAS,aAAa,KAAiC;AACrD,QACE,OAAO,QAAQ,YACf,QAAQ,QACR,UAAU,OACV,IAAI,SAAS,YAAY,OACzB,QAAQ,OACR,OAAO,IAAI,OAAO,YAClB,YAAY,OACZ,OAAO,IAAI,WAAW,YACtB,UAAU,OACV,MAAM,QAAS,IAAmB,KAAK;;;;;AAO3C,SAAS,qBAAqB,KAAyC;AACrE,QACE,OAAO,QAAQ,YACf,QAAQ,QACR,UAAU,OACV,IAAI,SAAS,YAAY,kBACzB,WAAW;;AAcf,MAAM,mCAAmB,IAAI,SAAqC;;;;AAKlE,IAAa,WAAb,cAA8B,MAAM;CAIlC,YAAY,OAAe,OAAgB;EACzC,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;AACtE,QAAM,qBAAqB,WAAW,EAAE,OAAO,CAAC;AAChD,OAAK,OAAO;AACZ,OAAK,QAAQ;;;;;;;AAQjB,SAA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Aa,IAAI,aAAa,IAAI,CACvE;;EAEH,MAAM,MAAM;EACZ,IAAI,MAAM;EACV,eAAe,YAAY;EAC5B;AAED,OAAM,MAAM,SAAS,kBAAkB;;;;;;;;;;;AAYzC,eAAsB,eAKpB,WACA,MACA,SAKA;AACA,QAAO,gBAAwB,WAAW,MAAM,QAAQ;;;;;AAM1D,IAAa,oBAAb,MAA+B;CAK7B,YAAY,YAAwB,IAAY;iBAF9B;AAGhB,OAAK,cAAc;AACnB,OAAK,MAAM;;;;;CAMb,IAAI,WAAoB;AACtB,SAAO,KAAK;;;;;;;CAQd,KAAK,OAAyB;AAC5B,MAAI,KAAK,SAAS;AAChB,WAAQ,KACN,0EACD;AACD,UAAO;;EAET,MAAM,WAAwB;GAC5B,MAAM;GACN,IAAI,KAAK;GACT,QAAQ;GACR,SAAS;GACT,MAAM,YAAY;GACnB;AACD,OAAK,YAAY,KAAK,KAAK,UAAU,SAAS,CAAC;AAC/C,SAAO;;;;;;;CAQT,IAAI,YAA+B;AACjC,MAAI,KAAK,QACP,QAAO;AAET,OAAK,UAAU;EACf,MAAM,WAAwB;GAC5B,MAAM;GACN,IAAI,KAAK;GACT,QAAQ;GACR,SAAS;GACT,MAAM,YAAY;GACnB;AACD,OAAK,YAAY,KAAK,KAAK,UAAU,SAAS,CAAC;AAC/C,SAAO;;;;;;;CAQT,MAAM,SAA0B;AAC9B,MAAI,KAAK,QACP,QAAO;AAET,OAAK,UAAU;EACf,MAAM,WAAwB;GAC5B,OAAO;GACP,IAAI,KAAK;GACT,SAAS;GACT,MAAM,YAAY;GACnB;AACD,OAAK,YAAY,KAAK,KAAK,UAAU,SAAS,CAAC;AAC/C,SAAO"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["agentContext"],"sources":["../src/index.ts"],"sourcesContent":["import type { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport {\n __DO_NOT_USE_WILL_BREAK__agentContext as agentContext,\n type AgentEmail\n} from \"./internal_context\";\nexport { __DO_NOT_USE_WILL_BREAK__agentContext } from \"./internal_context\";\nimport type { SSEClientTransportOptions } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport { signAgentHeaders } from \"./email\";\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 \"./utils\";\nimport {\n type RetryOptions,\n tryN,\n isErrorRetryable,\n validateRetryOptions\n} from \"./retries\";\nimport { MCPClientManager, type MCPClientOAuthResult } from \"./mcp/client\";\nimport type {\n WorkflowCallback,\n WorkflowTrackingRow,\n WorkflowStatus,\n RunWorkflowOptions,\n WorkflowEventPayload,\n WorkflowInfo,\n WorkflowQueryCriteria,\n WorkflowPage\n} from \"./workflow-types\";\nimport { MCPConnectionState } from \"./mcp/client-connection\";\nimport {\n DurableObjectOAuthClientProvider,\n type AgentMcpOAuthProvider\n} from \"./mcp/do-oauth-client-provider\";\nimport type { TransportType } from \"./mcp/types\";\nimport {\n genericObservability,\n type Observability,\n type ObservabilityEvent\n} from \"./observability\";\nimport { DisposableStore } from \"./core/events\";\nimport { MessageType } from \"./types\";\nimport { RPC_DO_PREFIX } from \"./mcp/rpc\";\nimport type { McpAgent } from \"./mcp\";\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 WeakMap<Function, CallableMetadata>();\n\n/**\n * Error class for SQL execution failures, containing the query that failed\n */\nexport class SqlError extends Error {\n /** The SQL query that failed */\n readonly query: string;\n\n constructor(query: string, cause: unknown) {\n const message = cause instanceof Error ? cause.message : String(cause);\n super(`SQL query failed: ${message}`, { cause });\n this.name = \"SqlError\";\n this.query = query;\n }\n}\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 _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 return callable(metadata);\n};\n\nexport type QueueItem<T = string> = {\n id: string;\n payload: T;\n callback: keyof Agent<Cloudflare.Env>;\n created_at: number;\n retry?: RetryOptions;\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 /** Retry options for callback execution */\n retry?: RetryOptions;\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 /** Type of schedule for recurring execution at fixed intervals */\n type: \"interval\";\n /** Timestamp for the next execution */\n time: number;\n /** Number of seconds between executions */\n intervalSeconds: number;\n }\n);\n\n/**\n * Represents the public state of a fiber.\n */\nfunction getNextCronTime(cron: string) {\n const interval = parseCronExpression(cron);\n return interval.getNextDate();\n}\n\nexport type { TransportType } from \"./mcp/types\";\nexport type { RetryOptions } from \"./retries\";\nexport {\n DurableObjectOAuthClientProvider,\n type AgentMcpOAuthProvider,\n /** @deprecated Use {@link AgentMcpOAuthProvider} instead. */\n type AgentsOAuthProvider\n} from \"./mcp/do-oauth-client-provider\";\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 & { serverId: string })[];\n prompts: (Prompt & { serverId: string })[];\n resources: (Resource & { serverId: string })[];\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: MCPConnectionState;\n /** May contain untrusted content from external OAuth providers. Escape appropriately for your output context. */\n error: string | null;\n instructions: string | null;\n capabilities: ServerCapabilities | null;\n};\n\n/**\n * Options for adding an MCP server\n */\nexport type AddMcpServerOptions = {\n /** OAuth callback host (auto-derived from request if omitted) */\n callbackHost?: string;\n /**\n * Custom callback URL path — bypasses the default `/agents/{class}/{name}/callback` construction.\n * Required when `sendIdentityOnConnect` is `false` to prevent leaking the instance name.\n * When set, the callback URL becomes `{callbackHost}/{callbackPath}`.\n * The developer must route this path to the agent instance via `getAgentByName`.\n * Should be a plain path (e.g., `/mcp-callback`) — do not include query strings or fragments.\n */\n callbackPath?: string;\n /** Agents routing prefix (default: \"agents\") */\n agentsPrefix?: string;\n /** MCP client options */\n client?: ConstructorParameters<typeof Client>[1];\n /** Transport options */\n transport?: {\n /** Custom headers for authentication (e.g., bearer tokens, CF Access) */\n headers?: HeadersInit;\n /** Transport type: \"sse\", \"streamable-http\", or \"auto\" (default) */\n type?: TransportType;\n };\n /** Retry options for connection and reconnection attempts */\n retry?: RetryOptions;\n};\n\n/**\n * Options for adding an MCP server via RPC (Durable Object binding)\n */\nexport type AddRpcMcpServerOptions = {\n /** Props to pass to the McpAgent instance */\n props?: Record<string, unknown>;\n};\n\nconst KEEP_ALIVE_INTERVAL_MS = 30_000;\n\nconst STATE_ROW_ID = \"cf_state_row_id\";\nconst STATE_WAS_CHANGED = \"cf_state_was_changed\";\n\nconst DEFAULT_STATE = {} as unknown;\n\n/**\n * Internal key used to store the readonly flag in connection state.\n * Prefixed with _cf_ to avoid collision with user state keys.\n */\nconst CF_READONLY_KEY = \"_cf_readonly\";\n\n/**\n * Internal key used to store the no-protocol flag in connection state.\n * When set, protocol messages (identity, state sync, MCP servers) are not\n * sent to this connection — neither on connect nor via broadcasts.\n */\nconst CF_NO_PROTOCOL_KEY = \"_cf_no_protocol\";\n\n/**\n * The set of all internal keys stored in connection state that must be\n * hidden from user code and preserved across setState calls.\n */\nconst CF_INTERNAL_KEYS: ReadonlySet<string> = new Set([\n CF_READONLY_KEY,\n CF_NO_PROTOCOL_KEY\n]);\n\n/** Check if a raw connection state object contains any internal keys. */\nfunction rawHasInternalKeys(raw: Record<string, unknown>): boolean {\n for (const key of Object.keys(raw)) {\n if (CF_INTERNAL_KEYS.has(key)) return true;\n }\n return false;\n}\n\n/** Return a copy of `raw` with all internal keys removed, or null if no user keys remain. */\nfunction stripInternalKeys(\n raw: Record<string, unknown>\n): Record<string, unknown> | null {\n const result: Record<string, unknown> = {};\n let hasUserKeys = false;\n for (const key of Object.keys(raw)) {\n if (!CF_INTERNAL_KEYS.has(key)) {\n result[key] = raw[key];\n hasUserKeys = true;\n }\n }\n return hasUserKeys ? result : null;\n}\n\n/** Return a copy containing only the internal keys present in `raw`. */\nfunction extractInternalFlags(\n raw: Record<string, unknown>\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(raw)) {\n if (CF_INTERNAL_KEYS.has(key)) {\n result[key] = raw[key];\n }\n }\n return result;\n}\n\n/** Max length for error strings broadcast to clients. */\nconst MAX_ERROR_STRING_LENGTH = 500;\n\n/**\n * Sanitize an error string before broadcasting to clients.\n * MCP error strings may contain untrusted content from external OAuth\n * providers — truncate and strip control characters to limit XSS risk.\n */\n// Regex to match C0 control characters (except \\t, \\n, \\r) and DEL.\nconst CONTROL_CHAR_RE = new RegExp(\n // oxlint-disable-next-line no-control-regex -- intentionally matching control chars for sanitization\n \"[\\\\u0000-\\\\u0008\\\\u000B\\\\u000C\\\\u000E-\\\\u001F\\\\u007F]\",\n \"g\"\n);\n\nfunction sanitizeErrorString(error: string | null): string | null {\n if (error === null) return null;\n // Strip control characters (keep printable ASCII + common unicode)\n let sanitized = error.replace(CONTROL_CHAR_RE, \"\");\n if (sanitized.length > MAX_ERROR_STRING_LENGTH) {\n sanitized = sanitized.substring(0, MAX_ERROR_STRING_LENGTH) + \"...\";\n }\n return sanitized;\n}\n\n/**\n * Tracks which agent constructors have already emitted the onStateUpdate\n * deprecation warning, so it fires at most once per class.\n */\nconst _onStateUpdateWarnedClasses = new WeakSet<Function>();\n\n/**\n * Tracks which agent constructors have already emitted the\n * sendIdentityOnConnect deprecation warning, so it fires at most once per class.\n */\nconst _sendIdentityWarnedClasses = new WeakSet<Function>();\n\n/**\n * Default options for Agent configuration.\n * Child classes can override specific options without spreading.\n */\nexport const DEFAULT_AGENT_STATIC_OPTIONS = {\n /** Whether the Agent should hibernate when inactive */\n hibernate: true,\n /** Whether to send identity (name, agent) to clients on connect */\n sendIdentityOnConnect: true,\n /**\n * Timeout in seconds before a running interval schedule is considered \"hung\"\n * and force-reset. Increase this if you have callbacks that legitimately\n * take longer than 30 seconds.\n */\n hungScheduleTimeoutSeconds: 30,\n /** Default retry options for schedule(), queue(), and this.retry() */\n retry: {\n maxAttempts: 3,\n baseDelayMs: 100,\n maxDelayMs: 3000\n } satisfies Required<RetryOptions>\n};\n\n/**\n * Fully resolved agent options — all fields are defined with concrete values.\n */\ninterface ResolvedAgentOptions {\n hibernate: boolean;\n sendIdentityOnConnect: boolean;\n hungScheduleTimeoutSeconds: number;\n retry: Required<RetryOptions>;\n}\n\n/**\n * Configuration options for the Agent.\n * Override in subclasses via `static options`.\n * All fields are optional - defaults are applied at runtime.\n * Note: `hibernate` defaults to `true` if not specified.\n */\nexport interface AgentStaticOptions {\n hibernate?: boolean;\n sendIdentityOnConnect?: boolean;\n hungScheduleTimeoutSeconds?: number;\n /** Default retry options for schedule(), queue(), and this.retry(). */\n retry?: RetryOptions;\n}\n\n/**\n * Parse the raw `retry_options` TEXT column from a SQLite row into a\n * typed `RetryOptions` object, or `undefined` if not set.\n */\nfunction parseRetryOptions(\n row: Record<string, unknown>\n): RetryOptions | undefined {\n const raw = row.retry_options;\n if (typeof raw !== \"string\") return undefined;\n return JSON.parse(raw) as RetryOptions;\n}\n\n/**\n * Resolve per-task retry options against class-level defaults and call\n * `tryN`. This is the shared retry-execution path used by both queue\n * flush and schedule alarm handlers.\n */\nfunction resolveRetryConfig(\n taskRetry: RetryOptions | undefined,\n defaults: Required<RetryOptions>\n): { maxAttempts: number; baseDelayMs: number; maxDelayMs: number } {\n return {\n maxAttempts: taskRetry?.maxAttempts ?? defaults.maxAttempts,\n baseDelayMs: taskRetry?.baseDelayMs ?? defaults.baseDelayMs,\n maxDelayMs: taskRetry?.maxDelayMs ?? defaults.maxDelayMs\n };\n}\n\nexport function getCurrentAgent<\n T extends Agent<Cloudflare.Env> = Agent<Cloudflare.Env>\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// oxlint-disable-next-line @typescript-eslint/no-explicit-any -- generic callable constraint\nfunction withAgentContext<T extends (...args: any[]) => any>(\n method: T\n): (\n this: Agent<Cloudflare.Env, unknown>,\n ...args: Parameters<T>\n) => 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 * Extract string keys from Env where the value is a Workflow binding.\n */\ntype WorkflowBinding<E> = {\n [K in keyof E & string]: E[K] extends Workflow ? K : never;\n}[keyof E & string];\n\n/**\n * Type for workflow name parameter.\n * When Env has typed Workflow bindings, provides autocomplete for those keys.\n * Also accepts any string for dynamic use cases and compatibility.\n * The `string & {}` trick preserves autocomplete while allowing any string.\n */\ntype WorkflowName<E> = WorkflowBinding<E> | (string & {});\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 extends Cloudflare.Env = Cloudflare.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 private _disposables = new DisposableStore();\n private _destroyed = false;\n\n /**\n * Stores raw state accessors for wrapped connections.\n * Used by internal flag methods (readonly, no-protocol) to read/write\n * _cf_-prefixed keys without going through the user-facing state/setState.\n */\n private _rawStateAccessors = new WeakMap<\n Connection,\n {\n getRaw: () => Record<string, unknown> | null;\n setRaw: (state: unknown) => unknown;\n }\n >();\n\n /**\n * Cached persistence-hook dispatch mode, computed once in the constructor.\n * - \"new\" → call onStateChanged\n * - \"old\" → call onStateUpdate (deprecated)\n * - \"none\" → neither hook is overridden, skip entirely\n */\n private _persistenceHookMode: \"new\" | \"old\" | \"none\" = \"none\";\n\n private _ParentClass: typeof Agent<Env, State> =\n Object.getPrototypeOf(this).constructor;\n\n readonly mcp: MCPClientManager;\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 try {\n this._state = JSON.parse(state);\n } catch (e) {\n console.error(\n \"Failed to parse stored state, falling back to initialState:\",\n e\n );\n if (this.initialState !== DEFAULT_STATE) {\n this._state = this.initialState;\n // Persist the fixed state to prevent future parse errors\n this._setStateInternal(this.initialState);\n } else {\n // No initialState defined - clear corrupted data to prevent infinite retry loop\n this.sql`DELETE FROM cf_agents_state WHERE id = ${STATE_ROW_ID}`;\n this.sql`DELETE FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}`;\n return undefined as State;\n }\n }\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._setStateInternal(this.initialState);\n return this.initialState;\n }\n\n /**\n * Agent configuration options.\n * Override in subclasses - only specify what you want to change.\n * @example\n * class SecureAgent extends Agent {\n * static options = { sendIdentityOnConnect: false };\n * }\n */\n static options: AgentStaticOptions = { hibernate: true };\n\n /**\n * Resolved options (merges defaults with subclass overrides).\n * Cached after first access — static options never change during the\n * lifetime of a Durable Object instance.\n */\n private _cachedOptions?: ResolvedAgentOptions;\n private get _resolvedOptions(): ResolvedAgentOptions {\n if (this._cachedOptions) return this._cachedOptions;\n const ctor = this.constructor as typeof Agent;\n const userRetry = ctor.options?.retry;\n this._cachedOptions = {\n hibernate:\n ctor.options?.hibernate ?? DEFAULT_AGENT_STATIC_OPTIONS.hibernate,\n sendIdentityOnConnect:\n ctor.options?.sendIdentityOnConnect ??\n DEFAULT_AGENT_STATIC_OPTIONS.sendIdentityOnConnect,\n hungScheduleTimeoutSeconds:\n ctor.options?.hungScheduleTimeoutSeconds ??\n DEFAULT_AGENT_STATIC_OPTIONS.hungScheduleTimeoutSeconds,\n retry: {\n maxAttempts:\n userRetry?.maxAttempts ??\n DEFAULT_AGENT_STATIC_OPTIONS.retry.maxAttempts,\n baseDelayMs:\n userRetry?.baseDelayMs ??\n DEFAULT_AGENT_STATIC_OPTIONS.retry.baseDelayMs,\n maxDelayMs:\n userRetry?.maxDelayMs ?? DEFAULT_AGENT_STATIC_OPTIONS.retry.maxDelayMs\n }\n };\n return this._cachedOptions;\n }\n\n /**\n * The observability implementation to use for the Agent\n */\n observability?: Observability = genericObservability;\n\n /**\n * Emit an observability event with auto-generated timestamp.\n * @internal\n */\n protected _emit(\n type: ObservabilityEvent[\"type\"],\n payload: Record<string, unknown> = {}\n ): void {\n this.observability?.emit({\n type,\n agent: this._ParentClass.name,\n name: this.name,\n payload,\n timestamp: Date.now()\n } as ObservabilityEvent);\n }\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 throw new SqlError(query, 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_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 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 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', 'interval')),\n time INTEGER,\n delayInSeconds INTEGER,\n cron TEXT,\n intervalSeconds INTEGER,\n running INTEGER DEFAULT 0,\n created_at INTEGER DEFAULT (unixepoch()),\n execution_started_at INTEGER,\n retry_options TEXT\n )\n `;\n\n // Migration: Add columns for interval scheduling (for existing agents)\n // Use raw exec to avoid error logging through onError for expected failures\n const addColumnIfNotExists = (sql: string) => {\n try {\n this.ctx.storage.sql.exec(sql);\n } catch (e) {\n // Only ignore \"duplicate column\" errors, re-throw unexpected errors\n const message = e instanceof Error ? e.message : String(e);\n if (!message.toLowerCase().includes(\"duplicate column\")) {\n throw e;\n }\n }\n };\n\n addColumnIfNotExists(\n \"ALTER TABLE cf_agents_schedules ADD COLUMN intervalSeconds INTEGER\"\n );\n addColumnIfNotExists(\n \"ALTER TABLE cf_agents_schedules ADD COLUMN running INTEGER DEFAULT 0\"\n );\n addColumnIfNotExists(\n \"ALTER TABLE cf_agents_schedules ADD COLUMN execution_started_at INTEGER\"\n );\n addColumnIfNotExists(\n \"ALTER TABLE cf_agents_schedules ADD COLUMN retry_options TEXT\"\n );\n addColumnIfNotExists(\n \"ALTER TABLE cf_agents_queues ADD COLUMN retry_options TEXT\"\n );\n\n // Migration: Update CHECK constraint on type column to include 'interval'.\n // SQLite doesn't support ALTER TABLE to modify constraints, so we recreate\n // the table when the old constraint is detected.\n {\n const rows = this.ctx.storage.sql\n .exec(\n \"SELECT sql FROM sqlite_master WHERE type='table' AND name='cf_agents_schedules'\"\n )\n .toArray();\n if (rows.length > 0) {\n const ddl = String(rows[0].sql);\n if (!ddl.includes(\"'interval'\")) {\n // Drop any leftover temp table from a previous partial migration\n this.ctx.storage.sql.exec(\n \"DROP TABLE IF EXISTS cf_agents_schedules_new\"\n );\n this.ctx.storage.sql.exec(`\n CREATE TABLE cf_agents_schedules_new (\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', 'interval')),\n time INTEGER,\n delayInSeconds INTEGER,\n cron TEXT,\n intervalSeconds INTEGER,\n running INTEGER DEFAULT 0,\n created_at INTEGER DEFAULT (unixepoch()),\n execution_started_at INTEGER,\n retry_options TEXT\n )\n `);\n this.ctx.storage.sql.exec(`\n INSERT INTO cf_agents_schedules_new\n (id, callback, payload, type, time, delayInSeconds, cron,\n intervalSeconds, running, created_at, execution_started_at, retry_options)\n SELECT id, callback, payload, type, time, delayInSeconds, cron,\n intervalSeconds, running, created_at, execution_started_at, retry_options\n FROM cf_agents_schedules\n `);\n this.ctx.storage.sql.exec(\"DROP TABLE cf_agents_schedules\");\n this.ctx.storage.sql.exec(\n \"ALTER TABLE cf_agents_schedules_new RENAME TO cf_agents_schedules\"\n );\n }\n }\n }\n\n // Workflow tracking table for Agent-Workflow integration\n this.sql`\n CREATE TABLE IF NOT EXISTS cf_agents_workflows (\n id TEXT PRIMARY KEY NOT NULL,\n workflow_id TEXT NOT NULL UNIQUE,\n workflow_name TEXT NOT NULL,\n status TEXT NOT NULL CHECK(status IN (\n 'queued', 'running', 'paused', 'errored',\n 'terminated', 'complete', 'waiting',\n 'waitingForPause', 'unknown'\n )),\n metadata TEXT,\n error_name TEXT,\n error_message TEXT,\n created_at INTEGER NOT NULL DEFAULT (unixepoch()),\n updated_at INTEGER NOT NULL DEFAULT (unixepoch()),\n completed_at INTEGER\n )\n `;\n\n this.sql`\n CREATE INDEX IF NOT EXISTS idx_workflows_status ON cf_agents_workflows(status)\n `;\n\n this.sql`\n CREATE INDEX IF NOT EXISTS idx_workflows_name ON cf_agents_workflows(workflow_name)\n `;\n\n // Initialize MCPClientManager AFTER tables are created\n this.mcp = new MCPClientManager(this._ParentClass.name, \"0.0.1\", {\n storage: this.ctx.storage,\n createAuthProvider: (callbackUrl) =>\n this.createMcpOAuthProvider(callbackUrl)\n });\n\n // Broadcast server state whenever MCP state changes (register, connect, OAuth, remove, etc.)\n this._disposables.add(\n this.mcp.onServerStateChanged(async () => {\n this.broadcastMcpServers();\n })\n );\n\n // Emit MCP observability events\n this._disposables.add(\n this.mcp.onObservabilityEvent((event) => {\n this.observability?.emit({\n ...event,\n agent: this._ParentClass.name,\n name: this.name\n });\n })\n );\n // Compute persistence-hook dispatch mode once.\n // Throws immediately if both hooks are overridden on the same class.\n {\n const proto = Object.getPrototypeOf(this);\n const hasOwnNew = Object.prototype.hasOwnProperty.call(\n proto,\n \"onStateChanged\"\n );\n const hasOwnOld = Object.prototype.hasOwnProperty.call(\n proto,\n \"onStateUpdate\"\n );\n\n if (hasOwnNew && hasOwnOld) {\n throw new Error(\n `[Agent] Cannot override both onStateChanged and onStateUpdate. ` +\n `Remove onStateUpdate — it has been renamed to onStateChanged.`\n );\n }\n\n if (hasOwnOld) {\n const ctor = this.constructor;\n if (!_onStateUpdateWarnedClasses.has(ctor)) {\n _onStateUpdateWarnedClasses.add(ctor);\n console.warn(\n `[Agent] onStateUpdate is deprecated. Rename to onStateChanged — the behavior is identical.`\n );\n }\n }\n\n const base = Agent.prototype;\n if (proto.onStateChanged !== base.onStateChanged) {\n this._persistenceHookMode = \"new\";\n } else if (proto.onStateUpdate !== base.onStateUpdate) {\n this._persistenceHookMode = \"old\";\n }\n // default \"none\" already set in field initializer\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 // TODO: make zod/ai sdk more performant and remove this\n // Late initialization of jsonSchemaFn (needed for getAITools)\n await this.mcp.ensureJsonSchema();\n\n // Handle MCP OAuth callback if this is one\n const oauthResponse = await this.handleMcpOAuthCallback(request);\n if (oauthResponse) {\n return oauthResponse;\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 this._ensureConnectionWrapped(connection);\n return agentContext.run(\n { agent: this, connection, request: undefined, email: undefined },\n async () => {\n // TODO: make zod/ai sdk more performant and remove this\n // Late initialization of jsonSchemaFn (needed for getAITools)\n await this.mcp.ensureJsonSchema();\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 // Check if connection is readonly\n if (this.isConnectionReadonly(connection)) {\n // Send error response back to the connection\n connection.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_STATE_ERROR,\n error: \"Connection is readonly\"\n })\n );\n return;\n }\n try {\n this._setStateInternal(parsed.state as State, connection);\n } catch (e) {\n // validateStateChange (or another sync error) rejected the update.\n // Log the full error server-side, send a generic message to the client.\n console.error(\"[Agent] State update rejected:\", e);\n connection.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_STATE_ERROR,\n error: \"State update rejected\"\n })\n );\n }\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\n this._emit(\"rpc\", { method, streaming: true });\n\n try {\n await methodFn.apply(this, [stream, ...args]);\n } catch (err) {\n console.error(`Error in streaming method \"${method}\":`, err);\n this._emit(\"rpc:error\", {\n method,\n error: err instanceof Error ? err.message : String(err)\n });\n // Auto-close stream with error if method throws before closing\n if (!stream.isClosed) {\n stream.error(\n err instanceof Error ? err.message : String(err)\n );\n }\n }\n return;\n }\n\n // For regular methods, execute and send response\n const result = await methodFn.apply(this, args);\n\n this._emit(\"rpc\", { method, streaming: metadata?.streaming });\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 this._emit(\"rpc:error\", {\n method: parsed.method,\n error: e instanceof Error ? e.message : String(e)\n });\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 this._ensureConnectionWrapped(connection);\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 async () => {\n // Check if connection should be readonly before sending any messages\n // so that the flag is set before the client can respond\n if (this.shouldConnectionBeReadonly(connection, ctx)) {\n this.setConnectionReadonly(connection, true);\n }\n\n // Check if protocol messages should be suppressed for this\n // connection. When disabled, no identity/state/MCP text frames\n // are sent — useful for binary-only clients (e.g. MQTT devices).\n if (this.shouldSendProtocolMessages(connection, ctx)) {\n // Send agent identity first so client knows which instance it's connected to\n // Can be disabled via static options for security-sensitive instance names\n if (this._resolvedOptions.sendIdentityOnConnect) {\n const ctor = this.constructor as typeof Agent;\n if (\n ctor.options?.sendIdentityOnConnect === undefined &&\n !_sendIdentityWarnedClasses.has(ctor)\n ) {\n // Only warn when using custom routing — with default routing\n // the name is already visible in the URL path (/agents/{class}/{name})\n // so sendIdentityOnConnect leaks no additional information.\n const urlPath = new URL(ctx.request.url).pathname;\n if (!urlPath.includes(this.name)) {\n _sendIdentityWarnedClasses.add(ctor);\n console.warn(\n `[Agent] ${ctor.name}: sending instance name \"${this.name}\" to clients ` +\n `via sendIdentityOnConnect (the name is not visible in the URL with ` +\n `custom routing). If this name is sensitive, add ` +\n `\\`static options = { sendIdentityOnConnect: false }\\` to opt out. ` +\n `Set it to true to silence this message.`\n );\n }\n }\n connection.send(\n JSON.stringify({\n name: this.name,\n agent: camelCaseToKebabCase(this._ParentClass.name),\n type: MessageType.CF_AGENT_IDENTITY\n })\n );\n }\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 } else {\n this._setConnectionNoProtocol(connection);\n }\n\n this._emit(\"connect\", { connectionId: connection.id });\n return this._tryCatch(() => _onConnect(connection, ctx));\n }\n );\n };\n\n const _onClose = this.onClose.bind(this);\n this.onClose = (\n connection: Connection,\n code: number,\n reason: string,\n wasClean: boolean\n ) => {\n return agentContext.run(\n { agent: this, connection, request: undefined, email: undefined },\n () => {\n this._emit(\"disconnect\", {\n connectionId: connection.id,\n code,\n reason\n });\n return _onClose(connection, code, reason, wasClean);\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(async () => {\n await this.mcp.restoreConnectionsFromStorage(this.name);\n await this._restoreRpcMcpServers();\n this.broadcastMcpServers();\n\n this._checkOrphanedWorkflows();\n\n return _onStart(props);\n });\n }\n );\n };\n }\n\n /**\n * Check for workflows referencing unknown bindings and warn with migration suggestion.\n */\n private _checkOrphanedWorkflows(): void {\n // Get distinct workflow names with counts by active/completed status\n const distinctNames = this.sql<{\n workflow_name: string;\n total: number;\n active: number;\n completed: number;\n }>`\n SELECT \n workflow_name,\n COUNT(*) as total,\n SUM(CASE WHEN status NOT IN ('complete', 'errored', 'terminated') THEN 1 ELSE 0 END) as active,\n SUM(CASE WHEN status IN ('complete', 'errored', 'terminated') THEN 1 ELSE 0 END) as completed\n FROM cf_agents_workflows \n GROUP BY workflow_name\n `;\n\n const orphaned = distinctNames.filter(\n (row) => !this._findWorkflowBindingByName(row.workflow_name)\n );\n\n if (orphaned.length > 0) {\n const currentBindings = this._getWorkflowBindingNames();\n for (const {\n workflow_name: oldName,\n total,\n active,\n completed\n } of orphaned) {\n const suggestion =\n currentBindings.length === 1\n ? `this.migrateWorkflowBinding('${oldName}', '${currentBindings[0]}')`\n : `this.migrateWorkflowBinding('${oldName}', '<NEW_BINDING_NAME>')`;\n const breakdown =\n active > 0 && completed > 0\n ? ` (${active} active, ${completed} completed)`\n : active > 0\n ? ` (${active} active)`\n : ` (${completed} completed)`;\n console.warn(\n `[Agent] Found ${total} workflow(s) referencing unknown binding '${oldName}'${breakdown}. ` +\n `If you renamed the binding, call: ${suggestion}`\n );\n }\n }\n }\n\n /**\n * Broadcast a protocol message only to connections that have protocol\n * messages enabled. Connections where shouldSendProtocolMessages returned\n * false are excluded automatically.\n * @param msg The JSON-encoded protocol message\n * @param excludeIds Additional connection IDs to exclude (e.g. the source)\n */\n private _broadcastProtocol(msg: string, excludeIds: string[] = []) {\n const exclude = [...excludeIds];\n for (const conn of this.getConnections()) {\n if (!this.isConnectionProtocolEnabled(conn)) {\n exclude.push(conn.id);\n }\n }\n this.broadcast(msg, exclude);\n }\n\n private _setStateInternal(\n nextState: State,\n source: Connection | \"server\" = \"server\"\n ): void {\n // Validation/gating hook (sync only)\n this.validateStateChange(nextState, source);\n\n // Persist state\n this._state = nextState;\n this.sql`\n INSERT OR REPLACE INTO cf_agents_state (id, state)\n VALUES (${STATE_ROW_ID}, ${JSON.stringify(nextState)})\n `;\n this.sql`\n INSERT OR REPLACE INTO cf_agents_state (id, state)\n VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})\n `;\n\n // Broadcast state to protocol-enabled connections, excluding the source\n this._broadcastProtocol(\n JSON.stringify({\n state: nextState,\n type: MessageType.CF_AGENT_STATE\n }),\n source !== \"server\" ? [source.id] : []\n );\n\n // Notification hook (non-gating). Run after broadcast and do not block.\n // Use waitUntil for reliability after the handler returns.\n const { connection, request, email } = agentContext.getStore() || {};\n this.ctx.waitUntil(\n (async () => {\n try {\n await agentContext.run(\n { agent: this, connection, request, email },\n async () => {\n this._emit(\"state:update\");\n await this._callStatePersistenceHook(nextState, source);\n }\n );\n } catch (e) {\n // onStateChanged/onStateUpdate errors should not affect state or broadcasts\n try {\n await this.onError(e);\n } catch {\n // swallow\n }\n }\n })()\n );\n }\n\n /**\n * Update the Agent's state\n * @param state New state to set\n * @throws Error if called from a readonly connection context\n */\n setState(state: State): void {\n // Check if the current context has a readonly connection\n const store = agentContext.getStore();\n if (store?.connection && this.isConnectionReadonly(store.connection)) {\n throw new Error(\"Connection is readonly\");\n }\n this._setStateInternal(state, \"server\");\n }\n\n /**\n * Wraps connection.state and connection.setState so that internal\n * _cf_-prefixed flags (readonly, no-protocol) are hidden from user code\n * and cannot be accidentally overwritten.\n *\n * Idempotent — safe to call multiple times on the same connection.\n * After hibernation, the _rawStateAccessors WeakMap is empty but the\n * connection's state getter still reads from the persisted WebSocket\n * attachment. Calling this method re-captures the raw getter so that\n * predicate methods (isConnectionReadonly, isConnectionProtocolEnabled)\n * work correctly post-hibernation.\n */\n private _ensureConnectionWrapped(connection: Connection) {\n if (this._rawStateAccessors.has(connection)) return;\n\n // Determine whether `state` is an accessor (getter) or a data property.\n // partyserver always defines `state` as a getter via Object.defineProperties,\n // but we handle the data-property case to stay robust for hibernate: false\n // and any future connection implementations.\n const descriptor = Object.getOwnPropertyDescriptor(connection, \"state\");\n\n let getRaw: () => Record<string, unknown> | null;\n let setRaw: (state: unknown) => unknown;\n\n if (descriptor?.get) {\n // Accessor property — bind the original getter directly.\n // The getter reads from the serialized WebSocket attachment, so it\n // always returns the latest value even after setState updates it.\n getRaw = descriptor.get.bind(connection) as () => Record<\n string,\n unknown\n > | null;\n setRaw = connection.setState.bind(connection);\n } else {\n // Data property — track raw state in a closure variable.\n // Reading `connection.state` after our override would call our filtered\n // getter (circular), so we snapshot the value here and keep it in sync.\n let rawState = (connection.state ?? null) as Record<\n string,\n unknown\n > | null;\n getRaw = () => rawState;\n setRaw = (state: unknown) => {\n rawState = state as Record<string, unknown> | null;\n return rawState;\n };\n }\n\n this._rawStateAccessors.set(connection, { getRaw, setRaw });\n\n // Override state getter to hide all internal _cf_ flags from user code\n Object.defineProperty(connection, \"state\", {\n configurable: true,\n enumerable: true,\n get() {\n const raw = getRaw();\n if (raw != null && typeof raw === \"object\" && rawHasInternalKeys(raw)) {\n return stripInternalKeys(raw);\n }\n return raw;\n }\n });\n\n // Override setState to preserve internal flags when user sets state\n Object.defineProperty(connection, \"setState\", {\n configurable: true,\n writable: true,\n value(stateOrFn: unknown | ((prev: unknown) => unknown)) {\n const raw = getRaw();\n const flags =\n raw != null && typeof raw === \"object\"\n ? extractInternalFlags(raw as Record<string, unknown>)\n : {};\n const hasFlags = Object.keys(flags).length > 0;\n\n let newUserState: unknown;\n if (typeof stateOrFn === \"function\") {\n // Pass only the user-visible state (without internal flags) to the callback\n const userVisible = hasFlags\n ? stripInternalKeys(raw as Record<string, unknown>)\n : raw;\n newUserState = (stateOrFn as (prev: unknown) => unknown)(userVisible);\n } else {\n newUserState = stateOrFn;\n }\n\n // Merge back internal flags if any were set\n if (hasFlags) {\n if (newUserState != null && typeof newUserState === \"object\") {\n return setRaw({\n ...(newUserState as Record<string, unknown>),\n ...flags\n });\n }\n // User set null — store just the flags\n return setRaw(flags);\n }\n return setRaw(newUserState);\n }\n });\n }\n\n /**\n * Mark a connection as readonly or readwrite\n * @param connection The connection to mark\n * @param readonly Whether the connection should be readonly (default: true)\n */\n setConnectionReadonly(connection: Connection, readonly = true) {\n this._ensureConnectionWrapped(connection);\n const accessors = this._rawStateAccessors.get(connection)!;\n const raw = (accessors.getRaw() as Record<string, unknown> | null) ?? {};\n if (readonly) {\n accessors.setRaw({ ...raw, [CF_READONLY_KEY]: true });\n } else {\n // Remove the key entirely instead of storing false — avoids dead keys\n // accumulating in the connection attachment.\n const { [CF_READONLY_KEY]: _, ...rest } = raw;\n accessors.setRaw(Object.keys(rest).length > 0 ? rest : null);\n }\n }\n\n /**\n * Check if a connection is marked as readonly.\n *\n * Safe to call after hibernation — re-wraps the connection if the\n * in-memory accessor cache was cleared.\n * @param connection The connection to check\n * @returns True if the connection is readonly\n */\n isConnectionReadonly(connection: Connection): boolean {\n this._ensureConnectionWrapped(connection);\n const raw = this._rawStateAccessors.get(connection)!.getRaw() as Record<\n string,\n unknown\n > | null;\n return !!raw?.[CF_READONLY_KEY];\n }\n\n /**\n * Override this method to determine if a connection should be readonly on connect\n * @param _connection The connection that is being established\n * @param _ctx Connection context\n * @returns True if the connection should be readonly\n */\n shouldConnectionBeReadonly(\n _connection: Connection,\n _ctx: ConnectionContext\n ): boolean {\n return false;\n }\n\n /**\n * Override this method to control whether protocol messages are sent to a\n * connection. Protocol messages include identity (CF_AGENT_IDENTITY), state\n * sync (CF_AGENT_STATE), and MCP server lists (CF_AGENT_MCP_SERVERS).\n *\n * When this returns `false` for a connection, that connection will not\n * receive any protocol text frames — neither on connect nor via broadcasts.\n * This is useful for binary-only clients (e.g. MQTT devices) that cannot\n * handle JSON text frames.\n *\n * The connection can still send and receive regular messages, use RPC, and\n * participate in all non-protocol communication.\n *\n * @param _connection The connection that is being established\n * @param _ctx Connection context (includes the upgrade request)\n * @returns True if protocol messages should be sent (default), false to suppress them\n */\n shouldSendProtocolMessages(\n _connection: Connection,\n _ctx: ConnectionContext\n ): boolean {\n return true;\n }\n\n /**\n * Check if a connection has protocol messages enabled.\n * Protocol messages include identity, state sync, and MCP server lists.\n *\n * Safe to call after hibernation — re-wraps the connection if the\n * in-memory accessor cache was cleared.\n * @param connection The connection to check\n * @returns True if the connection receives protocol messages\n */\n isConnectionProtocolEnabled(connection: Connection): boolean {\n this._ensureConnectionWrapped(connection);\n const raw = this._rawStateAccessors.get(connection)!.getRaw() as Record<\n string,\n unknown\n > | null;\n return !raw?.[CF_NO_PROTOCOL_KEY];\n }\n\n /**\n * Mark a connection as having protocol messages disabled.\n * Called internally when shouldSendProtocolMessages returns false.\n */\n private _setConnectionNoProtocol(connection: Connection) {\n this._ensureConnectionWrapped(connection);\n const accessors = this._rawStateAccessors.get(connection)!;\n const raw = (accessors.getRaw() as Record<string, unknown> | null) ?? {};\n accessors.setRaw({ ...raw, [CF_NO_PROTOCOL_KEY]: true });\n }\n\n /**\n * Called before the Agent's state is persisted and broadcast.\n * Override to validate or reject an update by throwing an error.\n *\n * IMPORTANT: This hook must be synchronous.\n */\n // oxlint-disable-next-line eslint(no-unused-vars) -- params used by subclass overrides\n validateStateChange(nextState: State, source: Connection | \"server\") {\n // override this to validate state updates\n }\n\n /**\n * Called after the Agent's state has been persisted and broadcast to all clients.\n * This is a notification hook — errors here are routed to onError and do not\n * affect state persistence or client broadcasts.\n *\n * @param state Updated state\n * @param source Source of the state update (\"server\" or a client connection)\n */\n // oxlint-disable-next-line eslint(no-unused-vars) -- params used by subclass overrides\n onStateChanged(state: State | undefined, source: Connection | \"server\") {\n // override this to handle state updates after persist + broadcast\n }\n\n /**\n * @deprecated Renamed to `onStateChanged` — the behavior is identical.\n * `onStateUpdate` will be removed in the next major version.\n *\n * Called after the Agent's state has been persisted and broadcast to all clients.\n * This is a server-side notification hook. For the client-side state callback,\n * see the `onStateUpdate` option in `useAgent` / `AgentClient`.\n *\n * @param state Updated state\n * @param source Source of the state update (\"server\" or a client connection)\n */\n // oxlint-disable-next-line eslint(no-unused-vars) -- params used by subclass overrides\n onStateUpdate(state: State | undefined, source: Connection | \"server\") {\n // override this to handle state updates (deprecated — use onStateChanged)\n }\n\n /**\n * Dispatch to the appropriate persistence hook based on the mode\n * cached in the constructor. No prototype walks at call time.\n */\n private async _callStatePersistenceHook(\n state: State | undefined,\n source: Connection | \"server\"\n ): Promise<void> {\n switch (this._persistenceHookMode) {\n case \"new\":\n await this.onStateChanged(state, source);\n break;\n case \"old\":\n await this.onStateUpdate(state, source);\n break;\n // \"none\": neither hook overridden — skip\n }\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 this._emit(\"email:receive\", {\n from: email.from,\n to: email.to,\n subject: email.headers.get(\"subject\") ?? undefined\n });\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 * @param options.secret Secret for signing agent headers (enables secure reply routing).\n * Required if the email was routed via createSecureReplyEmailResolver.\n * Pass explicit `null` to opt-out of signing (not recommended for secure routing).\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 secret?: string | null;\n }\n ): Promise<void> {\n return this._tryCatch(async () => {\n // Enforce signing for emails routed via createSecureReplyEmailResolver\n if (email._secureRouted && options.secret === undefined) {\n throw new Error(\n \"This email was routed via createSecureReplyEmailResolver. \" +\n \"You must pass a secret to replyToEmail() to sign replies, \" +\n \"or pass explicit null to opt-out (not recommended).\"\n );\n }\n\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 // Sign headers if secret is provided (enables secure reply routing)\n if (typeof options.secret === \"string\") {\n const signedHeaders = await signAgentHeaders(\n options.secret,\n agentName,\n agentId\n );\n msg.setHeader(\"X-Agent-Sig\", signedHeaders[\"X-Agent-Sig\"]);\n msg.setHeader(\"X-Agent-Sig-Ts\", signedHeaders[\"X-Agent-Sig-Ts\"]);\n }\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 // Emit after the send succeeds — from/to are swapped because\n // this is a reply: the agent (email.to) is now the sender.\n const rawSubject = email.headers.get(\"subject\");\n this._emit(\"email:reply\", {\n from: email.to,\n to: email.from,\n subject:\n options.subject ?? (rawSubject ? `Re: ${rawSubject}` : undefined)\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 /* oxlint-disable @typescript-eslint/no-explicit-any -- dynamic method wrapping requires any */\n const wrappedFunction = withAgentContext(\n this[methodName as keyof this] as (...args: any[]) => any\n ) as any;\n /* oxlint-enable @typescript-eslint/no-explicit-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 * Retry an async operation with exponential backoff and jitter.\n * Retries on all errors by default. Use `shouldRetry` to bail early on non-retryable errors.\n *\n * @param fn The async function to retry. Receives the current attempt number (1-indexed).\n * @param options Retry configuration.\n * @param options.maxAttempts Maximum number of attempts (including the first). Falls back to static options, then 3.\n * @param options.baseDelayMs Base delay in ms for exponential backoff. Falls back to static options, then 100.\n * @param options.maxDelayMs Maximum delay cap in ms. Falls back to static options, then 3000.\n * @param options.shouldRetry Predicate called with the error and next attempt number. Return false to stop retrying immediately. Default: retry all errors.\n * @returns The result of fn on success.\n * @throws The last error if all attempts fail or shouldRetry returns false.\n */\n async retry<T>(\n fn: (attempt: number) => Promise<T>,\n options?: RetryOptions & {\n /** Return false to stop retrying a specific error. Receives the error and the next attempt number. Default: retry all errors. */\n shouldRetry?: (err: unknown, nextAttempt: number) => boolean;\n }\n ): Promise<T> {\n const defaults = this._resolvedOptions.retry;\n if (options) {\n validateRetryOptions(options, defaults);\n }\n return tryN(options?.maxAttempts ?? defaults.maxAttempts, fn, {\n baseDelayMs: options?.baseDelayMs ?? defaults.baseDelayMs,\n maxDelayMs: options?.maxDelayMs ?? defaults.maxDelayMs,\n shouldRetry: options?.shouldRetry\n });\n }\n\n /**\n * Queue a task to be executed in the future\n * @param callback Name of the method to call\n * @param payload Payload to pass to the callback\n * @param options Options for the queued task\n * @param options.retry Retry options for the callback execution\n * @returns The ID of the queued task\n */\n async queue<T = unknown>(\n callback: keyof this,\n payload: T,\n options?: { retry?: RetryOptions }\n ): 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 if (options?.retry) {\n validateRetryOptions(options.retry, this._resolvedOptions.retry);\n }\n\n const retryJson = options?.retry ? JSON.stringify(options.retry) : null;\n\n this.sql`\n INSERT OR REPLACE INTO cf_agents_queues (id, payload, callback, retry_options)\n VALUES (${id}, ${JSON.stringify(payload)}, ${callback}, ${retryJson})\n `;\n\n this._emit(\"queue:create\", { callback: callback as string, id });\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 try {\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 await this.dequeue(row.id);\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 const retryOpts = parseRetryOptions(\n row as unknown as Record<string, unknown>\n );\n const { maxAttempts, baseDelayMs, maxDelayMs } =\n resolveRetryConfig(retryOpts, this._resolvedOptions.retry);\n const parsedPayload = JSON.parse(row.payload as string);\n try {\n await tryN(\n maxAttempts,\n async (attempt) => {\n if (attempt > 1) {\n this._emit(\"queue:retry\", {\n callback: row.callback,\n id: row.id,\n attempt,\n maxAttempts\n });\n }\n await (\n callback as (\n payload: unknown,\n queueItem: QueueItem<string>\n ) => Promise<void>\n ).bind(this)(parsedPayload, row);\n },\n { baseDelayMs, maxDelayMs }\n );\n } catch (e) {\n console.error(\n `queue callback \"${row.callback}\" failed after ${maxAttempts} attempts`,\n e\n );\n this._emit(\"queue:error\", {\n callback: row.callback,\n id: row.id,\n error: e instanceof Error ? e.message : String(e),\n attempts: maxAttempts\n });\n try {\n await this.onError(e);\n } catch {\n // swallow onError errors\n }\n } finally {\n this.dequeue(row.id);\n }\n }\n );\n }\n }\n } finally {\n this._flushingQueue = false;\n }\n }\n\n /**\n * Dequeue a task by ID\n * @param id ID of the task to dequeue\n */\n dequeue(id: string) {\n this.sql`DELETE FROM cf_agents_queues WHERE id = ${id}`;\n }\n\n /**\n * Dequeue all tasks\n */\n 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 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 getQueue(id: string): QueueItem<string> | undefined {\n const result = this.sql<QueueItem<string>>`\n SELECT * FROM cf_agents_queues WHERE id = ${id}\n `;\n if (!result || result.length === 0) return undefined;\n const row = result[0];\n return {\n ...row,\n payload: JSON.parse(row.payload as unknown as string),\n retry: parseRetryOptions(row as unknown as Record<string, unknown>)\n };\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 getQueues(key: string, value: string): QueueItem<string>[] {\n const result = this.sql<QueueItem<string>>`\n SELECT * FROM cf_agents_queues\n `;\n return result\n .filter(\n (row) => JSON.parse(row.payload as unknown as string)[key] === value\n )\n .map((row) => ({\n ...row,\n payload: JSON.parse(row.payload as unknown as string),\n retry: parseRetryOptions(row as unknown as Record<string, unknown>)\n }));\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 * @param options Options for the scheduled task\n * @param options.retry Retry options for the callback execution\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 options?: { retry?: RetryOptions }\n ): Promise<Schedule<T>> {\n const id = nanoid(9);\n\n if (options?.retry) {\n validateRetryOptions(options.retry, this._resolvedOptions.retry);\n }\n\n const retryJson = options?.retry ? JSON.stringify(options.retry) : null;\n\n const emitScheduleCreate = () =>\n this._emit(\"schedule:create\", { callback: callback as string, id });\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, retry_options)\n VALUES (${id}, ${callback}, ${JSON.stringify(\n payload\n )}, 'scheduled', ${timestamp}, ${retryJson})\n `;\n\n await this._scheduleNextAlarm();\n\n const schedule: Schedule<T> = {\n callback: callback,\n id,\n payload: payload as T,\n retry: options?.retry,\n time: timestamp,\n type: \"scheduled\"\n };\n\n emitScheduleCreate();\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, retry_options)\n VALUES (${id}, ${callback}, ${JSON.stringify(\n payload\n )}, 'delayed', ${when}, ${timestamp}, ${retryJson})\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 retry: options?.retry,\n time: timestamp,\n type: \"delayed\"\n };\n\n emitScheduleCreate();\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, retry_options)\n VALUES (${id}, ${callback}, ${JSON.stringify(\n payload\n )}, 'cron', ${when}, ${timestamp}, ${retryJson})\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 retry: options?.retry,\n time: timestamp,\n type: \"cron\"\n };\n\n emitScheduleCreate();\n\n return schedule;\n }\n throw new Error(\n `Invalid schedule type: ${JSON.stringify(when)}(${typeof when}) trying to schedule ${callback}`\n );\n }\n\n /**\n * Schedule a task to run repeatedly at a fixed interval.\n *\n * This method is **idempotent** — calling it multiple times with the same\n * `callback`, `intervalSeconds`, and `payload` returns the existing schedule\n * instead of creating a duplicate. A different interval or payload is\n * treated as a distinct schedule and creates a new row.\n *\n * This makes it safe to call in `onStart()`, which runs on every Durable\n * Object wake:\n *\n * ```ts\n * async onStart() {\n * // Only one schedule is created, no matter how many times the DO wakes\n * await this.scheduleEvery(30, \"tick\");\n * }\n * ```\n *\n * @template T Type of the payload data\n * @param intervalSeconds Number of seconds between executions\n * @param callback Name of the method to call\n * @param payload Data to pass to the callback\n * @param options Options for the scheduled task\n * @param options.retry Retry options for the callback execution\n * @returns Schedule object representing the scheduled task\n */\n async scheduleEvery<T = string>(\n intervalSeconds: number,\n callback: keyof this,\n payload?: T,\n options?: { retry?: RetryOptions; _idempotent?: boolean }\n ): Promise<Schedule<T>> {\n // DO alarms have a max schedule time of 30 days\n const MAX_INTERVAL_SECONDS = 30 * 24 * 60 * 60; // 30 days in seconds\n\n if (typeof intervalSeconds !== \"number\" || intervalSeconds <= 0) {\n throw new Error(\"intervalSeconds must be a positive number\");\n }\n\n if (intervalSeconds > MAX_INTERVAL_SECONDS) {\n throw new Error(\n `intervalSeconds cannot exceed ${MAX_INTERVAL_SECONDS} seconds (30 days)`\n );\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 (options?.retry) {\n validateRetryOptions(options.retry, this._resolvedOptions.retry);\n }\n\n const idempotent = options?._idempotent !== false;\n const payloadJson = JSON.stringify(payload);\n\n // Idempotency: check for an existing interval schedule with the same\n // callback, interval, and payload. A different interval or payload is\n // treated as a distinct schedule and gets its own row.\n if (idempotent) {\n const existing = this.sql<{\n id: string;\n callback: string;\n payload: string;\n type: string;\n time: number;\n intervalSeconds: number;\n retry_options: string | null;\n }>`\n SELECT * FROM cf_agents_schedules\n WHERE type = 'interval'\n AND callback = ${callback}\n AND intervalSeconds = ${intervalSeconds}\n AND payload IS ${payloadJson}\n LIMIT 1\n `;\n\n if (existing.length > 0) {\n const row = existing[0];\n\n // Exact match — return existing schedule as-is (no-op)\n return {\n callback: row.callback,\n id: row.id,\n intervalSeconds: row.intervalSeconds,\n payload: JSON.parse(row.payload) as T,\n retry: parseRetryOptions(row as unknown as Record<string, unknown>),\n time: row.time,\n type: \"interval\"\n };\n }\n }\n\n const id = nanoid(9);\n const time = new Date(Date.now() + intervalSeconds * 1000);\n const timestamp = Math.floor(time.getTime() / 1000);\n\n const retryJson = options?.retry ? JSON.stringify(options.retry) : null;\n\n this.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, intervalSeconds, time, running, retry_options)\n VALUES (${id}, ${callback}, ${payloadJson}, 'interval', ${intervalSeconds}, ${timestamp}, 0, ${retryJson})\n `;\n\n await this._scheduleNextAlarm();\n\n const schedule: Schedule<T> = {\n callback: callback,\n id,\n intervalSeconds,\n payload: payload as T,\n retry: options?.retry,\n time: timestamp,\n type: \"interval\"\n };\n\n this._emit(\"schedule:create\", { callback: callback as string, id });\n\n return schedule;\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 getSchedule<T = string>(id: string): Schedule<T> | undefined {\n const result = this.sql<Schedule<string>>`\n SELECT * FROM cf_agents_schedules WHERE id = ${id}\n `;\n if (!result || result.length === 0) {\n return undefined;\n }\n const row = result[0];\n return {\n ...row,\n payload: JSON.parse(row.payload) as T,\n retry: parseRetryOptions(row as unknown as Record<string, unknown>)\n };\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\" | \"interval\";\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 retry: parseRetryOptions(row as unknown as Record<string, unknown>)\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 if the task was not found\n */\n async cancelSchedule(id: string): Promise<boolean> {\n const schedule = this.getSchedule(id);\n if (!schedule) {\n return false;\n }\n\n this._emit(\"schedule:cancel\", {\n callback: schedule.callback,\n id: schedule.id\n });\n\n this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;\n\n await this._scheduleNextAlarm();\n return true;\n }\n\n /**\n * Keep the Durable Object alive via alarm heartbeats.\n * Returns a disposer function that stops the heartbeat when called.\n *\n * Use this when you have long-running work and need to prevent the\n * DO from going idle (eviction after ~70-140s of inactivity).\n * The heartbeat fires every 30 seconds via the scheduling system.\n *\n * @experimental This API may change between releases.\n *\n * @example\n * ```ts\n * const dispose = await this.keepAlive();\n * try {\n * // ... long-running work ...\n * } finally {\n * dispose();\n * }\n * ```\n */\n async keepAlive(): Promise<() => void> {\n const heartbeatSeconds = Math.ceil(KEEP_ALIVE_INTERVAL_MS / 1000);\n const schedule = await this.scheduleEvery(\n heartbeatSeconds,\n \"_cf_keepAliveHeartbeat\" as keyof this,\n undefined,\n { _idempotent: false }\n );\n\n let disposed = false;\n return () => {\n if (disposed) return;\n disposed = true;\n void this.cancelSchedule(schedule.id);\n };\n }\n\n /**\n * Run an async function while keeping the Durable Object alive.\n * The heartbeat is automatically stopped when the function completes\n * (whether it succeeds or throws).\n *\n * This is the recommended way to use keepAlive — it guarantees cleanup\n * so you cannot forget to dispose the heartbeat.\n *\n * @experimental This API may change between releases.\n *\n * @example\n * ```ts\n * const result = await this.keepAliveWhile(async () => {\n * const data = await longRunningComputation();\n * return data;\n * });\n * ```\n */\n async keepAliveWhile<T>(fn: () => Promise<T>): Promise<T> {\n const dispose = await this.keepAlive();\n try {\n return await fn();\n } finally {\n dispose();\n }\n }\n\n /**\n * Internal no-op callback invoked by the keepAlive heartbeat schedule.\n * Its only purpose is to keep the DO alive — the alarm machinery\n * handles the rest.\n * @internal\n */\n async _cf_keepAliveHeartbeat(): Promise<void> {\n // intentionally empty — the alarm firing is what keeps the DO alive\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 * Override PartyServer's onAlarm hook as a no-op.\n * Agent handles alarm logic directly in the alarm() method override,\n * but super.alarm() calls onAlarm() after #ensureInitialized(),\n * so we suppress the default \"Implement onAlarm\" warning.\n */\n onAlarm(): void {}\n\n /**\n * Method called when an alarm fires.\n * Executes any scheduled tasks that are due.\n *\n * Calls super.alarm() first to ensure PartyServer's #ensureInitialized()\n * runs, which hydrates this.name from storage and calls onStart() if needed.\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 async alarm() {\n // Ensure PartyServer initialization (name hydration, onStart) runs\n // before processing any scheduled tasks.\n await super.alarm();\n\n const now = Math.floor(Date.now() / 1000);\n\n // Get all schedules that should be executed now\n const result = this.sql<\n Schedule<string> & { running?: number; intervalSeconds?: number }\n >`\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\n // Overlap prevention for interval schedules with hung callback detection\n if (row.type === \"interval\" && row.running === 1) {\n const executionStartedAt =\n (row as { execution_started_at?: number }).execution_started_at ??\n 0;\n const hungTimeoutSeconds =\n this._resolvedOptions.hungScheduleTimeoutSeconds;\n const elapsedSeconds = now - executionStartedAt;\n\n if (elapsedSeconds < hungTimeoutSeconds) {\n console.warn(\n `Skipping interval schedule ${row.id}: previous execution still running`\n );\n continue;\n }\n // Previous execution appears hung, force reset and re-execute\n console.warn(\n `Forcing reset of hung interval schedule ${row.id} (started ${elapsedSeconds}s ago)`\n );\n }\n\n // Mark interval as running before execution\n if (row.type === \"interval\") {\n this\n .sql`UPDATE cf_agents_schedules SET running = 1, execution_started_at = ${now} WHERE id = ${row.id}`;\n }\n\n await agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n async () => {\n const retryOpts = parseRetryOptions(\n row as unknown as Record<string, unknown>\n );\n const { maxAttempts, baseDelayMs, maxDelayMs } = resolveRetryConfig(\n retryOpts,\n this._resolvedOptions.retry\n );\n const parsedPayload = JSON.parse(row.payload as string);\n\n try {\n this._emit(\"schedule:execute\", {\n callback: row.callback,\n id: row.id\n });\n\n await tryN(\n maxAttempts,\n async (attempt) => {\n if (attempt > 1) {\n this._emit(\"schedule:retry\", {\n callback: row.callback,\n id: row.id,\n attempt,\n maxAttempts\n });\n }\n await (\n callback as (\n payload: unknown,\n schedule: Schedule<unknown>\n ) => Promise<void>\n ).bind(this)(parsedPayload, row);\n },\n { baseDelayMs, maxDelayMs }\n );\n } catch (e) {\n console.error(\n `error executing callback \"${row.callback}\" after ${maxAttempts} attempts`,\n e\n );\n this._emit(\"schedule:error\", {\n callback: row.callback,\n id: row.id,\n error: e instanceof Error ? e.message : String(e),\n attempts: maxAttempts\n });\n // Route schedule errors through onError for consistency\n try {\n await this.onError(e);\n } catch {\n // swallow onError errors\n }\n }\n }\n );\n\n if (this._destroyed) return;\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 if (row.type === \"interval\") {\n // Reset running flag and schedule next interval execution\n const nextTimestamp =\n Math.floor(Date.now() / 1000) + (row.intervalSeconds ?? 0);\n\n this.sql`\n UPDATE cf_agents_schedules SET running = 0, 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 if (this._destroyed) return;\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_mcp_servers`;\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_queues`;\n this.sql`DROP TABLE IF EXISTS cf_agents_workflows`;\n\n // delete all alarms\n await this.ctx.storage.deleteAlarm();\n await this.ctx.storage.deleteAll();\n\n this._disposables.dispose();\n await this.mcp.dispose();\n\n this._destroyed = true;\n\n // `ctx.abort` throws an uncatchable error, so we yield to the event loop\n // to avoid capturing it and let handlers finish cleaning up\n setTimeout(() => {\n this.ctx.abort(\"destroyed\");\n }, 0);\n\n this._emit(\"destroy\");\n }\n\n /**\n * Check if a method is callable\n * @param method The method name to check\n * @returns True if the method is marked as callable\n */\n private _isCallable(method: string): boolean {\n return callableMetadata.has(this[method as keyof this] as Function);\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 getCallableMethods(): Map<string, CallableMetadata> {\n const result = new Map<string, CallableMetadata>();\n\n // Walk the entire prototype chain to find callable methods from parent classes\n let prototype = Object.getPrototypeOf(this);\n while (prototype && prototype !== Object.prototype) {\n for (const name of Object.getOwnPropertyNames(prototype)) {\n if (name === \"constructor\") continue;\n // Don't override child class methods (first one wins)\n if (result.has(name)) continue;\n\n try {\n const fn = prototype[name];\n if (typeof fn === \"function\") {\n const meta = callableMetadata.get(fn as Function);\n if (meta) {\n result.set(name, meta);\n }\n }\n } catch (e) {\n if (!(e instanceof TypeError)) {\n throw e;\n }\n }\n }\n prototype = Object.getPrototypeOf(prototype);\n }\n\n return result;\n }\n\n // ==========================================\n // Workflow Integration Methods\n // ==========================================\n\n /**\n * Start a workflow and track it in this Agent's database.\n * Automatically injects agent identity into the workflow params.\n *\n * @template P - Type of params to pass to the workflow\n * @param workflowName - Name of the workflow binding in env (e.g., 'MY_WORKFLOW')\n * @param params - Params to pass to the workflow\n * @param options - Optional workflow options\n * @returns The workflow instance ID\n *\n * @example\n * ```typescript\n * const workflowId = await this.runWorkflow(\n * 'MY_WORKFLOW',\n * { taskId: '123', data: 'process this' }\n * );\n * ```\n */\n async runWorkflow<P = unknown>(\n workflowName: WorkflowName<Env>,\n params: P,\n options?: RunWorkflowOptions\n ): Promise<string> {\n // Look up the workflow binding by name\n const workflow = this._findWorkflowBindingByName(workflowName);\n if (!workflow) {\n throw new Error(\n `Workflow binding '${workflowName}' not found in environment`\n );\n }\n\n // Find the binding name for this Agent's namespace\n const agentBindingName =\n options?.agentBinding ?? this._findAgentBindingName();\n if (!agentBindingName) {\n throw new Error(\n \"Could not detect Agent binding name from class name. \" +\n \"Pass it explicitly via options.agentBinding\"\n );\n }\n\n // Generate workflow ID if not provided\n const workflowId = options?.id ?? nanoid();\n\n // Inject agent identity and workflow name into params\n const augmentedParams = {\n ...params,\n __agentName: this.name,\n __agentBinding: agentBindingName,\n __workflowName: workflowName\n };\n\n // Create the workflow instance\n const instance = await workflow.create({\n id: workflowId,\n params: augmentedParams\n });\n\n // Track the workflow in our database\n const id = nanoid();\n const metadataJson = options?.metadata\n ? JSON.stringify(options.metadata)\n : null;\n try {\n this.sql`\n INSERT INTO cf_agents_workflows (id, workflow_id, workflow_name, status, metadata)\n VALUES (${id}, ${instance.id}, ${workflowName}, 'queued', ${metadataJson})\n `;\n } catch (e) {\n if (\n e instanceof Error &&\n e.message.includes(\"UNIQUE constraint failed\")\n ) {\n throw new Error(\n `Workflow with ID \"${workflowId}\" is already being tracked`\n );\n }\n throw e;\n }\n\n this._emit(\"workflow:start\", { workflowId: instance.id, workflowName });\n\n return instance.id;\n }\n\n /**\n * Send an event to a running workflow.\n * The workflow can wait for this event using step.waitForEvent().\n *\n * @param workflowName - Name of the workflow binding in env (e.g., 'MY_WORKFLOW')\n * @param workflowId - ID of the workflow instance\n * @param event - Event to send\n *\n * @example\n * ```typescript\n * await this.sendWorkflowEvent(\n * 'MY_WORKFLOW',\n * workflowId,\n * { type: 'approval', payload: { approved: true } }\n * );\n * ```\n */\n async sendWorkflowEvent(\n workflowName: WorkflowName<Env>,\n workflowId: string,\n event: WorkflowEventPayload\n ): Promise<void> {\n const workflow = this._findWorkflowBindingByName(workflowName);\n if (!workflow) {\n throw new Error(\n `Workflow binding '${workflowName}' not found in environment`\n );\n }\n\n const instance = await workflow.get(workflowId);\n await tryN(3, async () => instance.sendEvent(event), {\n shouldRetry: isErrorRetryable,\n baseDelayMs: 200,\n maxDelayMs: 3000\n });\n\n this._emit(\"workflow:event\", { workflowId, eventType: event.type });\n }\n\n /**\n * Approve a waiting workflow.\n * Sends an approval event to the workflow that can be received by waitForApproval().\n *\n * @param workflowId - ID of the workflow to approve\n * @param data - Optional approval data (reason, metadata)\n *\n * @example\n * ```typescript\n * await this.approveWorkflow(workflowId, {\n * reason: 'Approved by admin',\n * metadata: { approvedBy: userId }\n * });\n * ```\n */\n async approveWorkflow(\n workflowId: string,\n data?: { reason?: string; metadata?: Record<string, unknown> }\n ): Promise<void> {\n const workflowInfo = this.getWorkflow(workflowId);\n if (!workflowInfo) {\n throw new Error(`Workflow ${workflowId} not found in tracking table`);\n }\n\n await this.sendWorkflowEvent(\n workflowInfo.workflowName as WorkflowName<Env>,\n workflowId,\n {\n type: \"approval\",\n payload: {\n approved: true,\n reason: data?.reason,\n metadata: data?.metadata\n }\n }\n );\n\n this._emit(\"workflow:approved\", { workflowId, reason: data?.reason });\n }\n\n /**\n * Reject a waiting workflow.\n * Sends a rejection event to the workflow that will cause waitForApproval() to throw.\n *\n * @param workflowId - ID of the workflow to reject\n * @param data - Optional rejection data (reason)\n *\n * @example\n * ```typescript\n * await this.rejectWorkflow(workflowId, {\n * reason: 'Request denied by admin'\n * });\n * ```\n */\n async rejectWorkflow(\n workflowId: string,\n data?: { reason?: string }\n ): Promise<void> {\n const workflowInfo = this.getWorkflow(workflowId);\n if (!workflowInfo) {\n throw new Error(`Workflow ${workflowId} not found in tracking table`);\n }\n\n await this.sendWorkflowEvent(\n workflowInfo.workflowName as WorkflowName<Env>,\n workflowId,\n {\n type: \"approval\",\n payload: {\n approved: false,\n reason: data?.reason\n }\n }\n );\n\n this._emit(\"workflow:rejected\", { workflowId, reason: data?.reason });\n }\n\n /**\n * Terminate a running workflow.\n * This immediately stops the workflow and sets its status to \"terminated\".\n *\n * @param workflowId - ID of the workflow to terminate (must be tracked via runWorkflow)\n * @throws Error if workflow not found in tracking table\n * @throws Error if workflow binding not found in environment\n * @throws Error if workflow is already completed/errored/terminated (from Cloudflare)\n *\n * @note `terminate()` is not yet supported in local development (wrangler dev).\n * It will throw an error locally but works when deployed to Cloudflare.\n *\n * @example\n * ```typescript\n * await this.terminateWorkflow(workflowId);\n * ```\n */\n async terminateWorkflow(workflowId: string): Promise<void> {\n const workflowInfo = this.getWorkflow(workflowId);\n if (!workflowInfo) {\n throw new Error(`Workflow ${workflowId} not found in tracking table`);\n }\n\n const workflow = this._findWorkflowBindingByName(\n workflowInfo.workflowName as WorkflowName<Env>\n );\n if (!workflow) {\n throw new Error(\n `Workflow binding '${workflowInfo.workflowName}' not found in environment`\n );\n }\n\n const instance = await workflow.get(workflowId);\n try {\n await tryN(3, async () => instance.terminate(), {\n shouldRetry: isErrorRetryable,\n baseDelayMs: 200,\n maxDelayMs: 3000\n });\n } catch (err) {\n if (err instanceof Error && err.message.includes(\"Not implemented\")) {\n throw new Error(\n \"terminateWorkflow() is not supported in local development. \" +\n \"Deploy to Cloudflare to use this feature. \" +\n \"Follow https://github.com/cloudflare/agents/issues/823 for details and updates.\"\n );\n }\n throw err;\n }\n\n // Update tracking table with new status\n const status = await instance.status();\n this._updateWorkflowTracking(workflowId, status);\n\n this._emit(\"workflow:terminated\", {\n workflowId,\n workflowName: workflowInfo.workflowName\n });\n }\n\n /**\n * Pause a running workflow.\n * The workflow can be resumed later with resumeWorkflow().\n *\n * @param workflowId - ID of the workflow to pause (must be tracked via runWorkflow)\n * @throws Error if workflow not found in tracking table\n * @throws Error if workflow binding not found in environment\n * @throws Error if workflow is not running (from Cloudflare)\n *\n * @note `pause()` is not yet supported in local development (wrangler dev).\n * It will throw an error locally but works when deployed to Cloudflare.\n *\n * @example\n * ```typescript\n * await this.pauseWorkflow(workflowId);\n * ```\n */\n async pauseWorkflow(workflowId: string): Promise<void> {\n const workflowInfo = this.getWorkflow(workflowId);\n if (!workflowInfo) {\n throw new Error(`Workflow ${workflowId} not found in tracking table`);\n }\n\n const workflow = this._findWorkflowBindingByName(\n workflowInfo.workflowName as WorkflowName<Env>\n );\n if (!workflow) {\n throw new Error(\n `Workflow binding '${workflowInfo.workflowName}' not found in environment`\n );\n }\n\n const instance = await workflow.get(workflowId);\n try {\n await tryN(3, async () => instance.pause(), {\n shouldRetry: isErrorRetryable,\n baseDelayMs: 200,\n maxDelayMs: 3000\n });\n } catch (err) {\n if (err instanceof Error && err.message.includes(\"Not implemented\")) {\n throw new Error(\n \"pauseWorkflow() is not supported in local development. \" +\n \"Deploy to Cloudflare to use this feature. \" +\n \"Follow https://github.com/cloudflare/agents/issues/823 for details and updates.\"\n );\n }\n throw err;\n }\n\n const status = await instance.status();\n this._updateWorkflowTracking(workflowId, status);\n\n this._emit(\"workflow:paused\", {\n workflowId,\n workflowName: workflowInfo.workflowName\n });\n }\n\n /**\n * Resume a paused workflow.\n *\n * @param workflowId - ID of the workflow to resume (must be tracked via runWorkflow)\n * @throws Error if workflow not found in tracking table\n * @throws Error if workflow binding not found in environment\n * @throws Error if workflow is not paused (from Cloudflare)\n *\n * @note `resume()` is not yet supported in local development (wrangler dev).\n * It will throw an error locally but works when deployed to Cloudflare.\n *\n * @example\n * ```typescript\n * await this.resumeWorkflow(workflowId);\n * ```\n */\n async resumeWorkflow(workflowId: string): Promise<void> {\n const workflowInfo = this.getWorkflow(workflowId);\n if (!workflowInfo) {\n throw new Error(`Workflow ${workflowId} not found in tracking table`);\n }\n\n const workflow = this._findWorkflowBindingByName(\n workflowInfo.workflowName as WorkflowName<Env>\n );\n if (!workflow) {\n throw new Error(\n `Workflow binding '${workflowInfo.workflowName}' not found in environment`\n );\n }\n\n const instance = await workflow.get(workflowId);\n try {\n await tryN(3, async () => instance.resume(), {\n shouldRetry: isErrorRetryable,\n baseDelayMs: 200,\n maxDelayMs: 3000\n });\n } catch (err) {\n if (err instanceof Error && err.message.includes(\"Not implemented\")) {\n throw new Error(\n \"resumeWorkflow() is not supported in local development. \" +\n \"Deploy to Cloudflare to use this feature. \" +\n \"Follow https://github.com/cloudflare/agents/issues/823 for details and updates.\"\n );\n }\n throw err;\n }\n\n const status = await instance.status();\n this._updateWorkflowTracking(workflowId, status);\n\n this._emit(\"workflow:resumed\", {\n workflowId,\n workflowName: workflowInfo.workflowName\n });\n }\n\n /**\n * Restart a workflow instance.\n * This re-runs the workflow from the beginning with the same ID.\n *\n * @param workflowId - ID of the workflow to restart (must be tracked via runWorkflow)\n * @param options - Optional settings\n * @param options.resetTracking - If true (default), resets created_at and clears error fields.\n * If false, preserves original timestamps.\n * @throws Error if workflow not found in tracking table\n * @throws Error if workflow binding not found in environment\n *\n * @note `restart()` is not yet supported in local development (wrangler dev).\n * It will throw an error locally but works when deployed to Cloudflare.\n *\n * @example\n * ```typescript\n * // Reset tracking (default)\n * await this.restartWorkflow(workflowId);\n *\n * // Preserve original timestamps\n * await this.restartWorkflow(workflowId, { resetTracking: false });\n * ```\n */\n async restartWorkflow(\n workflowId: string,\n options: { resetTracking?: boolean } = {}\n ): Promise<void> {\n const { resetTracking = true } = options;\n\n const workflowInfo = this.getWorkflow(workflowId);\n if (!workflowInfo) {\n throw new Error(`Workflow ${workflowId} not found in tracking table`);\n }\n\n const workflow = this._findWorkflowBindingByName(\n workflowInfo.workflowName as WorkflowName<Env>\n );\n if (!workflow) {\n throw new Error(\n `Workflow binding '${workflowInfo.workflowName}' not found in environment`\n );\n }\n\n const instance = await workflow.get(workflowId);\n try {\n await tryN(3, async () => instance.restart(), {\n shouldRetry: isErrorRetryable,\n baseDelayMs: 200,\n maxDelayMs: 3000\n });\n } catch (err) {\n if (err instanceof Error && err.message.includes(\"Not implemented\")) {\n throw new Error(\n \"restartWorkflow() is not supported in local development. \" +\n \"Deploy to Cloudflare to use this feature. \" +\n \"Follow https://github.com/cloudflare/agents/issues/823 for details and updates.\"\n );\n }\n throw err;\n }\n\n if (resetTracking) {\n // Reset tracking fields for fresh start\n const now = Math.floor(Date.now() / 1000);\n this.sql`\n UPDATE cf_agents_workflows\n SET status = 'queued',\n created_at = ${now},\n updated_at = ${now},\n completed_at = NULL,\n error_name = NULL,\n error_message = NULL\n WHERE workflow_id = ${workflowId}\n `;\n } else {\n // Just update status from Cloudflare\n const status = await instance.status();\n this._updateWorkflowTracking(workflowId, status);\n }\n\n this._emit(\"workflow:restarted\", {\n workflowId,\n workflowName: workflowInfo.workflowName\n });\n }\n\n /**\n * Find a workflow binding by its name.\n */\n private _findWorkflowBindingByName(\n workflowName: string\n ): Workflow | undefined {\n const binding = (this.env as Record<string, unknown>)[workflowName];\n if (\n binding &&\n typeof binding === \"object\" &&\n \"create\" in binding &&\n \"get\" in binding\n ) {\n return binding as Workflow;\n }\n return undefined;\n }\n\n /**\n * Get all workflow binding names from the environment.\n */\n private _getWorkflowBindingNames(): string[] {\n const names: string[] = [];\n for (const [key, value] of Object.entries(\n this.env as Record<string, unknown>\n )) {\n if (\n value &&\n typeof value === \"object\" &&\n \"create\" in value &&\n \"get\" in value\n ) {\n names.push(key);\n }\n }\n return names;\n }\n\n /**\n * Get the status of a workflow and update the tracking record.\n *\n * @param workflowName - Name of the workflow binding in env (e.g., 'MY_WORKFLOW')\n * @param workflowId - ID of the workflow instance\n * @returns The workflow status\n */\n async getWorkflowStatus(\n workflowName: WorkflowName<Env>,\n workflowId: string\n ): Promise<InstanceStatus> {\n const workflow = this._findWorkflowBindingByName(workflowName);\n if (!workflow) {\n throw new Error(\n `Workflow binding '${workflowName}' not found in environment`\n );\n }\n\n const instance = await workflow.get(workflowId);\n const status = await instance.status();\n\n // Update the tracking record\n this._updateWorkflowTracking(workflowId, status);\n\n return status;\n }\n\n /**\n * Get a tracked workflow by ID.\n *\n * @param workflowId - Workflow instance ID\n * @returns Workflow info or undefined if not found\n */\n getWorkflow(workflowId: string): WorkflowInfo | undefined {\n const rows = this.sql<WorkflowTrackingRow>`\n SELECT * FROM cf_agents_workflows WHERE workflow_id = ${workflowId}\n `;\n\n if (!rows || rows.length === 0) {\n return undefined;\n }\n\n return this._rowToWorkflowInfo(rows[0]);\n }\n\n /**\n * Query tracked workflows with cursor-based pagination.\n *\n * @param criteria - Query criteria including optional cursor for pagination\n * @returns WorkflowPage with workflows, total count, and next cursor\n *\n * @example\n * ```typescript\n * // First page\n * const page1 = this.getWorkflows({ status: 'running', limit: 20 });\n *\n * // Next page\n * if (page1.nextCursor) {\n * const page2 = this.getWorkflows({\n * status: 'running',\n * limit: 20,\n * cursor: page1.nextCursor\n * });\n * }\n * ```\n */\n getWorkflows(criteria: WorkflowQueryCriteria = {}): WorkflowPage {\n const limit = Math.min(criteria.limit ?? 50, 100);\n const isAsc = criteria.orderBy === \"asc\";\n\n // Get total count (ignores cursor and limit)\n const total = this._countWorkflows(criteria);\n\n // Build base query\n let query = \"SELECT * FROM cf_agents_workflows WHERE 1=1\";\n const params: (string | number | boolean)[] = [];\n\n if (criteria.status) {\n const statuses = Array.isArray(criteria.status)\n ? criteria.status\n : [criteria.status];\n const placeholders = statuses.map(() => \"?\").join(\", \");\n query += ` AND status IN (${placeholders})`;\n params.push(...statuses);\n }\n\n if (criteria.workflowName) {\n query += \" AND workflow_name = ?\";\n params.push(criteria.workflowName);\n }\n\n if (criteria.metadata) {\n for (const [key, value] of Object.entries(criteria.metadata)) {\n query += ` AND json_extract(metadata, '$.' || ?) = ?`;\n params.push(key, value);\n }\n }\n\n // Apply cursor for keyset pagination\n if (criteria.cursor) {\n const cursor = this._decodeCursor(criteria.cursor);\n if (isAsc) {\n // ASC: get items after cursor\n query +=\n \" AND (created_at > ? OR (created_at = ? AND workflow_id > ?))\";\n } else {\n // DESC: get items before cursor\n query +=\n \" AND (created_at < ? OR (created_at = ? AND workflow_id < ?))\";\n }\n params.push(cursor.createdAt, cursor.createdAt, cursor.workflowId);\n }\n\n // Order by created_at and workflow_id for consistent keyset pagination\n query += ` ORDER BY created_at ${isAsc ? \"ASC\" : \"DESC\"}, workflow_id ${isAsc ? \"ASC\" : \"DESC\"}`;\n\n // Fetch limit + 1 to detect if there are more pages\n query += \" LIMIT ?\";\n params.push(limit + 1);\n\n const rows = this.ctx.storage.sql\n .exec(query, ...params)\n .toArray() as WorkflowTrackingRow[];\n\n const hasMore = rows.length > limit;\n const resultRows = hasMore ? rows.slice(0, limit) : rows;\n const workflows = resultRows.map((row) => this._rowToWorkflowInfo(row));\n\n // Build next cursor from last item\n const nextCursor =\n hasMore && workflows.length > 0\n ? this._encodeCursor(workflows[workflows.length - 1])\n : null;\n\n return { workflows, total, nextCursor };\n }\n\n /**\n * Count workflows matching criteria (for pagination total).\n */\n private _countWorkflows(\n criteria: Omit<WorkflowQueryCriteria, \"limit\" | \"cursor\" | \"orderBy\"> & {\n createdBefore?: Date;\n }\n ): number {\n let query = \"SELECT COUNT(*) as count FROM cf_agents_workflows WHERE 1=1\";\n const params: (string | number | boolean)[] = [];\n\n if (criteria.status) {\n const statuses = Array.isArray(criteria.status)\n ? criteria.status\n : [criteria.status];\n const placeholders = statuses.map(() => \"?\").join(\", \");\n query += ` AND status IN (${placeholders})`;\n params.push(...statuses);\n }\n\n if (criteria.workflowName) {\n query += \" AND workflow_name = ?\";\n params.push(criteria.workflowName);\n }\n\n if (criteria.metadata) {\n for (const [key, value] of Object.entries(criteria.metadata)) {\n query += ` AND json_extract(metadata, '$.' || ?) = ?`;\n params.push(key, value);\n }\n }\n\n if (criteria.createdBefore) {\n query += \" AND created_at < ?\";\n params.push(Math.floor(criteria.createdBefore.getTime() / 1000));\n }\n\n const result = this.ctx.storage.sql.exec(query, ...params).toArray() as {\n count: number;\n }[];\n\n return result[0]?.count ?? 0;\n }\n\n /**\n * Encode a cursor from workflow info for pagination.\n * Stores createdAt as Unix timestamp in seconds (matching DB storage).\n */\n private _encodeCursor(workflow: WorkflowInfo): string {\n return btoa(\n JSON.stringify({\n c: Math.floor(workflow.createdAt.getTime() / 1000),\n i: workflow.workflowId\n })\n );\n }\n\n /**\n * Decode a pagination cursor.\n * Returns createdAt as Unix timestamp in seconds (matching DB storage).\n */\n private _decodeCursor(cursor: string): {\n createdAt: number;\n workflowId: string;\n } {\n try {\n const data = JSON.parse(atob(cursor));\n if (typeof data.c !== \"number\" || typeof data.i !== \"string\") {\n throw new Error(\"Invalid cursor structure\");\n }\n return { createdAt: data.c, workflowId: data.i };\n } catch {\n throw new Error(\n \"Invalid pagination cursor. The cursor may be malformed or corrupted.\"\n );\n }\n }\n\n /**\n * Delete a workflow tracking record.\n *\n * @param workflowId - ID of the workflow to delete\n * @returns true if a record was deleted, false if not found\n */\n deleteWorkflow(workflowId: string): boolean {\n // First check if workflow exists\n const existing = this.sql<{ count: number }>`\n SELECT COUNT(*) as count FROM cf_agents_workflows WHERE workflow_id = ${workflowId}\n `;\n if (!existing[0] || existing[0].count === 0) {\n return false;\n }\n this.sql`DELETE FROM cf_agents_workflows WHERE workflow_id = ${workflowId}`;\n return true;\n }\n\n /**\n * Delete workflow tracking records matching criteria.\n * Useful for cleaning up old completed/errored workflows.\n *\n * @param criteria - Criteria for which workflows to delete\n * @returns Number of records matching criteria (expected deleted count)\n *\n * @example\n * ```typescript\n * // Delete all completed workflows created more than 7 days ago\n * const deleted = this.deleteWorkflows({\n * status: 'complete',\n * createdBefore: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)\n * });\n *\n * // Delete all errored and terminated workflows\n * const deleted = this.deleteWorkflows({\n * status: ['errored', 'terminated']\n * });\n * ```\n */\n deleteWorkflows(\n criteria: Omit<WorkflowQueryCriteria, \"limit\" | \"orderBy\"> & {\n createdBefore?: Date;\n } = {}\n ): number {\n let query = \"DELETE FROM cf_agents_workflows WHERE 1=1\";\n const params: (string | number | boolean)[] = [];\n\n if (criteria.status) {\n const statuses = Array.isArray(criteria.status)\n ? criteria.status\n : [criteria.status];\n const placeholders = statuses.map(() => \"?\").join(\", \");\n query += ` AND status IN (${placeholders})`;\n params.push(...statuses);\n }\n\n if (criteria.workflowName) {\n query += \" AND workflow_name = ?\";\n params.push(criteria.workflowName);\n }\n\n if (criteria.metadata) {\n for (const [key, value] of Object.entries(criteria.metadata)) {\n query += ` AND json_extract(metadata, '$.' || ?) = ?`;\n params.push(key, value);\n }\n }\n\n if (criteria.createdBefore) {\n query += \" AND created_at < ?\";\n params.push(Math.floor(criteria.createdBefore.getTime() / 1000));\n }\n\n const cursor = this.ctx.storage.sql.exec(query, ...params);\n return cursor.rowsWritten;\n }\n\n /**\n * Migrate workflow tracking records from an old binding name to a new one.\n * Use this after renaming a workflow binding in wrangler.toml.\n *\n * @param oldName - Previous workflow binding name\n * @param newName - New workflow binding name\n * @returns Number of records migrated\n *\n * @example\n * ```typescript\n * // After renaming OLD_WORKFLOW to NEW_WORKFLOW in wrangler.toml\n * async onStart() {\n * const migrated = this.migrateWorkflowBinding('OLD_WORKFLOW', 'NEW_WORKFLOW');\n * }\n * ```\n */\n migrateWorkflowBinding(oldName: string, newName: string): number {\n // Validate new binding exists\n if (!this._findWorkflowBindingByName(newName)) {\n throw new Error(`Workflow binding '${newName}' not found in environment`);\n }\n\n const result = this.sql<{ count: number }>`\n SELECT COUNT(*) as count FROM cf_agents_workflows WHERE workflow_name = ${oldName}\n `;\n const count = result[0]?.count ?? 0;\n\n if (count > 0) {\n this\n .sql`UPDATE cf_agents_workflows SET workflow_name = ${newName} WHERE workflow_name = ${oldName}`;\n console.log(\n `[Agent] Migrated ${count} workflow(s) from '${oldName}' to '${newName}'`\n );\n }\n\n return count;\n }\n\n /**\n * Update workflow tracking record from InstanceStatus\n */\n private _updateWorkflowTracking(\n workflowId: string,\n status: InstanceStatus\n ): void {\n const statusName = status.status;\n const now = Math.floor(Date.now() / 1000);\n\n // Determine if workflow is complete\n const completedStatuses: WorkflowStatus[] = [\n \"complete\",\n \"errored\",\n \"terminated\"\n ];\n const completedAt = completedStatuses.includes(statusName) ? now : null;\n\n // Extract error info if present\n const errorName = status.error?.name ?? null;\n const errorMessage = status.error?.message ?? null;\n\n this.sql`\n UPDATE cf_agents_workflows\n SET status = ${statusName},\n error_name = ${errorName},\n error_message = ${errorMessage},\n updated_at = ${now},\n completed_at = ${completedAt}\n WHERE workflow_id = ${workflowId}\n `;\n }\n\n /**\n * Convert a database row to WorkflowInfo\n */\n private _rowToWorkflowInfo(row: WorkflowTrackingRow): WorkflowInfo {\n return {\n id: row.id,\n workflowId: row.workflow_id,\n workflowName: row.workflow_name,\n status: row.status,\n metadata: row.metadata ? JSON.parse(row.metadata) : null,\n error: row.error_name\n ? { name: row.error_name, message: row.error_message ?? \"\" }\n : null,\n createdAt: new Date(row.created_at * 1000),\n updatedAt: new Date(row.updated_at * 1000),\n completedAt: row.completed_at ? new Date(row.completed_at * 1000) : null\n };\n }\n\n /**\n * Find the binding name for this Agent's namespace by matching class name.\n * Returns undefined if no match found - use options.agentBinding as fallback.\n */\n private _findAgentBindingName(): string | undefined {\n const className = this._ParentClass.name;\n for (const [key, value] of Object.entries(\n this.env as Record<string, unknown>\n )) {\n if (\n value &&\n typeof value === \"object\" &&\n \"idFromName\" in value &&\n typeof value.idFromName === \"function\"\n ) {\n // Check if this namespace's binding name matches our class name\n if (\n key === className ||\n camelCaseToKebabCase(key) === camelCaseToKebabCase(className)\n ) {\n return key;\n }\n }\n }\n return undefined;\n }\n\n private _findBindingNameForNamespace(\n namespace: DurableObjectNamespace<McpAgent>\n ): string | undefined {\n for (const [key, value] of Object.entries(\n this.env as Record<string, unknown>\n )) {\n if (value === namespace) {\n return key;\n }\n }\n return undefined;\n }\n\n private async _restoreRpcMcpServers(): Promise<void> {\n const rpcServers = this.mcp.getRpcServersFromStorage();\n for (const server of rpcServers) {\n if (this.mcp.mcpConnections[server.id]) {\n continue;\n }\n\n const opts: { bindingName: string; props?: Record<string, unknown> } =\n server.server_options ? JSON.parse(server.server_options) : {};\n\n const namespace = (this.env as Record<string, unknown>)[\n opts.bindingName\n ] as DurableObjectNamespace<McpAgent> | undefined;\n if (!namespace) {\n console.warn(\n `[Agent] Cannot restore RPC MCP server \"${server.name}\": binding \"${opts.bindingName}\" not found in env`\n );\n continue;\n }\n\n const normalizedName = server.server_url.replace(RPC_DO_PREFIX, \"\");\n\n try {\n await this.mcp.connect(`${RPC_DO_PREFIX}${normalizedName}`, {\n reconnect: { id: server.id },\n transport: {\n type: \"rpc\" as TransportType,\n namespace,\n name: normalizedName,\n props: opts.props\n }\n });\n\n const conn = this.mcp.mcpConnections[server.id];\n if (conn && conn.connectionState === MCPConnectionState.CONNECTED) {\n await this.mcp.discoverIfConnected(server.id);\n }\n } catch (error) {\n console.error(\n `[Agent] Error restoring RPC MCP server \"${server.name}\":`,\n error\n );\n }\n }\n }\n\n // ==========================================\n // Workflow Lifecycle Callbacks\n // ==========================================\n\n /**\n * Handle a callback from a workflow.\n * Called when the Agent receives a callback at /_workflow/callback.\n * Override this to handle all callback types in one place.\n *\n * @param callback - The callback payload\n */\n async onWorkflowCallback(callback: WorkflowCallback): Promise<void> {\n const now = Math.floor(Date.now() / 1000);\n\n switch (callback.type) {\n case \"progress\":\n // Update tracking status to \"running\" when receiving progress\n // Only transition from queued/waiting to avoid overwriting terminal states\n this.sql`\n UPDATE cf_agents_workflows\n SET status = 'running', updated_at = ${now}\n WHERE workflow_id = ${callback.workflowId} AND status IN ('queued', 'waiting')\n `;\n await this.onWorkflowProgress(\n callback.workflowName,\n callback.workflowId,\n callback.progress\n );\n break;\n case \"complete\":\n // Update tracking status to \"complete\"\n // Don't overwrite if already terminated/paused (race condition protection)\n this.sql`\n UPDATE cf_agents_workflows\n SET status = 'complete', updated_at = ${now}, completed_at = ${now}\n WHERE workflow_id = ${callback.workflowId}\n AND status NOT IN ('terminated', 'paused')\n `;\n await this.onWorkflowComplete(\n callback.workflowName,\n callback.workflowId,\n callback.result\n );\n break;\n case \"error\":\n // Update tracking status to \"errored\"\n // Don't overwrite if already terminated/paused (race condition protection)\n this.sql`\n UPDATE cf_agents_workflows\n SET status = 'errored', updated_at = ${now}, completed_at = ${now},\n error_name = 'WorkflowError', error_message = ${callback.error}\n WHERE workflow_id = ${callback.workflowId}\n AND status NOT IN ('terminated', 'paused')\n `;\n await this.onWorkflowError(\n callback.workflowName,\n callback.workflowId,\n callback.error\n );\n break;\n case \"event\":\n // No status change for events - they can occur at any stage\n await this.onWorkflowEvent(\n callback.workflowName,\n callback.workflowId,\n callback.event\n );\n break;\n }\n }\n\n /**\n * Called when a workflow reports progress.\n * Override to handle progress updates.\n *\n * @param workflowName - Workflow binding name\n * @param workflowId - ID of the workflow\n * @param progress - Typed progress data (default: DefaultProgress)\n */\n async onWorkflowProgress(\n _workflowName: string,\n _workflowId: string,\n _progress: unknown\n ): Promise<void> {\n // Override to handle progress updates\n }\n\n /**\n * Called when a workflow completes successfully.\n * Override to handle completion.\n *\n * @param workflowName - Workflow binding name\n * @param workflowId - ID of the workflow\n * @param result - Optional result data\n */\n async onWorkflowComplete(\n _workflowName: string,\n _workflowId: string,\n _result?: unknown\n ): Promise<void> {\n // Override to handle completion\n }\n\n /**\n * Called when a workflow encounters an error.\n * Override to handle errors.\n *\n * @param workflowName - Workflow binding name\n * @param workflowId - ID of the workflow\n * @param error - Error message\n */\n async onWorkflowError(\n _workflowName: string,\n _workflowId: string,\n _error: string\n ): Promise<void> {\n // Override to handle errors\n }\n\n /**\n * Called when a workflow sends a custom event.\n * Override to handle custom events.\n *\n * @param workflowName - Workflow binding name\n * @param workflowId - ID of the workflow\n * @param event - Custom event payload\n */\n async onWorkflowEvent(\n _workflowName: string,\n _workflowId: string,\n _event: unknown\n ): Promise<void> {\n // Override to handle custom events\n }\n\n // ============================================================\n // Internal RPC methods for AgentWorkflow communication\n // These are called via DO RPC, not exposed via HTTP\n // ============================================================\n\n /**\n * Handle a workflow callback via RPC.\n * @internal - Called by AgentWorkflow, do not call directly\n */\n async _workflow_handleCallback(callback: WorkflowCallback): Promise<void> {\n await this.__unsafe_ensureInitialized();\n await this.onWorkflowCallback(callback);\n }\n\n /**\n * Broadcast a message to all connected clients via RPC.\n * @internal - Called by AgentWorkflow, do not call directly\n */\n async _workflow_broadcast(message: unknown): Promise<void> {\n await this.__unsafe_ensureInitialized();\n this.broadcast(JSON.stringify(message));\n }\n\n /**\n * Update agent state via RPC.\n * @internal - Called by AgentWorkflow, do not call directly\n */\n async _workflow_updateState(\n action: \"set\" | \"merge\" | \"reset\",\n state?: unknown\n ): Promise<void> {\n await this.__unsafe_ensureInitialized();\n if (action === \"set\") {\n this.setState(state as State);\n } else if (action === \"merge\") {\n const currentState = this.state ?? ({} as State);\n this.setState({\n ...currentState,\n ...(state as Record<string, unknown>)\n } as State);\n } else if (action === \"reset\") {\n this.setState(this.initialState);\n }\n }\n\n /**\n * Connect to a new MCP Server via RPC (Durable Object binding)\n *\n * The binding name and props are persisted to storage so the connection\n * is automatically restored after Durable Object hibernation.\n *\n * @example\n * await this.addMcpServer(\"counter\", env.MY_MCP);\n * await this.addMcpServer(\"counter\", env.MY_MCP, { props: { userId: \"123\" } });\n */\n async addMcpServer<T extends McpAgent>(\n serverName: string,\n binding: DurableObjectNamespace<T>,\n options?: AddRpcMcpServerOptions\n ): Promise<{ id: string; state: typeof MCPConnectionState.READY }>;\n\n /**\n * Connect to a new MCP Server via HTTP (SSE or Streamable HTTP)\n *\n * @example\n * await this.addMcpServer(\"github\", \"https://mcp.github.com\");\n * await this.addMcpServer(\"github\", \"https://mcp.github.com\", { transport: { type: \"sse\" } });\n * await this.addMcpServer(\"github\", url, callbackHost, agentsPrefix, options); // legacy\n */\n async addMcpServer(\n serverName: string,\n url: string,\n callbackHostOrOptions?: string | AddMcpServerOptions,\n agentsPrefix?: string,\n options?: {\n client?: ConstructorParameters<typeof Client>[1];\n transport?: { headers?: HeadersInit; type?: TransportType };\n }\n ): Promise<\n | {\n id: string;\n state: typeof MCPConnectionState.AUTHENTICATING;\n authUrl: string;\n }\n | { id: string; state: typeof MCPConnectionState.READY }\n >;\n\n async addMcpServer<T extends McpAgent>(\n serverName: string,\n urlOrBinding: string | DurableObjectNamespace<T>,\n callbackHostOrOptions?:\n | string\n | AddMcpServerOptions\n | AddRpcMcpServerOptions,\n agentsPrefix?: string,\n options?: {\n client?: ConstructorParameters<typeof Client>[1];\n transport?: {\n headers?: HeadersInit;\n type?: TransportType;\n };\n }\n ): Promise<\n | {\n id: string;\n state: typeof MCPConnectionState.AUTHENTICATING;\n authUrl: string;\n }\n | {\n id: string;\n state: typeof MCPConnectionState.READY;\n authUrl?: undefined;\n }\n > {\n const isHttpTransport = typeof urlOrBinding === \"string\";\n const normalizedUrl = isHttpTransport\n ? new URL(urlOrBinding).href\n : undefined;\n const existingServer = this.mcp\n .listServers()\n .find(\n (s) =>\n s.name === serverName &&\n (!isHttpTransport || new URL(s.server_url).href === normalizedUrl)\n );\n if (existingServer && this.mcp.mcpConnections[existingServer.id]) {\n const conn = this.mcp.mcpConnections[existingServer.id];\n if (\n conn.connectionState === MCPConnectionState.AUTHENTICATING &&\n conn.options.transport.authProvider?.authUrl\n ) {\n return {\n id: existingServer.id,\n state: MCPConnectionState.AUTHENTICATING,\n authUrl: conn.options.transport.authProvider.authUrl\n };\n }\n if (conn.connectionState === MCPConnectionState.FAILED) {\n throw new Error(\n `MCP server \"${serverName}\" is in failed state: ${conn.connectionError}`\n );\n }\n return { id: existingServer.id, state: MCPConnectionState.READY };\n }\n\n // RPC transport path: second argument is a DurableObjectNamespace\n if (typeof urlOrBinding !== \"string\") {\n const rpcOpts = callbackHostOrOptions as\n | AddRpcMcpServerOptions\n | undefined;\n\n const normalizedName = serverName.toLowerCase().replace(/\\s+/g, \"-\");\n\n const reconnectId = existingServer?.id;\n const { id } = await this.mcp.connect(\n `${RPC_DO_PREFIX}${normalizedName}`,\n {\n reconnect: reconnectId ? { id: reconnectId } : undefined,\n transport: {\n type: \"rpc\" as TransportType,\n namespace:\n urlOrBinding as unknown as DurableObjectNamespace<McpAgent>,\n name: normalizedName,\n props: rpcOpts?.props\n }\n }\n );\n\n const conn = this.mcp.mcpConnections[id];\n if (conn && conn.connectionState === MCPConnectionState.CONNECTED) {\n const discoverResult = await this.mcp.discoverIfConnected(id);\n if (discoverResult && !discoverResult.success) {\n throw new Error(\n `Failed to discover MCP server capabilities: ${discoverResult.error}`\n );\n }\n } else if (conn && conn.connectionState === MCPConnectionState.FAILED) {\n throw new Error(\n `Failed to connect to MCP server \"${serverName}\" via RPC: ${conn.connectionError}`\n );\n }\n\n const bindingName = this._findBindingNameForNamespace(\n urlOrBinding as unknown as DurableObjectNamespace<McpAgent>\n );\n if (bindingName) {\n this.mcp.saveRpcServerToStorage(\n id,\n serverName,\n normalizedName,\n bindingName,\n rpcOpts?.props\n );\n }\n\n return { id, state: MCPConnectionState.READY };\n }\n\n // HTTP transport path\n const httpOptions = callbackHostOrOptions as\n | string\n | AddMcpServerOptions\n | undefined;\n\n let resolvedCallbackHost: string | undefined;\n let resolvedAgentsPrefix: string;\n let resolvedOptions:\n | {\n client?: ConstructorParameters<typeof Client>[1];\n transport?: {\n headers?: HeadersInit;\n type?: TransportType;\n };\n retry?: RetryOptions;\n }\n | undefined;\n\n let resolvedCallbackPath: string | undefined;\n\n if (typeof httpOptions === \"object\" && httpOptions !== null) {\n resolvedCallbackHost = httpOptions.callbackHost;\n resolvedCallbackPath = httpOptions.callbackPath;\n resolvedAgentsPrefix = httpOptions.agentsPrefix ?? \"agents\";\n resolvedOptions = {\n client: httpOptions.client,\n transport: httpOptions.transport,\n retry: httpOptions.retry\n };\n } else {\n resolvedCallbackHost = httpOptions;\n resolvedAgentsPrefix = agentsPrefix ?? \"agents\";\n resolvedOptions = options;\n }\n\n // Enforce callbackPath when sendIdentityOnConnect is false and callbackHost is provided\n if (\n !this._resolvedOptions.sendIdentityOnConnect &&\n resolvedCallbackHost &&\n !resolvedCallbackPath\n ) {\n throw new Error(\n \"callbackPath is required in addMcpServer options when sendIdentityOnConnect is false — \" +\n \"the default callback URL would expose the instance name. \" +\n \"Provide a callbackPath and route the callback request to this agent via getAgentByName.\"\n );\n }\n\n // Try to derive callbackHost from the current request if not explicitly provided\n if (!resolvedCallbackHost) {\n const { request } = getCurrentAgent();\n if (request) {\n const requestUrl = new URL(request.url);\n resolvedCallbackHost = `${requestUrl.protocol}//${requestUrl.host}`;\n }\n }\n\n // Build the callback URL if we have a host (needed for OAuth, optional for non-OAuth servers)\n let callbackUrl: string | undefined;\n if (resolvedCallbackHost) {\n const normalizedHost = resolvedCallbackHost.replace(/\\/$/, \"\");\n callbackUrl = resolvedCallbackPath\n ? `${normalizedHost}/${resolvedCallbackPath.replace(/^\\//, \"\")}`\n : `${normalizedHost}/${resolvedAgentsPrefix}/${camelCaseToKebabCase(this._ParentClass.name)}/${this.name}/callback`;\n }\n\n await this.mcp.ensureJsonSchema();\n\n const id = nanoid(8);\n\n // Only create authProvider if we have a callbackUrl (needed for OAuth servers)\n let authProvider:\n | ReturnType<typeof this.createMcpOAuthProvider>\n | undefined;\n if (callbackUrl) {\n authProvider = this.createMcpOAuthProvider(callbackUrl);\n authProvider.serverId = id;\n }\n\n // Use the transport type specified in options, or default to \"auto\"\n const transportType: TransportType =\n resolvedOptions?.transport?.type ?? \"auto\";\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 (resolvedOptions?.transport?.headers) {\n headerTransportOpts = {\n eventSourceInit: {\n fetch: (url, init) =>\n fetch(url, {\n ...init,\n headers: resolvedOptions?.transport?.headers\n })\n },\n requestInit: {\n headers: resolvedOptions?.transport?.headers\n }\n };\n }\n\n // Register server (also saves to storage)\n await this.mcp.registerServer(id, {\n url: normalizedUrl!,\n name: serverName,\n callbackUrl,\n client: resolvedOptions?.client,\n transport: {\n ...headerTransportOpts,\n authProvider,\n type: transportType\n },\n retry: resolvedOptions?.retry\n });\n\n const result = await this.mcp.connectToServer(id);\n\n if (result.state === MCPConnectionState.FAILED) {\n // Server stays in storage so user can retry via connectToServer(id)\n throw new Error(\n `Failed to connect to MCP server at ${normalizedUrl}: ${result.error}`\n );\n }\n\n if (result.state === MCPConnectionState.AUTHENTICATING) {\n if (!callbackUrl) {\n throw new Error(\n \"This MCP server requires OAuth authentication. \" +\n \"Provide callbackHost in addMcpServer options to enable the OAuth flow.\"\n );\n }\n return { id, state: result.state, authUrl: result.authUrl };\n }\n\n // State is CONNECTED - discover capabilities\n const discoverResult = await this.mcp.discoverIfConnected(id);\n\n if (discoverResult && !discoverResult.success) {\n // Server stays in storage - connection is still valid, user can retry discovery\n throw new Error(\n `Failed to discover MCP server capabilities: ${discoverResult.error}`\n );\n }\n\n return { id, state: MCPConnectionState.READY };\n }\n\n async removeMcpServer(id: string) {\n await this.mcp.removeServer(id);\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.mcp.listServers();\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\n // Determine the default state when no connection exists\n let defaultState: \"authenticating\" | \"not-connected\" = \"not-connected\";\n if (!serverConn && server.auth_url) {\n // If there's an auth_url but no connection, it's waiting for OAuth\n defaultState = \"authenticating\";\n }\n\n mcpState.servers[server.id] = {\n auth_url: server.auth_url,\n capabilities: serverConn?.serverCapabilities ?? null,\n error: sanitizeErrorString(serverConn?.connectionError ?? null),\n instructions: serverConn?.instructions ?? null,\n name: server.name,\n server_url: server.server_url,\n state: serverConn?.connectionState ?? defaultState\n };\n }\n }\n\n return mcpState;\n }\n\n /**\n * Create the OAuth provider used when connecting to MCP servers that require authentication.\n *\n * Override this method in a subclass to supply a custom OAuth provider implementation,\n * for example to use pre-registered client credentials, mTLS-based authentication,\n * or any other OAuth flow beyond dynamic client registration.\n *\n * @example\n * // Custom OAuth provider\n * class MyAgent extends Agent {\n * createMcpOAuthProvider(callbackUrl: string): AgentMcpOAuthProvider {\n * return new MyCustomOAuthProvider(\n * this.ctx.storage,\n * this.name,\n * callbackUrl\n * );\n * }\n * }\n *\n * @param callbackUrl The OAuth callback URL for the authorization flow\n * @returns An {@link AgentMcpOAuthProvider} instance used by {@link addMcpServer}\n */\n createMcpOAuthProvider(callbackUrl: string): AgentMcpOAuthProvider {\n return new DurableObjectOAuthClientProvider(\n this.ctx.storage,\n this.name,\n callbackUrl\n );\n }\n\n private broadcastMcpServers() {\n this._broadcastProtocol(\n JSON.stringify({\n mcp: this.getMcpServers(),\n type: MessageType.CF_AGENT_MCP_SERVERS\n })\n );\n }\n\n /**\n * Handle MCP OAuth callback request if it's an OAuth callback.\n *\n * This method encapsulates the entire OAuth callback flow:\n * 1. Checks if the request is an MCP OAuth callback\n * 2. Processes the OAuth code exchange\n * 3. Establishes the connection if successful\n * 4. Broadcasts MCP server state updates\n * 5. Returns the appropriate HTTP response\n *\n * @param request The incoming HTTP request\n * @returns Response if this was an OAuth callback, null otherwise\n */\n private async handleMcpOAuthCallback(\n request: Request\n ): Promise<Response | null> {\n // Check if this is an OAuth callback request\n const isCallback = this.mcp.isCallbackRequest(request);\n if (!isCallback) {\n return null;\n }\n\n // Handle the OAuth callback (exchanges code for token, clears OAuth credentials from storage)\n // This fires onServerStateChanged event which triggers broadcast\n const result = await this.mcp.handleCallbackRequest(request);\n\n // If auth was successful, establish the connection in the background\n // (establishConnection handles retries internally using per-server retry config)\n if (result.authSuccess) {\n this.mcp.establishConnection(result.serverId).catch((error) => {\n console.error(\n \"[Agent handleMcpOAuthCallback] Connection establishment failed:\",\n error\n );\n });\n }\n\n this.broadcastMcpServers();\n\n // Return the HTTP response for the OAuth callback\n return this.handleOAuthCallbackResponse(result, request);\n }\n\n /**\n * Handle OAuth callback response using MCPClientManager configuration\n * @param result OAuth callback result\n * @param request The original request (needed for base URL)\n * @returns Response for the OAuth callback\n */\n private handleOAuthCallbackResponse(\n result: MCPClientOAuthResult,\n request: Request\n ): Response {\n const config = this.mcp.getOAuthCallbackConfig();\n\n // Use custom handler if configured\n if (config?.customHandler) {\n return config.customHandler(result);\n }\n\n const baseOrigin = new URL(request.url).origin;\n\n // Redirect to success URL if configured\n if (config?.successRedirect && result.authSuccess) {\n try {\n return Response.redirect(\n new URL(config.successRedirect, baseOrigin).href\n );\n } catch (e) {\n console.error(\n \"Invalid successRedirect URL:\",\n config.successRedirect,\n e\n );\n return Response.redirect(baseOrigin);\n }\n }\n\n // Redirect to error URL if configured\n if (config?.errorRedirect && !result.authSuccess) {\n try {\n const errorUrl = `${config.errorRedirect}?error=${encodeURIComponent(\n result.authError || \"Unknown error\"\n )}`;\n return Response.redirect(new URL(errorUrl, baseOrigin).href);\n } catch (e) {\n console.error(\"Invalid errorRedirect URL:\", config.errorRedirect, e);\n return Response.redirect(baseOrigin);\n }\n }\n\n return Response.redirect(baseOrigin);\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 * @deprecated Use DurableObjectNamespace instead\n */\nexport type AgentNamespace<Agentic extends Agent<Cloudflare.Env>> =\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/**\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 return routePartykitRequest(request, env as Record<string, unknown>, {\n prefix: \"agents\",\n ...(options as PartyServerOptions<Record<string, unknown>>)\n });\n}\n\n// Email routing - deprecated resolver kept in root for upgrade discoverability\n// Other email utilities moved to agents/email subpath\nexport { createHeaderBasedEmailResolver } from \"./email\";\n\nimport type { EmailResolver } from \"./email\";\n\nexport type EmailRoutingOptions<Env> = AgentOptions<Env> & {\n resolver: EmailResolver<Env>;\n /**\n * Callback invoked when no routing information is found for an email.\n * Use this to reject the email or perform custom handling.\n * If not provided, a warning is logged and the email is dropped.\n */\n onNoRoute?: (email: ForwardableEmailMessage) => void | Promise<void>;\n};\n\n// Cache the agent namespace map for email routing\n// This maps original names, kebab-case, and lowercase versions to namespaces\nconst agentMapCache = new WeakMap<\n Record<string, unknown>,\n { map: Record<string, unknown>; originalNames: string[] }\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<\n Env extends Cloudflare.Env = Cloudflare.Env\n>(\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 if (options.onNoRoute) {\n await options.onNoRoute(email);\n } else {\n console.warn(\"No routing information found for email, dropping message\");\n }\n return;\n }\n\n // Build a map that includes original names, kebab-case, and lowercase versions\n if (!agentMapCache.has(env as Record<string, unknown>)) {\n const map: Record<string, unknown> = {};\n const originalNames: string[] = [];\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 the original name, kebab-case version, and lowercase version\n map[key] = value;\n map[camelCaseToKebabCase(key)] = value;\n map[key.toLowerCase()] = value;\n originalNames.push(key);\n }\n }\n agentMapCache.set(env as Record<string, unknown>, {\n map,\n originalNames\n });\n }\n\n const cached = agentMapCache.get(env as Record<string, unknown>)!;\n const namespace = cached.map[routingInfo.agentName];\n\n if (!namespace) {\n // Provide helpful error message listing available agents\n const availableAgents = cached.originalNames.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 DurableObjectNamespace<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: (replyOptions: { from: string; to: string; raw: string }) => {\n return email.reply(\n new EmailMessage(replyOptions.from, replyOptions.to, replyOptions.raw)\n );\n },\n from: email.from,\n to: email.to,\n _secureRouted: routingInfo._secureRouted\n };\n\n await agent._onEmail(serialisableEmail);\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 extends Cloudflare.Env = Cloudflare.Env,\n T extends Agent<Env> = Agent<Env>,\n Props extends Record<string, unknown> = Record<string, unknown>\n>(\n namespace: DurableObjectNamespace<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 * Whether the stream has been closed (via end() or error())\n */\n get isClosed(): boolean {\n return this._closed;\n }\n\n /**\n * Send a chunk of data to the client\n * @param chunk The data to send\n * @returns false if stream is already closed (no-op), true if sent\n */\n send(chunk: unknown): boolean {\n if (this._closed) {\n console.warn(\n \"StreamingResponse.send() called after stream was closed - data not sent\"\n );\n return false;\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 return true;\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 * @returns false if stream is already closed (no-op), true if sent\n */\n end(finalChunk?: unknown): boolean {\n if (this._closed) {\n return false;\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 return true;\n }\n\n /**\n * Send an error to the client and close the stream\n * @param message Error message to send\n * @returns false if stream is already closed (no-op), true if sent\n */\n error(message: string): boolean {\n if (this._closed) {\n return false;\n }\n this._closed = true;\n const response: RPCResponse = {\n error: message,\n id: this._id,\n success: false,\n type: MessageType.RPC\n };\n this._connection.send(JSON.stringify(response));\n return true;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2GA,SAAS,aAAa,KAAiC;AACrD,QACE,OAAO,QAAQ,YACf,QAAQ,QACR,UAAU,OACV,IAAI,SAAS,YAAY,OACzB,QAAQ,OACR,OAAO,IAAI,OAAO,YAClB,YAAY,OACZ,OAAO,IAAI,WAAW,YACtB,UAAU,OACV,MAAM,QAAS,IAAmB,KAAK;;;;;AAO3C,SAAS,qBAAqB,KAAyC;AACrE,QACE,OAAO,QAAQ,YACf,QAAQ,QACR,UAAU,OACV,IAAI,SAAS,YAAY,kBACzB,WAAW;;AAcf,MAAM,mCAAmB,IAAI,SAAqC;;;;AAKlE,IAAa,WAAb,cAA8B,MAAM;CAIlC,YAAY,OAAe,OAAgB;EACzC,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;AACtE,QAAM,qBAAqB,WAAW,EAAE,OAAO,CAAC;AAChD,OAAK,OAAO;AACZ,OAAK,QAAQ;;;;;;;AAQjB,SAAgB,SAAS,WAA6B,EAAE,EAAE;AACxD,QAAO,SAAS,kBACd,QACA,UACA;AACA,MAAI,CAAC,iBAAiB,IAAI,OAAO,CAC/B,kBAAiB,IAAI,QAAQ,SAAS;AAGxC,SAAO;;;AAIX,IAAI,+BAA+B;;;;;;AAOnC,MAAa,qBAAqB,WAA6B,EAAE,KAAK;AACpE,KAAI,CAAC,8BAA8B;AACjC,iCAA+B;AAC/B,UAAQ,KACN,sHACD;;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
import { RetryOptions } from "../retries.js";
|
|
2
|
-
import { E as Event, T as Emitter, i as MCPTransportOptions, n as MCPClientConnection, r as MCPConnectionState, t as MCPServerRow, w as TransportType } from "../client-storage-
|
|
2
|
+
import { E as Event, T as Emitter, i as MCPTransportOptions, n as MCPClientConnection, r as MCPConnectionState, t as MCPServerRow, w as TransportType } from "../client-storage-BPjfP_is.js";
|
|
3
3
|
import { n as MCPObservabilityEvent } from "../agent-eZnMHidZ.js";
|
|
4
4
|
import { AgentMcpOAuthProvider } from "./do-oauth-client-provider.js";
|
|
5
5
|
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
package/dist/mcp/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as ServeOptions, S as McpClientOptions, _ as WorkerTransportOptions, a as RPCClientTransport, b as BaseTransportType, c as RPCServerTransportOptions, d as createMcpHandler, f as experimental_createMcpHandler, g as WorkerTransport, h as TransportState, l as RPC_DO_PREFIX, m as getMcpAuthContext, o as RPCClientTransportOptions, p as McpAuthContext, s as RPCServerTransport, u as CreateMcpHandlerOptions, v as SSEEdgeClientTransport, x as MaybePromise, y as StreamableHTTPEdgeClientTransport } from "../client-storage-
|
|
1
|
+
import { C as ServeOptions, S as McpClientOptions, _ as WorkerTransportOptions, a as RPCClientTransport, b as BaseTransportType, c as RPCServerTransportOptions, d as createMcpHandler, f as experimental_createMcpHandler, g as WorkerTransport, h as TransportState, l as RPC_DO_PREFIX, m as getMcpAuthContext, o as RPCClientTransportOptions, p as McpAuthContext, s as RPCServerTransport, u as CreateMcpHandlerOptions, v as SSEEdgeClientTransport, x as MaybePromise, y as StreamableHTTPEdgeClientTransport } from "../client-storage-BPjfP_is.js";
|
|
2
2
|
import { MCPClientOAuthCallbackConfig, MCPClientOAuthResult, MCPConnectionResult, MCPDiscoverResult, MCPServerOptions } from "./client.js";
|
|
3
3
|
import { Agent, Connection, ConnectionContext } from "../index.js";
|
|
4
4
|
import { ElicitRequest, ElicitRequestSchema, ElicitResult, ElicitResult as ElicitResult$1, JSONRPCMessage, MessageExtraInfo } from "@modelcontextprotocol/sdk/types.js";
|
package/dist/react.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Method, RPCMethod } from "./serializable.js";
|
|
2
2
|
import { StreamOptions } from "./client.js";
|
|
3
|
-
import "./client-storage-
|
|
3
|
+
import "./client-storage-BPjfP_is.js";
|
|
4
4
|
import { Agent, MCPServersState } from "./index.js";
|
|
5
5
|
import { PartySocket } from "partysocket";
|
|
6
6
|
import { usePartySocket } from "partysocket/react";
|
package/dist/workflows.d.ts
CHANGED