UNPKG

@dexwox-labs/a2a-client

Version:

TypeScript client implementation for Google's Agent-to-Agent (A2A) protocol - includes HTTP/WebSocket communication, circuit breakers and error handling

281 lines 13 kB
"use strict"; /** * @module MessageClient * @description Client for sending and receiving messages between A2A agents */ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); var _, done = false; for (var i = decorators.length - 1; i >= 0; i--) { var context = {}; for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; for (var p in contextIn.access) context.access[p] = contextIn.access[p]; context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); if (kind === "accessor") { if (result === void 0) continue; if (result === null || typeof result !== "object") throw new TypeError("Object expected"); if (_ = accept(result.get)) descriptor.get = _; if (_ = accept(result.set)) descriptor.set = _; if (_ = accept(result.init)) initializers.unshift(_); } else if (_ = accept(result)) { if (kind === "field") initializers.unshift(_); else descriptor[key] = _; } } if (target) Object.defineProperty(target, contextIn.name, descriptor); done = true; }; var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) { var useValue = arguments.length > 2; for (var i = 0; i < initializers.length; i++) { value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); } return useValue ? value : void 0; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.MessageClient = void 0; const events_1 = require("events"); const a2a_core_1 = require("@dexwox-labs/a2a-core"); const a2a_core_2 = require("@dexwox-labs/a2a-core"); const error_handler_1 = require("./utils/error-handler"); const http_utils_1 = require("./utils/http-utils"); const task_client_1 = require("./task-client"); const agent_client_1 = require("./agent-client"); /** * Client for sending and receiving messages between A2A agents * * The MessageClient provides methods for sending messages to agents and * streaming real-time communication. It also provides access to related * TaskClient and AgentClient instances for convenience. * * @example * ```typescript * const messageClient = new MessageClient({ baseUrl: 'https://a2a-server.example.com' }); * * // Send a simple text message to an agent * const messageId = await messageClient.sendMessage([ * { type: 'text', content: 'What is the weather in New York?' } * ], 'weather-agent'); * ``` */ let MessageClient = (() => { let _classDecorators = [(0, a2a_core_1.TraceClass)()]; let _classDescriptor; let _classExtraInitializers = []; let _classThis; let _classSuper = events_1.EventEmitter; var MessageClient = class extends _classSuper { static { _classThis = this; } static { const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0; __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers); MessageClient = _classThis = _classDescriptor.value; if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata }); __runInitializers(_classThis, _classExtraInitializers); } /** Configuration options for the client */ options; /** Task client for managing tasks */ tasks; /** Agent client for discovering and interacting with agents */ agents; /** * Creates a new MessageClient instance * @param options - Configuration options for the client */ constructor(options) { super(); this.options = { timeout: 5000, ...options }; this.tasks = new task_client_1.TaskClient(this.options); this.agents = new agent_client_1.AgentClient(this.options); } /** * Sends a message synchronously to an agent * * This method sends a message to a specified agent and waits for the server to * acknowledge receipt. It validates the message parts before sending and handles * network errors appropriately. * * @param parts - Array of message parts to send (text, file, data, etc.) * @param agentId - ID of the target agent to receive the message * @returns Promise resolving to the message ID assigned by the server * @throws {A2ANetworkError} If there's a network issue contacting the server * @throws {A2AValidationError} If the message parts are invalid * * @example * ```typescript * // Send a text message * const textMessageId = await messageClient.sendMessage([ * { type: 'text', content: 'Hello, agent!' } * ], 'assistant-agent'); * * // Send a message with multiple parts * const multipartMessageId = await messageClient.sendMessage([ * { type: 'text', content: 'Here is the data you requested' }, * { * type: 'data', * content: { temperature: 72, humidity: 65 }, * schema: 'weather-data' * } * ], 'weather-agent'); * ``` */ async sendMessage(parts, agentId) { (0, a2a_core_2.validateMessageParts)(parts); const request = { jsonrpc: '2.0', method: 'sendMessage', params: { parts, agentId } }; try { const response = await (0, http_utils_1.sendRequest)(this.options, request); return response.result; } catch (err) { if (err instanceof Error && err.message.includes('Network')) { throw new error_handler_1.A2ANetworkError('Failed to send message', { originalError: err, agentId }); } throw (0, error_handler_1.normalizeError)(err); } } /** * Streams messages to and from an agent * * This method establishes a real-time streaming connection with an agent, * allowing for continuous message exchange with automatic error handling. * * @param parts - Initial message parts to send to the agent * @param agentId - ID of the target agent to stream with * @param options - Configuration options and event handlers for the stream * @param options.onMessage - Callback function for received messages * @param options.onError - Optional callback function for stream errors * @param options.onComplete - Optional callback function when stream completes * @returns Promise that resolves when the stream completes * @throws {A2ANetworkError} If there's a network issue establishing the stream * @throws {A2AValidationError} If the message parts are invalid * * @example * ```typescript * await messageClient.streamMessage( * [{ type: 'text', content: 'Tell me a story about dragons' }], * 'storyteller-agent', * { * onMessage: (data) => console.log('Received:', data), * onError: (error) => console.error('Stream error:', error), * onComplete: () => console.log('Stream completed') * } * ); * ``` */ async streamMessage(parts, agentId, options) { const { maxRetries = 5, retryDelay = 1000, backoffFactor = 2, maxRetryDelay = 30000, heartbeatInterval = 10000, heartbeatTimeout = 30000, onMessage, onError, onComplete } = options; let retryCount = 0; let isStreaming = true; let lastHeartbeat = Date.now(); const calculateDelay = (attempt) => { const delay = retryDelay * Math.pow(backoffFactor, attempt); return Math.min(delay, maxRetryDelay); }; const handleEvent = (event) => { try { const data = JSON.parse(event.data); if (data.type === 'heartbeat') { lastHeartbeat = Date.now(); } else { if (data.type === 'taskUpdate' && this.tasks) { this.tasks.handleTaskUpdate(data.task); } onMessage(data); } } catch (err) { onError?.(new Error('Failed to parse SSE event')); } }; const setupEventSource = () => { const streamUrl = `${this.options.baseUrl}/stream?agentId=${agentId}`; const eventSource = new EventSource(streamUrl); eventSource.onmessage = handleEvent; eventSource.onerror = (error) => { eventSource.close(); isStreaming = false; if (retryCount < maxRetries) { const delay = calculateDelay(retryCount); retryCount++; setTimeout(doStream, delay); } else { onError?.(new Error('Stream connection failed after retries')); } }; eventSource.addEventListener('close', () => { isStreaming = false; onComplete?.(); }); return eventSource; }; const doStream = async () => { const request = { jsonrpc: '2.0', method: 'streamMessage', params: { parts, agentId } }; try { const response = await fetch(this.options.baseUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', ...this.options.headers }, body: JSON.stringify(request) }); if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`); if (!response.body) throw new Error('No response body for streaming'); const eventSource = setupEventSource(); // Heartbeat monitoring const heartbeatMonitor = setInterval(() => { if (isStreaming && Date.now() - lastHeartbeat > heartbeatTimeout) { eventSource.close(); onError?.(new Error('Heartbeat timeout exceeded')); } }, heartbeatInterval); // Cleanup on completion return new Promise((resolve) => { eventSource.addEventListener('close', () => { clearInterval(heartbeatMonitor); resolve(); }); }); } catch (err) { if (err instanceof Error && err.message.includes('Network')) { throw new error_handler_1.A2ANetworkError('Streaming connection failed', { originalError: err, agentId, retryCount }); } throw (0, error_handler_1.normalizeError)(err); } }; return doStream(); } }; return MessageClient = _classThis; })(); exports.MessageClient = MessageClient; //# sourceMappingURL=message-client.js.map