/**
* Unified Events Module - World and Agent Event Functions
*
* Purpose: Event-driven message publishing, agent response processing, and memory persistence
*
* Logging: Enable with LOG_EVENTS=debug or specific categories:
* - LOG_EVENTS_PUBLISH, LOG_EVENTS_AGENT, LOG_EVENTS_RESPONSE, LOG_EVENTS_MEMORY
* - LOG_EVENTS_AUTOMENTION, LOG_EVENTS_TURNLIMIT, LOG_EVENTS_CHATTITLE
*
* Core Features:
* - Event publishing/subscription via World.eventEmitter with type safety
* - Agent message filtering with mention detection and turn limits
* - Auto-mention logic with loop prevention and world tags (STOP|TO:a,b)
* - Message threading with replyToMessageId preservation
* - Event persistence with automatic chatId defaulting to world.currentChatId
* - Tool approval system with session/one-time approval tracking
* - Chat title generation on world idle events
*
* Recent Changes (2025-11):
* - Fixed tool event metadata validation errors: Added required ownerAgentId and
* triggeredByMessageId fields to toolHandler, added validation guards to reject
* tool events missing messageId or agentName
* - Removed unnecessary 'info' event emission from tool-utils.ts to prevent validation errors
* - Fixed approval response broadcast bug: Removed HUMAN check from shouldAutoMention to ensure
* agent responses to HUMAN approval messages include proper targeting mentions (@HUMAN),
* preventing unintended broadcast to all agents
* - Consolidated redundant logging and streamlined approval checking
* - Added tool_calls/tool_call_id persistence for approval messages
* - Pre-generate message IDs for agent responses
* - Fixed activity tracking to prevent premature idle signals
*/
import { World, Agent, WorldMessageEvent, WorldSSEEvent, WorldToolEvent, AgentMessage } from './types.js';
export declare function enableStreaming(): void;
export declare function disableStreaming(): void;
/**
* Publish CRUD event for agent, chat, or world configuration changes
* Allows subscribed clients to receive real-time updates for all CRUD operations
*/
export declare function publishCRUDEvent(world: World, operation: 'create' | 'update' | 'delete', entityType: 'agent' | 'chat' | 'world', entityId: string, entityData?: any): void;
/**
* Setup automatic event persistence listeners on World event emitter.
* Should be called once during World initialization.
*
* Events are persisted synchronously/awaitable for reliability.
* Failures are logged but don't block event emission.
* Returns a cleanup function to remove listeners.
*
* Environment variables:
* - DISABLE_EVENT_PERSISTENCE=true: Skip all persistence
*/
export declare function setupEventPersistence(world: World): () => void;
/**
* Publish event to a specific channel using World.eventEmitter
*/
export declare function publishEvent(world: World, type: string, content: any): void;
/**
* Message publishing using World.eventEmitter with chat session management
* Parses enhanced string protocol and automatically prepends @mention if agentId detected
* Returns the messageEvent so callers can access the generated messageId
*
* @param chatId - Optional chat ID. If not provided, uses world.currentChatId
* @param replyToMessageId - Optional parent message ID for threading
*/
export declare function publishMessage(world: World, content: string, sender: string, chatId?: string | null, replyToMessageId?: string): WorldMessageEvent;
/**
* Message publishing with pre-generated messageId
* Used when messageId needs to be known before publishing (e.g., for agent responses)
*
* @param chatId - Optional chat ID. If not provided, uses world.currentChatId
* @param replyToMessageId - Optional parent message ID for threading
*/
export declare function publishMessageWithId(world: World, content: string, sender: string, messageId: string, chatId?: string | null, replyToMessageId?: string): WorldMessageEvent;
export declare function subscribeToMessages(world: World, handler: (event: WorldMessageEvent) => void): () => void;
/**
* SSE events using World.eventEmitter (for LLM streaming)
*/
export declare function publishSSE(world: World, data: Partial): void;
/**
* Tool events using World.eventEmitter (for agent behavioral events)
*/
export declare function publishToolEvent(world: World, data: Partial): void;
/**
* Publish approval request event
* Used when a tool requires approval before execution
* Note: This function is legacy - approval requests now use direct message events
* with OpenAI tool call protocol (see tool-utils.ts)
*/
export declare function publishApprovalRequest(world: World, approvalRequest: any, agentId: string, messageId: string): void;
/**
* SSE subscription using World.eventEmitter
*/
export declare function subscribeToSSE(world: World, handler: (event: WorldSSEEvent) => void): () => void;
export declare function hasAnyMentionAtBeginning(response: string): boolean;
export declare function removeMentionsFromParagraphBeginnings(text: string, specificMention?: string): string;
export declare function addAutoMention(response: string, sender: string): string;
export declare function getValidMentions(response: string, agentId: string): string[];
export declare function shouldAutoMention(response: string, sender: string, agentId: string): boolean;
export declare function removeSelfMentions(response: string, agentId: string): string; /**
* Agent subscription with automatic message processing
*/
export declare function subscribeAgentToMessages(world: World, agent: Agent): () => void;
/**
* Save incoming message to agent memory with auto-save
*/
export declare function saveIncomingMessageToMemory(world: World, agent: Agent, messageEvent: WorldMessageEvent): Promise;
/**
* Agent message processing with LLM response generation and auto-mention logic
*/
export declare function processAgentMessage(world: World, agent: Agent, messageEvent: WorldMessageEvent): Promise;
/**
* Reset LLM call count for human/world messages with persistence
*/
export declare function resetLLMCallCountIfNeeded(world: World, agent: Agent, messageEvent: WorldMessageEvent): Promise;
/**
* Enhanced message filtering logic with turn limits and mention detection
*/
export declare function shouldAgentRespond(world: World, agent: Agent, messageEvent: WorldMessageEvent): Promise;
/**
* Subscribe world to messages with cleanup function
*/
export declare function subscribeWorldToMessages(world: World): () => void;
/**
* Setup world activity listener for chat title updates
* Triggers title generation when world becomes idle (pendingOperations === 0)
*/
export declare function setupWorldActivityListener(world: World): () => void;
/**
* Check if a specific tool requires approval based on message history
* Simplified: Only checks for session-wide approval, not one-time or denials
*
* Logic:
* 1. Search for session approval → Execute immediately
* 2. No session approval → Request approval
*
* @param context - Execution context with workingDirectory (CRITICAL FIX: AR Issue #1)
*/
export declare function checkToolApproval(world: World, toolName: string, toolArgs: any, message: string, messages: AgentMessage[], context?: {
workingDirectory?: string;
[key: string]: any;
}): Promise<{
needsApproval: boolean;
canExecute: boolean;
approvalRequest?: any;
reason?: string;
}>;
/**
* Find session-wide approval for a tool in message history
* Supports both enhanced string protocol (JSON) and legacy text parsing
*
* Session approval matches on:
* - Tool name (required)
* - Working directory (if provided)
* - Parameters (exact match)
*
* Enhanced protocol format:
* {
* role: 'tool',
* tool_call_id: 'approval_...',
* content: '{"__type":"tool_result","content":"{\"decision\":\"approve\",\"scope\":\"session\",\"toolName\":\"...\",\"toolArgs\":{...},\"workingDirectory\":\"...\"}"}'
* }
*/
export declare function findSessionApproval(messages: AgentMessage[], toolName: string, toolArgs?: any, workingDirectory?: string): {
decision: 'approve';
scope: 'session';
toolName: string;
} | undefined;
/**
* @deprecated This function is no longer used in approval checking logic.
* One-time approvals are consumed after tool execution, checking for them is redundant.
* Kept for backwards compatibility only.
*/
export declare function findRecentApproval(messages: AgentMessage[], toolName: string): {
decision: 'approve' | 'deny';
scope: 'once';
toolName: string;
} | undefined;
/**
* @deprecated This function is no longer used in approval checking logic.
* Users should be allowed to change their mind about denials.
* Kept for backwards compatibility only.
*/
export declare function findRecentDenial(messages: AgentMessage[], toolName: string): {
decision: 'deny';
toolName: string;
} | undefined;
//# sourceMappingURL=events.d.ts.map