@gravityai-dev/gravity-server
Version:
Integration SDK for the Gravity AI orchestration platform - Connect any AI platform in minutes
1,085 lines (1,036 loc) • 36.1 kB
TypeScript
import Redis from 'ioredis';
export { default as Redis } from 'ioredis';
/**
* Base publisher functionality and types
*
* This module provides the foundation for all publisher classes in the messaging system.
* It includes the BasePublisher abstract class which handles core Redis connection
* management and message publishing functionality.
*
* @module messaging/publishers/base
*/
/**
* Options for publishing messages
*
* @interface PublishOptions
* @property {string} [channel] - Optional Redis channel to publish to. If not provided,
* the publisher will use a default channel based on context.
* @property {boolean} [useStream] - Whether to use Redis Streams for guaranteed delivery
*
* @example
* ```typescript
* // Publish to a specific channel
* const options: PublishOptions = {
* channel: "gravity:output"
* };
* ```
*/
interface PublishOptions {
channel?: string;
useStream?: boolean;
}
/**
* Base publisher class with core functionality
*
* This abstract class provides the foundation for all specialized publishers.
* It manages the Redis connection, provider ID, and core publishing logic.
*
* Key responsibilities:
* - Maintain Redis connection for publishing
* - Store and provide access to provider ID
* - Create base messages with required fields
* - Publish messages to Redis channels
*
* @abstract
* @class BasePublisher
*
* @example
* ```typescript
* // Extend BasePublisher to create a specialized publisher
* class MyPublisher extends BasePublisher {
* async publishCustomMessage(data: any): Promise<void> {
* const message = {
* ...this.createBaseMessage({
* chatId: "chat123",
* conversationId: "conv456",
* userId: "user789"
* }),
* data
* };
* await this.publish(message, "my:channel");
* }
* }
*
* // Use the publisher
* const redis = new Redis();
* const publisher = new MyPublisher(redis, "my-service");
* await publisher.publishCustomMessage({ foo: "bar" });
* ```
*/
declare abstract class BasePublisher {
/**
* Redis connection used for publishing messages
* @protected
*/
protected redis: Redis;
/**
* Provider ID identifying the service using this publisher
* @protected
*/
protected providerId: string;
/**
* Creates a new BasePublisher instance
*
* @param {Redis} redis - Redis connection instance for publishing
* @param {string} providerId - Unique identifier for the service/provider
*
* @example
* ```typescript
* const redis = new Redis({
* host: "localhost",
* port: 6379
* });
* const publisher = new MyPublisher(redis, "my-service");
* ```
*/
constructor(redis: Redis, providerId: string);
/**
* Gets the provider ID for the publisher
*
* This method is used by other components (like EventBus) to access
* the provider ID when creating related instances.
*
* @returns {string} The provider ID
*
* @example
* ```typescript
* const providerId = publisher.getProviderId();
* console.log(`Publisher provider: ${providerId}`);
* ```
*/
getProviderId(): string;
/**
* Gets the Redis connection for the publisher
*
* This method exposes the Redis connection for use by other components
* that need to create their own connections with the same configuration.
*
* @returns {Redis} The Redis connection instance
*
* @example
* ```typescript
* const redis = publisher.getRedisConnection();
* const options = {
* host: redis.options.host,
* port: redis.options.port
* };
* ```
*/
getRedisConnection(): Redis;
/**
* Creates a base message with the given partial data
*
* This method constructs a complete BaseMessage by merging provided fields
* with defaults. It ensures all required fields are present and validates
* that chatId, conversationId, and userId are provided.
*
* @protected
* @param {Partial<BaseMessage>} partial - Partial message data to merge with defaults
* @returns {BaseMessage} Complete base message with all required fields
* @throws {Error} If chatId, conversationId, or userId are missing
*
* @example
* ```typescript
* const baseMessage = this.createBaseMessage({
* chatId: "chat123",
* conversationId: "conv456",
* userId: "user789",
* type: MessageType.TEXT
* });
* // Result: {
* // id: "generated-uuid",
* // chatId: "chat123",
* // conversationId: "conv456",
* // userId: "user789",
* // providerId: "my-service",
* // timestamp: "2023-12-08T10:30:00.000Z",
* // type: MessageType.TEXT
* // }
* ```
*/
protected createBaseMessage(partial: Partial<BaseMessage>): BaseMessage;
/**
* Publishes a message to the given channel
*
* This method serializes the message to JSON and publishes it to the
* specified Redis channel. This is the core publishing mechanism used
* by all specialized publishers.
*
* @protected
* @param {GravityMessage} message - The message object to publish
* @param {PublishOptions} [options] - Optional publishing options
* @returns {Promise<void>} Promise that resolves when message is published
*
* @example
* ```typescript
* const message = {
* __typename: "Text",
* text: "Hello, world!",
* ...baseMessage
* };
* await this.publish(message, { channel: "custom:channel" });
* ```
*/
protected publish(message: GravityMessage, options?: PublishOptions): Promise<void>;
/**
* Publishes a message to Redis Streams for guaranteed delivery
*
* @protected
* @param {string} channel - The channel name
* @param {GravityMessage} message - The message to publish
* @returns {Promise<string>} The stream entry ID
*/
private publishToStream;
}
/**
* Text message publisher
*
* @module messaging/publishers/text
*/
/**
* Text message type
*/
interface Text extends BaseMessage {
__typename: "Text";
component: {
type: "Text";
props: {
text: string;
};
};
}
/**
* TextPublisher - Handles text messages
*/
declare class TextPublisher extends BasePublisher {
/**
* Publishes a text message
*
* @param text - The text content
* @param baseMessage - Base message with required fields (chatId, conversationId, userId)
* @param options - Optional publishing options (e.g., custom channel)
*/
publishText(text: string, baseMessage: Partial<BaseMessage>, options?: PublishOptions): Promise<void>;
}
/**
* Get singleton TextPublisher instance
* Maximum performance - no new objects created after first call
*
* @param host - Redis host (required on first call)
* @param port - Redis port (required on first call)
* @param password - Redis password (required on first call)
* @param providerId - Provider ID (required on first call)
* @param username - Redis username (optional)
* @param db - Redis database number (optional)
* @returns Singleton TextPublisher instance
*/
declare function getTextPublisher(host?: string, port?: number, password?: string, providerId?: string, username?: string, db?: number): TextPublisher;
/**
* JSON data message publisher
*
* @module messaging/publishers/jsonData
*/
/**
* JSON data message type
*/
interface JsonData extends BaseMessage {
__typename: "JsonData";
component: {
type: "JsonData";
props: {
data: any;
};
};
}
/**
* JsonDataPublisher - Handles JSON data messages
*/
declare class JsonDataPublisher extends BasePublisher {
/**
* Publishes a JSON data message
*
* @param data - The JSON data to publish
* @param baseMessage - Base message with required fields (chatId, conversationId, userId)
* @param options - Optional publishing options (e.g., custom channel)
*/
publishJsonData(data: any, baseMessage: Partial<BaseMessage>, options?: PublishOptions): Promise<void>;
}
/**
* Get singleton JsonDataPublisher instance
* Maximum performance - no new objects created after first call
*
* @param host - Redis host (required on first call)
* @param port - Redis port (required on first call)
* @param password - Redis password (required on first call)
* @param providerId - Provider ID (required on first call)
* @param username - Redis username (optional)
* @param db - Redis database number (optional)
* @returns Singleton JsonDataPublisher instance
*/
declare function getJsonDataPublisher(host?: string, port?: number, password?: string, providerId?: string, username?: string, db?: number): JsonDataPublisher;
/**
* Action suggestion message publisher
*
* @module messaging/publishers/actionSuggestion
*/
/**
* Action suggestion message type
*/
interface ActionSuggestion extends BaseMessage {
__typename: "ActionSuggestion";
component: {
type: "ActionSuggestion";
props: {
actionType: string;
payload: any;
};
};
}
/**
* Metadata message publisher
*
* @module messaging/publishers/metadata
*/
/**
* Metadata message type
*/
interface Metadata extends BaseMessage {
__typename: "Metadata";
component: {
type: "Metadata";
props: {
message: string;
};
};
}
/**
* Image response message publisher
*
* @module messaging/publishers/imageResponse
*/
/**
* Image response message type
*/
interface ImageResponse extends BaseMessage {
__typename: "ImageResponse";
component: {
type: "ImageResponse";
props: {
url: string;
alt?: string;
};
};
}
/**
* Tool output message publisher
*
* @module messaging/publishers/toolOutput
*/
/**
* Tool output message type
*/
interface ToolOutput extends BaseMessage {
__typename: "ToolOutput";
component: {
type: "ToolOutput";
props: {
tool: string;
result: any;
};
};
}
/**
* Audio chunk message publisher
*
* @module messaging/publishers/audioChunk
*/
/**
* Audio chunk message type
*/
interface AudioChunk extends BaseMessage {
__typename: "AudioChunk";
component: {
type: "AudioChunk";
props: {
audioData: string;
format: string;
duration?: number;
textReference: string;
sourceType: string;
index?: number;
};
};
}
/**
* Helper function to create an AudioChunk object without publishing it
*/
declare function createAudioChunk(base: BaseMessage, audioData: string, format: string, textReference: string, sourceType: string, duration?: number, index?: number): AudioChunk;
/**
* MessageChunk publisher
*
* Handles publishing of message chunk updates to Redis channels
*/
/**
* MessageChunk message type
*/
interface MessageChunk extends BaseMessage {
__typename: "MessageChunk";
component: {
type: "MessageChunk";
props: {
text: string;
index?: number;
};
};
}
/**
* Publisher for message chunks
*/
declare class MessageChunkPublisher extends BasePublisher {
/**
* Publishes a message chunk
*
* @param text - The text content of the chunk
* @param baseMessage - Base message with required fields (chatId, conversationId, userId)
* @param index - Optional sequence index for ordering
* @param options - Optional publishing options (e.g., custom channel)
*/
publishMessageChunk(text: string, baseMessage: Partial<BaseMessage>, index?: number, options?: PublishOptions): Promise<void>;
}
/**
* Get singleton MessageChunkPublisher instance
* Maximum performance - no new objects created after first call
*
* @param host - Redis host (required on first call)
* @param port - Redis port (required on first call)
* @param password - Redis password (required on first call)
* @param providerId - Provider ID (required on first call)
* @param username - Redis username (optional)
* @param db - Redis database number (optional)
* @returns Singleton MessageChunkPublisher instance
*/
declare function getMessageChunkPublisher(host?: string, port?: number, password?: string, providerId?: string, username?: string, db?: number): MessageChunkPublisher;
/**
* Progress update publisher
*
* Simple, focused publisher for progress update messages.
*
* @module messaging/publishers/progress
*/
/**
* Progress update message type
*/
interface ProgressUpdate extends BaseMessage {
__typename: "ProgressUpdate";
component: {
type: "ProgressUpdate";
props: {
message: string;
progress?: number;
};
};
}
/**
* ProgressPublisher - Handles progress update messages
*/
declare class ProgressPublisher extends BasePublisher {
/**
* Publishes a progress update
*
* @param message - The progress message text
* @param progress - Optional progress percentage (0-100)
* @param baseMessage - Base message with required fields (chatId, conversationId, userId)
* @param options - Optional publishing options (e.g., custom channel)
*/
publishProgressUpdate(message: string, progress: number | undefined, baseMessage: Partial<BaseMessage>, options?: PublishOptions): Promise<void>;
}
/**
* Get singleton ProgressPublisher instance
* Maximum performance - no new objects created after first call
*
* @param host - Redis host (required on first call)
* @param port - Redis port (required on first call)
* @param password - Redis password (required on first call)
* @param providerId - Provider ID (required on first call)
* @param username - Redis username (optional)
* @param db - Redis database number (optional)
* @returns Singleton ProgressPublisher instance
*/
declare function getProgressPublisher(host?: string, port?: number, password?: string, providerId?: string, username?: string, db?: number): ProgressPublisher;
/**
* System message publisher
*
* @module messaging/publishers/system
*/
/**
* System message interface
*/
interface SystemMessage extends BaseMessage {
__typename: "SystemMessage";
message: string;
level: "info" | "warning" | "error";
}
/**
* SystemPublisher - Handles system messages
*
* System messages are used for service-level notifications, errors, and warnings
* that need to be communicated to users or other services.
*
* @example
* ```typescript
* const publisher = new SystemPublisher(redis);
*
* // Publish a system message
* await publisher.publishSystemMessage("Service started", "info", {
* chatId: "chat123",
* conversationId: "conv123",
* userId: "user456"
* });
* ```
*/
declare class SystemPublisher extends BasePublisher {
/**
* Publishes a system message
*
* System messages are used for service notifications, errors, and warnings.
*
* @param message - The system message text
* @param level - The message level (info, warning, or error)
* @param baseMessage - Base message with required fields (chatId, conversationId, userId)
* @param options - Optional publishing options (e.g., custom channel)
* @returns Promise that resolves when message is published
*
* @example
* ```typescript
* // Service startup notification
* await publisher.publishSystemMessage("Service started", "info", {
* chatId: "chat123",
* conversationId: "conv123",
* userId: "user456"
* });
*
* // Error notification
* await publisher.publishSystemMessage("Database connection failed", "error", {
* chatId: "chat123",
* conversationId: "conv123",
* userId: "user456"
* });
* ```
*/
publishSystemMessage(message: string, level: "info" | "warning" | "error", baseMessage: Partial<BaseMessage>, options?: PublishOptions): Promise<void>;
}
/**
* Get singleton SystemPublisher instance
* Maximum performance - no new objects created after first call
*
* @param host - Redis host (required on first call)
* @param port - Redis port (required on first call)
* @param password - Redis password (required on first call)
* @param providerId - Provider ID (required on first call)
* @param username - Redis username (optional)
* @param db - Redis database number (optional)
* @returns Singleton SystemPublisher instance
*/
declare function getSystemPublisher(host?: string, port?: number, password?: string, providerId?: string, username?: string, db?: number): SystemPublisher;
/**
* State publisher for chat state updates
*/
/**
* State message type for chat state updates
*/
interface StateMessage extends BaseMessage {
__typename: "State";
component?: {
type: string;
props: {
state: string;
label?: string;
[key: string]: any;
};
};
data?: any;
label?: string;
variables?: any;
}
/**
* StatePublisher - Handles chat state update messages
*/
declare class StatePublisher extends BasePublisher {
/**
* Publishes a chat state update
*
* @param state - The chat state (e.g., THINKING, RESPONDING, etc.)
* @param baseMessage - Base message with required fields (chatId, conversationId, userId)
* @param label - Optional human-readable label for the state
* @param data - Optional additional data for the state
* @param variables - Optional variables associated with the state
* @param options - Optional publishing options (e.g., custom channel)
*/
publishState(state: string, baseMessage: Partial<BaseMessage>, label?: string, data?: any, variables?: any, options?: PublishOptions): Promise<void>;
/**
* Convenience method to publish common state transitions
*/
publishThinking(baseMessage: Partial<BaseMessage>, options?: PublishOptions): Promise<void>;
publishResponding(baseMessage: Partial<BaseMessage>, options?: PublishOptions): Promise<void>;
publishWaiting(baseMessage: Partial<BaseMessage>, options?: PublishOptions): Promise<void>;
publishComplete(baseMessage: Partial<BaseMessage>, options?: PublishOptions): Promise<void>;
publishError(error: string, baseMessage: Partial<BaseMessage>, options?: PublishOptions): Promise<void>;
}
/**
* Get singleton StatePublisher instance
* Maximum performance - no new objects created after first call
*
* @param host - Redis host (required on first call)
* @param port - Redis port (required on first call)
* @param password - Redis password (required on first call)
* @param providerId - Provider ID (required on first call)
* @param username - Redis username (optional)
* @param db - Redis database number (optional)
* @returns Singleton StatePublisher instance
*/
declare function getStatePublisher(host?: string, port?: number, password?: string, providerId?: string, username?: string, db?: number): StatePublisher;
/**
* Card Publisher - Publisher for card component data
*
* This publisher accepts flexible card JSON structures and publishes them as card components.
* The client renders these as card components with the provided data structure.
*/
interface Card extends BaseMessage {
__typename: "Cards";
component: {
type: "cards";
props: any;
};
}
declare class CardPublisher extends BasePublisher {
/**
* Publish card data with flexible JSON structure
* @param cardData - Any JSON structure for card data
* @param baseMessage - Base message properties
* @param options - Optional publishing options (e.g., custom channel)
*/
publishCard(cardData: any, baseMessage: Partial<BaseMessage>, options?: PublishOptions): Promise<void>;
/**
* Publish multiple cards (for workflow service compatibility)
* @param cardsData - Array of card data or single card data
* @param baseMessage - Base message properties
* @param options - Optional publishing options (e.g., custom channel)
*/
publishCards(cardsData: any[] | any, baseMessage: Partial<BaseMessage>, options?: PublishOptions): Promise<void>;
}
/**
* Get singleton CardPublisher instance
* Maximum performance - no new objects created after first call
*
* @param host - Redis host (required on first call)
* @param port - Redis port (required on first call)
* @param password - Redis password (required on first call)
* @param providerId - Provider ID (required on first call)
* @param username - Redis username (optional)
* @param db - Redis database number (optional)
* @returns Singleton CardPublisher instance
*/
declare function getCardPublisher(host?: string, port?: number, password?: string, providerId?: string, username?: string, db?: number): CardPublisher;
/**
* Questions Publisher - Publisher for follow-up questions data
*
* This publisher accepts an array of question strings and publishes them as follow-up questions.
* The client renders these as interactive question buttons or suggestions.
*/
interface Questions extends BaseMessage {
__typename: "Questions";
component: {
type: "questions";
props: string[];
};
}
declare class QuestionsPublisher extends BasePublisher {
/**
* Publish follow-up questions
* @param questions - Array of question strings
* @param baseMessage - Base message properties
* @param options - Optional publishing options (e.g., custom channel)
*/
publishQuestions(questions: string[], baseMessage: Partial<BaseMessage>, options?: PublishOptions): Promise<void>;
}
/**
* Get singleton QuestionsPublisher instance
* Maximum performance - no new objects created after first call
*
* @param host - Redis host (required on first call)
* @param port - Redis port (required on first call)
* @param password - Redis password (required on first call)
* @param providerId - Provider ID (required on first call)
* @param username - Redis username (optional)
* @param db - Redis database number (optional)
* @returns Singleton QuestionsPublisher instance
*/
declare function getQuestionsPublisher(host?: string, port?: number, password?: string, providerId?: string, username?: string, db?: number): QuestionsPublisher;
/**
* Form Publisher - Publisher for dynamic form structures
*
* This publisher accepts form configurations with steps, inputs, and validation rules.
* The client renders these as interactive multi-step forms with various input types.
*/
type FormInputType = "text" | "phone" | "email" | "date" | "number" | "password" | "url" | "textarea" | "boolean" | "select";
type FormLanguage = "ar" | "en";
interface FormInputOption {
label: string;
value: string;
}
interface FormInput {
description: string;
value: string | boolean;
inputType: FormInputType;
required?: boolean;
options: FormInputOption[];
placeholder?: string;
validation?: {
min?: number;
max?: number;
pattern?: string;
message?: string;
};
}
interface FormStep {
stepId: string;
title: string;
description?: string;
inputs: FormInput[];
nextStep?: string;
previousStep?: string;
}
interface FormStructure {
lang: FormLanguage;
steps: FormStep[];
}
interface Form extends BaseMessage {
__typename: "Form";
component: {
type: "form";
props: any;
};
}
declare class FormPublisher extends BasePublisher {
/**
* Publish a form structure
* @param formData - Form configuration with steps and inputs
* @param baseMessage - Base message properties
* @param options - Optional publishing options (e.g., custom channel)
*/
publishForm(formData: FormStructure, baseMessage: Partial<BaseMessage>, options?: PublishOptions): Promise<void>;
}
/**
* Get singleton FormPublisher instance
* Maximum performance - no new objects created after first call
*
* @param host - Redis host (required on first call)
* @param port - Redis port (required on first call)
* @param password - Redis password (required on first call)
* @param providerId - Provider ID (required on first call)
* @param username - Redis username (optional)
* @param db - Redis database number (optional)
* @returns Singleton FormPublisher instance
*/
declare function getFormPublisher(host?: string, port?: number, password?: string, providerId?: string, username?: string, db?: number): FormPublisher;
/**
* Messaging Types
*
* Exports all messaging-related type definitions
*/
interface BaseMessage {
id: string;
timestamp: string;
type: MessageType;
chatId?: string;
conversationId?: string;
userId?: string;
agentId?: string;
providerId?: string;
metadata?: Record<string, any>;
}
interface State extends BaseMessage {
__typename: "State";
stateData: Record<string, any>;
variables?: Record<string, any>;
}
type GravityMessage = Text | JsonData | ActionSuggestion | Metadata | ImageResponse | ToolOutput | AudioChunk | State | StateMessage | SystemMessage | ProgressUpdate | MessageChunk | Card | Questions | Form;
/**
* Shared Types
*
* Core types shared between client and server
*
* @module shared/types
*/
declare enum MessageType {
TEXT = "TEXT",
JSON_DATA = "JSON_DATA",
IMAGE_RESPONSE = "IMAGE_RESPONSE",
TOOL_OUTPUT = "TOOL_OUTPUT",
ACTION_SUGGESTION = "ACTION_SUGGESTION",
METADATA = "METADATA",
AUDIO_CHUNK = "AUDIO_CHUNK",
SYSTEM_MESSAGE = "SYSTEM_MESSAGE",
PROGRESS_UPDATE = "PROGRESS_UPDATE",
MESSAGE_CHUNK = "MESSAGE_CHUNK",
STATE = "STATE",
CARD = "CARD",
QUESTIONS = "QUESTIONS",
FORM = "FORM",
NODE_EXECUTION_EVENT = "NODE_EXECUTION_EVENT"
}
declare enum ChatState {
IDLE = "IDLE",
ACTIVE = "ACTIVE",
COMPLETE = "COMPLETE",
THINKING = "THINKING",
RESPONDING = "RESPONDING",
WAITING = "WAITING",
ERROR = "ERROR",
CANCELLED = "CANCELLED"
}
interface ServerMessage extends Omit<BaseMessage, "timestamp"> {
id: string;
providerId: string;
timestamp: number;
type: MessageType;
__typename: string;
}
declare const SYSTEM_CHANNEL = "gravity:system";
declare const AI_RESULT_CHANNEL = "gravity:output";
declare const QUERY_MESSAGE_CHANNEL = "gravity:query";
declare const INTERNAL_REQUEST_CHANNEL = "gravity:internal";
declare const WORKFLOW_EXECUTION_CHANNEL = "workflow:execution";
declare const WORKFLOW_STATE_CHANNEL = "gravity:workflow:state";
declare const TIMEOUTS: {
readonly DEFAULT: 5000;
readonly REQUEST: 10000;
};
declare const TYPE_TO_TYPENAME: Record<MessageType, string>;
/**
* Redis Connection Manager
*
* Centralizes Redis connection management to avoid redundant connections.
* Maintains separate pools for standard and pub/sub connections.
*/
/**
* Redis connection options with standardized fields
*/
interface RedisOptions {
host: string;
port: number;
password?: string;
username?: string;
db?: number;
}
/**
* Get a Redis connection for standard commands
* Reuses existing connections when possible
*/
declare function getStandardConnection(options: RedisOptions): Redis;
/**
* Get a dedicated Redis connection for pub/sub operations
* Always creates a new connection for pub/sub to avoid conflicts
*/
declare function getPubSubConnection(options: RedisOptions): Redis;
/**
* Get Redis options from environment variables
*/
declare function getRedisOptions(): RedisOptions;
/**
* Create RedisOptions from server config values
* Preferred method for proper Redis configuration
*/
declare function getOptionsFromConfig(host: string, port: number, username?: string | null, password?: string | null): RedisOptions;
/**
* Close all connections in the pool
* Useful for cleanup or tests
*/
declare function closeAllConnections(): Promise<void>;
/**
* Publisher for Gravity AI
*
* Handles publishing messages to Redis channels.
* This is the client-facing publisher that external services use.
*
* Key features:
* - Simple API for publishing to channels
* - Automatic connection management
* - Support for Redis credentials-based initialization
*
* Usage:
* ```typescript
* const publisher = Publisher.fromRedisCredentials({
* host: 'localhost',
* port: 6379,
* password: 'your-password'
* }, 'my-service');
* await publisher.publishEvent('channel', { data: 'hello' });
* ```
*/
declare class Publisher {
private redis;
private providerId;
constructor(options: RedisOptions, providerId: string);
static fromRedisCredentials(redisOptions: RedisOptions, providerId: string): Publisher;
static fromConfig(host: string, port: number, password: string | undefined, providerId: string, username?: string, db?: number): Publisher;
getProviderId(): string;
getRedisConnection(): Redis;
/**
* Publish system-level events
* Used by EventBus and system services
*/
publishSystem(message: any): Promise<void>;
/**
* Publish to arbitrary event channels
* Used by EventBus, n8n resolver, and health monitor
*/
publishEvent(eventType: string, payload: any): Promise<void>;
disconnect(): Promise<void>;
}
/**
* Simple Event Bus for Gravity AI
*/
type EventHandler<T = any> = (event: T) => void | Promise<void>;
declare class EventBus {
private options;
private serviceId;
private publisher;
private subscriber;
private handlers;
constructor(options: RedisOptions, serviceId: string);
static fromRedisConfig(host: string, port: number, password: string | undefined, serviceId: string, username?: string, db?: number): EventBus;
static fromCredentials(host: string, port: number, password: string | undefined, serviceId: string): EventBus;
private setupSubscriber;
publish(channel: string, payload: any): Promise<void>;
subscribe<T = any>(channel: string, handler: EventHandler<T>): Promise<() => Promise<void>>;
disconnect(): Promise<void>;
}
/**
* Batch Publisher - Maximum Performance
*
* Batches multiple messages into single Redis pipeline for ultra-fast publishing
* Use when you need to send multiple messages at once with minimal latency
*/
interface BatchMessage {
message: GravityMessage;
channel?: string;
}
/**
* High-performance batch publisher
* Sends multiple messages in a single Redis pipeline operation
*/
declare class BatchPublisher extends BasePublisher {
/**
* Publish multiple messages in a single batch operation
* Maximum performance - single Redis roundtrip for all messages
*
* @param messages - Array of messages to publish
* @param defaultChannel - Default channel if message doesn't specify one
*/
publishBatch(messages: BatchMessage[], defaultChannel?: string): Promise<void>;
/**
* Publish multiple messages to same channel
* Even faster when all messages go to same destination
*/
publishBatchToChannel(messages: GravityMessage[], channel: string): Promise<void>;
/**
* Publish streaming chunks in batch
* Optimized for high-frequency message chunks
*/
publishStreamingBatch(chunks: string[], baseMessage: any, channel?: string): Promise<void>;
}
/**
* Get singleton BatchPublisher instance
* Maximum performance - no new objects created after first call
*
* @param host - Redis host (required on first call)
* @param port - Redis port (required on first call)
* @param password - Redis password (required on first call)
* @param providerId - Provider ID (required on first call)
* @param username - Redis username (optional)
* @param db - Redis database number (optional)
* @returns Singleton BatchPublisher instance
*/
declare function getBatchPublisher(host?: string, port?: number, password?: string, providerId?: string, username?: string, db?: number): BatchPublisher;
/**
* Node execution event publisher
*
* Publishes node execution events to the unified AI channel for debugging and monitoring.
*
* @module messaging/publishers/nodeExecution
*/
/**
* NodeExecutionPublisher - Handles node execution events in unified AI channel
*/
declare class NodeExecutionPublisher extends BasePublisher {
/**
* Publishes a workflow node completion event
*
* @param workflowId - Workflow ID
* @param executionId - Execution ID
* @param nodeId - Node ID that completed
* @param nodeType - Type of node
* @param status - Completion status
* @param result - Node execution result
* @param error - Error message if failed
* @param duration - Execution duration in milliseconds
* @param triggeredSignals - Signals triggered by this completion
* @param baseMessage - Base message with required fields (chatId, conversationId, userId)
* @param options - Optional publishing options (e.g., custom channel)
*/
publishNodeCompletion(workflowId: string, executionId: string, nodeId: string, nodeType: string, status: "completed" | "failed" | "running", result: any, error: string | undefined, duration: number | null, triggeredSignals: Array<{
targetNode: string;
signal: string;
inputs?: any;
}>, baseMessage: Partial<BaseMessage>, options?: PublishOptions): Promise<void>;
}
/**
* Get singleton NodeExecutionPublisher instance
* Maximum performance - no new objects created after first call
*
* @param host - Redis host (required on first call)
* @param port - Redis port (required on first call)
* @param password - Redis password (required on first call)
* @param providerId - Provider ID (required on first call)
* @param username - Redis username (optional)
* @param db - Redis database number (optional)
* @returns Singleton NodeExecutionPublisher instance
*/
declare function getNodeExecutionPublisher(host?: string, port?: number, password?: string, providerId?: string, username?: string, db?: number): NodeExecutionPublisher;
/**
* Input Message Types
*
* Defines input message structures for workflow triggers and user input
*/
/**
* Raw input message structure (from GraphQL AgentInput)
*/
interface InputMessage {
chatId: string;
conversationId: string;
userId: string;
providerId: string;
timestamp: string | number;
message: string;
metadata?: any;
}
/**
* Typed input message for GraphQL/messaging system
*/
interface TypedInputMessage extends BaseMessage {
__typename: "InputMessage";
message: string;
metadata?: any;
}
export { AI_RESULT_CHANNEL, type ActionSuggestion, type AudioChunk, type BaseMessage, BasePublisher, type BatchMessage, BatchPublisher, type Card, CardPublisher, ChatState, EventBus, type EventHandler, type Form, type FormInput, type FormInputOption, type FormInputType, type FormLanguage, FormPublisher, type FormStep, type FormStructure, type GravityMessage, INTERNAL_REQUEST_CHANNEL, type ImageResponse, type InputMessage, type JsonData, JsonDataPublisher, type MessageChunk, MessageChunkPublisher, MessageType, type Metadata, NodeExecutionPublisher, ProgressPublisher, type ProgressUpdate, type PublishOptions, Publisher, QUERY_MESSAGE_CHANNEL, type Questions, QuestionsPublisher, type RedisOptions, SYSTEM_CHANNEL, type ServerMessage, type State, type StateMessage, StatePublisher, type SystemMessage, SystemPublisher, TIMEOUTS, TYPE_TO_TYPENAME, type Text, TextPublisher, type ToolOutput, type TypedInputMessage, WORKFLOW_EXECUTION_CHANNEL, WORKFLOW_STATE_CHANNEL, closeAllConnections, createAudioChunk, getBatchPublisher, getCardPublisher, getFormPublisher, getJsonDataPublisher, getMessageChunkPublisher, getNodeExecutionPublisher, getOptionsFromConfig, getProgressPublisher, getPubSubConnection, getQuestionsPublisher, getRedisOptions, getStandardConnection, getStatePublisher, getSystemPublisher, getTextPublisher };