/** * Headless Session Manager for Gateway Type 3 * Manages multi-turn inference sessions without UI for remote automation * * Purpose: * - Enable Type 1 web chat/API to remotely execute inference sessions on Type 3 * - Execute MCP tools (bash, file operations) for automation tasks * - Support streaming responses back to Type 1 * - Manage session state and conversation history */ import { EventEmitter } from 'events'; import { LocalVault } from './local-vault'; export interface SystemEnvironment { platform: 'windows' | 'linux' | 'darwin' | 'unknown'; platformName: string; shell: string; shellType: 'powershell' | 'cmd' | 'bash' | 'zsh' | 'sh' | 'unknown'; arch: string; hostname: string; homeDir: string; tempDir: string; nodeVersion: string; cpuCount: number; totalMemory: string; freeMemory: string; } /** * Detect the current system environment */ export declare function detectSystemEnvironment(): SystemEnvironment; export interface ConversationMessage { role: 'user' | 'assistant' | 'system' | 'tool'; content: string; timestamp: string; tool_calls?: ToolCall[]; tool_call_id?: string; name?: string; } export interface ToolCall { id: string; type: 'function'; function: { name: string; arguments: string; }; } export interface SessionConfig { sessionId?: string; userId: string; organizationId?: string; templateId?: string; systemPrompt?: string; includeEnvironmentInfo?: boolean; initialMessage?: string; modelId?: string; connectionId?: string; maxTurns?: number; timeout?: number; disabledTools?: string[]; } export interface SessionState { sessionId: string; gatewayId: string; userId: string; organizationId?: string; templateId?: string; status: 'active' | 'completed' | 'failed' | 'cancelled' | 'timeout'; messages: ConversationMessage[]; modelId: string; connectionId: string; startedAt: Date; lastActivityAt: Date; completedAt?: Date; totalTokens: number; toolCallsCount: number; errorMessage?: string; disabledTools: Set; } export interface SessionResponse { sessionId: string; status: SessionState['status']; message?: ConversationMessage; isComplete: boolean; error?: string; retryable?: boolean; assistant_message?: string; tool_calls?: ToolCallBundle[]; tools_available?: string[]; tools_enabled?: string[]; llm_iterations?: number; request_log_ids?: string[]; usage?: { prompt_tokens: number; completion_tokens: number; total_tokens: number; }; toolResults?: ToolExecutionResult[]; toolCalls?: ToolCall[]; requestIds?: string[]; } /** * ToolCallBundle - Tool call with result bundled together * This is what gets stored in session.messages */ export interface ToolCallBundle { tool_call_id: string; tool_name: string; arguments: Record; result: { success: boolean; output: string | null; error: string | null; duration_ms: number; }; } export interface ToolExecutionResult { toolName: string; success: boolean; output?: string; error?: string; duration: number; } export interface StreamChunk { type: 'content' | 'tool_call' | 'tool_result' | 'error' | 'done'; content?: string; toolCall?: ToolCall; toolResult?: ToolExecutionResult; error?: string; sessionId: string; timestamp: string; } export declare class HeadlessSessionManager extends EventEmitter { private sessions; private coreTools; private webTools; private automationTools; private userTools; private organizationTools; private collectionTools; private billingTools; private supportTools; private adminTools; private agentTools; private sellerTools; private registryTools; private vault; private keyVault; private gatewayId; private registryUrl; private inferenceUrl; private inferenceUrlExpiry; private apiKey; private toolsValidated; private readonly DEFAULT_MAX_TURNS; private readonly DEFAULT_TIMEOUT; private readonly MAX_TOOL_OUTPUT_LENGTH; private readonly INFERENCE_URL_CACHE_TTL; constructor(config: { gatewayId: string; vault: LocalVault; registryUrl: string; apiKey: string; }); /** * Get the active inference server URL * Checks the platform for the configured active inference server and caches the result * Falls back to registryUrl if the check fails */ private getInferenceUrl; /** * Get all available tools (for tool discovery) */ getAvailableTools(): any[]; /** * Start a new headless session */ startSession(config: SessionConfig): Promise; /** * Restore a session from existing messages * Used when Gateway Type 3 receives a message for a session that is no longer in memory * (e.g., after gateway restart, session completion, or long idle period) */ restoreSession(sessionId: string, config: { userId: string; organizationId?: string; sessionType?: string; modelId?: string; messages: Array<{ role: string; content: string; timestamp?: string; }>; systemPrompt?: string; includeEnvironmentInfo?: boolean; disabledTools?: string[]; }): Promise; /** * Process a message in an existing session * Handles multi-turn tool calling loop * @param modelId - Optional model ID to use for this specific message (overrides session default) */ processMessage(sessionId: string, message: string, onChunk?: (chunk: StreamChunk) => void, modelId?: string): Promise; /** * Cancel an active session */ cancelSession(sessionId: string): Promise; /** * Get session state */ getSession(sessionId: string): SessionState | undefined; /** * Get all active sessions */ getActiveSessions(): SessionState[]; /** * Complete a session */ completeSession(sessionId: string): boolean; /** * Build environment information block * Returns OS, shell, and platform-specific command guidance */ private buildEnvironmentInfo; /** * Build default system prompt for automation * @param includeEnvInfo Whether to include environment information (default: true) */ private buildDefaultSystemPrompt; /** * Call LLM via marketplace API * Returns both the response data and the request ID for logging */ private callLLM; /** * Execute a tool call */ private executeTool; /** * Check and handle session timeout */ private checkSessionTimeout; /** * Cleanup old sessions (called periodically) */ cleanupOldSessions(maxAgeMs?: number): number; /** * Export session for persistence */ exportSession(sessionId: string): object | null; } /** * Usage Example: * * const sessionManager = new HeadlessSessionManager({ * gatewayId: 'gw3-local-001', * vault: localVault, * marketplaceUrl: 'http://localhost:8081', * apiKey: 'sk-test-inference-key' * }); * * // Start a session * const session = await sessionManager.startSession({ * userId: 'user-123', * systemPrompt: 'You are an automation assistant...', * initialMessage: 'Install vLLM on this system' * }); * * // Process messages * const response = await sessionManager.processMessage( * session.sessionId, * 'Check the GPU status first', * (chunk) => console.log('Chunk:', chunk) * ); * * // Complete session * sessionManager.completeSession(session.sessionId); */ //# sourceMappingURL=headless-session.d.ts.map