import { createRandomId } from './random-id'; export interface JsonRpcRequest { jsonrpc: '2.0'; id: string | number; method: string; params?: unknown; } export interface JsonRpcResponse { jsonrpc: '2.0'; id: string | number; result?: T; error?: JsonRpcError; } export interface JsonRpcError { code: number; message: string; data?: unknown; } export interface JsonRpcNotification { jsonrpc: '2.0'; method: string; params?: unknown; } export enum JsonRpcErrorCode { PARSE_ERROR = -32700, INVALID_REQUEST = -32600, METHOD_NOT_FOUND = -32601, INVALID_PARAMS = -32602, INTERNAL_ERROR = -32603, SERVER_ERROR = -32000, } export enum GatewayErrorCode { NOT_CONNECTED = -32001, AUTH_REQUIRED = -32002, PERMISSION_DENIED = -32003, NOT_FOUND = -32004, TIMEOUT = -32005, RATE_LIMITED = -32006, } export enum GatewayEventType { STATUS_CHANGED = 'gateway.status_changed', CHANNEL_STATUS_CHANGED = 'channel.status_changed', MESSAGE_RECEIVED = 'chat.message_received', MESSAGE_SENT = 'chat.message_sent', TOOL_CALL_STARTED = 'tool.call_started', TOOL_CALL_COMPLETED = 'tool.call_completed', ERROR = 'error', } export interface GatewayProtocolEvent { type: GatewayEventType; timestamp: string; data: T; } export function createRequest( method: string, params?: unknown, id?: string | number, ): JsonRpcRequest { return { jsonrpc: '2.0', id: id ?? createRandomId(), method, params, }; } export function createSuccessResponse( id: string | number, result: T, ): JsonRpcResponse { return { jsonrpc: '2.0', id, result, }; } export function createErrorResponse( id: string | number, code: number, message: string, data?: unknown, ): JsonRpcResponse { return { jsonrpc: '2.0', id, error: { code, message, data, }, }; } export function isRequest(message: unknown): message is JsonRpcRequest { return ( typeof message === 'object' && message !== null && 'jsonrpc' in message && message.jsonrpc === '2.0' && 'method' in message && typeof message.method === 'string' && 'id' in message ); } export function isResponse(message: unknown): message is JsonRpcResponse { return ( typeof message === 'object' && message !== null && 'jsonrpc' in message && message.jsonrpc === '2.0' && 'id' in message && ('result' in message || 'error' in message) ); } export function isNotification(message: unknown): message is JsonRpcNotification { return ( typeof message === 'object' && message !== null && 'jsonrpc' in message && message.jsonrpc === '2.0' && 'method' in message && !('id' in message) ); }