declare class EventEmitter { private events; on(eventName: string, listener: Function): void; off(eventName: string, listener: Function): void; removeListener(eventName: string, listener: Function): void; emit(eventName: string, ...args: any[]): void; setMaxListeners(n: number): void; } import { KernelEvents, IKernel, IFileSystemMountOptions } from "./types"; export { KernelEvents }; export declare enum KernelMode { MAIN_THREAD = "main_thread", WORKER = "worker" } export declare enum KernelLanguage { PYTHON = "python" } export interface IKernelPoolConfig { enabled: boolean; poolSize: number; autoRefill: boolean; preloadConfigs: Array<{ mode: KernelMode; language: KernelLanguage; }>; } export interface IKernelManagerOptions { pool?: IKernelPoolConfig; allowedKernelTypes?: Array<{ mode: KernelMode; language: KernelLanguage; }>; interruptionMode?: 'shared-array-buffer' | 'kernel-interrupt' | 'auto'; workerUrl?: string; } export interface IKernelInstance { id: string; kernel: IKernel; mode: KernelMode; language: KernelLanguage; worker?: Worker; created: string; options: IManagerKernelOptions; isFromPool?: boolean; destroy(): Promise; } export interface IDenoPermissions { read?: (string | URL)[]; write?: (string | URL)[]; net?: string[]; env?: string[]; run?: string[]; ffi?: string[]; hrtime?: boolean; } export interface IManagerKernelOptions { id?: string; mode?: KernelMode; lang?: KernelLanguage; namespace?: string; deno?: { permissions?: IDenoPermissions; }; filesystem?: IFileSystemMountOptions; env?: Record; lockFileURL?: string; autoSyncFs?: boolean; inactivityTimeout?: number; maxExecutionTime?: number; } /** * KernelManager class manages multiple kernel instances * in either main thread or worker mode */ export declare class KernelManager extends EventEmitter { private kernels; private listenerWrappers; private lastActivityTime; private inactivityTimers; private ongoingExecutions; private executionTimeouts; private executionStartTimes; private executionMetadata; private abortControllers; private pool; private poolConfig; private isPreloading; private prefillingInProgress; private allowedKernelTypes; private interruptBuffers; private interruptionMode; private workerUrl; /** * Resolve the worker URL based on the current environment * @private * @returns The resolved worker URL */ private resolveWorkerUrl; /** * Helper function to check if an error is a KeyboardInterrupt * @private */ private isKeyboardInterrupt; /** * Helper function to create a standardized KeyboardInterrupt error result * @private */ private createKeyboardInterruptResult; /** * Store an AbortController for a specific kernel execution * @private */ private storeAbortController; /** * Remove and return an AbortController for a specific kernel execution * @private */ private removeAbortController; /** * Abort all ongoing operations for a specific kernel * @private */ private abortAllKernelOperations; constructor(options?: IKernelManagerOptions); /** * Generate a pool key for a given mode and language combination * @param mode Kernel mode * @param language Kernel language * @returns Pool key string * @private */ private getPoolKey; /** * Get a kernel promise from the pool if available * @param mode Kernel mode * @param language Kernel language * @returns Kernel promise or null if none available * @private */ private getFromPool; /** * Add a kernel promise to the pool * @param mode Kernel mode * @param language Kernel language * @param kernelPromise Kernel promise * @private */ private addToPool; /** * Refill the pool with a single kernel promise * @param mode Kernel mode * @param language Kernel language * @private */ private refillPoolSingle; /** * Refill the pool for a specific configuration with parallel creation * @param mode Kernel mode * @param language Kernel language * @private */ private refillPool; /** * Create a kernel promise for the pool * @param mode Kernel mode * @param language Kernel language * @returns Promise that resolves to a kernel instance * @private */ private createPoolKernelPromise; /** * Create a kernel specifically for the pool * @param mode Kernel mode * @param language Kernel language * @returns Kernel instance * @private */ private createPoolKernel; /** * Preload the kernel pool with configured kernel types * @private */ private preloadPool; /** * Check if a kernel request can use the pool * @param options Kernel creation options * @returns True if the request can use pool * @private */ private canUsePool; /** * Reassign a pool kernel with new ID and options * @param poolKernel Kernel from pool * @param newId New kernel ID * @param options Kernel options * @returns Updated kernel instance * @private */ private reassignPoolKernel; /** * Get pool statistics for debugging/monitoring * @returns Pool statistics */ getPoolStats(): Record; /** * Get pool configuration information * @returns Pool configuration details */ getPoolConfig(): { enabled: boolean; poolSize: number; autoRefill: boolean; preloadConfigs: Array<{ mode: KernelMode; language: KernelLanguage; }>; isPreloading: boolean; }; /** * Get the current worker URL configuration * @returns The worker URL or undefined if using auto-detection */ getWorkerUrl(): string | undefined; /** * Set a custom worker URL for kernel workers * @param url The URL to the kernel.worker.js file * @example * // For CDN usage: * manager.setWorkerUrl('https://cdn.jsdelivr.net/npm/web-python-kernel@latest/dist/kernel.worker.js'); * // For local development: * manager.setWorkerUrl('/dist/kernel.worker.js'); */ setWorkerUrl(url: string | undefined): void; /** * Create a new kernel instance * @param options Options for creating the kernel * @param options.id Optional custom ID for the kernel * @param options.mode Optional kernel mode (main_thread or worker) * @param options.lang Optional kernel language (python or typescript) * @param options.namespace Optional namespace prefix for the kernel ID * @param options.deno.permissions Optional Deno permissions for worker mode * @param options.filesystem Optional filesystem mounting options * @param options.inactivityTimeout Optional timeout in ms after which an inactive kernel will be shut down * @param options.maxExecutionTime Optional maximum time in ms an execution can run before considered stuck * @returns Promise resolving to the kernel instance ID */ createKernel(options?: IManagerKernelOptions): Promise; /** * Setup a pool kernel from a promise with new ID and options * @param poolKernelPromise Kernel promise from pool * @param id New kernel ID * @param options Kernel options * @returns Kernel ID (returned after kernel is ready) * @private */ private setupPoolKernelFromPromise; /** * Setup a pool kernel with new ID and options (for already resolved kernels) * @param poolKernel Kernel from pool * @param id New kernel ID * @param options Kernel options * @returns Kernel ID * @private */ private setupPoolKernel; /** * Create a kernel on-demand (not from pool) * @param id Kernel ID * @param mode Kernel mode * @param language Kernel language * @param options Kernel options * @returns Kernel ID * @private */ private createOnDemandKernel; /** * Create a kernel instance running in the main thread * @param id Kernel ID * @returns Kernel instance */ private createMainThreadKernel; /** * Create a kernel instance running in a worker * @param id Kernel ID * @returns Kernel instance */ private createWorkerKernel; /** * Setup event forwarding from kernel to manager * @param instance Kernel instance */ private setupEventForwarding; /** * Get a kernel instance by ID * @param id Kernel ID * @returns Kernel instance or undefined if not found */ getKernel(id: string): IKernelInstance | undefined; /** * Get a list of all kernel IDs * @returns Array of kernel IDs */ getKernelIds(): string[]; /** * Get a list of all kernels with their details * @param namespace Optional namespace to filter kernels by * @returns Array of kernel information objects */ listKernels(namespace?: string): Promise>; /** * Destroy a kernel instance * @param id Kernel ID * @returns Promise resolving when kernel is destroyed */ destroyKernel(id: string): Promise; /** * Destroy all kernel instances * @param namespace Optional namespace to filter kernels to destroy * @returns Promise resolving when all kernels are destroyed */ destroyAll(namespace?: string): Promise; /** * Destroy all kernels in the pool * @private */ private destroyPool; /** * Register an event listener for a specific kernel's events * @param kernelId Kernel ID * @param eventType Event type * @param listener Event listener */ onKernelEvent(kernelId: string, eventType: KernelEvents, listener: (data: any) => void): void; /** * Remove an event listener for a specific kernel * @param kernelId Kernel ID * @param eventType Event type * @param listener Event listener */ offKernelEvent(kernelId: string, eventType: KernelEvents, listener: (data: any) => void): void; /** * Store a listener wrapper for later removal */ private storeListener; /** * Get a stored listener wrapper */ private getListener; /** * Remove a stored listener wrapper */ private removeStoredListener; /** * Remove all listeners for a specific kernel */ private removeAllKernelListeners; /** * Get all listeners for a specific kernel and event type * @param kernelId Kernel ID * @param eventType Event type * @returns Array of listeners */ getListeners(kernelId: string, eventType: KernelEvents): ((data: any) => void)[]; /** * Execute Python code with streaming output * This method works in both main thread and worker modes * @param kernelId ID of the kernel to use * @param code The Python code to execute * @param parent Optional parent message header * @returns AsyncGenerator yielding intermediate outputs */ executeStream(kernelId: string, code: string, parent?: any): AsyncGenerator; /** * Track a new execution task for a kernel * @param kernelId Kernel ID * @param code Optional code being executed for metadata * @returns Unique execution ID * @private */ private trackExecution; /** * Complete tracking for an execution * @param kernelId Kernel ID * @param executionId Execution ID * @private */ private completeExecution; /** * Check if a kernel has any ongoing executions * @param kernelId Kernel ID * @returns True if the kernel has ongoing executions * @private */ private hasOngoingExecutions; /** * Get the count of ongoing executions for a kernel * @param id Kernel ID * @returns Number of ongoing executions */ getOngoingExecutionCount(id: string): number; /** * Set up an inactivity timeout for a kernel * @param id Kernel ID * @param timeout Timeout in milliseconds * @private */ private setupInactivityTimeout; /** * Clear any existing inactivity timeout for a kernel * @param id Kernel ID * @private */ private clearInactivityTimeout; /** * Update activity timestamp for a kernel and reset inactivity timer if present * @param id Kernel ID * @private */ private updateKernelActivity; /** * Get the last activity time for a kernel * @param id Kernel ID * @returns Last activity time in milliseconds since epoch, or undefined if not found */ getLastActivityTime(id: string): number | undefined; /** * Get the inactivity timeout for a kernel * @param id Kernel ID * @returns Inactivity timeout in milliseconds, or undefined if not set */ getInactivityTimeout(id: string): number | undefined; /** * Set or update the inactivity timeout for a kernel * @param id Kernel ID * @param timeout Timeout in milliseconds, or 0 to disable * @returns True if the timeout was set, false if the kernel was not found */ setInactivityTimeout(id: string, timeout: number): boolean; /** * Get time until auto-shutdown for a kernel * @param id Kernel ID * @returns Time in milliseconds until auto-shutdown, or undefined if no timeout is set */ getTimeUntilShutdown(id: string): number | undefined; /** * Get the map of inactivity timers (for debugging/testing only) * @returns Object with kernel IDs as keys and timer IDs as values */ getInactivityTimers(): Record; /** * Set up a handler for stalled executions * @param id Kernel ID * @private */ private setupStalledExecutionHandler; /** * Force terminate a potentially stuck kernel * @param id Kernel ID * @param reason Optional reason for termination * @returns Promise resolving to true if the kernel was terminated */ forceTerminateKernel(id: string, reason?: string): Promise; /** * Get information about ongoing executions for a kernel * @param id Kernel ID * @returns Information about ongoing executions with accurate timing */ getExecutionInfo(id: string): { count: number; isStuck: boolean; executionIds: string[]; longestRunningTime?: number; executions: Array<{ id: string; startTime: number; runtime: number; code?: string; isStuck: boolean; }>; }; /** * Execute Python code in a kernel * Uses executeStream to collect all outputs and return them * @param kernelId ID of the kernel to use * @param code Python code to execute * @param parent Optional parent message header * @returns Promise resolving to execution result with collected outputs */ execute(kernelId: string, code: string, parent?: any): Promise<{ success: boolean; outputs?: any; error?: Error; ename?: string; evalue?: string; traceback?: any; }>; /** * Check if a kernel type is allowed * @param mode Kernel mode * @param language Kernel language * @returns True if the kernel type is allowed * @private */ private isKernelTypeAllowed; /** * Get the list of allowed kernel types * @returns Array of allowed kernel type configurations */ getAllowedKernelTypes(): Array<{ mode: KernelMode; language: KernelLanguage; }>; /** * Ping a kernel to reset its activity timer and extend the deadline * @param id Kernel ID * @returns True if the kernel was pinged successfully, false if not found */ pingKernel(id: string): boolean; /** * Restart a kernel by destroying it and creating a new one with the same ID and configuration * @param id Kernel ID * @returns Promise resolving to true if the kernel was restarted successfully, false if not found */ restartKernel(id: string): Promise; /** * Interrupt a running kernel execution * @param id Kernel ID * @returns Promise resolving to true if the interrupt was successful, false if not found or failed */ interruptKernel(id: string): Promise; /** * Interrupt a main thread kernel * @param id Kernel ID * @param instance Kernel instance * @returns Promise resolving to interrupt success * @private */ private interruptMainThreadKernel; /** * Interrupt a worker kernel using SharedArrayBuffer according to Pyodide documentation * @param id Kernel ID * @param instance Kernel instance * @returns Promise resolving to interrupt success * @private */ private interruptWorkerKernel; /** * Fallback interrupt method for worker kernels when SharedArrayBuffer is not available * @param id Kernel ID * @param worker Worker instance * @returns Promise resolving to interrupt success * @private */ private interruptWorkerKernelFallback; /** * Handle a stuck execution with configurable strategies * @param kernelId Kernel ID * @param executionId Execution ID that's stuck * @param actualRuntime How long the execution has been running * @param code The code that was being executed * @private */ private handleStuckExecution; /** * Get detailed information about stuck executions across all kernels * @returns Array of stuck execution details */ getStuckExecutions(): Array<{ kernelId: string; executionId: string; startTime: number; runtime: number; maxAllowed: number; code?: string; kernelMode: KernelMode; kernelLanguage: KernelLanguage; }>; /** * Force interrupt all stuck executions across all kernels * @returns Promise resolving to array of intervention results */ handleAllStuckExecutions(): Promise>; /** * Set up interrupt buffer for a worker kernel during creation * @param id Kernel ID * @param worker Worker instance * @private */ private setupWorkerInterruptBuffer; /** * Get information about mounted filesystems for a specific kernel * @param id Kernel ID * @returns Promise resolving to array of mounted filesystem info */ getMountedFileSystems(id: string): Promise>; /** * Manually sync a specific mounted filesystem for a kernel * @param id Kernel ID * @param mountPath The path of the mounted filesystem to sync * @returns Promise resolving to sync result */ syncFileSystem(id: string, mountPath: string): Promise<{ success: boolean; error?: string; }>; /** * Upgrade a mounted filesystem from read-only to read-write permission * @param id Kernel ID * @param mountPath The path of the mounted filesystem to upgrade * @returns Promise resolving to upgrade result */ upgradeFileSystemPermission(id: string, mountPath: string): Promise<{ success: boolean; error?: string; }>; } //# sourceMappingURL=manager.d.ts.map