UNPKG

agents

Version:
1,262 lines (1,260 loc) • 41.7 kB
import { AgentEmail, __DO_NOT_USE_WILL_BREAK__agentContext } from "./internal_context.js"; import { EmailResolver, createHeaderBasedEmailResolver } from "./email.js"; import { RetryOptions } from "./retries.js"; import { l as TransportType, r as MCPConnectionState } from "./client-storage-D633wI1S.js"; import { AgentMcpOAuthProvider, AgentsOAuthProvider, DurableObjectOAuthClientProvider } from "./mcp/do-oauth-client-provider.js"; import { MCPClientManager } from "./mcp/client.js"; import { RunWorkflowOptions, WorkflowCallback, WorkflowEventPayload, WorkflowInfo, WorkflowPage, WorkflowQueryCriteria } from "./workflow-types.js"; import { Observability } from "./observability/index.js"; import { MessageType } from "./types.js"; import { Connection, Connection as Connection$1, ConnectionContext, ConnectionContext as ConnectionContext$1, PartyServerOptions, Server, WSMessage } from "partyserver"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { Prompt, Resource, ServerCapabilities, Tool } from "@modelcontextprotocol/sdk/types.js"; //#region src/index.d.ts /** * RPC request message from client */ type RPCRequest = { type: "rpc"; id: string; method: string; args: unknown[]; }; /** * State update message from client */ type StateUpdateMessage = { type: MessageType.CF_AGENT_STATE; state: unknown; }; /** * RPC response message to client */ type RPCResponse = { type: MessageType.RPC; id: string; } & ( | { success: true; result: unknown; done?: false; } | { success: true; result: unknown; done: true; } | { success: false; error: string; } ); /** * Metadata for a callable method */ type CallableMetadata = { /** Optional description of what the method does */ description?: string /** Whether the method supports streaming responses */; streaming?: boolean; }; /** * Error class for SQL execution failures, containing the query that failed */ declare class SqlError extends Error { /** The SQL query that failed */ readonly query: string; constructor(query: string, cause: unknown); } /** * Decorator that marks a method as callable by clients * @param metadata Optional metadata about the callable method */ declare function callable( metadata?: CallableMetadata ): <This, Args extends unknown[], Return>( target: (this: This, ...args: Args) => Return, _context: ClassMethodDecoratorContext ) => (this: This, ...args: Args) => Return; /** * Decorator that marks a method as callable by clients * @deprecated this has been renamed to callable, and unstable_callable will be removed in the next major version * @param metadata Optional metadata about the callable method */ declare const unstable_callable: ( metadata?: CallableMetadata ) => <This, Args extends unknown[], Return>( target: (this: This, ...args: Args) => Return, _context: ClassMethodDecoratorContext ) => (this: This, ...args: Args) => Return; type QueueItem<T = string> = { id: string; payload: T; callback: keyof Agent<Cloudflare.Env>; created_at: number; retry?: RetryOptions; }; /** * Represents a scheduled task within an Agent * @template T Type of the payload data */ type Schedule<T = string> = { /** Unique identifier for the schedule */ id: string /** Name of the method to be called */; callback: string /** Data to be passed to the callback */; payload: T /** Retry options for callback execution */; retry?: RetryOptions; } & ( | { /** Type of schedule for one-time execution at a specific time */ type: "scheduled" /** Timestamp when the task should execute */; time: number; } | { /** Type of schedule for delayed execution */ type: "delayed" /** Timestamp when the task should execute */; time: number /** Number of seconds to delay execution */; delayInSeconds: number; } | { /** Type of schedule for recurring execution based on cron expression */ type: "cron" /** Timestamp for the next execution */; time: number /** Cron expression defining the schedule */; cron: string; } | { /** Type of schedule for recurring execution at fixed intervals */ type: "interval" /** Timestamp for the next execution */; time: number /** Number of seconds between executions */; intervalSeconds: number; } ); /** * MCP Server state update message from server -> Client */ type MCPServerMessage = { type: MessageType.CF_AGENT_MCP_SERVERS; mcp: MCPServersState; }; type MCPServersState = { servers: { [id: string]: MCPServer; }; tools: (Tool & { serverId: string; })[]; prompts: (Prompt & { serverId: string; })[]; resources: (Resource & { serverId: string; })[]; }; type MCPServer = { name: string; server_url: string; auth_url: string | null; state: MCPConnectionState /** May contain untrusted content from external OAuth providers. Escape appropriately for your output context. */; error: string | null; instructions: string | null; capabilities: ServerCapabilities | null; }; /** * Options for adding an MCP server */ type AddMcpServerOptions = { /** OAuth callback host (auto-derived from request if omitted) */ callbackHost?: string; /** * Custom callback URL path — bypasses the default `/agents/{class}/{name}/callback` construction. * Required when `sendIdentityOnConnect` is `false` to prevent leaking the instance name. * When set, the callback URL becomes `{callbackHost}/{callbackPath}`. * The developer must route this path to the agent instance via `getAgentByName`. * Should be a plain path (e.g., `/mcp-callback`) — do not include query strings or fragments. */ callbackPath?: string /** Agents routing prefix (default: "agents") */; agentsPrefix?: string /** MCP client options */; client?: ConstructorParameters<typeof Client>[1] /** Transport options */; transport?: { /** Custom headers for authentication (e.g., bearer tokens, CF Access) */ headers?: HeadersInit /** Transport type: "sse", "streamable-http", or "auto" (default) */; type?: TransportType; } /** Retry options for connection and reconnection attempts */; retry?: RetryOptions; }; /** * Default options for Agent configuration. * Child classes can override specific options without spreading. */ declare const DEFAULT_AGENT_STATIC_OPTIONS: { /** Whether the Agent should hibernate when inactive */ hibernate: boolean /** Whether to send identity (name, agent) to clients on connect */; sendIdentityOnConnect: boolean; /** * Timeout in seconds before a running interval schedule is considered "hung" * and force-reset. Increase this if you have callbacks that legitimately * take longer than 30 seconds. */ hungScheduleTimeoutSeconds: number /** Default retry options for schedule(), queue(), and this.retry() */; retry: { maxAttempts: number; baseDelayMs: number; maxDelayMs: number; }; }; /** * Configuration options for the Agent. * Override in subclasses via `static options`. * All fields are optional - defaults are applied at runtime. * Note: `hibernate` defaults to `true` if not specified. */ interface AgentStaticOptions { hibernate?: boolean; sendIdentityOnConnect?: boolean; hungScheduleTimeoutSeconds?: number; /** Default retry options for schedule(), queue(), and this.retry(). */ retry?: RetryOptions; } declare function getCurrentAgent< T extends Agent<Cloudflare.Env> = Agent<Cloudflare.Env> >(): { agent: T | undefined; connection: Connection$1 | undefined; request: Request | undefined; email: AgentEmail | undefined; }; /** * Extract string keys from Env where the value is a Workflow binding. */ type WorkflowBinding<E> = { [K in keyof E & string]: E[K] extends Workflow ? K : never; }[keyof E & string]; /** * Type for workflow name parameter. * When Env has typed Workflow bindings, provides autocomplete for those keys. * Also accepts any string for dynamic use cases and compatibility. * The `string & {}` trick preserves autocomplete while allowing any string. */ type WorkflowName<E> = WorkflowBinding<E> | (string & {}); /** * Base class for creating Agent implementations * @template Env Environment type containing bindings * @template State State type to store within the Agent */ declare class Agent< Env extends Cloudflare.Env = Cloudflare.Env, State = unknown, Props extends Record<string, unknown> = Record<string, unknown> > extends Server<Env, Props> { private _state; private _disposables; private _destroyed; /** * Stores raw state accessors for wrapped connections. * Used by internal flag methods (readonly, no-protocol) to read/write * _cf_-prefixed keys without going through the user-facing state/setState. */ private _rawStateAccessors; /** * Cached persistence-hook dispatch mode, computed once in the constructor. * - "new" → call onStateChanged * - "old" → call onStateUpdate (deprecated) * - "none" → neither hook is overridden, skip entirely */ private _persistenceHookMode; private _ParentClass; readonly mcp: MCPClientManager; /** * Initial state for the Agent * Override to provide default state values */ initialState: State; /** * Current state of the Agent */ get state(): State; /** * Agent configuration options. * Override in subclasses - only specify what you want to change. * @example * class SecureAgent extends Agent { * static options = { sendIdentityOnConnect: false }; * } */ static options: AgentStaticOptions; /** * Resolved options (merges defaults with subclass overrides). * Cached after first access — static options never change during the * lifetime of a Durable Object instance. */ private _cachedOptions?; private get _resolvedOptions(); /** * The observability implementation to use for the Agent */ observability?: Observability; /** * Execute SQL queries against the Agent's database * @template T Type of the returned rows * @param strings SQL query template strings * @param values Values to be inserted into the query * @returns Array of query results */ sql<T = Record<string, string | number | boolean | null>>( strings: TemplateStringsArray, ...values: (string | number | boolean | null)[] ): T[]; constructor(ctx: AgentContext, env: Env); /** * Check for workflows referencing unknown bindings and warn with migration suggestion. */ private _checkOrphanedWorkflows; /** * Broadcast a protocol message only to connections that have protocol * messages enabled. Connections where shouldSendProtocolMessages returned * false are excluded automatically. * @param msg The JSON-encoded protocol message * @param excludeIds Additional connection IDs to exclude (e.g. the source) */ private _broadcastProtocol; private _setStateInternal; /** * Update the Agent's state * @param state New state to set * @throws Error if called from a readonly connection context */ setState(state: State): void; /** * Wraps connection.state and connection.setState so that internal * _cf_-prefixed flags (readonly, no-protocol) are hidden from user code * and cannot be accidentally overwritten. * * Idempotent — safe to call multiple times on the same connection. * After hibernation, the _rawStateAccessors WeakMap is empty but the * connection's state getter still reads from the persisted WebSocket * attachment. Calling this method re-captures the raw getter so that * predicate methods (isConnectionReadonly, isConnectionProtocolEnabled) * work correctly post-hibernation. */ private _ensureConnectionWrapped; /** * Mark a connection as readonly or readwrite * @param connection The connection to mark * @param readonly Whether the connection should be readonly (default: true) */ setConnectionReadonly(connection: Connection$1, readonly?: boolean): void; /** * Check if a connection is marked as readonly. * * Safe to call after hibernation — re-wraps the connection if the * in-memory accessor cache was cleared. * @param connection The connection to check * @returns True if the connection is readonly */ isConnectionReadonly(connection: Connection$1): boolean; /** * Override this method to determine if a connection should be readonly on connect * @param _connection The connection that is being established * @param _ctx Connection context * @returns True if the connection should be readonly */ shouldConnectionBeReadonly( _connection: Connection$1, _ctx: ConnectionContext$1 ): boolean; /** * Override this method to control whether protocol messages are sent to a * connection. Protocol messages include identity (CF_AGENT_IDENTITY), state * sync (CF_AGENT_STATE), and MCP server lists (CF_AGENT_MCP_SERVERS). * * When this returns `false` for a connection, that connection will not * receive any protocol text frames — neither on connect nor via broadcasts. * This is useful for binary-only clients (e.g. MQTT devices) that cannot * handle JSON text frames. * * The connection can still send and receive regular messages, use RPC, and * participate in all non-protocol communication. * * @param _connection The connection that is being established * @param _ctx Connection context (includes the upgrade request) * @returns True if protocol messages should be sent (default), false to suppress them */ shouldSendProtocolMessages( _connection: Connection$1, _ctx: ConnectionContext$1 ): boolean; /** * Check if a connection has protocol messages enabled. * Protocol messages include identity, state sync, and MCP server lists. * * Safe to call after hibernation — re-wraps the connection if the * in-memory accessor cache was cleared. * @param connection The connection to check * @returns True if the connection receives protocol messages */ isConnectionProtocolEnabled(connection: Connection$1): boolean; /** * Mark a connection as having protocol messages disabled. * Called internally when shouldSendProtocolMessages returns false. */ private _setConnectionNoProtocol; /** * Called before the Agent's state is persisted and broadcast. * Override to validate or reject an update by throwing an error. * * IMPORTANT: This hook must be synchronous. */ validateStateChange(nextState: State, source: Connection$1 | "server"): void; /** * Called after the Agent's state has been persisted and broadcast to all clients. * This is a notification hook — errors here are routed to onError and do not * affect state persistence or client broadcasts. * * @param state Updated state * @param source Source of the state update ("server" or a client connection) */ onStateChanged( state: State | undefined, source: Connection$1 | "server" ): void; /** * @deprecated Renamed to `onStateChanged` — the behavior is identical. * `onStateUpdate` will be removed in the next major version. * * Called after the Agent's state has been persisted and broadcast to all clients. * This is a server-side notification hook. For the client-side state callback, * see the `onStateUpdate` option in `useAgent` / `AgentClient`. * * @param state Updated state * @param source Source of the state update ("server" or a client connection) */ onStateUpdate( state: State | undefined, source: Connection$1 | "server" ): void; /** * Dispatch to the appropriate persistence hook based on the mode * cached in the constructor. No prototype walks at call time. */ private _callStatePersistenceHook; /** * Called when the Agent receives an email via routeAgentEmail() * Override this method to handle incoming emails * @param email Email message to process */ _onEmail(email: AgentEmail): Promise<void>; /** * Reply to an email * @param email The email to reply to * @param options Options for the reply * @param options.secret Secret for signing agent headers (enables secure reply routing). * Required if the email was routed via createSecureReplyEmailResolver. * Pass explicit `null` to opt-out of signing (not recommended for secure routing). * @returns void */ replyToEmail( email: AgentEmail, options: { fromName: string; subject?: string | undefined; body: string; contentType?: string; headers?: Record<string, string>; secret?: string | null; } ): Promise<void>; private _tryCatch; /** * Automatically wrap custom methods with agent context * This ensures getCurrentAgent() works in all custom methods without decorators */ private _autoWrapCustomMethods; onError(connection: Connection$1, error: unknown): void | Promise<void>; onError(error: unknown): void | Promise<void>; /** * Render content (not implemented in base class) */ render(): void; /** * Retry an async operation with exponential backoff and jitter. * Retries on all errors by default. Use `shouldRetry` to bail early on non-retryable errors. * * @param fn The async function to retry. Receives the current attempt number (1-indexed). * @param options Retry configuration. * @param options.maxAttempts Maximum number of attempts (including the first). Falls back to static options, then 3. * @param options.baseDelayMs Base delay in ms for exponential backoff. Falls back to static options, then 100. * @param options.maxDelayMs Maximum delay cap in ms. Falls back to static options, then 3000. * @param options.shouldRetry Predicate called with the error and next attempt number. Return false to stop retrying immediately. Default: retry all errors. * @returns The result of fn on success. * @throws The last error if all attempts fail or shouldRetry returns false. */ retry<T>( fn: (attempt: number) => Promise<T>, options?: RetryOptions & { /** Return false to stop retrying a specific error. Receives the error and the next attempt number. Default: retry all errors. */ shouldRetry?: ( err: unknown, nextAttempt: number ) => boolean; } ): Promise<T>; /** * Queue a task to be executed in the future * @param callback Name of the method to call * @param payload Payload to pass to the callback * @param options Options for the queued task * @param options.retry Retry options for the callback execution * @returns The ID of the queued task */ queue<T = unknown>( callback: keyof this, payload: T, options?: { retry?: RetryOptions; } ): Promise<string>; private _flushingQueue; private _flushQueue; /** * Dequeue a task by ID * @param id ID of the task to dequeue */ dequeue(id: string): void; /** * Dequeue all tasks */ dequeueAll(): void; /** * Dequeue all tasks by callback * @param callback Name of the callback to dequeue */ dequeueAllByCallback(callback: string): void; /** * Get a queued task by ID * @param id ID of the task to get * @returns The task or undefined if not found */ getQueue(id: string): QueueItem<string> | undefined; /** * Get all queues by key and value * @param key Key to filter by * @param value Value to filter by * @returns Array of matching QueueItem objects */ getQueues(key: string, value: string): QueueItem<string>[]; /** * Schedule a task to be executed in the future * @template T Type of the payload data * @param when When to execute the task (Date, seconds delay, or cron expression) * @param callback Name of the method to call * @param payload Data to pass to the callback * @param options Options for the scheduled task * @param options.retry Retry options for the callback execution * @returns Schedule object representing the scheduled task */ schedule<T = string>( when: Date | string | number, callback: keyof this, payload?: T, options?: { retry?: RetryOptions; } ): Promise<Schedule<T>>; /** * Schedule a task to run repeatedly at a fixed interval * @template T Type of the payload data * @param intervalSeconds Number of seconds between executions * @param callback Name of the method to call * @param payload Data to pass to the callback * @param options Options for the scheduled task * @param options.retry Retry options for the callback execution * @returns Schedule object representing the scheduled task */ scheduleEvery<T = string>( intervalSeconds: number, callback: keyof this, payload?: T, options?: { retry?: RetryOptions; } ): Promise<Schedule<T>>; /** * Get a scheduled task by ID * @template T Type of the payload data * @param id ID of the scheduled task * @returns The Schedule object or undefined if not found */ getSchedule<T = string>(id: string): Schedule<T> | undefined; /** * Get scheduled tasks matching the given criteria * @template T Type of the payload data * @param criteria Criteria to filter schedules * @returns Array of matching Schedule objects */ getSchedules<T = string>(criteria?: { id?: string; type?: "scheduled" | "delayed" | "cron" | "interval"; timeRange?: { start?: Date; end?: Date; }; }): Schedule<T>[]; /** * Cancel a scheduled task * @param id ID of the task to cancel * @returns true if the task was cancelled, false if the task was not found */ cancelSchedule(id: string): Promise<boolean>; private _scheduleNextAlarm; /** * Method called when an alarm fires. * Executes any scheduled tasks that are due. * * @remarks * To schedule a task, please use the `this.schedule` method instead. * See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/} */ readonly alarm: () => Promise<void>; /** * Destroy the Agent, removing all state and scheduled tasks */ destroy(): Promise<void>; /** * Check if a method is callable * @param method The method name to check * @returns True if the method is marked as callable */ private _isCallable; /** * Get all methods marked as callable on this Agent * @returns A map of method names to their metadata */ getCallableMethods(): Map<string, CallableMetadata>; /** * Start a workflow and track it in this Agent's database. * Automatically injects agent identity into the workflow params. * * @template P - Type of params to pass to the workflow * @param workflowName - Name of the workflow binding in env (e.g., 'MY_WORKFLOW') * @param params - Params to pass to the workflow * @param options - Optional workflow options * @returns The workflow instance ID * * @example * ```typescript * const workflowId = await this.runWorkflow( * 'MY_WORKFLOW', * { taskId: '123', data: 'process this' } * ); * ``` */ runWorkflow<P = unknown>( workflowName: WorkflowName<Env>, params: P, options?: RunWorkflowOptions ): Promise<string>; /** * Send an event to a running workflow. * The workflow can wait for this event using step.waitForEvent(). * * @param workflowName - Name of the workflow binding in env (e.g., 'MY_WORKFLOW') * @param workflowId - ID of the workflow instance * @param event - Event to send * * @example * ```typescript * await this.sendWorkflowEvent( * 'MY_WORKFLOW', * workflowId, * { type: 'approval', payload: { approved: true } } * ); * ``` */ sendWorkflowEvent( workflowName: WorkflowName<Env>, workflowId: string, event: WorkflowEventPayload ): Promise<void>; /** * Approve a waiting workflow. * Sends an approval event to the workflow that can be received by waitForApproval(). * * @param workflowId - ID of the workflow to approve * @param data - Optional approval data (reason, metadata) * * @example * ```typescript * await this.approveWorkflow(workflowId, { * reason: 'Approved by admin', * metadata: { approvedBy: userId } * }); * ``` */ approveWorkflow( workflowId: string, data?: { reason?: string; metadata?: Record<string, unknown>; } ): Promise<void>; /** * Reject a waiting workflow. * Sends a rejection event to the workflow that will cause waitForApproval() to throw. * * @param workflowId - ID of the workflow to reject * @param data - Optional rejection data (reason) * * @example * ```typescript * await this.rejectWorkflow(workflowId, { * reason: 'Request denied by admin' * }); * ``` */ rejectWorkflow( workflowId: string, data?: { reason?: string; } ): Promise<void>; /** * Terminate a running workflow. * This immediately stops the workflow and sets its status to "terminated". * * @param workflowId - ID of the workflow to terminate (must be tracked via runWorkflow) * @throws Error if workflow not found in tracking table * @throws Error if workflow binding not found in environment * @throws Error if workflow is already completed/errored/terminated (from Cloudflare) * * @note `terminate()` is not yet supported in local development (wrangler dev). * It will throw an error locally but works when deployed to Cloudflare. * * @example * ```typescript * await this.terminateWorkflow(workflowId); * ``` */ terminateWorkflow(workflowId: string): Promise<void>; /** * Pause a running workflow. * The workflow can be resumed later with resumeWorkflow(). * * @param workflowId - ID of the workflow to pause (must be tracked via runWorkflow) * @throws Error if workflow not found in tracking table * @throws Error if workflow binding not found in environment * @throws Error if workflow is not running (from Cloudflare) * * @note `pause()` is not yet supported in local development (wrangler dev). * It will throw an error locally but works when deployed to Cloudflare. * * @example * ```typescript * await this.pauseWorkflow(workflowId); * ``` */ pauseWorkflow(workflowId: string): Promise<void>; /** * Resume a paused workflow. * * @param workflowId - ID of the workflow to resume (must be tracked via runWorkflow) * @throws Error if workflow not found in tracking table * @throws Error if workflow binding not found in environment * @throws Error if workflow is not paused (from Cloudflare) * * @note `resume()` is not yet supported in local development (wrangler dev). * It will throw an error locally but works when deployed to Cloudflare. * * @example * ```typescript * await this.resumeWorkflow(workflowId); * ``` */ resumeWorkflow(workflowId: string): Promise<void>; /** * Restart a workflow instance. * This re-runs the workflow from the beginning with the same ID. * * @param workflowId - ID of the workflow to restart (must be tracked via runWorkflow) * @param options - Optional settings * @param options.resetTracking - If true (default), resets created_at and clears error fields. * If false, preserves original timestamps. * @throws Error if workflow not found in tracking table * @throws Error if workflow binding not found in environment * * @note `restart()` is not yet supported in local development (wrangler dev). * It will throw an error locally but works when deployed to Cloudflare. * * @example * ```typescript * // Reset tracking (default) * await this.restartWorkflow(workflowId); * * // Preserve original timestamps * await this.restartWorkflow(workflowId, { resetTracking: false }); * ``` */ restartWorkflow( workflowId: string, options?: { resetTracking?: boolean; } ): Promise<void>; /** * Find a workflow binding by its name. */ private _findWorkflowBindingByName; /** * Get all workflow binding names from the environment. */ private _getWorkflowBindingNames; /** * Get the status of a workflow and update the tracking record. * * @param workflowName - Name of the workflow binding in env (e.g., 'MY_WORKFLOW') * @param workflowId - ID of the workflow instance * @returns The workflow status */ getWorkflowStatus( workflowName: WorkflowName<Env>, workflowId: string ): Promise<InstanceStatus>; /** * Get a tracked workflow by ID. * * @param workflowId - Workflow instance ID * @returns Workflow info or undefined if not found */ getWorkflow(workflowId: string): WorkflowInfo | undefined; /** * Query tracked workflows with cursor-based pagination. * * @param criteria - Query criteria including optional cursor for pagination * @returns WorkflowPage with workflows, total count, and next cursor * * @example * ```typescript * // First page * const page1 = this.getWorkflows({ status: 'running', limit: 20 }); * * // Next page * if (page1.nextCursor) { * const page2 = this.getWorkflows({ * status: 'running', * limit: 20, * cursor: page1.nextCursor * }); * } * ``` */ getWorkflows(criteria?: WorkflowQueryCriteria): WorkflowPage; /** * Count workflows matching criteria (for pagination total). */ private _countWorkflows; /** * Encode a cursor from workflow info for pagination. * Stores createdAt as Unix timestamp in seconds (matching DB storage). */ private _encodeCursor; /** * Decode a pagination cursor. * Returns createdAt as Unix timestamp in seconds (matching DB storage). */ private _decodeCursor; /** * Delete a workflow tracking record. * * @param workflowId - ID of the workflow to delete * @returns true if a record was deleted, false if not found */ deleteWorkflow(workflowId: string): boolean; /** * Delete workflow tracking records matching criteria. * Useful for cleaning up old completed/errored workflows. * * @param criteria - Criteria for which workflows to delete * @returns Number of records matching criteria (expected deleted count) * * @example * ```typescript * // Delete all completed workflows created more than 7 days ago * const deleted = this.deleteWorkflows({ * status: 'complete', * createdBefore: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000) * }); * * // Delete all errored and terminated workflows * const deleted = this.deleteWorkflows({ * status: ['errored', 'terminated'] * }); * ``` */ deleteWorkflows( criteria?: Omit<WorkflowQueryCriteria, "limit" | "orderBy"> & { createdBefore?: Date; } ): number; /** * Migrate workflow tracking records from an old binding name to a new one. * Use this after renaming a workflow binding in wrangler.toml. * * @param oldName - Previous workflow binding name * @param newName - New workflow binding name * @returns Number of records migrated * * @example * ```typescript * // After renaming OLD_WORKFLOW to NEW_WORKFLOW in wrangler.toml * async onStart() { * const migrated = this.migrateWorkflowBinding('OLD_WORKFLOW', 'NEW_WORKFLOW'); * } * ``` */ migrateWorkflowBinding(oldName: string, newName: string): number; /** * Update workflow tracking record from InstanceStatus */ private _updateWorkflowTracking; /** * Convert a database row to WorkflowInfo */ private _rowToWorkflowInfo; /** * Find the binding name for this Agent's namespace by matching class name. * Returns undefined if no match found - use options.agentBinding as fallback. */ private _findAgentBindingName; /** * Handle a callback from a workflow. * Called when the Agent receives a callback at /_workflow/callback. * Override this to handle all callback types in one place. * * @param callback - The callback payload */ onWorkflowCallback(callback: WorkflowCallback): Promise<void>; /** * Called when a workflow reports progress. * Override to handle progress updates. * * @param workflowName - Workflow binding name * @param workflowId - ID of the workflow * @param progress - Typed progress data (default: DefaultProgress) */ onWorkflowProgress( _workflowName: string, _workflowId: string, _progress: unknown ): Promise<void>; /** * Called when a workflow completes successfully. * Override to handle completion. * * @param workflowName - Workflow binding name * @param workflowId - ID of the workflow * @param result - Optional result data */ onWorkflowComplete( _workflowName: string, _workflowId: string, _result?: unknown ): Promise<void>; /** * Called when a workflow encounters an error. * Override to handle errors. * * @param workflowName - Workflow binding name * @param workflowId - ID of the workflow * @param error - Error message */ onWorkflowError( _workflowName: string, _workflowId: string, _error: string ): Promise<void>; /** * Called when a workflow sends a custom event. * Override to handle custom events. * * @param workflowName - Workflow binding name * @param workflowId - ID of the workflow * @param event - Custom event payload */ onWorkflowEvent( _workflowName: string, _workflowId: string, _event: unknown ): Promise<void>; /** * Handle a workflow callback via RPC. * @internal - Called by AgentWorkflow, do not call directly */ _workflow_handleCallback(callback: WorkflowCallback): Promise<void>; /** * Broadcast a message to all connected clients via RPC. * @internal - Called by AgentWorkflow, do not call directly */ _workflow_broadcast(message: unknown): void; /** * Update agent state via RPC. * @internal - Called by AgentWorkflow, do not call directly */ _workflow_updateState( action: "set" | "merge" | "reset", state?: unknown ): void; /** * Connect to a new MCP Server * * @example * // Simple usage * await this.addMcpServer("github", "https://mcp.github.com"); * * @example * // With options (preferred for custom headers, transport, etc.) * await this.addMcpServer("github", "https://mcp.github.com", { * transport: { headers: { "Authorization": "Bearer ..." } } * }); * * @example * // Legacy 5-parameter signature (still supported) * await this.addMcpServer("github", url, callbackHost, agentsPrefix, options); * * @param serverName Name of the MCP server * @param url MCP Server URL * @param callbackHostOrOptions Options object, or callback host string (legacy) * @param agentsPrefix agents routing prefix if not using `agents` (legacy) * @param options MCP client and transport options (legacy) * @returns Server id and state - either "authenticating" with authUrl, or "ready" * @throws If connection or discovery fails */ addMcpServer( serverName: string, url: string, callbackHostOrOptions?: string | AddMcpServerOptions, agentsPrefix?: string, options?: { client?: ConstructorParameters<typeof Client>[1]; transport?: { headers?: HeadersInit; type?: TransportType; }; } ): Promise< | { id: string; state: typeof MCPConnectionState.AUTHENTICATING; authUrl: string; } | { id: string; state: typeof MCPConnectionState.READY; authUrl?: undefined; } >; removeMcpServer(id: string): Promise<void>; getMcpServers(): MCPServersState; /** * Create the OAuth provider used when connecting to MCP servers that require authentication. * * Override this method in a subclass to supply a custom OAuth provider implementation, * for example to use pre-registered client credentials, mTLS-based authentication, * or any other OAuth flow beyond dynamic client registration. * * @example * // Custom OAuth provider * class MyAgent extends Agent { * createMcpOAuthProvider(callbackUrl: string): AgentMcpOAuthProvider { * return new MyCustomOAuthProvider( * this.ctx.storage, * this.name, * callbackUrl * ); * } * } * * @param callbackUrl The OAuth callback URL for the authorization flow * @returns An {@link AgentMcpOAuthProvider} instance used by {@link addMcpServer} */ createMcpOAuthProvider(callbackUrl: string): AgentMcpOAuthProvider; private broadcastMcpServers; /** * Handle MCP OAuth callback request if it's an OAuth callback. * * This method encapsulates the entire OAuth callback flow: * 1. Checks if the request is an MCP OAuth callback * 2. Processes the OAuth code exchange * 3. Establishes the connection if successful * 4. Broadcasts MCP server state updates * 5. Returns the appropriate HTTP response * * @param request The incoming HTTP request * @returns Response if this was an OAuth callback, null otherwise */ private handleMcpOAuthCallback; /** * Handle OAuth callback response using MCPClientManager configuration * @param result OAuth callback result * @param request The original request (needed for base URL) * @returns Response for the OAuth callback */ private handleOAuthCallbackResponse; } /** * Namespace for creating Agent instances * @template Agentic Type of the Agent class * @deprecated Use DurableObjectNamespace instead */ type AgentNamespace<Agentic extends Agent<Cloudflare.Env>> = DurableObjectNamespace<Agentic>; /** * Agent's durable context */ type AgentContext = DurableObjectState; /** * Configuration options for Agent routing */ type AgentOptions<Env> = PartyServerOptions<Env>; /** * Route a request to the appropriate Agent * @param request Request to route * @param env Environment containing Agent bindings * @param options Routing options * @returns Response from the Agent or undefined if no route matched */ declare function routeAgentRequest<Env>( request: Request, env: Env, options?: AgentOptions<Env> ): Promise<Response | null>; type EmailRoutingOptions<Env> = AgentOptions<Env> & { resolver: EmailResolver<Env>; /** * Callback invoked when no routing information is found for an email. * Use this to reject the email or perform custom handling. * If not provided, a warning is logged and the email is dropped. */ onNoRoute?: (email: ForwardableEmailMessage) => void | Promise<void>; }; /** * Route an email to the appropriate Agent * @param email The email to route * @param env The environment containing the Agent bindings * @param options The options for routing the email * @returns A promise that resolves when the email has been routed */ declare function routeAgentEmail<Env extends Cloudflare.Env = Cloudflare.Env>( email: ForwardableEmailMessage, env: Env, options: EmailRoutingOptions<Env> ): Promise<void>; /** * Get or create an Agent by name * @template Env Environment type containing bindings * @template T Type of the Agent class * @param namespace Agent namespace * @param name Name of the Agent instance * @param options Options for Agent creation * @returns Promise resolving to an Agent instance stub */ declare function getAgentByName< Env extends Cloudflare.Env = Cloudflare.Env, T extends Agent<Env> = Agent<Env>, Props extends Record<string, unknown> = Record<string, unknown> >( namespace: DurableObjectNamespace<T>, name: string, options?: { jurisdiction?: DurableObjectJurisdiction; locationHint?: DurableObjectLocationHint; props?: Props; } ): Promise<DurableObjectStub<T>>; /** * A wrapper for streaming responses in callable methods */ declare class StreamingResponse { private _connection; private _id; private _closed; constructor(connection: Connection$1, id: string); /** * Whether the stream has been closed (via end() or error()) */ get isClosed(): boolean; /** * Send a chunk of data to the client * @param chunk The data to send * @returns false if stream is already closed (no-op), true if sent */ send(chunk: unknown): boolean; /** * End the stream and send the final chunk (if any) * @param finalChunk Optional final chunk of data to send * @returns false if stream is already closed (no-op), true if sent */ end(finalChunk?: unknown): boolean; /** * Send an error to the client and close the stream * @param message Error message to send * @returns false if stream is already closed (no-op), true if sent */ error(message: string): boolean; } //#endregion export { AddMcpServerOptions, Agent, AgentContext, type AgentMcpOAuthProvider, AgentNamespace, AgentOptions, AgentStaticOptions, type AgentsOAuthProvider, CallableMetadata, type Connection, type ConnectionContext, DEFAULT_AGENT_STATIC_OPTIONS, DurableObjectOAuthClientProvider, EmailRoutingOptions, MCPServer, MCPServerMessage, MCPServersState, QueueItem, RPCRequest, RPCResponse, type RetryOptions, Schedule, SqlError, StateUpdateMessage, StreamingResponse, type TransportType, type WSMessage, __DO_NOT_USE_WILL_BREAK__agentContext, callable, createHeaderBasedEmailResolver, getAgentByName, getCurrentAgent, routeAgentEmail, routeAgentRequest, unstable_callable }; //# sourceMappingURL=index.d.ts.map