import { WorkerAdapterConfig, HttpAdapterConfig, Logger, PackDataMessage, Pack, Pod, ExecutionHandle, TaskHandle, PackExecutionResult, ShutdownHandler, PodLifecyclePhase, PodLogSink, PoolStats, VolumeFileEntry } from '@stark-o/shared'; export { ExecutionHandle, PackExecutionContext, PackExecutionResult } from '@stark-o/shared'; import { FsAdapterConfig } from '../adapters/fs-adapter.js'; import 'node:fs'; /** * Pack Executor * @module @stark-o/node-runtime/executor/pack-executor * * Executes pack bundles in sub-processes for isolated, concurrent execution. * Provides lifecycle management, resource tracking, and error handling. */ /** * Pack executor configuration */ interface PackExecutorConfig { /** Base directory for pack bundles (default: process.cwd()) */ bundleDir?: string; /** Orchestrator URL for downloading bundles (optional) */ orchestratorUrl?: string; /** Auth token for bundle downloads */ authToken?: string; /** Orchestrator WebSocket URL for pod networking (e.g., wss://localhost/ws) */ orchestratorWsUrl?: string; /** Skip TLS verification for orchestrator WebSocket (dev only) */ insecure?: boolean; /** Worker adapter configuration */ workerConfig?: WorkerAdapterConfig; /** File system adapter configuration */ fsConfig?: FsAdapterConfig; /** HTTP adapter configuration */ httpConfig?: HttpAdapterConfig; /** Default execution timeout in milliseconds (default: 0 = no timeout) */ defaultTimeout?: number; /** Maximum concurrent executions (default: 10) */ maxConcurrent?: number; /** Maximum memory per worker process in MB (sets --max-old-space-size for sub-processes) */ maxMemoryMB?: number; /** * Graceful shutdown timeout in milliseconds (default: 5000 = 5 seconds) * Time to wait for pack code to handle shutdown before force terminating */ gracefulShutdownTimeout?: number; /** Logger instance */ logger?: Logger; } /** * Execution status for tracking */ interface ExecutionState { executionId: string; podId: string; packId: string; status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled'; handle?: TaskHandle; startedAt: Date; completedAt?: Date; result?: PackExecutionResult; /** Shutdown handlers registered by pack code */ shutdownHandlers: ShutdownHandler[]; /** Function to update lifecycle phase */ setLifecyclePhase: (phase: PodLifecyclePhase) => void; /** Function to request shutdown */ requestShutdown: (reason?: string) => void; /** Log sink for stdout/stderr */ logSink: PodLogSink; /** Worker adapter taskId (set when pack runs in a subprocess) */ workerTaskId?: string; } /** * Pack Executor * * Manages the execution of pack bundles in isolated sub-processes. * Features: * - Concurrent execution with worker pool * - Execution lifecycle management (start, stop, cancel) * - Resource tracking and limits * - Timeout handling * - Error isolation per execution */ declare class PackExecutor { private readonly config; private workerAdapter; private fsAdapter; private httpAdapter; private initialized; private readonly executions; private readonly podExecutions; /** Message handlers for main-thread packs (keyed by podId) */ private readonly mainThreadMessageHandlers; constructor(config?: PackExecutorConfig); /** * Update the auth token on the existing HTTP adapter without * recreating the executor or disrupting running pods. */ updateAuthToken(token: string): void; /** * Send a data-update message to a running pod. * * Transport is chosen automatically: * - main-thread packs → direct callback invocation * - subprocess packs → IPC (process.send) * * @returns `true` if the message was delivered, `false` if the pod was * not found or not running. */ sendMessage(podId: string, message: PackDataMessage): boolean; /** * Initialize the pack executor. * Must be called before executing any packs. */ initialize(): Promise; /** * Check if the executor is initialized */ isInitialized(): boolean; /** * Ensure the executor is initialized before operations */ private ensureInitialized; /** * Execute a pack for a pod. * * @param pack - Pack to execute * @param pod - Pod requesting the execution * @param options - Execution options * @returns Execution handle for tracking and cancellation */ execute(pack: Pack, pod: Pod, options?: { env?: Record; timeout?: number; args?: unknown[]; /** Service ID for network policy checks (required for inter-service comm) */ serviceId?: string; /** Pod authentication token for data plane connections */ podToken?: string; /** Refresh token for automatic token renewal */ podRefreshToken?: string; /** Token expiration timestamp (ISO string) */ podTokenExpiresAt?: string; }): ExecutionHandle; /** * Internal async execution logic */ private executeAsync; /** * Resolve the bundle path for a pack */ private resolveBundlePath; /** * Download a bundle from a URL */ private downloadBundle; /** * Download a bundle from orchestrator storage */ private downloadFromStorage; /** * Load a bundle from the file system */ private loadBundle; /** * Execute a pack directly on the main thread (for root capability packs). * * Root packs run on the main thread without worker isolation, which is required for: * - UI packs that need DOM access (in browser) * - Privileged operations that need direct node access * * Per the Root Package Execution Contract, root packs must: * - Use budgeted execution with explicit max time per slice * - Yield control cooperatively back to the runtime * - Use only async/non-blocking I/O * - Never perform unbounded synchronous work * * @param bundleCode - The JavaScript bundle code to execute * @param context - Execution context with environment and metadata * @param args - Arguments to pass to the entrypoint * @returns The return value from the pack entrypoint */ private executeOnMainThread; /** * Stop execution for a pod * * @param podId - Pod ID to stop * @param graceful - If true, allow in-flight operations to complete * @returns True if execution was stopped */ stop(podId: string, graceful?: boolean): boolean; /** * Get execution status for a pod * * @param podId - Pod ID * @returns Execution state or undefined */ getExecutionStatus(podId: string): ExecutionState | undefined; /** * Get execution result for a pod * * @param podId - Pod ID * @returns Execution result or undefined */ getExecutionResult(podId: string): PackExecutionResult | undefined; /** * Get all active executions * * @returns Array of execution states for running executions */ getActiveExecutions(): ExecutionState[]; /** * Get worker pool statistics */ getPoolStats(): PoolStats; /** * Cancel all running executions */ cancelAll(): void; /** * Clean up completed executions older than the specified age * * @param maxAgeMs - Maximum age in milliseconds (default: 1 hour) * @returns Number of executions cleaned up */ cleanup(maxAgeMs?: number): number; /** * Clear all files from a named volume. * Removes the volume directory and recreates it empty. */ clearVolume(volumeName: string): Promise; /** * Collect all files from a named volume using native node:fs. * Uses the same path convention as the pack-worker and in-process volume * helpers: join(process.cwd(), 'volumes', name). * Returns serializable file entries with base64-encoded content. */ collectVolumeFiles(volumeName: string): Promise; /** * Terminate the executor and clean up all resources * * @param force - If true, immediately terminate all workers */ terminate(force?: boolean): Promise; } /** * Create a pack executor with default configuration */ declare function createPackExecutor(config?: PackExecutorConfig): PackExecutor; /** * Default pack executor instance */ declare const defaultPackExecutor: PackExecutor; export { PackExecutor, type PackExecutorConfig, createPackExecutor, defaultPackExecutor };