UNPKG

@dexwox-labs/a2a-server

Version:

TypeScript server implementation for Google's Agent-to-Agent (A2A) protocol - includes Express/WebSocket handlers, request validation and queue management

301 lines 10.6 kB
/** * @module RequestHandler * @description Core request handling and routing for the A2A server * * This module provides the main request handler implementation for the A2A server, * handling all incoming requests, routing them to the appropriate handlers, and * managing the lifecycle of tasks and messages. */ import { Router } from 'express'; import { DefaultJsonRpcRequestHandler } from './request-handlers/default-jsonrpc-handler'; import { MessagePart, Task, AgentCard, A2AError } from '@dexwox-labs/a2a-core'; /** * Configuration for push notifications * * This interface defines how push notifications should be configured for a task, * including which events to listen for and where to send notifications. * * @example * ```typescript * const config: PushNotificationConfig = { * enabled: true, * endpoint: 'https://webhook.example.com/notifications', * authToken: 'your-auth-token', * events: ['taskCompleted', 'taskFailed'] * }; * ``` */ interface PushNotificationConfig { /** Whether push notifications are enabled */ enabled: boolean; /** Endpoint URL where notifications should be sent */ endpoint?: string; /** Authentication token for the push endpoint */ authToken?: string; /** List of event types to receive notifications for */ events: string[]; } /** * Interface for request handlers in the A2A server * * This interface defines the contract for all request handlers in the A2A server, * including methods for handling messages, managing tasks, configuring push * notifications, and discovering agents. */ export interface RequestHandler { /** Express router for handling HTTP requests */ readonly router: Router; /** * Handles sending a message to an agent * * @param parts - Message parts to send * @param agentId - ID of the target agent * @returns Promise resolving to the created task ID */ handleSendMessage(parts: MessagePart[], agentId: string): Promise<string>; /** * Handles streaming a message to an agent * * @param parts - Message parts to send * @param agentId - ID of the target agent * @returns AsyncGenerator yielding message parts as they are processed */ handleStreamMessage(parts: MessagePart[], agentId: string): AsyncGenerator<MessagePart, void, unknown>; /** * Gets the status of a task * * @param taskId - ID of the task * @returns Promise resolving to the task object */ handleGetTaskStatus(taskId: string): Promise<Task>; /** * Cancels a running task * * @param taskId - ID of the task to cancel * @returns Promise resolving when the task is canceled */ handleCancelTask(taskId: string): Promise<void>; /** * Resubscribes to a task's message stream * * @param taskId - ID of the task * @returns AsyncGenerator yielding message parts for the task */ handleTaskResubscription(taskId: string): AsyncGenerator<MessagePart, void, unknown>; /** * Sets push notification configuration for a task * * @param taskId - ID of the task * @param config - Push notification configuration * @returns Promise resolving when the configuration is set */ handleSetPushConfig(taskId: string, config: PushNotificationConfig): Promise<void>; /** * Gets push notification configuration for a task * * @param taskId - ID of the task * @returns Promise resolving to the push notification configuration */ handleGetPushConfig(taskId: string): Promise<PushNotificationConfig>; /** * Discovers available agents, optionally filtered by capability * * @param capability - Optional capability to filter agents by * @returns Promise resolving to an array of agent cards */ handleDiscoverAgents(capability?: string): Promise<AgentCard[]>; /** * Normalizes errors to A2AError format * * @param err - Error to normalize * @returns Normalized A2AError */ normalizeError(err: unknown): A2AError; } /** * Default implementation of the RequestHandler interface * * This class provides the standard implementation of the RequestHandler interface, * handling all A2A protocol requests including message sending, task management, * push notifications, and agent discovery. * * @example * ```typescript * // Create a request handler with available agents * const agents: AgentCard[] = [ * { * id: 'assistant-agent', * name: 'Assistant', * description: 'A helpful assistant', * capabilities: ['chat', 'answer-questions'] * } * ]; * * const requestHandler = new DefaultRequestHandler(agents); * * // Use in an Express app * app.use('/a2a', requestHandler.router); * ``` */ export declare class DefaultRequestHandler extends DefaultJsonRpcRequestHandler implements RequestHandler { /** Express router for handling HTTP requests */ readonly router: Router; /** Queue for handling events */ private readonly eventQueue; /** Manager for task events */ private readonly taskEventManager; /** Manager for request queues */ private readonly queueManager; /** Executor for agent operations */ private readonly agentExecutor; /** Manager for tasks */ private readonly taskManager; /** Service for push notifications */ private readonly pushService; /** Available agents */ private readonly agents; /** * Creates a new DefaultRequestHandler * * @param agents - Array of available agent cards */ constructor(agents?: AgentCard[]); /** * Sets up the Express routes for handling A2A protocol requests * * @private */ private setupRoutes; handleSendMessage(parts: MessagePart[], agentId: string): Promise<string>; private createArtifactEvent; private createHeartbeat; handleStreamMessage(parts: MessagePart[], agentId: string): AsyncGenerator<MessagePart, void, unknown>; /** * Gets the status of a task * * Retrieves the current status and details of a task by its ID. * * @param taskId - ID of the task to retrieve * @returns Promise resolving to the task object * @throws {A2AError} If the task is not found * * @example * ```typescript * try { * const task = await requestHandler.handleGetTaskStatus('task-123'); * console.log('Task status:', task.status); * console.log('Task result:', task.result); * } catch (error) { * console.error('Failed to get task:', error); * } * ``` */ handleGetTaskStatus(taskId: string): Promise<Task>; /** * Cancels a running task * * Attempts to cancel a task that is currently in progress. This will notify * the agent to stop processing and update the task status to 'canceled'. * * @param taskId - ID of the task to cancel * @returns Promise resolving when the task is canceled * @throws {A2AError} If the task is not found or has no agent ID * * @example * ```typescript * try { * await requestHandler.handleCancelTask('task-123'); * console.log('Task canceled successfully'); * } catch (error) { * console.error('Failed to cancel task:', error); * } * ``` */ handleCancelTask(taskId: string): Promise<void>; /** * Discovers available agents * * Returns a list of available agents, optionally filtered by capability. * * @param capability - Optional capability to filter agents by * @returns Promise resolving to an array of agent cards * * @example * ```typescript * // Get all agents * const allAgents = await requestHandler.handleDiscoverAgents(); * console.log('All agents:', allAgents); * * // Get agents with a specific capability * const chatAgents = await requestHandler.handleDiscoverAgents('chat'); * console.log('Chat agents:', chatAgents); * ``` */ handleDiscoverAgents(capability?: string): Promise<AgentCard[]>; handleTaskResubscription(taskId: string): AsyncGenerator<MessagePart, void, unknown>; /** * Sets push notification configuration for a task * * Configures push notifications for a specific task, including the endpoint * to send notifications to and which events to notify about. * * @param taskId - ID of the task * @param config - Push notification configuration * @returns Promise resolving when the configuration is set * @throws {A2AError} If the task is not found * * @example * ```typescript * await requestHandler.handleSetPushConfig('task-123', { * enabled: true, * endpoint: 'https://webhook.example.com/notifications', * authToken: 'your-auth-token', * events: ['taskCompleted', 'taskFailed'] * }); * ``` */ handleSetPushConfig(taskId: string, config: PushNotificationConfig): Promise<void>; /** * Gets push notification configuration for a task * * Retrieves the current push notification configuration for a specific task. * * @param taskId - ID of the task * @returns Promise resolving to the push notification configuration * @throws {A2AError} If the task is not found * * @example * ```typescript * const config = await requestHandler.handleGetPushConfig('task-123'); * console.log('Push notification config:', config); * console.log('Enabled:', config.enabled); * console.log('Events:', config.events); * ``` */ handleGetPushConfig(taskId: string): Promise<PushNotificationConfig>; /** * Normalizes errors to A2AError format * * Converts various error types to the standardized A2AError format used * throughout the A2A protocol. * * @param err - Error to normalize * @returns Normalized A2AError * * @example * ```typescript * try { * // Some operation that might fail * throw new Error('Something went wrong'); * } catch (error) { * // Normalize the error to A2AError format * const normalizedError = requestHandler.normalizeError(error); * console.error('Normalized error:', normalizedError); * console.error('Error code:', normalizedError.code); * } * ``` */ normalizeError(err: unknown): A2AError; } export {}; //# sourceMappingURL=request-handler.d.ts.map