import { RuntimeType, NodeCapabilities, AllocatableResources, Labels, Annotations, Taint, Logger } from '@stark-o/shared'; /** * Node State Store * @module @stark-o/node-runtime/agent/node-state-store * * Persistent storage for node agent credentials and registered nodes. * This is separate from CLI credentials to allow nodes to maintain their own auth state. */ /** * Stored node credentials (separate from CLI user credentials) */ interface NodeCredentials { /** The access token for node authentication */ accessToken: string; /** The refresh token for token renewal */ refreshToken?: string; /** Token expiration timestamp (ISO string) */ expiresAt: string; /** The user ID associated with this credential */ userId: string; /** The email used for this credential */ email: string; /** Timestamp when credentials were created */ createdAt: string; } /** * Information about a registered node */ interface RegisteredNode { /** Node's unique ID from the orchestrator */ nodeId: string; /** Node's name */ name: string; /** Orchestrator URL this node is registered with */ orchestratorUrl: string; /** Timestamp when the node was registered (ISO string) */ registeredAt: string; /** The user ID that registered this node */ registeredBy: string; /** Last time this node was successfully started */ lastStarted?: string; } /** * Map of node names to registered node info */ interface RegisteredNodesMap { [orchestratorUrl: string]: { [nodeName: string]: RegisteredNode; }; } /** * Load node credentials from disk */ declare function loadNodeCredentials(): NodeCredentials | null; /** * Save node credentials to disk */ declare function saveNodeCredentials(credentials: NodeCredentials): void; /** * Clear stored node credentials */ declare function clearNodeCredentials(): void; /** * Check if node credentials are valid (not expired) */ declare function areNodeCredentialsValid(): boolean; /** * Get the node access token if valid */ declare function getNodeAccessToken(): string | null; /** * Load registered nodes from disk */ declare function loadRegisteredNodes(): RegisteredNodesMap; /** * Save registered nodes to disk */ declare function saveRegisteredNodes(nodes: RegisteredNodesMap): void; /** * Get or create the machine UUID. * The machine UUID is generated once and persisted in ~/.stark/nodes/machine-id. * It uniquely identifies the physical/virtual machine that node agents run on. */ declare function getMachineId(): string; /** * Get a registered node by name for a specific orchestrator */ declare function getRegisteredNode(orchestratorUrl: string, nodeName: string): RegisteredNode | null; /** * Save a registered node */ declare function saveRegisteredNode(orchestratorUrl: string, node: RegisteredNode): void; /** * Remove a registered node */ declare function removeRegisteredNode(orchestratorUrl: string, nodeName: string): void; /** * Get all registered nodes for an orchestrator */ declare function getRegisteredNodesForOrchestrator(orchestratorUrl: string): RegisteredNode[]; /** * Update the last started timestamp for a node */ declare function updateNodeLastStarted(orchestratorUrl: string, nodeName: string): void; /** * Node State Store class for object-oriented access */ declare class NodeStateStore { private readonly orchestratorUrl; constructor(orchestratorUrl: string); /** * Get credentials for node authentication */ getCredentials(): NodeCredentials | null; /** * Save credentials for node authentication */ saveCredentials(credentials: NodeCredentials): void; /** * Clear stored credentials */ clearCredentials(): void; /** * Check if credentials are valid */ hasValidCredentials(): boolean; /** * Check if credentials should be refreshed */ shouldRefreshCredentials(): boolean; /** * Get time remaining until token expiration in milliseconds */ getTokenTimeRemaining(): number; /** * Get refresh token if available */ getRefreshToken(): string | null; /** * Get access token if valid */ getAccessToken(): string | null; /** * Get a registered node by name */ getNode(nodeName: string): RegisteredNode | null; /** * Save a registered node */ saveNode(node: RegisteredNode): void; /** * Remove a registered node */ removeNode(nodeName: string): void; /** * Get all registered nodes for this orchestrator */ getAllNodes(): RegisteredNode[]; /** * Update the last started timestamp for a node */ updateLastStarted(nodeName: string): void; /** * Get or create the machine UUID for this machine */ getMachineId(): string; } /** * Create a new NodeStateStore instance */ declare function createNodeStateStore(orchestratorUrl: string): NodeStateStore; /** * Node Agent * @module @stark-o/node-runtime/agent/node-agent * * Agent that runs on Node.js servers to register with the orchestrator, * send heartbeats, and receive pod service commands. */ /** * Node agent configuration */ interface NodeAgentConfig { /** Orchestrator WebSocket URL (e.g., wss://localhost:443/ws) */ orchestratorUrl: string; /** Authentication token (optional if using stored credentials or auto-registration) */ authToken?: string; /** Node name (must be unique) */ nodeName: string; /** Runtime type (always 'node' for this agent) */ runtimeType?: RuntimeType; /** Node capabilities */ capabilities?: NodeCapabilities; /** Allocatable resources */ allocatable?: Partial; /** Node labels */ labels?: Labels; /** Node annotations */ annotations?: Annotations; /** Node taints */ taints?: Taint[]; /** Heartbeat interval in milliseconds (default: 15000) */ heartbeatInterval?: number; /** Metrics reporting interval in milliseconds (default: 30000) */ metricsInterval?: number; /** Reconnect delay in milliseconds (default: 5000) */ reconnectDelay?: number; /** Maximum reconnect attempts (default: 10, -1 for infinite) */ maxReconnectAttempts?: number; /** Directory for pack bundles (default: process.cwd()) */ bundleDir?: string; /** Logger instance */ logger?: Logger; /** Enable persistent storage of node registration (default: true) */ persistState?: boolean; /** Automatically resume an existing node with the same name (default: true) */ resumeExisting?: boolean; /** Whether to validate SSL/TLS certificates (default: true, set to false for self-signed certs) */ validateSsl?: boolean; } /** * Node agent events */ type NodeAgentEvent = 'connecting' | 'connected' | 'authenticated' | 'registered' | 'heartbeat' | 'disconnected' | 'reconnecting' | 'error' | 'credentials_invalid' | 'stopped' | 'pod:deployed' | 'pod:started' | 'pod:stopped' | 'pod:failed'; /** * Event handler type */ type NodeAgentEventHandler = (event: NodeAgentEvent, data?: unknown) => void; /** * Connection state */ type ConnectionState = 'disconnected' | 'connecting' | 'connected' | 'authenticating' | 'authenticated' | 'registering' | 'registered'; /** * Node Agent * * Manages the connection between a Node.js runtime and the orchestrator. * Handles: * - WebSocket connection and reconnection * - Authentication with the orchestrator * - Node registration * - Periodic heartbeats * - Resource reporting * - Pod service and lifecycle * - Persistent storage of node state for resumption */ declare class NodeAgent { private readonly config; private authToken; private readonly stateStore; private ws; private nodeId; private connectionId; private state; private heartbeatTimer; private metricsTimer; private reconnectTimer; private tokenRefreshTimer; private reconnectAttempts; private isShuttingDown; private isRefreshingToken; private startTime; private lastCpuUsage; private lastCpuUsageTime; private pendingRequests; private eventHandlers; private allocatedResources; private executor; private podHandler; constructor(config: NodeAgentConfig); /** * Get the current connection state */ getState(): ConnectionState; /** * Get the registered node ID */ getNodeId(): string | null; /** * Get the connection ID */ getConnectionId(): string | null; /** * Check if the agent is connected and registered */ isRegistered(): boolean; /** * Add an event handler */ on(handler: NodeAgentEventHandler): () => void; /** * Remove an event handler */ off(handler: NodeAgentEventHandler): void; /** * Emit an event to all handlers */ private emit; /** * Start the agent - connect, authenticate, register, and begin heartbeats */ start(): Promise; /** * Stop the agent - disconnect and cleanup */ stop(): Promise; /** * Update allocated resources (called when pods are added/removed) */ updateAllocatedResources(resources: Partial): void; /** * Connect to the orchestrator */ private connect; /** * Handle incoming WebSocket message */ private handleMessage; /** * Handle WebSocket close * * Connection closes are classified as transient network failures. * We preserve nodeId and credentials, then retry connection. * Only explicit auth errors (AUTH_FAILED) should clear credentials. */ private handleClose; /** * Schedule a reconnection attempt */ private scheduleReconnect; /** * Cancel pending reconnection */ private cancelReconnect; /** * Authenticate with the orchestrator */ private authenticate; /** * Register the node with the orchestrator */ private register; /** * Reconnect an existing node to the orchestrator * Used when reconnecting after a connection drop or when resuming a previously registered node */ private reconnect; /** * Start the heartbeat timer */ private startHeartbeat; /** * Stop the heartbeat timer */ private stopHeartbeat; /** * Start the metrics collection timer */ private startMetricsCollection; /** * Stop the metrics collection timer */ private stopMetricsCollection; /** * Collect and send node metrics to the orchestrator */ private sendMetrics; /** * Collect system metrics (CPU, memory, uptime) */ private collectSystemMetrics; /** * Calculate CPU usage as a percentage * Uses process.cpuUsage() to calculate the percentage of CPU time used */ private calculateCpuUsage; /** * Token refresh check interval - check every minute */ private static readonly TOKEN_REFRESH_CHECK_INTERVAL_MS; /** * Start the token refresh timer * Periodically checks if the token needs to be refreshed */ private startTokenRefresh; /** * Stop the token refresh timer */ private stopTokenRefresh; /** * Check if token needs refresh and refresh if necessary */ private checkAndRefreshToken; /** * Refresh the access token using the refresh token */ private refreshToken; /** * Send a heartbeat to the orchestrator */ private sendHeartbeat; /** * Handle pod status change from PodHandler * Reports the status change to the orchestrator */ private handlePodStatusChange; /** * Map local pod status to orchestrator pod status */ private mapLocalStatusToPodStatus; /** * Send a message over WebSocket */ private send; /** * Send a request and wait for response */ private sendRequest; /** * Clear all pending requests with an error */ private clearPendingRequests; /** * Get the state store for direct access to persisted state */ getStateStore(): NodeStateStore; /** * Save credentials for future node agent sessions * This stores credentials separately from CLI user credentials */ saveCredentials(credentials: NodeCredentials): Promise; /** * Check if valid stored credentials exist */ hasStoredCredentials(): boolean; /** * Get the current auth token */ getAuthToken(): string; /** * Set the auth token (updates executor as well) */ setAuthToken(token: string): Promise; } /** * Create a new NodeAgent instance */ declare function createNodeAgent(config: NodeAgentConfig): NodeAgent; export { type ConnectionState as C, NodeAgent as N, type RegisteredNode as R, type NodeAgentConfig as a, type NodeAgentEvent as b, createNodeAgent as c, type NodeAgentEventHandler as d, NodeStateStore as e, createNodeStateStore as f, clearNodeCredentials as g, areNodeCredentialsValid as h, getNodeAccessToken as i, loadRegisteredNodes as j, saveRegisteredNodes as k, loadNodeCredentials as l, getRegisteredNode as m, saveRegisteredNode as n, getRegisteredNodesForOrchestrator as o, getMachineId as p, type NodeCredentials as q, removeRegisteredNode as r, saveNodeCredentials as s, type RegisteredNodesMap as t, updateNodeLastStarted as u };