/** * Pack type definitions * @module @stark-o/shared/types/pack */ /** * Runtime tags for targeting execution environment * - node: Only runs on Node.js runtimes * - browser: Only runs on browser runtimes * - universal: Runs on both Node.js and browser */ type RuntimeTag = 'node' | 'browser' | 'universal'; /** * Pack metadata for configuration and dependencies */ interface PackMetadata { /** Entry point function name */ entrypoint?: string; /** Execution timeout in milliseconds */ timeout?: number; /** Environment variables */ env?: Record; /** * Capabilities requested by this pack. * These are validated and granted based on namespace and context. * See capabilities.ts for available capabilities. */ requestedCapabilities?: Capability[]; /** * Minimum Node.js version required to run this pack. * Format: semver string (e.g., "18.0.0", "20.10.0") * If not specified, the pack is assumed compatible with any Node version. * Scheduler will refuse to schedule on nodes with incompatible versions. */ minNodeVersion?: string; /** * Enable the ephemeral data plane for this pack. * When true, the runtime injects an `EphemeralDataPlane` instance as * `context.ephemeral`, enabling transient pod-to-pod group membership, * fan-out queries, and presence tracking. * @default false */ enableEphemeral?: boolean; /** Additional configuration */ [key: string]: unknown; } /** * Pack visibility for access control * - private: Only owner and admins can access * - public: Anyone can access */ type PackVisibility = 'private' | 'public'; /** * Pack namespace for trust boundary * - system: Can access cluster state, manage packs, subscribe to global events (admin only) * - user: Scoped access, self-lifecycle only, resource capped (default) */ type PackNamespace = 'system' | 'user'; /** * Pack entity - a registered software package */ interface Pack { /** Unique identifier (UUID) */ id: string; /** Pack name (unique with version) */ name: string; /** Semantic version */ version: string; /** Target runtime */ runtimeTag: RuntimeTag; /** Owner user ID */ ownerId: string; /** Pack namespace (system or user) - determines trust level */ namespace: PackNamespace; /** Pack visibility (private or public) */ visibility: PackVisibility; /** Path to bundle in storage */ bundlePath: string; /** JavaScript bundle content (stored directly in database) */ bundleContent?: string; /** Pack description */ description?: string; /** Additional metadata */ metadata: PackMetadata; /** * Capabilities granted to this pack. * Determined at registration time based on namespace, runtime, and requested capabilities. * 'root' capability means pack runs on main thread (not in worker). */ grantedCapabilities: Capability[]; /** Creation timestamp */ createdAt: Date; /** Last update timestamp */ updatedAt: Date; } /** * Pack registration input */ interface RegisterPackInput { /** Pack name */ name: string; /** Semantic version */ version: string; /** Target runtime */ runtimeTag: RuntimeTag; /** Pack namespace (default: user) - system requires admin role */ namespace?: PackNamespace; /** Pack visibility (default: private) */ visibility?: PackVisibility; /** Pack description */ description?: string; /** JavaScript bundle content */ bundleContent?: string; /** Additional metadata */ metadata?: PackMetadata; } /** * Pack update input */ interface UpdatePackInput { description?: string; visibility?: PackVisibility; metadata?: PackMetadata; } /** * Pack version summary (for listing) */ interface PackVersionSummary { /** Pack ID */ id: string; /** Version string */ version: string; /** Runtime tag */ runtimeTag: RuntimeTag; /** Creation timestamp */ createdAt: Date; } /** * Pack list item (for search/listing) */ interface PackListItem { /** Pack ID */ id: string; /** Pack name */ name: string; /** Latest version */ latestVersion: string; /** Runtime tag */ runtimeTag: RuntimeTag; /** Description */ description?: string; /** Version count */ versionCount: number; /** Owner ID */ ownerId: string; /** Granted capabilities */ grantedCapabilities: Capability[]; /** Pack metadata (includes requestedCapabilities) */ metadata?: PackMetadata; /** Creation timestamp */ createdAt: Date; } /** * Check if a runtime tag is compatible with a target runtime * @param packTag - The pack's runtime tag * @param nodeRuntime - The node's runtime type ('node' or 'browser') */ declare function isRuntimeCompatible(packTag: RuntimeTag, nodeRuntime: 'node' | 'browser'): boolean; /** * Parse a semver version string */ interface SemVer { major: number; minor: number; patch: number; prerelease?: string; } /** * Parse a semantic version string */ declare function parseSemVer(version: string): SemVer | null; /** * Compare two semantic versions * @returns -1 if a < b, 0 if a === b, 1 if a > b */ declare function compareSemVer(a: string, b: string): number; /** * Check if a node's version is compatible with a pack's minimum version requirement. * @param nodeVersion - The node's runtime version (e.g., "22.0.0", "Chrome 120") * @param minNodeVersion - The pack's minimum Node.js version requirement (e.g., "18.0.0") * @returns true if compatible (node version >= min version), false otherwise * * Returns true if: * - minNodeVersion is not specified (pack accepts any version) * - nodeVersion is not specified (assume compatible for flexibility) * - nodeVersion >= minNodeVersion (satisfies requirement) * * Returns false if: * - Both versions are valid semver and nodeVersion < minNodeVersion */ declare function isNodeVersionCompatible(nodeVersion: string | undefined, minNodeVersion: string | undefined): boolean; /** * All available runtime tags */ declare const ALL_RUNTIME_TAGS: readonly RuntimeTag[]; /** * Capability type definitions for Stark Orchestrator * @module @stark-o/shared/types/capabilities * * Capabilities define what a pack can do at runtime. * Instead of ad-hoc permission flags, packs declare capabilities they need, * and the orchestrator grants them based on namespace, pack type, and context. */ /** * Available capabilities for packs * * Capabilities are hierarchical: 'cluster:read' is separate from 'cluster:write' * * Special capabilities: * - 'root': Runs on main thread (not in worker pool), required for UI packs * that need DOM access. Must be explicitly requested via * --capabilities root when registering a pack. */ type Capability = 'root' | 'cluster:read' | 'cluster:write' | 'packs:read' | 'packs:manage' | 'pods:read' | 'pods:manage' | 'pods:self' | 'events:self' | 'events:global' | 'ui:render' | 'ui:system' | 'storage:self' | 'storage:shared'; /** * All available capabilities as a const array */ declare const ALL_CAPABILITIES: readonly Capability[]; /** * Capabilities that require system namespace * These cannot be granted to user namespace packs */ declare const SYSTEM_ONLY_CAPABILITIES: readonly Capability[]; /** * Default capabilities granted based on namespace */ declare const DEFAULT_CAPABILITIES: Record; /** * Capabilities automatically granted to browser UI packs */ declare const UI_PACK_CAPABILITIES: readonly Capability[]; /** * Context for capability granting decisions */ interface CapabilityGrantContext { /** Pack's declared namespace */ namespace: PackNamespace; /** Pack's runtime tag */ runtimeTag: RuntimeTag; /** Whether registering user is admin */ isAdmin: boolean; /** Additional context for special cases */ installContext?: 'bootstrap' | 'user-install' | 'system-upgrade'; } /** * Result of capability granting */ interface CapabilityGrantResult { /** Capabilities that were granted */ granted: Capability[]; /** Capabilities that were denied (with reasons) */ denied: Array<{ capability: Capability; reason: string; }>; } /** * Check if a capability is valid */ declare function isValidCapability(cap: string): cap is Capability; /** * Check if a capability requires system namespace */ declare function requiresSystemNamespace(cap: Capability): boolean; /** * Grant capabilities to a pack based on context * * Rules: * 1. System namespace packs can request any capability * 2. User namespace packs cannot request system-only capabilities * 3. Browser packs automatically get ui:render and root if needed * 4. 'root' capability is granted by default to both user and system namespace packs * - This allows users to run UI apps on their own nodes * - Root packs run on main thread (not in worker pool) * - Required for DOM access and UI rendering * * @param requested - Capabilities the pack is requesting * @param context - Context for the granting decision * @returns Which capabilities are granted and which are denied */ declare function grantCapabilities(requested: Capability[], context: CapabilityGrantContext): CapabilityGrantResult; /** * Check if a set of capabilities includes a specific capability */ declare function hasCapability(capabilities: Capability[], cap: Capability): boolean; /** * Check if a set of capabilities includes any of the specified capabilities */ declare function hasAnyCapability(capabilities: Capability[], caps: Capability[]): boolean; /** * Check if a set of capabilities includes all of the specified capabilities */ declare function hasAllCapabilities(capabilities: Capability[], caps: Capability[]): boolean; /** * Check if capabilities include 'root' (main thread execution) * This is a convenience function for the common UI pack check */ declare function requiresMainThread(capabilities: Capability[]): boolean; /** * Validate that requested capabilities are valid strings * @returns Array of invalid capability strings */ declare function validateCapabilities(requested: string[]): string[]; /** * Compute effective capabilities: the intersection of requested and granted. * If no requested capabilities are specified, effective capabilities are empty — * the pack runs with no special privileges (worker-only execution). * * @param requested - Capabilities the pack declared it needs (may be undefined) * @param granted - Capabilities the orchestrator actually granted * @returns The capabilities that are both requested and granted */ declare function effectiveCapabilities(requested: Capability[] | undefined, granted: Capability[]): Capability[]; /** * User type definitions * @module @stark-o/shared/types/user */ /** * User roles for RBAC * - admin: Full access to all resources (manage users, cluster config, all entities) * - user: Self-service users - can manage own packs, nodes, and services * - node: Node agents - can register/update own node and update pods assigned to it * - viewer: Read-only access to packs, pods, nodes, namespaces */ type UserRole = 'admin' | 'user' | 'node' | 'viewer'; /** * User entity */ interface User { /** Unique identifier (UUID) */ id: string; /** Email address */ email: string; /** Display name */ displayName?: string; /** Assigned roles */ roles: UserRole[]; /** Creation timestamp */ createdAt: Date; /** Last update timestamp */ updatedAt: Date; } /** * User creation input */ interface CreateUserInput { email: string; displayName?: string; roles?: UserRole[]; } /** * User update input */ interface UpdateUserInput { displayName?: string; roles?: UserRole[]; } /** * User session from authentication */ interface UserSession { /** User data */ user: User; /** Access token (JWT) */ accessToken: string; /** Refresh token */ refreshToken?: string; /** Token expiration timestamp */ expiresAt: Date; } /** * Check if user has a specific role */ declare function hasRole(user: User, role: UserRole): boolean; /** * Check if user has any of the specified roles */ declare function hasAnyRole(user: User, roles: UserRole[]): boolean; /** * Check if user has all of the specified roles */ declare function hasAllRoles(user: User, roles: UserRole[]): boolean; /** * Check if user can manage resources (admin only) */ declare function canManageResources(user: User): boolean; /** * Check if user is a node agent */ declare function isNodeAgent(user: User): boolean; /** * All available roles */ declare const ALL_ROLES: readonly UserRole[]; /** * Labels, Annotations, and LabelSelector types (Kubernetes-like) * @module @stark-o/shared/types/labels */ /** * Labels are key-value pairs used for organization and selection * Keys and values must be strings * * @example * { * "app": "frontend", * "environment": "production", * "version": "v1.2.3" * } */ type Labels = Record; /** * Annotations are key-value pairs for non-identifying metadata * Used for tooling, documentation, and integrations * * @example * { * "description": "Main frontend application", * "owner": "team-frontend", * "docs-url": "https://docs.example.com/frontend" * } */ type Annotations = Record; /** * Label selector operator for match expressions */ type LabelSelectorOperator = 'In' | 'NotIn' | 'Exists' | 'DoesNotExist'; /** * Match expression for advanced label selection * * @example * // In: key must have one of these values * { key: "environment", operator: "In", values: ["production", "staging"] } * * // NotIn: key must not have these values * { key: "environment", operator: "NotIn", values: ["development"] } * * // Exists: key must exist (value doesn't matter) * { key: "gpu", operator: "Exists" } * * // DoesNotExist: key must not exist * { key: "deprecated", operator: "DoesNotExist" } */ interface LabelSelectorMatchExpression { /** Label key to match */ key: string; /** Operator for comparison */ operator: LabelSelectorOperator; /** Values to match (required for In/NotIn, ignored for Exists/DoesNotExist) */ values?: string[]; } /** * Label selector for querying resources * * @example * { * matchLabels: { "app": "frontend" }, * matchExpressions: [ * { key: "environment", operator: "In", values: ["production", "staging"] } * ] * } */ interface LabelSelector { /** Simple key-value matching (all must match) */ matchLabels?: Labels; /** Advanced expression matching (all must match) */ matchExpressions?: LabelSelectorMatchExpression[]; } /** * Check if a match expression matches a set of labels */ declare function matchesExpression(labels: Labels, expr: LabelSelectorMatchExpression): boolean; /** * Check if labels match a label selector */ declare function matchesSelector(labels: Labels, selector: LabelSelector): boolean; /** * Check if labels match simple key-value requirements */ declare function matchesLabels(labels: Labels, required: Labels): boolean; /** * Merge labels (later values override earlier) */ declare function mergeLabels(...labelSets: (Labels | undefined)[]): Labels; /** * Create a label selector from simple labels */ declare function createSelector(matchLabels: Labels): LabelSelector; /** * Validate a label key * - Must be non-empty * - Must start with alphanumeric * - Can contain alphanumeric, dash, underscore, dot * - Optional prefix (DNS subdomain) followed by / */ declare function isValidLabelKey(key: string): boolean; /** * Validate a label value * - Can be empty * - Must be 63 characters or less * - If non-empty, must start and end with alphanumeric * - Can contain alphanumeric, dash, underscore, dot */ declare function isValidLabelValue(value: string): boolean; /** * Validate all labels in a set */ declare function validateLabels$1(labels: Labels): { valid: boolean; errors: string[]; }; /** * Taints and Tolerations types (Kubernetes-like) * @module @stark-o/shared/types/taints */ /** * Taint effect - what happens to pods that don't tolerate the taint * - NoSchedule: Don't schedule new pods * - PreferNoSchedule: Try not to schedule new pods * - NoExecute: Evict existing pods and don't schedule new ones */ type TaintEffect = 'NoSchedule' | 'PreferNoSchedule' | 'NoExecute'; /** * Taint applied to a node * Repels pods unless they have a matching toleration * * @example * // GPU node - only GPU workloads should run here * { key: "dedicated", value: "gpu", effect: "NoSchedule" } * * // Maintenance mode - evict all pods * { key: "node.stark.io/maintenance", effect: "NoExecute" } * * // Prefer other nodes * { key: "cost", value: "high", effect: "PreferNoSchedule" } */ interface Taint { /** Taint key */ key: string; /** Taint value (optional) */ value?: string; /** Effect on non-tolerating pods */ effect: TaintEffect; /** For NoExecute: seconds to wait before eviction (optional) */ timeAdded?: Date; } /** * Toleration operator * - Equal: key and value must match (default) * - Exists: only key must match, value is ignored */ type TolerationOperator = 'Equal' | 'Exists'; /** * Toleration allows a pod to be scheduled on a tainted node * * @example * // Tolerate specific taint * { key: "dedicated", operator: "Equal", value: "gpu", effect: "NoSchedule" } * * // Tolerate any value for a key * { key: "node.stark.io/maintenance", operator: "Exists", effect: "NoExecute" } * * // Tolerate all NoSchedule taints with this key (any effect) * { key: "dedicated", operator: "Exists" } * * // Tolerate everything (super-toleration) * { operator: "Exists" } */ interface Toleration { /** Taint key to tolerate (empty = all keys) */ key?: string; /** Match operator */ operator?: TolerationOperator; /** Value to match (for Equal operator) */ value?: string; /** Effect to tolerate (empty = all effects) */ effect?: TaintEffect; /** For NoExecute: seconds to tolerate before eviction */ tolerationSeconds?: number; } /** * Check if a toleration matches a taint */ declare function tolerationMatchesTaint(toleration: Toleration, taint: Taint): boolean; /** * Check if a pod (via tolerations) tolerates a node's taints */ declare function toleratesTaints(tolerations: Toleration[], taints: Taint[]): boolean; /** * Get taints that would cause immediate eviction (NoExecute without toleration) */ declare function getEvictionTaints(tolerations: Toleration[], taints: Taint[]): Taint[]; /** * Check if a pod tolerates all blocking taints (NoSchedule and NoExecute). * PreferNoSchedule taints are soft constraints and don't block scheduling. * This is used for the scheduling filter step. */ declare function toleratesBlockingTaints(tolerations: Toleration[], taints: Taint[]): boolean; /** * Get PreferNoSchedule taints that are not tolerated by the pod. * These are soft constraints that should reduce the node's scheduling score. */ declare function getUntoleratedPreferNoScheduleTaints(tolerations: Toleration[], taints: Taint[]): Taint[]; /** * Create a common taint */ declare const CommonTaints: { /** Node is not ready */ readonly notReady: (effect?: TaintEffect) => Taint; /** Node is unreachable */ readonly unreachable: (effect?: TaintEffect) => Taint; /** Node is in maintenance mode */ readonly maintenance: (effect?: TaintEffect) => Taint; /** Node has dedicated workload type */ readonly dedicated: (value: string, effect?: TaintEffect) => Taint; /** Node is unschedulable */ readonly unschedulable: () => Taint; }; /** * Create common tolerations */ declare const CommonTolerations: { /** Tolerate all taints (super-toleration) */ readonly all: () => Toleration; /** Tolerate not-ready nodes */ readonly notReady: (seconds?: number) => Toleration; /** Tolerate unreachable nodes */ readonly unreachable: (seconds?: number) => Toleration; /** Tolerate dedicated workload */ readonly dedicated: (value: string) => Toleration; /** Tolerate maintenance mode (for critical system pods) */ readonly maintenance: () => Toleration; }; /** * All taint effects */ declare const ALL_TAINT_EFFECTS: readonly TaintEffect[]; /** * All toleration operators */ declare const ALL_TOLERATION_OPERATORS: readonly TolerationOperator[]; /** * Node type definitions * @module @stark-o/shared/types/node */ /** * Runtime types for nodes * - node: Node.js server runtime * - browser: Browser runtime */ type RuntimeType = 'node' | 'browser'; /** * Node status values * - online: Node is healthy and accepting pods * - suspect: Node disconnected but lease hasn't expired; pods remain logically owned * - offline: Node is disconnected (lease expired or never connected) * - unhealthy: Node missed heartbeats * - draining: Node is being evacuated (no new pods) * - maintenance: Node is under maintenance */ type NodeStatus = 'online' | 'suspect' | 'offline' | 'unhealthy' | 'draining' | 'maintenance'; /** * Node capabilities - features supported by the node */ interface NodeCapabilities { /** Node.js or browser version */ version?: string; /** Supported features */ features?: string[]; /** Custom capabilities */ [key: string]: unknown; } /** * Allocatable resources on a node */ interface AllocatableResources { /** CPU in millicores (1000 = 1 CPU) */ cpu: number; /** Memory in MB */ memory: number; /** Maximum number of pods */ pods: number; /** Storage in MB */ storage: number; } /** * Node entity - a registered runtime node */ interface Node { /** Unique identifier (UUID) */ id: string; /** Node name (unique) */ name: string; /** Runtime type */ runtimeType: RuntimeType; /** Current status */ status: NodeStatus; /** Last heartbeat timestamp */ lastHeartbeat?: Date; /** Timestamp when node entered suspect state (for lease expiration) */ suspectSince?: Date; /** Node capabilities */ capabilities: NodeCapabilities; /** User who registered the node */ registeredBy?: string; /** Whether this node is trusted (can run system packs). Derived from owner's admin role. */ trusted: boolean; /** WebSocket connection ID */ connectionId?: string; /** IP address */ ipAddress?: string; /** User agent string */ userAgent?: string; /** Total allocatable resources */ allocatable: AllocatableResources; /** Currently allocated resources */ allocated: AllocatableResources; /** Labels for organization and selection */ labels: Labels; /** Annotations for metadata */ annotations: Annotations; /** Taints to repel pods */ taints: Taint[]; /** UUID identifying the machine this node runs on */ machineId?: string; /** Whether node is unschedulable */ unschedulable: boolean; /** Creation timestamp */ createdAt: Date; /** Last update timestamp */ updatedAt: Date; } /** * Node registration input */ interface RegisterNodeInput { /** Node name */ name: string; /** Runtime type */ runtimeType: RuntimeType; /** Node capabilities */ capabilities?: NodeCapabilities; /** Allocatable resources */ allocatable?: Partial; /** Labels */ labels?: Labels; /** Annotations */ annotations?: Annotations; /** Taints */ taints?: Taint[]; /** UUID identifying the machine this node runs on */ machineId?: string; } /** * Node update input */ interface UpdateNodeInput { status?: NodeStatus; capabilities?: NodeCapabilities; allocatable?: Partial; labels?: Labels; annotations?: Annotations; taints?: Taint[]; unschedulable?: boolean; } /** * Node heartbeat payload */ interface NodeHeartbeat { /** Node ID */ nodeId: string; /** Current status */ status?: NodeStatus; /** Currently allocated resources */ allocated?: Partial; /** Active pod IDs */ activePods?: string[]; /** Timestamp */ timestamp: Date; } /** * Node list item (for search/listing) */ interface NodeListItem { id: string; name: string; runtimeType: RuntimeType; status: NodeStatus; lastHeartbeat?: Date; labels: Labels; allocatable: AllocatableResources; allocated: AllocatableResources; podCount: number; connectionId?: string; /** User who registered the node */ registeredBy?: string; /** Node capabilities including runtime version */ capabilities?: NodeCapabilities; /** UUID identifying the machine this node runs on */ machineId?: string; } /** * Calculate available resources on a node */ declare function getAvailableResources(node: Node): AllocatableResources; /** * Check if a node has sufficient resources */ declare function hasAvailableResources(node: Node, required: Partial): boolean; /** * Check if a node can accept new pods */ declare function isNodeSchedulable(node: Node): boolean; /** * Check if a node can run system namespace packs. * Only trusted nodes (owned by admins) can run system packs. */ declare function canRunSystemPacks(node: Node): boolean; /** * All available node statuses */ declare const ALL_NODE_STATUSES: readonly NodeStatus[]; /** * All available runtime types */ declare const ALL_RUNTIME_TYPES: readonly RuntimeType[]; /** * Default allocatable resources */ declare const DEFAULT_ALLOCATABLE: AllocatableResources; /** * Default allocated resources (empty) */ declare const DEFAULT_ALLOCATED: AllocatableResources; /** * Node affinity, pod affinity, and scheduling config types (Kubernetes-like) * @module @stark-o/shared/types/scheduling */ /** * Scheduling policy for the cluster */ type SchedulingPolicy = 'spread' | 'binpack' | 'random' | 'affinity' | 'least_loaded'; /** * Node selector term for node affinity */ interface NodeSelectorTerm { /** Match expressions (all must match) */ matchExpressions?: NodeSelectorRequirement[]; /** Match fields (all must match) */ matchFields?: NodeSelectorRequirement[]; } /** * Node selector requirement (single expression) */ interface NodeSelectorRequirement { /** Label/field key */ key: string; /** Operator */ operator: 'In' | 'NotIn' | 'Exists' | 'DoesNotExist' | 'Gt' | 'Lt'; /** Values for In/NotIn */ values?: string[]; } /** * Preferred scheduling term with weight */ interface PreferredSchedulingTerm { /** Weight (1-100) */ weight: number; /** Node selector term */ preference: NodeSelectorTerm; } /** * Node affinity rules * * @example * { * requiredDuringSchedulingIgnoredDuringExecution: { * nodeSelectorTerms: [ * { matchExpressions: [{ key: "zone", operator: "In", values: ["us-west-1", "us-west-2"] }] } * ] * }, * preferredDuringSchedulingIgnoredDuringExecution: [ * { weight: 100, preference: { matchExpressions: [{ key: "disktype", operator: "In", values: ["ssd"] }] } } * ] * } */ interface NodeAffinity { /** Required: pod can only be scheduled if conditions are met */ requiredDuringSchedulingIgnoredDuringExecution?: { /** Node selector terms (any one must match) */ nodeSelectorTerms: NodeSelectorTerm[]; }; /** Preferred: scheduler will try to meet these conditions */ preferredDuringSchedulingIgnoredDuringExecution?: PreferredSchedulingTerm[]; } /** * Pod affinity term */ interface PodAffinityTerm { /** Label selector for pods */ labelSelector?: LabelSelector; /** Namespaces to consider (empty = same namespace) */ namespaces?: string[]; /** Topology key (e.g., "node", "zone") */ topologyKey: string; } /** * Weighted pod affinity term */ interface WeightedPodAffinityTerm { /** Weight (1-100) */ weight: number; /** Pod affinity term */ podAffinityTerm: PodAffinityTerm; } /** * Pod affinity rules - co-locate pods * * @example * { * requiredDuringSchedulingIgnoredDuringExecution: [ * { * labelSelector: { matchLabels: { "app": "cache" } }, * topologyKey: "node" * } * ] * } */ interface PodAffinity { /** Required: pod can only be scheduled if conditions are met */ requiredDuringSchedulingIgnoredDuringExecution?: PodAffinityTerm[]; /** Preferred: scheduler will try to meet these conditions */ preferredDuringSchedulingIgnoredDuringExecution?: WeightedPodAffinityTerm[]; } /** * Pod anti-affinity rules - spread pods apart * * @example * { * preferredDuringSchedulingIgnoredDuringExecution: [ * { * weight: 100, * podAffinityTerm: { * labelSelector: { matchLabels: { "app": "frontend" } }, * topologyKey: "node" * } * } * ] * } */ interface PodAntiAffinity { /** Required: pod cannot be scheduled if conditions are met */ requiredDuringSchedulingIgnoredDuringExecution?: PodAffinityTerm[]; /** Preferred: scheduler will try to avoid these conditions */ preferredDuringSchedulingIgnoredDuringExecution?: WeightedPodAffinityTerm[]; } /** * Full scheduling configuration for a pod */ interface SchedulingConfig { /** Simple node label matching */ nodeSelector?: Record; /** Node affinity rules */ nodeAffinity?: NodeAffinity; /** Pod affinity rules */ podAffinity?: PodAffinity; /** Pod anti-affinity rules */ podAntiAffinity?: PodAntiAffinity; /** Scheduler name (for custom schedulers) */ schedulerName?: string; /** Priority class name */ priorityClassName?: string; } /** * Check if a node selector requirement matches a value */ declare function matchesRequirement(value: string | undefined, req: NodeSelectorRequirement): boolean; /** * Check if a node matches a selector term */ declare function matchesNodeSelectorTerm(nodeLabels: Record, term: NodeSelectorTerm): boolean; /** * Calculate affinity score for a node * Higher score = more preferred */ declare function calculateAffinityScore(nodeLabels: Record, affinity: NodeAffinity): number; /** * All scheduling policies */ declare const ALL_SCHEDULING_POLICIES: readonly SchedulingPolicy[]; /** * Volume type definitions * @module @stark-o/shared/types/volume */ /** * Volume mount definition for pods and services. * Maps a named volume to a path inside the container/pack runtime. */ interface VolumeMount { /** Volume name (must exist on the target node) */ name: string; /** Mount path inside the container/pack runtime */ mountPath: string; } /** * Volume entity — a named, node-local persistent storage unit * managed by the orchestrator. */ interface Volume { /** Unique identifier (UUID) */ id: string; /** Volume name (unique per node) */ name: string; /** Node ID the volume resides on */ nodeId: string; /** Creation timestamp */ createdAt: Date; /** Last update timestamp */ updatedAt: Date; } /** * Volume creation input */ interface CreateVolumeInput { /** Volume name */ name: string; /** Target node ID */ nodeId: string; } /** * Volume list item (summary) */ interface VolumeListItem { id: string; name: string; nodeId: string; createdAt: Date; updatedAt: Date; } /** * A single file entry in a volume download response. * Content is base64-encoded so it can be serialized over JSON/WebSocket. */ interface VolumeFileEntry { /** Relative path within the volume (e.g. "subdir/file.txt") */ path: string; /** File content, base64-encoded */ data: string; } /** * Payload sent by the orchestrator to a runtime to request volume contents. */ interface VolumeDownloadRequest { /** Name of the volume to download */ volumeName: string; } /** * Payload returned by a runtime with the volume's file contents. */ interface VolumeDownloadResponse { /** Volume name */ volumeName: string; /** All files in the volume, with base64-encoded content */ files: VolumeFileEntry[]; } /** * Pod and PodHistory type definitions * @module @stark-o/shared/types/pod */ /** * Pod status values */ type PodStatus = 'pending' | 'scheduled' | 'starting' | 'running' | 'stopping' | 'stopped' | 'failed' | 'evicted' | 'unknown'; /** * Canonical termination reason for pods * Used for crash loop detection and observability */ type PodTerminationReason = 'node_lost' | 'node_restart' | 'node_unhealthy' | 'node_draining' | 'node_maintenance' | 'oom_killed' | 'evicted_resources' | 'preempted' | 'quota_exceeded' | 'error' | 'init_error' | 'config_error' | 'pack_load_error' | 'user_stopped' | 'rolling_update' | 'scaled_down' | 'service_deleted' | 'completed' | 'deadline_exceeded' | 'unknown'; /** * Termination reasons that indicate infrastructure issues (not application bugs) * These should NOT count toward crash loop detection */ declare const INFRASTRUCTURE_TERMINATION_REASONS: readonly PodTerminationReason[]; /** * Termination reasons initiated by operators/users * These should NOT count toward crash loop detection */ declare const OPERATOR_TERMINATION_REASONS: readonly PodTerminationReason[]; /** * Termination reasons that indicate application errors * These SHOULD count toward crash loop detection */ declare const APPLICATION_TERMINATION_REASONS: readonly PodTerminationReason[]; /** * Check if a termination reason should count toward crash loop detection */ declare function shouldCountTowardCrashLoop(reason: PodTerminationReason | undefined): boolean; /** * All available termination reasons */ declare const ALL_TERMINATION_REASONS: readonly PodTerminationReason[]; /** * Resource requests/limits */ interface ResourceRequirements { /** CPU in millicores */ cpu: number; /** Memory in MB */ memory: number; } /** * Pod scheduling configuration */ interface PodSchedulingConfig { /** Simple label-based node selection */ nodeSelector?: Record; /** Advanced node selection rules */ nodeAffinity?: NodeAffinity; /** Co-location rules */ podAffinity?: PodAffinity; /** Anti co-location rules */ podAntiAffinity?: PodAntiAffinity; } /** * Pod entity - a pack service to a node */ interface Pod { /** Unique identifier (UUID) */ id: string; /** Pack ID */ packId: string; /** Pack version */ packVersion: string; /** Assigned node ID (null if pending) */ nodeId: string | null; /** Service ID that owns this pod (for service-based pods) */ serviceId?: string; /** Current status */ status: PodStatus; /** Status message (for errors) */ statusMessage?: string; /** Canonical termination reason (for stopped/failed/evicted pods) */ terminationReason?: PodTerminationReason; /** Namespace */ namespace: string; /** Labels for organization and selection */ labels: Labels; /** Annotations for metadata */ annotations: Annotations; /** Priority class name */ priorityClassName?: string; /** Priority value (cached) */ priority: number; /** Tolerations for tainted nodes */ tolerations: Toleration[]; /** Resource requests */ resourceRequests: ResourceRequirements; /** Resource limits */ resourceLimits: ResourceRequirements; /** Scheduling configuration */ scheduling?: PodSchedulingConfig; /** Volume mounts for this pod */ volumeMounts: VolumeMount[]; /** User who created the pod */ createdBy: string; /** When pod was scheduled */ scheduledAt?: Date; /** When pod started running */ startedAt?: Date; /** When pod stopped */ stoppedAt?: Date; /** Additional metadata */ metadata: Record; /** * Capabilities granted to this pod (copied from pack at scheduling time). * 'root' capability means pod runs on main thread (not in worker). */ grantedCapabilities: Capability[]; /** * Monotonic incarnation ID. Incremented when scheduling replacements. * Used to reject late messages from old incarnations and prevent double-deploy. */ incarnation: number; /** Creation timestamp */ createdAt: Date; /** Last update timestamp */ updatedAt: Date; } /** * Pod creation input */ interface CreatePodInput { /** Pack ID */ packId: string; /** Pack version (optional, defaults to latest) */ packVersion?: string; /** Target namespace */ namespace?: string; /** Labels */ labels?: Labels; /** Annotations */ annotations?: Annotations; /** Priority class name */ priorityClassName?: string; /** Tolerations */ tolerations?: Toleration[]; /** Resource requests */ resourceRequests?: Partial; /** Resource limits */ resourceLimits?: Partial; /** Scheduling configuration */ scheduling?: PodSchedulingConfig; /** Target node ID (optional — used for volume auto-provisioning and pinned scheduling) */ nodeId?: string; /** Volume mounts */ volumeMounts?: VolumeMount[]; /** Additional metadata */ metadata?: Record; } /** * Pod update input */ interface UpdatePodInput { status?: PodStatus; statusMessage?: string; terminationReason?: PodTerminationReason; nodeId?: string | null; labels?: Labels; annotations?: Annotations; } /** * Pod action for history tracking */ type PodAction = 'created' | 'scheduled' | 'started' | 'stopped' | 'failed' | 'restarted' | 'rolled_back' | 'evicted' | 'scaled' | 'updated' | 'deleted'; /** * Pod history entry */ interface PodHistoryEntry { /** Unique identifier */ id: string; /** Pod ID */ podId: string; /** Action that occurred */ action: PodAction; /** User who performed the action */ actorId?: string; /** Previous status */ previousStatus?: PodStatus; /** New status */ newStatus?: PodStatus; /** Previous version */ previousVersion?: string; /** New version */ newVersion?: string; /** Previous node ID */ previousNodeId?: string; /** New node ID */ newNodeId?: string; /** Reason code */ reason?: string; /** Human-readable message */ message?: string; /** Additional metadata */ metadata: Record; /** Timestamp */ timestamp: Date; } /** * Pod list item (for search/listing) */ interface PodListItem { id: string; packId: string; packVersion: string; nodeId: string | null; status: PodStatus; statusMessage?: string; terminationReason?: PodTerminationReason; namespace: string; labels: Labels; priority: number; incarnation: number; createdBy: string; createdAt: Date; updatedAt: Date; startedAt?: Date; stoppedAt?: Date; } /** * Check if a pod is active (not terminated) */ declare function isPodActive(pod: Pod): boolean; /** * Check if a pod is running */ declare function isPodRunning(pod: Pod): boolean; /** * Check if a pod has terminated */ declare function isPodTerminated(pod: Pod): boolean; /** * Check if a pod can be scheduled */ declare function isPodSchedulable(pod: Pod): boolean; /** * All available pod statuses */ declare const ALL_POD_STATUSES: readonly PodStatus[]; /** * All available pod actions */ declare const ALL_POD_ACTIONS: readonly PodAction[]; /** * Default resource requests */ declare const DEFAULT_RESOURCE_REQUESTS: ResourceRequirements; /** * Default resource limits */ declare const DEFAULT_RESOURCE_LIMITS: ResourceRequirements; /** * Namespace, ResourceQuota, and LimitRange types (Kubernetes-like) * @module @stark-o/shared/types/namespace */ /** * Namespace phase * - active: Namespace is active and accepting resources * - terminating: Namespace is being deleted */ type NamespacePhase = 'active' | 'terminating'; /** * Resource quota hard limits */ interface ResourceQuotaHard { /** Maximum number of pods */ pods?: number; /** Maximum CPU in millicores */ cpu?: number; /** Maximum memory in MB */ memory?: number; /** Maximum storage in MB */ storage?: number; } /** * Resource quota for a namespace */ interface ResourceQuota { /** Hard limits on resources */ hard: ResourceQuotaHard; } /** * Resource limit values */ interface ResourceLimitValue { /** CPU in millicores */ cpu?: number; /** Memory in MB */ memory?: number; } /** * Limit range for pods in a namespace */ interface LimitRange { /** Default limits applied to pods without explicit limits */ default?: ResourceLimitValue; /** Default requests applied to pods without explicit requests */ defaultRequest?: ResourceLimitValue; /** Maximum allowed limits */ max?: ResourceLimitValue; /** Minimum allowed limits */ min?: ResourceLimitValue; } /** * Current resource usage in a namespace */ interface ResourceUsage { /** Number of pods */ pods: number; /** CPU in millicores */ cpu: number; /** Memory in MB */ memory: number; /** Storage in MB */ storage: number; } /** * Namespace entity */ interface Namespace { /** Unique identifier (UUID) */ id: string; /** Namespace name (unique) */ name: string; /** Lifecycle phase */ phase: NamespacePhase; /** Labels for organization */ labels: Labels; /** Annotations for metadata */ annotations: Annotations; /** Resource quota (optional) */ resourceQuota?: ResourceQuota; /** Limit range for pods (optional) */ limitRange?: LimitRange; /** Current resource usage */ resourceUsage: ResourceUsage; /** User who created the namespace */ createdBy?: string; /** Creation timestamp */ createdAt: Date; /** Last update timestamp */ updatedAt: Date; } /** * Namespace creation input */ interface CreateNamespaceInput { /** Namespace name */ name: string; /** Labels */ labels?: Labels; /** Annotations */ annotations?: Annotations; /** Resource quota */ resourceQuota?: ResourceQuota; /** Limit range */ limitRange?: LimitRange; } /** * Namespace update input */ interface UpdateNamespaceInput { /** Labels */ labels?: Labels; /** Annotations */ annotations?: Annotations; /** Resource quota */ resourceQuota?: ResourceQuota; /** Limit range */ limitRange?: LimitRange; } /** * Namespace list item */ interface NamespaceListItem { id: string; name: string; phase: NamespacePhase; labels: Labels; resourceUsage: ResourceUsage; hasQuota: boolean; createdAt: Date; } /** * Reserved namespace names */ declare const RESERVED_NAMESPACES: readonly ["default", "stark-system", "stark-public"]; /** * Check if a namespace name is reserved */ declare function isReservedNamespace(name: string): boolean; /** * Check if a namespace has available quota for resources */ declare function hasQuotaAvailable(namespace: Namespace, required: Partial): boolean; /** * Get remaining quota for a namespace */ declare function getRemainingQuota(namespace: Namespace): ResourceQuotaHard | null; /** * Apply limit range defaults to resource values */ declare function applyLimitRangeDefaults(limitRange: LimitRange | undefined, requests?: Partial, limits?: Partial): { requests: ResourceLimitValue; limits: ResourceLimitValue; }; /** * Validate resources against limit range */ declare function validateAgainstLimitRange(limitRange: LimitRange | undefined, requests: ResourceLimitValue, limits: ResourceLimitValue): { valid: boolean; errors: string[]; }; /** * Default resource usage (empty) */ declare const DEFAULT_RESOURCE_USAGE: ResourceUsage; /** * All namespace phases */ declare const ALL_NAMESPACE_PHASES: readonly NamespacePhase[]; /** * ClusterConfig, ResourceLimits, and SchedulingPolicy types (Kubernetes-like) * @module @stark-o/shared/types/cluster */ /** * Default resource configuration */ interface DefaultResources { /** CPU in millicores */ cpu: number; /** Memory in MB */ memory: number; } /** * Cluster configuration */ interface ClusterConfig { /** Unique identifier (UUID) */ id: string; /** Config name */ name: string; /** Maximum pods per node */ maxPodsPerNode: number; /** Default namespace for resources */ defaultNamespace: string; /** Default scheduling policy */ schedulingPolicy: SchedulingPolicy; /** Default resource requests for pods */ defaultResourceRequests: DefaultResources; /** Default resource limits for pods */ defaultResourceLimits: DefaultResources; /** Maximum total pods in cluster */ maxTotalPods?: number; /** Maximum total nodes in cluster */ maxTotalNodes?: number; /** Heartbeat interval in milliseconds */ heartbeatIntervalMs: number; /** Heartbeat timeout in milliseconds */ heartbeatTimeoutMs: number; /** Pod termination grace period in milliseconds */ podTerminationGracePeriodMs: number; /** Whether priority-based preemption is enabled */ enablePreemption: boolean; /** Annotations for metadata */ annotations: Annotations; /** Creation timestamp */ createdAt: Date; /** Last update timestamp */ updatedAt: Date; } /** * Cluster config update input */ interface UpdateClusterConfigInput { maxPodsPerNode?: number; defaultNamespace?: string; schedulingPolicy?: SchedulingPolicy; defaultResourceRequests?: Partial; defaultResourceLimits?: Partial; maxTotalPods?: number; maxTotalNodes?: number; heartbeatIntervalMs?: number; heartbeatTimeoutMs?: number; podTerminationGracePeriodMs?: number; enablePreemption?: boolean; annotations?: Annotations; } /** * Cluster statistics */ interface ClusterStats { /** Total number of nodes */ totalNodes: number; /** Number of healthy nodes */ healthyNodes: number; /** Number of unhealthy nodes */ unhealthyNodes: number; /** Total number of pods */ totalPods: number; /** Number of running pods */ runningPods: number; /** Number of pending pods */ pendingPods: number; /** Total allocatable CPU across all nodes */ totalCpu: number; /** Total allocated CPU */ allocatedCpu: number; /** Total allocatable memory across all nodes */ totalMemory: number; /** Total allocated memory */ allocatedMemory: number; /** Number of namespaces */ namespaceCount: number; /** Number of registered packs */ packCount: number; } /** * Cluster health status */ type ClusterHealthStatus = 'healthy' | 'degraded' | 'critical'; /** * Cluster health report */ interface ClusterHealth { /** Overall status */ status: ClusterHealthStatus; /** Health message */ message: string; /** Individual component statuses */ components: { nodes: { healthy: number; total: number; }; pods: { running: number; failed: number; pending: number; }; schedulerReady: boolean; }; /** Last check timestamp */ checkedAt: Date; } /** * Priority class definition */ interface PriorityClass { /** Unique identifier (UUID) */ id: string; /** Priority class name */ name: string; /** Priority value (higher = more important) */ value: number; /** Whether this is the global default */ globalDefault: boolean; /** Preemption policy */ preemptionPolicy: 'PreemptLowerPriority' | 'Never'; /** Description */ description?: string; /** Labels */ labels: Record; /** Annotations */ annotations: Annotations; /** Creation timestamp */ createdAt: Date; /** Last update timestamp */ updatedAt: Date; } /** * Priority class creation input */ interface CreatePriorityClassInput { name: string; value: number; globalDefault?: boolean; preemptionPolicy?: 'PreemptLowerPriority' | 'Never'; description?: string; labels?: Record; annotations?: Annotations; } /** * Built-in priority classes */ declare const BUILTIN_PRIORITY_CLASSES: { /** System node critical (highest) */ readonly SYSTEM_NODE_CRITICAL: { readonly name: "system-node-critical"; readonly value: 2000001000; }; /** System cluster critical */ readonly SYSTEM_CLUSTER_CRITICAL: { readonly name: "system-cluster-critical"; readonly value: 2000000000; }; /** High priority */ readonly HIGH_PRIORITY: { readonly name: "high-priority"; readonly value: 1000000; }; /** Default priority */ readonly DEFAULT: { readonly name: "default"; readonly value: 0; }; /** Low priority */ readonly LOW_PRIORITY: { readonly name: "low-priority"; readonly value: -1000; }; /** Best effort (lowest) */ readonly BEST_EFFORT: { readonly name: "best-effort"; readonly value: -1000000; }; }; /** * Default cluster configuration */ declare const DEFAULT_CLUSTER_CONFIG: Omit; /** * Calculate cluster health status from stats */ declare function getClusterHealthStatus(stats: ClusterStats): ClusterHealth; /** * Calculate resource utilization percentage */ declare function getResourceUtilization(stats: ClusterStats): { cpu: number; memory: number; }; /** * Shared Storage Adapter Interface for Stark Orchestrator * * This interface defines a unified file system abstraction that can be * implemented by different runtimes (Node.js, Browser) using * platform-appropriate backends. * * @module @stark-o/shared/types/storage-adapter */ /** * File statistics information. * Compatible with Node.js fs.Stats interface. */ interface FileStats { /** Size of the file in bytes */ size: number; /** True if the path is a file */ isFile: () => boolean; /** True if the path is a directory */ isDirectory: () => boolean; /** True if the path is a symbolic link */ isSymbolicLink: () => boolean; /** Last access time */ atime: Date; /** Last modification time */ mtime: Date; /** Creation time */ birthtime: Date; /** File mode (permissions) */ mode: number; } /** * Directory entry with type information. */ interface DirectoryEntry { /** Name of the file or directory */ name: string; /** True if the entry is a file */ isFile: () => boolean; /** True if the entry is a directory */ isDirectory: () => boolean; /** True if the entry is a symbolic link */ isSymbolicLink: () => boolean; } /** * Configuration options for storage adapters. */ interface StorageAdapterConfig { /** * The root path prefix for all file system operations. * All operations will be scoped to this directory. */ rootPath?: string; /** * Unique identifier for the storage instance. * Used for IndexedDB database naming in browser. */ storeName?: string; } /** * Unified storage adapter interface. * * This interface provides a consistent API for file system operations * across different runtime environments (Node.js and Browser). * Implementations use platform-appropriate backends (native fs for Node.js, * OPFS for browsers). * * Note: Sync methods may not be available in all implementations * (e.g., browser with IndexedDB). Use async methods for maximum compatibility. */ interface IStorageAdapter { /** * Initialize the storage adapter. * Must be called before using any file system operations. */ initialize(): Promise; /** * Check if the adapter has been initialized. */ isInitialized(): boolean; /** * Get the configured root path. */ getRootPath(): string; /** * Read file contents as a string. * @param path - Path to the file (relative to root path) * @param encoding - Character encoding (default: 'utf-8') */ readFile(path: string, encoding?: BufferEncoding): Promise; /** * Read file contents as a Uint8Array. * @param path - Path to the file (relative to root path) */ readFileBytes(path: string): Promise; /** * Write string content to a file. * @param path - Path to the file (relative to root path) * @param content - Content to write * @param encoding - Character encoding (default: 'utf-8') */ writeFile(path: string, content: string | Uint8Array, encoding?: BufferEncoding): Promise; /** * Append content to a file. * @param path - Path to the file (relative to root path) * @param content - Content to append * @param encoding - Character encoding (default: 'utf-8') */ appendFile(path: string, content: string | Uint8Array, encoding?: BufferEncoding): Promise; /** * Create a directory. * @param path - Path to the directory (relative to root path) * @param recursive - Create parent directories if they don't exist (default: true) */ mkdir(path: string, recursive?: boolean): Promise; /** * Read directory contents. * @param path - Path to the directory (relative to root path) * @returns Array of file/directory names */ readdir(path: string): Promise; /** * Read directory contents with file type information. * @param path - Path to the directory (relative to root path) * @returns Array of directory entries with type info */ readdirWithTypes(path: string): Promise; /** * Remove a directory. * @param path - Path to the directory (relative to root path) * @param recursive - Remove contents recursively (default: false) */ rmdir(path: string, recursive?: boolean): Promise; /** * Check if a file or directory exists. * @param path - Path to check (relative to root path) */ exists(path: string): Promise; /** * Get file or directory statistics. * @param path - Path to the file or directory (relative to root path) */ stat(path: string): Promise; /** * Remove a file. * @param path - Path to the file (relative to root path) */ unlink(path: string): Promise; /** * Rename/move a file or directory. * @param oldPath - Current path (relative to root path) * @param newPath - New path (relative to root path) */ rename(oldPath: string, newPath: string): Promise; /** * Copy a file. * @param src - Source path (relative to root path) * @param dest - Destination path (relative to root path) */ copyFile(src: string, dest: string): Promise; /** * Check if path is a file. * @param path - Path to check (relative to root path) */ isFile(path: string): Promise; /** * Check if path is a directory. * @param path - Path to check (relative to root path) */ isDirectory(path: string): Promise; } /** * Extended storage adapter interface with synchronous operations. * * These methods are only available in environments that support * synchronous file system access (e.g., Node.js). * Browser implementations using IndexedDB cannot implement these. */ interface ISyncStorageAdapter extends IStorageAdapter { /** Read file contents as a string synchronously. */ readFileSync(path: string, encoding?: BufferEncoding): string; /** Read file contents as Uint8Array synchronously. */ readFileBytesSync(path: string): Uint8Array; /** Write content to a file synchronously. */ writeFileSync(path: string, content: string | Uint8Array, encoding?: BufferEncoding): void; /** Append content to a file synchronously. */ appendFileSync(path: string, content: string | Uint8Array, encoding?: BufferEncoding): void; /** Create a directory synchronously. */ mkdirSync(path: string, recursive?: boolean): void; /** Read directory contents synchronously. */ readdirSync(path: string): string[]; /** Remove a directory synchronously. */ rmdirSync(path: string, recursive?: boolean): void; /** Check if a file or directory exists synchronously. */ existsSync(path: string): boolean; /** Get file or directory statistics synchronously. */ statSync(path: string): FileStats; /** Remove a file synchronously. */ unlinkSync(path: string): void; /** Rename/move a file or directory synchronously. */ renameSync(oldPath: string, newPath: string): void; /** Copy a file synchronously. */ copyFileSync(src: string, dest: string): void; /** Check if path is a file synchronously. */ isFileSync(path: string): boolean; /** Check if path is a directory synchronously. */ isDirectorySync(path: string): boolean; } /** * Shared HTTP Adapter Interface for Stark Orchestrator * * This interface defines a unified HTTP client abstraction that can be * implemented by different runtimes (Node.js, Browser) using Axios. * * @module @stark-o/shared/types/http-adapter */ /** * HTTP method types supported by the adapter. */ type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS'; /** * Configuration options for the HTTP adapter. */ interface HttpAdapterConfig { /** * Base URL for all requests. * All request paths will be relative to this URL. */ baseUrl?: string; /** * Default timeout in milliseconds. * @default 30000 (30 seconds) */ timeout?: number; /** * Default headers to include in every request. */ headers?: Record; /** * Maximum number of automatic retries for failed requests. * @default 0 (no retries) */ maxRetries?: number; /** * Delay between retries in milliseconds. * @default 1000 */ retryDelay?: number; /** * HTTP status codes that should trigger a retry. * @default [408, 429, 500, 502, 503, 504] */ retryStatusCodes?: number[]; } /** * Request options for individual HTTP requests. */ interface HttpRequestOptions { /** * Request headers. */ headers?: Record; /** * Query parameters. */ params?: Record; /** * Request timeout in milliseconds (overrides default). */ timeout?: number; /** * Response type. * @default 'json' */ responseType?: 'json' | 'text' | 'arraybuffer' | 'blob'; /** * Abort signal for request cancellation. */ signal?: AbortSignal; /** * Whether to throw on non-2xx status codes. * @default true */ throwOnError?: boolean; /** * Maximum number of retries for this specific request. * Overrides the adapter-level setting. */ maxRetries?: number; } /** * HTTP response structure returned by the adapter. */ interface HttpResponse { /** * Response data. */ data: T; /** * HTTP status code. */ status: number; /** * HTTP status text. */ statusText: string; /** * Response headers. */ headers: Record; /** * Request duration in milliseconds. */ duration: number; } /** * Options for creating an HttpAdapterError. */ interface HttpAdapterErrorOptions { status?: number; data?: unknown; code?: string; isTimeout?: boolean; isNetworkError?: boolean; isCancelled?: boolean; cause?: Error; } /** * HTTP error structure for failed requests. */ declare class HttpAdapterError extends Error { /** * HTTP status code (if available). */ readonly status?: number; /** * Response data (if available). */ readonly data?: unknown; /** * Original error code. */ readonly code?: string; /** * Whether this is a timeout error. */ readonly isTimeout: boolean; /** * Whether this is a network error. */ readonly isNetworkError: boolean; /** * Whether the request was cancelled. */ readonly isCancelled: boolean; constructor(message: string, options?: HttpAdapterErrorOptions); } /** * Unified HTTP adapter interface. * * This interface provides a consistent API for HTTP operations * across different runtime environments (Node.js and Browser). * Implementations should use Axios for maximum compatibility. */ interface IHttpAdapter { /** * Initialize the HTTP adapter. * Must be called before using any HTTP operations. */ initialize(): Promise; /** * Check if the adapter has been initialized. */ isInitialized(): boolean; /** * Perform an HTTP GET request. * @param url - Request URL (relative to base URL) * @param options - Request options */ get(url: string, options?: HttpRequestOptions): Promise>; /** * Perform an HTTP POST request. * @param url - Request URL (relative to base URL) * @param data - Request body * @param options - Request options */ post(url: string, data?: unknown, options?: HttpRequestOptions): Promise>; /** * Perform an HTTP PUT request. * @param url - Request URL (relative to base URL) * @param data - Request body * @param options - Request options */ put(url: string, data?: unknown, options?: HttpRequestOptions): Promise>; /** * Perform an HTTP PATCH request. * @param url - Request URL (relative to base URL) * @param data - Request body * @param options - Request options */ patch(url: string, data?: unknown, options?: HttpRequestOptions): Promise>; /** * Perform an HTTP DELETE request. * @param url - Request URL (relative to base URL) * @param options - Request options */ delete(url: string, options?: HttpRequestOptions): Promise>; /** * Perform an HTTP HEAD request. * @param url - Request URL (relative to base URL) * @param options - Request options */ head(url: string, options?: HttpRequestOptions): Promise>; /** * Perform an HTTP OPTIONS request. * @param url - Request URL (relative to base URL) * @param options - Request options */ options(url: string, options?: HttpRequestOptions): Promise>; /** * Perform a generic HTTP request. * @param method - HTTP method * @param url - Request URL (relative to base URL) * @param data - Request body (for POST, PUT, PATCH) * @param options - Request options */ request(method: HttpMethod, url: string, data?: unknown, options?: HttpRequestOptions): Promise>; /** * Set the authorization header. * @param token - Bearer token */ setAuthToken(token: string): void; /** * Remove the authorization header. */ clearAuthToken(): void; /** * Set a default header for all requests. * @param name - Header name * @param value - Header value */ setDefaultHeader(name: string, value: string): void; /** * Remove a default header. * @param name - Header name */ removeDefaultHeader(name: string): void; /** * Update the base URL. * @param baseUrl - New base URL */ setBaseUrl(baseUrl: string): void; /** * Get the current base URL. */ getBaseUrl(): string; /** * Create an abort controller for request cancellation. * @returns AbortController instance */ createAbortController(): AbortController; /** * Clean up resources and reset the adapter. */ dispose(): void; } /** * Shared Worker Adapter Interface for Stark Orchestrator * * This interface defines a unified worker pool abstraction that can be * implemented by different runtimes: * - Node.js: Using sub-processes via child_process.fork() * - Browser: Using native Web Workers * * @module @stark-o/shared/types/worker-adapter */ /** * Transferable object type for worker communication. * In Node.js: ArrayBuffer, MessagePort * In Browser: ArrayBuffer, MessagePort, ImageBitmap, OffscreenCanvas * We use a minimal common type that works across environments. */ type TransferableObject = ArrayBuffer | { readonly byteLength: number; }; /** * Configuration options for the worker adapter. */ interface WorkerAdapterConfig { /** * Minimum number of workers in the pool. * @default 0 */ minWorkers?: number | 'max'; /** * Maximum number of workers in the pool. * @default Number of CPU cores (Node.js) or navigator.hardwareConcurrency (Browser) */ maxWorkers?: number; /** * Maximum number of tasks to queue before rejecting new tasks. * @default Infinity */ maxQueueSize?: number; /** * Timeout in milliseconds for task execution. * @default 60000 (60 seconds) */ taskTimeout?: number; /** * Timeout in milliseconds before terminating idle workers. * @default 1000 */ workerTerminateTimeout?: number; /** * Path to a custom worker script. * If not provided, tasks must be self-contained functions. */ workerScript?: string; /** * Custom error handler for worker errors. */ onError?: (error: Error) => void; } /** * Task execution options. */ interface TaskOptions { /** * Task-specific timeout in milliseconds. * Overrides the adapter's default timeout. */ timeout?: number; /** * Transfer list for transferable objects (ArrayBuffer, MessagePort, etc.). * Enables zero-copy transfer of data to workers. */ transfer?: TransferableObject[]; /** * Callback invoked when the task is cancelled. */ onCancel?: () => void; } /** * Result of a task execution. */ interface TaskResult { /** * The result value from the task. */ value: T; /** * Execution duration in milliseconds. */ duration: number; /** * Worker ID that executed the task (if available). */ workerId?: string; } /** * Worker pool statistics. */ interface PoolStats { /** * Total number of workers in the pool. */ totalWorkers: number; /** * Number of currently busy workers. */ busyWorkers: number; /** * Number of idle workers. */ idleWorkers: number; /** * Number of tasks waiting in the queue. */ pendingTasks: number; /** * Number of tasks currently being executed. */ activeTasks: number; } /** * Cancellable task handle. */ interface TaskHandle { /** * Promise that resolves with the task result. */ promise: Promise>; /** * Cancel the task execution. * This is a cooperative cancellation - the task may continue running * until it checks for cancellation. */ cancel: () => void; /** * Force terminate the worker executing this task. * This immediately kills the worker thread, ensuring the task stops. * Use this when you need guaranteed termination (e.g., when a pod is stopped). * The worker will be replaced with a new one automatically. */ forceTerminate: () => Promise; /** * Whether the task has been cancelled. */ isCancelled: () => boolean; } /** * Unified worker adapter interface. * * This interface provides a consistent API for executing tasks in worker threads * across different runtime environments (Node.js and Browser). * Implementations should use native isolation primitives (child_process, Web Workers). */ interface IWorkerAdapter { /** * Initialize the worker pool. * Must be called before executing any tasks. */ initialize(): Promise; /** * Check if the adapter has been initialized. */ isInitialized(): boolean; /** * Terminate all workers and shut down the pool. * * @param force - If true, terminate immediately without waiting for pending tasks * @param timeout - Timeout in milliseconds to wait for pending tasks */ terminate(force?: boolean, timeout?: number): Promise; /** * Execute a function in a worker. * The function must be self-contained and serializable. * * @param fn - The function to execute * @param args - Arguments to pass to the function * @param options - Task execution options * @returns Promise resolving to the task result */ exec(fn: (...args: Args) => T | Promise, args?: Args, options?: TaskOptions): Promise>; /** * Execute a function in a worker with cancellation support. * * @param fn - The function to execute * @param args - Arguments to pass to the function * @param options - Task execution options * @returns Task handle with promise and cancel function */ execCancellable(fn: (...args: Args) => T | Promise, args?: Args, options?: TaskOptions): TaskHandle; /** * Execute a named method on a worker script. * Requires the adapter to be initialized with a workerScript. * * @param method - The method name to call on the worker * @param args - Arguments to pass to the method * @param options - Task execution options * @returns Promise resolving to the task result */ execMethod(method: string, args?: unknown[], options?: TaskOptions): Promise>; /** * Execute a named method on a worker script with cancellation support. * * @param method - The method name to call on the worker * @param args - Arguments to pass to the method * @param options - Task execution options * @returns Task handle with promise and cancel function */ execMethodCancellable(method: string, args?: unknown[], options?: TaskOptions): TaskHandle; /** * Get current pool statistics. * * @returns Pool statistics */ getStats(): PoolStats; /** * Cancel all pending tasks. */ cancelAll(): void; } /** * Error thrown when a task is cancelled. */ declare class TaskCancelledError extends Error { readonly name = "TaskCancelledError"; constructor(message?: string); } /** * Error thrown when a task times out. */ declare class TaskTimeoutError extends Error { readonly name = "TaskTimeoutError"; readonly timeout: number; constructor(timeout: number, message?: string); } /** * Error thrown when the worker pool is not initialized. */ declare class WorkerNotInitializedError extends Error { readonly name = "WorkerNotInitializedError"; constructor(message?: string); } /** * Error thrown when trying to use worker script methods without a script configured. */ declare class WorkerScriptRequiredError extends Error { readonly name = "WorkerScriptRequiredError"; constructor(method: string); } /** * Service type definitions * @module @stark-o/shared/types/service */ /** * Service status values */ type ServiceStatus = 'active' | 'paused' | 'scaling' | 'deleting'; /** * Network visibility level for a service. * * Controls internal (service-to-service) access: * - `public` → internal traffic allowed by default * - `private` → internal traffic denied unless caller is in `allowedSources` * - `system` → internal traffic denied unless caller is in `allowedSources` */ type ServiceVisibility = 'public' | 'private' | 'system'; /** * Valid visibility values (for validation) */ declare const VALID_SERVICE_VISIBILITY_VALUES: ServiceVisibility[]; /** * Service entity - persistent pod scheduling configuration * * A Service maintains a desired number of pod replicas: * - replicas = 0: Deploy to ALL matching nodes (DaemonSet-like behavior) * - replicas > 0: Maintain exactly N pods across eligible nodes * * @example * // Deploy to all production nodes * { * name: "log-collector", * packId: "...", * replicas: 0, * scheduling: { nodeSelector: { env: "production" } } * } * * // Maintain 3 replicas * { * name: "web-frontend", * packId: "...", * replicas: 3 * } */ interface Service { /** Unique identifier (UUID) */ id: string; /** Service name (unique within namespace) */ name: string; /** Pack ID to deploy */ packId: string; /** Pack version to deploy */ packVersion: string; /** * Whether to automatically update to the latest pack version. * When true, pods are updated when new pack versions are registered. */ followLatest: boolean; /** Namespace */ namespace: string; /** * Target node ID. When set, all replicas are scheduled on this node. * Required when volumeMounts are specified (volumes are node-local). */ nodeId?: string; /** * Number of desired replicas: * - 0 = deploy to all matching nodes (DaemonSet-like) * - >0 = maintain exactly N pods */ replicas: number; /** Current status */ status: ServiceStatus; /** Status message */ statusMessage?: string; /** Labels on the service itself */ labels: Labels; /** Annotations on the service itself */ annotations: Annotations; /** Labels applied to created pods */ podLabels: Labels; /** Annotations applied to created pods */ podAnnotations: Annotations; /** Priority class name for pods */ priorityClassName?: string; /** Priority value for pods */ priority: number; /** Tolerations for pods */ tolerations: Toleration[]; /** Resource requests for pods */ resourceRequests: ResourceRequirements; /** Resource limits for pods */ resourceLimits: ResourceRequirements; /** Scheduling configuration for pods */ scheduling?: PodSchedulingConfig; /** Volume mounts for pods in this service */ volumeMounts: VolumeMount[]; /** Observed generation (for reconciliation) */ observedGeneration: number; /** Number of ready replicas */ readyReplicas: number; /** Number of available replicas */ availableReplicas: number; /** Number of updated replicas */ updatedReplicas: number; /** * Last pack version that ran successfully. * Used for auto-rollback when new versions fail. */ lastSuccessfulVersion?: string; /** * Pack version that failed during upgrade. * Prevents retry loops by skipping this version. */ failedVersion?: string; /** * Count of consecutive pod failures since last success. * Used for crash-loop detection. */ consecutiveFailures: number; /** * Timestamp until which upgrade retries should be skipped. * Implements exponential backoff for failed upgrades. */ failureBackoffUntil?: Date; /** * Ingress port exposed on the orchestrator server. * When set, the orchestrator opens an HTTP listener on this port * and proxies incoming requests to a healthy pod in the service * via WebSocket relay. */ ingressPort?: number; /** * Network visibility level. * - `public` → internal traffic allowed by default * - `private` → internal traffic denied unless caller is in `allowedSources` * - `system` → internal traffic denied unless caller is in `allowedSources` * @default 'private' */ visibility: ServiceVisibility; /** * Whether this service is reachable from ingress (external traffic). * Exposure alone determines external access — visibility is irrelevant for ingress. * @default false */ exposed: boolean; /** * List of service IDs (names) allowed to call this service internally. * Only evaluated when visibility is `private` or `system`. * If empty/undefined and visibility is private/system, all internal traffic is denied. */ allowedSources?: string[]; /** * List of secret names referenced by this service. * Secrets are resolved by name within the service's namespace. * Injection behavior is defined by each Secret resource — the service * only declares which secrets it needs. */ secrets: string[]; /** * Enable the ephemeral data plane for pods in this service. * When true, each pod receives an `EphemeralDataPlane` instance * as `context.ephemeral`. * @default false */ enableEphemeral: boolean; /** Additional metadata */ metadata: Record; /** User who created the service */ createdBy: string; /** Creation timestamp */ createdAt: Date; /** Last update timestamp */ updatedAt: Date; } /** * Service creation input */ interface CreateServiceInput { /** Service name */ name: string; /** Pack ID or pack name */ packId?: string; /** Pack name (alternative to packId) */ packName?: string; /** Pack version (defaults to latest) */ packVersion?: string; /** * Whether to automatically update to the latest pack version. * When true, pods are updated when new pack versions are registered. * @default false */ followLatest?: boolean; /** Target namespace */ namespace?: string; /** * Target node ID. When set, all replicas are scheduled on this node. * Required when volumeMounts are specified (volumes are node-local). */ nodeId?: string; /** * Number of replicas: * - 0 = deploy to all matching nodes * - >0 = maintain exactly N pods * @default 1 */ replicas?: number; /** Labels on the service */ labels?: Labels; /** Annotations on the service */ annotations?: Annotations; /** Labels applied to created pods */ podLabels?: Labels; /** Annotations applied to created pods */ podAnnotations?: Annotations; /** Priority class name */ priorityClassName?: string; /** Tolerations for pods */ tolerations?: Toleration[]; /** Resource requests for pods */ resourceRequests?: Partial; /** Resource limits for pods */ resourceLimits?: Partial; /** Scheduling configuration */ scheduling?: PodSchedulingConfig; /** Volume mounts for pods */ volumeMounts?: VolumeMount[]; /** * Ingress port to expose on the orchestrator server. * The orchestrator will open an HTTP listener on this port * and route requests to healthy pods in this service. */ ingressPort?: number; /** * Network visibility level. * @default 'private' */ visibility?: ServiceVisibility; /** * Whether this service is reachable from ingress. * @default false */ exposed?: boolean; /** * List of service IDs allowed to call this service internally. * Only relevant for private/system visibility. */ allowedSources?: string[]; /** * List of secret names to attach to this service's pods. * Each secret must exist in the same namespace. * Injection behavior is defined inside the Secret resource. */ secrets?: string[]; /** * Enable the ephemeral data plane for pods in this service. * When true, each pod receives an `EphemeralDataPlane` instance as * `context.ephemeral` — enabling transient group membership, * fan-out queries, and presence tracking. * @default false */ enableEphemeral?: boolean; /** Additional metadata */ metadata?: Record; } /** * Service update input */ interface UpdateServiceInput { /** New pack ID (when following latest, points to the new version's pack row) */ packId?: string; /** New pack version */ packVersion?: string; /** Enable or disable follow latest */ followLatest?: boolean; /** Target node update */ nodeId?: string | null; /** New replica count */ replicas?: number; /** New status */ status?: ServiceStatus; /** Status message */ statusMessage?: string; /** Labels update */ labels?: Labels; /** Annotations update */ annotations?: Annotations; /** Pod labels update */ podLabels?: Labels; /** Pod annotations update */ podAnnotations?: Annotations; /** Priority class name update */ priorityClassName?: string; /** Tolerations update */ tolerations?: Toleration[]; /** Resource requests update */ resourceRequests?: Partial; /** Resource limits update */ resourceLimits?: Partial; /** Scheduling configuration update */ scheduling?: PodSchedulingConfig; /** Volume mounts update */ volumeMounts?: VolumeMount[]; /** Metadata update */ metadata?: Record; /** Last successful version (for auto-rollback tracking) */ lastSuccessfulVersion?: string | null; /** Failed version (to prevent retry loops) */ failedVersion?: string | null; /** Consecutive failure count (for crash-loop detection) */ consecutiveFailures?: number; /** Backoff timestamp (for exponential backoff) */ failureBackoffUntil?: Date | null; /** Ingress port update (null to remove) */ ingressPort?: number | null; /** Network visibility update */ visibility?: ServiceVisibility; /** Exposed flag update */ exposed?: boolean; /** Allowed sources update (null to clear) */ allowedSources?: string[] | null; /** Secrets update (replace list) */ secrets?: string[]; /** Enable/disable ephemeral data plane */ enableEphemeral?: boolean; } /** * Service list item (summary) */ interface ServiceListItem { id: string; name: string; packId: string; packVersion: string; followLatest: boolean; namespace: string; replicas: number; readyReplicas: number; availableReplicas: number; status: ServiceStatus; ingressPort?: number; createdAt: Date; updatedAt: Date; } /** * Check if service is active */ declare function isServiceActive(service: Service): boolean; /** * Check if service is a DaemonSet (replicas = 0) */ declare function isServiceDaemonSet(service: Service): boolean; /** * Check if service has reached desired state */ declare function isServiceReady(service: Service): boolean; /** * Default resource requests for service pods */ declare const DEFAULT_SERVICE_RESOURCE_REQUESTS: ResourceRequirements; /** * Default resource limits for service pods */ declare const DEFAULT_SERVICE_RESOURCE_LIMITS: ResourceRequirements; /** * Secret type definitions for Stark Orchestrator * * Secrets are first-class resources with self-contained injection definitions. * The secret itself declares how it should be injected into pods (env or volume), * keeping service specs clean and declarative. * * @module @stark-o/shared/types/secret */ /** * Secret types supported by the orchestrator. * * - `opaque` — generic key-value pairs (passwords, API keys, tokens) * - `tls` — TLS certificate + private key pair * - `docker-registry` — Docker registry authentication credentials */ type SecretType = 'opaque' | 'tls' | 'docker-registry'; /** * Valid secret type values (for validation) */ declare const VALID_SECRET_TYPES: SecretType[]; /** * Secret injection mode. * Defines how the secret is delivered to pods. * * - `env` — inject as environment variables * - `volume` — mount as files in a directory */ type SecretInjectionMode = 'env' | 'volume'; /** * Valid injection modes (for validation) */ declare const VALID_INJECTION_MODES: SecretInjectionMode[]; /** * Environment variable injection configuration. * * When mode is `env`, each key in the secret data becomes an * environment variable. An optional prefix and key-to-env mapping * allow fine-grained control. * * @example * // Secret data: { username: "admin", password: "s3cret" } * // With prefix "DB_": * // DB_USERNAME=admin * // DB_PASSWORD=s3cret * * @example * // With explicit keyMapping: * // { username: "PGUSER", password: "PGPASSWORD" } * // PGUSER=admin * // PGPASSWORD=s3cret */ interface SecretEnvInjection { mode: 'env'; /** * Prefix applied to environment variable names. * Each secret key is uppercased and prepended with this prefix. * Ignored for keys that have an explicit keyMapping entry. */ prefix?: string; /** * Explicit key-to-environment-variable-name mapping. * Overrides the default "PREFIX + UPPERCASE_KEY" naming. * Keys not listed fall back to the default naming. */ keyMapping?: Record; } /** * Volume mount injection configuration. * * When mode is `volume`, each key in the secret data is written * as a file under mountPath. Optional fileMapping allows renaming. * * @example * // Secret data: { cert: "...", key: "..." } * // With mountPath "/etc/tls": * // /etc/tls/cert * // /etc/tls/key * * @example * // With fileMapping: { cert: "tls.crt", key: "tls.key" } * // /etc/tls/tls.crt * // /etc/tls/tls.key */ interface SecretVolumeInjection { mode: 'volume'; /** * Absolute path inside the pod where secret files are mounted. * Must start with `/`. */ mountPath: string; /** * Optional per-key file name mapping. * Keys not listed use their secret data key name as filename. */ fileMapping?: Record; } /** * Union type for secret injection configuration. * Defined inside the Secret resource itself — services only reference names. */ type SecretInjection = SecretEnvInjection | SecretVolumeInjection; /** * Secret resource — a first-class orchestrator resource. * * Secrets are independent of services. A service only references a secret * by name; the secret itself defines the injection behavior. This design * keeps service specs clean and makes secrets portable across services. * * Secret data is stored encrypted at rest and is NEVER included in API * responses, logs, event streams, or crash dumps. */ interface Secret { /** Unique identifier (UUID) */ id: string; /** Secret name (unique within namespace, DNS-like) */ name: string; /** Namespace the secret belongs to */ namespace: string; /** Secret type */ type: SecretType; /** * Encrypted secret data. * This field contains the AES-256-GCM encrypted payload. * At rest the value is a base64-encoded ciphertext blob. * In memory during pod injection it is decrypted transiently. * * The plaintext shape is Record. * NEVER log, serialize to API responses, or embed in events. */ encryptedData: string; /** * Initialization vector used for AES-GCM encryption. * Stored alongside the ciphertext for decryption. */ iv: string; /** * AES-GCM authentication tag for integrity verification. */ authTag: string; /** Injection configuration (how to deliver to pods) */ injection: SecretInjection; /** * Version counter. Incremented on every data update. * Used for rotation tracking and future multi-version support. */ version: number; /** User who created the secret */ createdBy: string; /** Creation timestamp */ createdAt: Date; /** Last update timestamp */ updatedAt: Date; } /** * Input for creating a secret. * Data is provided in plaintext — encryption happens internally. */ interface CreateSecretInput { /** Secret name */ name: string; /** Target namespace */ namespace?: string; /** Secret type */ type: SecretType; /** * Plaintext key-value data. * For opaque: arbitrary key-value pairs. * For tls: must include `cert` and `key`. * For docker-registry: must include `server`, `username`, `password`. */ data: Record; /** Injection configuration */ injection: SecretInjection; } /** * Input for updating a secret. * Updating data triggers a version bump and pod rotation. */ interface UpdateSecretInput { /** Updated plaintext data (replaces all existing data) */ data?: Record; /** Updated injection configuration */ injection?: SecretInjection; } /** * Summary view of a secret for listing (no secret data exposed). */ interface SecretListItem { id: string; name: string; namespace: string; type: SecretType; injection: SecretInjection; /** Number of keys in the secret (without revealing key names) */ keyCount: number; version: number; createdBy: string; createdAt: Date; updatedAt: Date; } /** * Resolved secret material for pod injection. * This is a transient, in-memory-only structure. * Must be zeroed/discarded after injection. * * @internal — never returned via API or logged */ interface ResolvedSecretMaterial { /** Secret name */ name: string; /** Secret type */ type: SecretType; /** Decrypted plaintext data */ data: Record; /** Injection configuration */ injection: SecretInjection; } /** * Computed environment variables from one or more secrets. * Used during pod startup to populate the process environment. * * @internal */ interface SecretEnvBundle { /** Merged environment variable map */ env: Record; } /** * Computed volume mounts from one or more secrets. * Used during pod startup to write secret files. * * @internal */ interface SecretVolumeMount { /** Absolute mount path */ mountPath: string; /** Filename → content mapping */ files: Record; } /** * Complete injection payload for a pod. * Contains all resolved env vars and volume mounts. * * @internal — transient, zero after use */ interface PodSecretPayload { /** Environment variables from all env-mode secrets */ env: Record; /** Volume mounts from all volume-mode secrets */ volumes: SecretVolumeMount[]; } /** * Required data keys for TLS secrets */ declare const TLS_REQUIRED_KEYS: readonly ["cert", "key"]; /** * Required data keys for docker-registry secrets */ declare const DOCKER_REGISTRY_REQUIRED_KEYS: readonly ["server", "username", "password"]; /** * Check if a secret type requires specific data keys */ declare function getRequiredKeysForType(type: SecretType): readonly string[]; /** * Maximum secret name length */ declare const MAX_SECRET_NAME_LENGTH = 253; /** * Maximum number of keys in a secret */ declare const MAX_SECRET_KEYS = 64; /** * Maximum total secret data size in bytes (1 MB) */ declare const MAX_SECRET_DATA_SIZE = 1048576; /** * Secret name pattern (DNS subdomain: lowercase, alphanumeric, hyphens, dots) */ declare const SECRET_NAME_PATTERN: RegExp; /** * AppConfig types for application-level settings * @module @stark-o/shared/types/app-config */ /** * Application configuration */ interface AppConfig { /** Unique identifier (UUID) */ id: string; /** Config name */ name: string; /** Whether public registration is enabled */ enablePublicRegistration: boolean; /** Creation timestamp */ createdAt: Date; /** Last update timestamp */ updatedAt: Date; } /** * App config update input */ interface UpdateAppConfigInput { enablePublicRegistration?: boolean; } /** * Default app configuration */ declare const DEFAULT_APP_CONFIG: Omit; /** * Ephemeral Data Plane Types * * Types for transient pod-to-pod state: PodGroups, ephemeral queries, * and ephemeral responses. Designed for high-throughput in-memory * communication patterns (presence, signal exchange, contact tracing) * that live outside the persistent control plane. * * **Separation of concerns:** * - Control plane (ServiceRegistry, PodStore): authoritative, persistent state * - Ephemeral data plane (PodGroupStore): transient, TTL-scoped state * * @module @stark-o/shared/types/ephemeral */ /** * A single pod's membership within a PodGroup. * Each membership carries its own TTL — stale members are reaped automatically. */ interface PodGroupMembership { /** The pod that joined this group */ podId: string; /** Epoch ms when this membership was created */ joinedAt: number; /** Epoch ms when this membership was last refreshed */ lastRefreshedAt: number; /** TTL in ms for this membership (0 = infinite, manual removal only) */ ttl: number; /** Optional caller-supplied metadata (e.g. presence payload, capability tags) */ metadata?: Record; } /** * A PodGroup is an ephemeral, overlapping collection of pods grouped * by a locally-computed `groupId`. Groups are created lazily on first * join and garbage-collected when all members expire. */ interface PodGroup { /** Group identifier (locally computed by the joining pod) */ groupId: string; /** Active memberships in this group */ members: PodGroupMembership[]; /** Epoch ms when this group was first created */ createdAt: number; /** Epoch ms of the most recent membership change */ updatedAt: number; } /** * A query sent to one or more pods for ephemeral (non-persistent) data. * Unlike ServiceRequest (which is a full HTTP-like RPC), an ephemeral query * is a lightweight read-only probe for transient state. */ interface EphemeralQuery { /** Unique query ID for correlation */ queryId: string; /** The pod IDs to query */ targetPodIds: string[]; /** Virtual path to query (e.g. '/health', '/state/presence') */ path: string; /** Optional query parameters */ query?: Record; /** Epoch ms when this query was issued */ issuedAt: number; /** Timeout in ms (0 = use default) */ timeout?: number; } /** * A single pod's ephemeral response to a query. */ interface EphemeralResponse { /** Correlation query ID */ queryId: string; /** The responding pod */ podId: string; /** HTTP-like status code */ status: number; /** Response payload (ephemeral, never persisted) */ body?: unknown; /** Epoch ms when this response was recorded */ respondedAt: number; } /** * Aggregated responses from querying a list of pods. * Keyed by podId for O(1) lookup per pod. */ interface EphemeralQueryResult { /** The original query */ query: EphemeralQuery; /** Responses keyed by podId */ responses: Map; /** Pod IDs that did not respond before timeout */ timedOut: string[]; /** Whether all targeted pods responded */ complete: boolean; /** Epoch ms when the result was finalized */ completedAt: number; } /** * Ephemeral event types emitted by the data plane. * These are separate from the control plane's StarkEventType. */ type EphemeralEventType = 'PodJoinedGroup' | 'PodLeftGroup' | 'PodGroupCreated' | 'PodGroupDissolved' | 'PodMembershipExpired' | 'PodMembershipRefreshed' | 'EphemeralQueryIssued' | 'EphemeralResponseReceived'; /** * An ephemeral event payload for audit/logging hooks. */ interface EphemeralEvent { /** Event type */ type: EphemeralEventType; /** ISO timestamp */ timestamp: string; /** Primary group ID (if applicable) */ groupId?: string; /** Primary pod ID (if applicable) */ podId?: string; /** Query ID (if applicable) */ queryId?: string; /** Human-readable detail message */ message?: string; /** Additional context */ metadata?: Record; } /** * Callback signature for ephemeral audit hooks. * Hooks are fire-and-forget — they must not throw or block. */ type EphemeralAuditHook = (event: EphemeralEvent) => void; /** * Configuration for the ephemeral data plane. */ interface EphemeralDataPlaneConfig { /** Default TTL for PodGroup memberships in ms (default: 60_000 — 1 minute) */ defaultMembershipTtl?: number; /** Interval in ms between stale-membership reap cycles (default: 10_000) */ reapIntervalMs?: number; /** Default timeout for ephemeral queries in ms (default: 5_000) */ defaultQueryTimeout?: number; /** Maximum number of concurrent groups (0 = unlimited) */ maxGroups?: number; /** Maximum members per group (0 = unlimited) */ maxMembersPerGroup?: number; /** Whether to use node-cache for the backing store (default: true) */ useNodeCache?: boolean; } /** Default membership TTL: 60 seconds */ declare const DEFAULT_MEMBERSHIP_TTL = 60000; /** Default reap interval: 10 seconds */ declare const DEFAULT_REAP_INTERVAL = 10000; /** Default ephemeral query timeout: 5 seconds */ declare const DEFAULT_EPHEMERAL_QUERY_TIMEOUT = 5000; /** * PodGroup Store * * In-memory, TTL-scoped store for ephemeral PodGroup memberships. * Backed by `node-cache` for automatic key expiration without blocking * the main event loop — optimized for single-process Node.js execution. * * **Design goals:** * - Overlapping groups: a pod can belong to many groups simultaneously * - Per-member TTL: each membership expires independently * - Automatic reaping: stale members are swept on a configurable interval * - Non-blocking: reap cycles use `setInterval`, never `setImmediate` * - Deterministic separation: ephemeral data plane state is isolated * from the control plane (PodStore / ClusterState) * * @module @stark-o/shared/network/pod-group-store */ declare class PodGroupStore { /** * node-cache instance for individual membership entries. * Each key is `grp::pod:` → PodGroupMembership. * TTL is set per-key to the membership's own TTL. */ private cache; /** * Secondary index: groupId → Set of podIds currently in this group. * Kept in sync with the cache via add/remove/expire. */ private groupIndex; /** * Reverse index: podId → Set of groupIds the pod belongs to. * Enables efficient `leaveAllGroups(podId)`. */ private podIndex; /** * Group metadata (createdAt / updatedAt timestamps). */ private groupMeta; /** * Registered audit hooks. */ private hooks; /** * Reap interval handle (for cleanup on dispose). */ private reapTimer; /** * Configuration snapshot. */ private config; constructor(config?: EphemeralDataPlaneConfig); /** * Join a group by groupId. * * If the pod is already a member, the membership is refreshed * (timestamp + TTL reset). Groups are created lazily. * * @param groupId Locally-computed group identifier * @param podId The pod joining the group * @param ttl Optional TTL override in ms (0 = infinite) * @param metadata Optional metadata attached to this membership * @returns The created or refreshed membership */ joinGroup(groupId: string, podId: string, ttl?: number, metadata?: Record): PodGroupMembership; /** * Leave a specific group. * * @returns true if the pod was a member and was removed. */ leaveGroup(groupId: string, podId: string): boolean; /** * Remove a pod from all groups it belongs to. * Useful when a pod is terminated or evicted. * * @returns The list of groupIds the pod was removed from. */ leaveAllGroups(podId: string): string[]; /** * Get all pods currently in a group. * * @returns Array of active memberships, or empty if the group doesn't exist. */ getGroupPods(groupId: string): PodGroupMembership[]; /** * Get the PodGroup metadata (including the member list). * * @returns The full PodGroup or undefined if it doesn't exist. */ getGroup(groupId: string): PodGroup | undefined; /** * Get all group IDs that a pod belongs to. */ getGroupsForPod(podId: string): string[]; /** * Check if a pod is a member of a specific group. */ isMember(groupId: string, podId: string): boolean; /** * List all active group IDs. */ listGroups(): string[]; /** * Get the number of active groups. */ get groupCount(): number; /** * Get the total number of membership entries across all groups. */ get membershipCount(): number; /** * Get a snapshot of the full store for debugging/API. */ snapshot(): Record; /** * Manually trigger a stale-membership reap cycle. * Normally called automatically on the configured interval. * * This checks manual TTL expiration for entries that node-cache's * internal checkperiod may not have swept yet. * * @returns Number of memberships reaped. */ reapStaleMembers(): number; /** * Register an audit hook for ephemeral events. * Hooks are invoked synchronously but must not throw. * * @returns A dispose function to unregister the hook. */ onEvent(hook: EphemeralAuditHook): () => void; /** * Clear all groups, memberships, and indices. */ clear(): void; /** * Dispose the store, clearing the reap interval and flushing all data. * Call this when the orchestrator shuts down. */ dispose(): void; private addMemberToIndices; private removeMemberFromIndices; private emit; } /** * Get (or create) the global singleton PodGroupStore. * For orchestrator-side use in the ephemeral data plane. */ declare function getPodGroupStore(config?: EphemeralDataPlaneConfig): PodGroupStore; /** * Reset the global PodGroupStore (for testing). */ declare function resetPodGroupStore(): void; /** * Network Types for Inter-Service Communication * * Defines types for pod-to-pod WebRTC communication, service routing, * network policies, and the orchestrator service registry. * * @module @stark-o/shared/types/network */ /** * Status of a pod within the service registry. */ type RegistryPodStatus = 'healthy' | 'unhealthy' | 'unknown'; /** * An entry in the orchestrator's service registry. * Maps a service to its backing pods. */ interface ServiceRegistryEntry { podId: string; nodeId: string; status: RegistryPodStatus; lastHeartbeat: number; } /** * A cached target pod for a specific service, stored on the caller pod. * Sticky by default: the same target pod is reused until TTL or failure. */ interface CachedTargetPod { serviceId: string; podId: string; nodeId: string; cachedAt: number; ttl: number; healthy: boolean; } /** * A network policy rule controlling inter-service communication. */ type NetworkPolicyAction = 'allow' | 'deny'; interface NetworkPolicy { id: string; sourceService: string; targetService: string; action: NetworkPolicyAction; namespace?: string; createdAt: number; } /** * Input for creating a network policy via API or CLI. */ interface CreateNetworkPolicyInput { sourceService: string; targetService: string; action: NetworkPolicyAction; namespace?: string; } /** * A service call request envelope sent pod-to-pod via WebRTC. */ interface ServiceRequest { /** Unique request ID for correlation */ requestId: string; /** The calling pod's ID */ sourcePodId: string; /** The calling pod's service ID */ sourceServiceId: string; /** The target service virtual URL was resolved to this pod */ targetPodId: string; /** The target service ID */ targetServiceId: string; /** HTTP-like method */ method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; /** Path portion of the virtual URL (e.g. /users/123) */ path: string; /** Optional headers */ headers?: Record; /** Optional body (serialised) */ body?: unknown; /** If true, bypass sticky cache and ask orchestrator for a fresh pod */ nonSticky?: boolean; } /** * A service call response envelope returned pod-to-pod via WebRTC. */ interface ServiceResponse { requestId: string; status: number; headers?: Record; body?: unknown; error?: string; } /** * State of a WebRTC connection to a target pod. */ type PeerConnectionState = 'new' | 'connecting' | 'connected' | 'disconnected' | 'failed' | 'closed'; /** * Configuration for the WebRTC connection manager. */ interface WebRTCConfig { /** ICE servers for NAT traversal */ iceServers?: RTCIceServerInit[]; /** Connection timeout in ms (default: 10_000) */ connectionTimeout?: number; /** Whether to use trickle ICE (default: true) */ trickleICE?: boolean; } /** * Minimal ICE server config (isomorphic — no dependency on browser globals). */ interface RTCIceServerInit { urls: string | string[]; username?: string; credential?: string; } /** * Signalling message exchanged via the orchestrator WebSocket * to establish WebRTC connections between pods. */ type SignallingMessageType = 'offer' | 'answer' | 'ice-candidate'; interface SignallingMessage { type: SignallingMessageType; sourcePodId: string; targetPodId: string; payload: unknown; } /** * Request from a pod to the orchestrator asking for a target pod * for a given service. */ interface RoutingRequest { callerPodId: string; callerServiceId: string; targetServiceId: string; /** If true, orchestrator should pick a fresh pod even if the caller has a cached one */ nonSticky?: boolean; } /** * Response from the orchestrator with the selected target pod. */ interface RoutingResponse { targetPodId: string; targetNodeId: string; /** Whether the policy check passed (always true if policies are disabled) */ policyAllowed: boolean; /** If policyAllowed is false, the reason */ policyDeniedReason?: string; } /** * Options for making a service call from a pod. */ interface ServiceCallOptions { /** HTTP-like method (default: GET) */ method?: ServiceRequest['method']; /** Request headers */ headers?: Record; /** Request body */ body?: unknown; /** Bypass sticky session and request a fresh target pod */ nonSticky?: boolean; /** Request timeout in ms (default: 30_000) */ timeout?: number; } type NetworkEventType = 'NetworkPolicyCreated' | 'NetworkPolicyDeleted' | 'NetworkPolicyDenied' | 'ServiceCallRouted' | 'PeerConnectionOpened' | 'PeerConnectionClosed' | 'PeerConnectionFailed'; /** Default TTL for cached target pods: 5 minutes */ declare const DEFAULT_CACHE_TTL: number; /** Default WebRTC connection timeout: 10 seconds */ declare const DEFAULT_CONNECTION_TIMEOUT = 10000; /** Default service call timeout: 30 seconds */ declare const DEFAULT_SERVICE_CALL_TIMEOUT = 30000; /** Virtual URL suffix for internal service calls */ declare const INTERNAL_URL_SUFFIX = ".internal"; /** * Parse a virtual internal URL into serviceId, optional namespace, and path. * Input: `http://my-service.internal/api/users` → `{ serviceId: 'my-service', path: '/api/users' }` * Input: `http://my-service.production.internal/api/users` → `{ serviceId: 'my-service', namespace: 'production', path: '/api/users' }` */ declare function parseInternalUrl(url: string): { serviceId: string; namespace?: string; path: string; } | null; /** * Network Policy Engine * * Enforces inter-service communication policies. Runs isomorphically * on both orchestrator (server-side) and pod (client-side). * * **Deny-by-default**: all inter-service traffic is blocked until * explicit 'allow' rules are configured. * * @module @stark-o/shared/network/network-policy */ /** * In-memory network policy store. * Can be used on the orchestrator or synced to pods. */ declare class NetworkPolicyEngine { private policies; private nextId; /** * Add a new network policy. * If a policy for the same source→target pair already exists, it is replaced. */ addPolicy(input: CreateNetworkPolicyInput): NetworkPolicy; /** * Remove a policy by ID. */ removePolicy(id: string): boolean; /** * Remove all policies for a source→target pair. */ removePolicyByPair(sourceService: string, targetService: string): boolean; /** * Check if a service call is allowed. * * Rules (deny-by-default): * 1. If no policies exist at all → **denied** (no allow rules configured). * 2. If an explicit 'allow' exists for source→target → **allowed**. * 3. If an explicit 'deny' exists for source→target → **denied**. * 4. If policies exist but none match this pair → **denied** (default-deny). */ isAllowed(sourceService: string, targetService: string): { allowed: boolean; reason?: string; }; /** * Get all policies. */ listPolicies(): NetworkPolicy[]; /** * Get a policy by ID. */ getPolicy(id: string): NetworkPolicy | undefined; /** * Replace the entire policy set (used for syncing from orchestrator). */ syncPolicies(policies: NetworkPolicy[]): void; /** * Clear all policies. */ clear(): void; /** * Number of active policies. */ get size(): number; private pairKey; /** * Filter policies by namespace. */ listPoliciesByNamespace(namespace: string): NetworkPolicy[]; } declare function getNetworkPolicyEngine(): NetworkPolicyEngine; /** * Quick check: is traffic from source to target allowed? * Uses the global policy engine singleton. */ declare function isServiceCallAllowed(sourceService: string, targetService: string): { allowed: boolean; reason?: string; }; /** * Network metadata for a service, used by the centralized policy evaluator. * This is a lightweight subset of the full Service type. */ interface ServiceNetworkMeta { /** Service ID (name) */ serviceId: string; /** Namespace the service belongs to */ namespace: string; /** Network visibility: public, private, or system */ visibility: ServiceVisibility; /** Whether this service is reachable from ingress */ exposed: boolean; /** Service IDs allowed to call this service internally (for private/system) */ allowedSources?: string[]; } /** * Lookup function to retrieve network metadata for a service by ID/name. * Implementations will query the service registry / database. */ type ServiceNetworkMetaLookup = (serviceId: string) => ServiceNetworkMeta | undefined; /** * Request context for centralized policy evaluation. */ interface PolicyEvaluationRequest { /** The calling service ID (use 'ingress' for external traffic) */ sourceServiceId: string; /** The target service ID */ targetServiceId: string; /** Whether this request originates from ingress (external) */ isIngressRequest: boolean; } /** * Result of a centralized policy evaluation. */ interface PolicyEvaluationResult { /** Whether the request is allowed */ allowed: boolean; /** Human-readable reason (populated on deny) */ reason?: string; } /** * Centralized network policy evaluation function. * * Implements the two-step policy model: * Step 1 — Ingress Check: if isIngressRequest, only `exposed` matters. * Step 2 — Internal Policy Check: uses visibility + allowedSources. * * This function is the single source of truth for network policy decisions. * It must be called at the ingress routing layer and at the node routing layer. * Pods must NOT call this — enforcement is centralized. * * @param request The policy evaluation request context * @param lookup Function to resolve service network metadata * @returns PolicyEvaluationResult with allowed/denied + reason */ declare function evaluateNetworkPolicy(request: PolicyEvaluationRequest, lookup: ServiceNetworkMetaLookup): PolicyEvaluationResult; /** * In-memory store for service network metadata. * Used by the orchestrator to track visibility/exposed/allowedSources * for all registered services. */ declare class ServiceNetworkMetaStore { private store; /** * Build a composite key from namespace and serviceId. */ private key; /** * Set or update network metadata for a service. */ set(meta: ServiceNetworkMeta): void; /** * Get network metadata for a service. */ get(serviceId: string, namespace?: string): ServiceNetworkMeta | undefined; /** * Remove network metadata for a service. */ remove(serviceId: string, namespace?: string): boolean; /** * List all service network metadata. */ list(): ServiceNetworkMeta[]; /** * Set visibility for a service. */ setVisibility(serviceId: string, visibility: ServiceVisibility, namespace?: string): boolean; /** * Set exposed flag for a service. */ setExposed(serviceId: string, exposed: boolean, namespace?: string): boolean; /** * Add a source to a service's allowed sources. */ addAllowedSource(serviceId: string, sourceServiceId: string, namespace?: string): boolean; /** * Remove a source from a service's allowed sources. */ removeAllowedSource(serviceId: string, sourceServiceId: string, namespace?: string): boolean; /** * Create a lookup function bound to this store. * Use this as the `lookup` argument to `evaluateNetworkPolicy`. * When namespace is provided, lookups are scoped to that namespace. */ createLookup(namespace?: string): ServiceNetworkMetaLookup; /** * Clear all entries. */ clear(): void; /** * Number of entries. */ get size(): number; } declare function getServiceNetworkMetaStore(): ServiceNetworkMetaStore; /** * PodGroupHandle * * A high-level handle returned by `EphemeralDataPlane.joinGroup()`. * Encapsulates group membership, member discovery, fan-out queries, * and lifecycle (leave / refresh) into a single ergonomic object. * * @module @stark-o/shared/network/pod-group-handle */ /** * Subset of EphemeralDataPlane that PodGroupHandle needs. * Avoids a circular import between the handle and the plane. */ interface PodGroupPlaneRef { /** The pod ID that owns this plane instance. */ readonly podId: string; joinGroup(groupId: string, options?: { ttl?: number; metadata?: Record; }): PodGroupMembership | Promise; joinGroupRaw(groupId: string, options?: { ttl?: number; metadata?: Record; }): PodGroupMembership | Promise; leaveGroup(groupId: string): boolean | Promise; getGroupPods(groupId: string): PodGroupMembership[] | Promise; queryPods(podIds: string[], path: string, query?: Record, timeout?: number): Promise; } interface PodGroupHandleOptions { /** The group this handle belongs to */ groupId: string; /** TTL used when joining / refreshing the group */ ttl?: number; /** Metadata attached to this pod's membership */ metadata?: Record; /** Initial membership snapshot returned by the join call */ membership: PodGroupMembership; /** Initial member list (fetched right after join) */ members: PodGroupMembership[]; /** Back-reference to the owning plane */ plane: PodGroupPlaneRef; } declare class PodGroupHandle { /** Group identifier */ readonly groupId: string; /** This pod's membership record (refreshed on `.refresh()`) */ membership: PodGroupMembership; /** Cached pod IDs of all group members (refreshed on `.refresh()`) */ podIds: string[]; /** Full membership records of all group members */ members: PodGroupMembership[]; private _plane; private _ttl; private _metadata; private _left; constructor(options: PodGroupHandleOptions); /** Pod IDs of every member *except* the current pod. */ get otherPodIds(): string[]; /** Whether `.leave()` has been called on this handle. */ get isLeft(): boolean; /** * Fan-out a query to every *other* pod in the group. * * Returns an array of promises — one per target pod — so callers can * `await Promise.all(group.queryPods(...))` or process individually. * * Each promise resolves with an `EphemeralQueryResult` scoped to that * single target pod. */ queryPods(path: string, query?: Record, timeout?: number, includeSelf?: boolean): Promise[]; /** * Re-join the group (refreshing TTL) and update the cached member list. */ refresh(): Promise; /** * Leave this PodGroup and mark the handle as dead. */ leave(): Promise; } /** * Ephemeral Data Plane * * High-level, developer-friendly API for transient pod communication. * Sits atop the PodGroupStore and integrates with the existing * orchestrator routing and policy architecture. * * **API surface:** * - `joinGroup(groupId)` — join a group, returns a PodGroupHandle * - `handle(path, handler)` — register an ephemeral query handler * - `leaveAllGroups()` — leave every group (graceful shutdown) * * **PodGroupHandle API:** * - `group.podIds` — current member pod IDs * - `group.otherPodIds` — members excluding this pod * - `group.queryPods(path, q)` — fan-out query (one Promise per peer) * - `group.refresh()` — re-join + refresh members * - `group.leave()` — leave this group * * All state is in-memory and fully TTL-scoped. No persistent storage * or external dependencies beyond `node-cache`. * * **Extensibility hooks:** * - Contact tracing: who talked to whom * - Presence updates: heartbeat-style membership refresh * - Signal exchange: WebRTC offer/answer relay via ephemeral queries * * @module @stark-o/shared/network/ephemeral-data-plane */ /** * Handler registered by a pod to respond to ephemeral queries. * Mirrors the lightweight `RequestHandler` pattern from orchestrator-router. */ type EphemeralQueryHandler = (path: string, query?: Record) => Promise<{ status: number; body?: unknown; }> | { status: number; body?: unknown; }; /** * Transport abstraction for delivering ephemeral queries to pods. * Implementations differ per runtime (WebRTC data channel, postMessage, direct call). */ type EphemeralTransport = (targetPodId: string, query: EphemeralQuery) => Promise; /** * Transport abstraction for group operations via WS to the orchestrator. * When provided, group join/leave/getGroupPods are proxied through the * orchestrator's central PodGroupStore instead of using a local store. */ interface GroupTransport { join(groupId: string, podId: string, ttl?: number, metadata?: Record): Promise; leave(groupId: string, podId: string): Promise; leaveAll(podId: string): Promise; getGroupPods(groupId: string): Promise; getGroupsForPod(podId: string): Promise; } /** * Configuration for the EphemeralDataPlane. */ interface EphemeralDataPlaneOptions { /** This pod's ID (used as the caller identity) */ podId: string; /** This pod's service ID (for policy checks) */ serviceId?: string; /** Network policy engine (optional — omit to skip policy checks) */ policyEngine?: NetworkPolicyEngine; /** Transport function for sending queries to remote pods */ transport?: EphemeralTransport; /** * Transport for group operations via WS to the orchestrator. * When provided, group state is managed centrally on the server * instead of in a local PodGroupStore. */ groupTransport?: GroupTransport; /** Backing PodGroupStore (a default one is created if omitted; ignored when groupTransport is set) */ groupStore?: PodGroupStore; /** Data plane configuration */ config?: EphemeralDataPlaneConfig; } declare class EphemeralDataPlane { private podId; private transport; private groupTransport; private store; private config; /** * Ephemeral query handlers registered by this pod. * Path → handler, matching orchestrator-router's PodRequestRouter pattern. */ private handlers; /** * In-memory store of the latest query results, keyed by queryId. * `podResponses[podId]` is accessible via `getResponses(queryId)`. */ private queryResults; /** Monotonic query counter for ID generation */ private queryCounter; /** Active PodGroupHandle instances, keyed by groupId */ private activeHandles; constructor(options: EphemeralDataPlaneOptions); /** Whether group ops are proxied through the orchestrator. */ get isRemoteGroupMode(): boolean; /** * Join a group by a locally-computed groupId. * * Returns a `PodGroupHandle` that encapsulates the membership, member * list, fan-out queries, refresh, and leave lifecycle for this group. * * If this pod already holds a handle for the given `groupId`, the * existing handle is refreshed and returned (no duplicate handles). * * @param groupId Group identifier (locally computed by the pod) * @param options Optional TTL and metadata overrides * @returns A PodGroupHandle (always async) */ joinGroup(groupId: string, options?: { ttl?: number; metadata?: Record; }): Promise; /** * Low-level join that returns the raw PodGroupMembership without * creating a PodGroupHandle. Used internally by PodGroupHandle.refresh(). * @internal */ joinGroupRaw(groupId: string, options?: { ttl?: number; metadata?: Record; }): PodGroupMembership | Promise; /** * Leave a specific group. * Also marks and cleans up the associated PodGroupHandle (if any). */ leaveGroup(groupId: string): boolean | Promise; /** * Leave all groups this pod belongs to. * Marks all active PodGroupHandle instances as left. * Call during graceful shutdown. */ leaveAllGroups(): Promise; /** * Get all pods currently in a PodGroup. * * When a `groupTransport` is configured this returns a Promise that * resolves with the authoritative member list from the orchestrator. */ getGroupPods(groupId: string): PodGroupMembership[] | Promise; /** * Get the full PodGroup (metadata + members). * Note: only available in local mode (returns undefined in remote mode). */ getGroup(groupId: string): PodGroup | undefined; /** * List all groups this pod currently belongs to. */ myGroups(): string[] | Promise; /** * Fan-out an ephemeral query to a list of pods. * * @example * ```ts * const result = await plane.queryPods( * ['pod-abc', 'pod-def'], * '/state/presence', * { room: 'lobby' }, * ); * const abcResponse = result.responses.get('pod-abc'); * ``` * * @param podIds Target pod IDs * @param path Virtual path to query * @param query Optional query parameters * @param timeout Optional timeout override in ms * @returns Aggregated EphemeralQueryResult */ queryPods(podIds: string[], path: string, query?: Record, timeout?: number): Promise; /** * Get the stored result of a previous query by queryId. */ getQueryResult(queryId: string): EphemeralQueryResult | undefined; /** * Get the ephemeral response map for a specific query result. * Returns a `podResponses[podId]` view. */ getResponses(queryId: string): Map | undefined; /** * Clear stored query results older than the given age in ms. * Call periodically to prevent unbounded memory growth. * * @param maxAgeMs Maximum age for query results (default: 60_000) * @returns Number of results evicted */ evictStaleResults(maxAgeMs?: number): number; /** * Register a handler for incoming ephemeral queries on this pod. * Mirrors `PodRequestRouter.handle()` from orchestrator-router. * * @param pathPrefix Path prefix to match (e.g. '/state', '/health') * @param handler Handler function */ handle(pathPrefix: string, handler: EphemeralQueryHandler): void; /** * Dispatch an incoming ephemeral query to a registered handler. * Called by the transport layer when this pod receives a query. * * @returns The EphemeralResponse, or null if no handler matched. */ handleIncomingQuery(query: EphemeralQuery): Promise; /** * Register an audit hook on the backing PodGroupStore. * Only available in local mode (no-op in remote mode). * @returns A dispose function to unregister the hook. */ onEvent(hook: EphemeralAuditHook): () => void; /** * Get the backing PodGroupStore (for advanced use or testing). * Returns null when operating in remote group mode. */ getStore(): PodGroupStore | null; /** * Graceful shutdown: leave all groups, clear results, dispose the store. */ dispose(): void; /** * Dispatch a query to a local handler (longest-prefix match). */ private dispatchLocal; private nextQueryId; } /** * Create an EphemeralDataPlane instance for a pod. * * @example * ```ts * const plane = createEphemeralDataPlane({ * podId: 'pod-abc-123', * serviceId: 'my-service', * }); * * const group = await plane.joinGroup('room:lobby'); * console.log(group.podIds); // all members * console.log(group.otherPodIds); // everyone except me * * // Fan-out query — one promise per remote pod * const results = await Promise.all(group.queryPods('/state/presence')); * * // Refresh TTL + member list * await group.refresh(); * * // Leave when done * await group.leave(); * ``` */ declare function createEphemeralDataPlane(options: EphemeralDataPlaneOptions): EphemeralDataPlane; /** * Shared Runtime Types for Stark Orchestrator * * This module defines common types used by both Node.js and Browser runtime agents. * These types enable code sharing between the runtime implementations. * * @module @stark-o/shared/types/runtime */ /** * WebSocket message structure used for agent communication */ interface WsMessage { type: string; payload: T; correlationId?: string; } /** * Connection state for runtime agents */ type ConnectionState = 'disconnected' | 'connecting' | 'connected' | 'authenticating' | 'authenticated' | 'registering' | 'registered'; /** * Common agent events shared between Node.js and Browser agents */ type BaseAgentEvent = 'connecting' | 'connected' | 'authenticated' | 'registered' | 'heartbeat' | 'disconnected' | 'reconnecting' | 'error' | 'stopped'; /** * Pod-related agent events */ type PodAgentEvent = 'pod:deployed' | 'pod:started' | 'pod:stopped' | 'pod:failed'; /** * All agent events (base + pod events) */ type AgentEvent = BaseAgentEvent | PodAgentEvent; /** * Agent event handler function type */ type AgentEventHandler = (event: E, data?: unknown) => void; /** * Pod deploy payload received from orchestrator */ interface PodDeployPayload { podId: string; nodeId: string; serviceId?: string; /** Pod authentication token for data plane (network) connections */ podToken?: string; /** Refresh token for automatic token renewal */ podRefreshToken?: string; /** Token expiration timestamp (ISO string) */ podTokenExpiresAt?: string; pack: { id: string; name: string; version: string; runtimeTag: RuntimeTag; namespace?: PackNamespace; bundlePath: string; bundleContent?: string; metadata?: Record; grantedCapabilities?: Capability[]; }; resourceRequests?: ResourceRequirements; resourceLimits?: ResourceRequirements; volumeMounts?: VolumeMount[]; labels?: Labels; annotations?: Annotations; namespace?: string; } /** * Pod stop payload received from orchestrator */ interface PodStopPayload { podId: string; reason?: string; } /** * Pod status for local tracking in runtime agents */ type LocalPodStatus = 'pending' | 'starting' | 'running' | 'stopping' | 'stopped' | 'failed'; /** * Result of a pod operation (deploy/stop) */ interface PodOperationResult { success: boolean; error?: string; } /** * Pod lifecycle phase - represents the current phase in the pod's lifecycle. * Exposed as a "fact" that running pack code can query. */ type PodLifecyclePhase = 'initializing' | 'running' | 'stopping' | 'terminated'; /** * Pod lifecycle facts - queryable state about the pod's lifecycle. * These are "facts" that the running pack code can query to understand its execution context. */ interface PodLifecycleFacts { /** Current lifecycle phase */ readonly phase: PodLifecyclePhase; /** Whether a shutdown has been requested (graceful stop signal received) */ readonly isShuttingDown: boolean; /** Reason for shutdown (if stopping/terminated) */ readonly shutdownReason?: string; /** Timestamp when shutdown was requested (if stopping) */ readonly shutdownRequestedAt?: Date; /** Time remaining for graceful shutdown in ms (if stopping), undefined if not stopping */ readonly gracefulShutdownRemainingMs?: number; } /** * Callback for shutdown notification - allows pack code to handle graceful shutdown */ type ShutdownHandler = (reason?: string) => void | Promise; /** * Data message pushed to a running pack by the runtime. * Used for auth token refreshes, open-count changes, and other live updates. * * Transport is runtime-specific but the shape is identical everywhere: * - browser / Node.js main thread → direct callback ("mock sendMessage") * - browser Web Worker → postMessage() * - Node.js subprocess → IPC (process.send) */ interface PackDataMessage { /** Discriminator, e.g. 'auth:token-refreshed', 'start-menu:opened' */ type: string; /** Arbitrary payload associated with the message */ payload?: unknown; } /** * Handler for receiving data update messages inside a running pack. */ type PackMessageHandler = (message: PackDataMessage) => void; /** * Pack execution context passed to the pack's entry point. * Shared between Node.js and Browser runtimes. */ interface PackExecutionContext { /** Unique execution ID */ executionId: string; /** Pod ID */ podId: string; /** Pack ID */ packId: string; /** Pack version */ packVersion: string; /** Pack name */ packName: string; /** Runtime tag */ runtimeTag: RuntimeTag; /** Environment variables */ env: Record; /** Execution timeout in milliseconds */ timeout: number; /** Additional metadata */ metadata: Record; /** * Pod lifecycle facts - queryable state about the pod's lifecycle. * Use this to check if the pod is shutting down and respond gracefully. * * @example * ```typescript * // Check if shutdown was requested * if (context.lifecycle.isShuttingDown) { * await cleanup(); * return; * } * * // Periodic check in long-running operations * while (!context.lifecycle.isShuttingDown) { * await doWork(); * } * ``` */ lifecycle: PodLifecycleFacts; /** * Register a handler to be called when shutdown is requested. * The handler will be invoked during graceful shutdown before force termination. * * @param handler - Async function to call on shutdown * @example * ```typescript * context.onShutdown(async (reason) => { * console.log(`Shutting down: ${reason}`); * await saveState(); * await closeConnections(); * }); * ``` */ onShutdown: (handler: ShutdownHandler) => void; /** * Register a handler to receive data-update messages from the runtime. * The transport is runtime-specific but the API is identical: * * - **browser / Node.js main thread** – direct callback invocation * - **browser Web Worker** – `postMessage()` bridge * - **Node.js subprocess** – IPC bridge * * @param handler - Callback invoked for every incoming message * @example * ```typescript * context.onMessage((msg) => { * if (msg.type === 'auth:token-refreshed') { * updateToken(msg.payload); * } * }); * ``` */ onMessage: (handler: PackMessageHandler) => void; /** * The service ID for this pod (set by the runtime when networking is enabled). * Used by HTTP interceptors for policy checking and routing. */ serviceId?: string; /** * Pod authentication token for orchestrator registration. * Used to prevent pod spoofing by verifying the pod's identity. * @internal Set by the runtime, not intended for pack code use. */ authToken?: string; /** * Pod refresh token for automatic token renewal. * @internal Set by the runtime, not intended for pack code use. */ refreshToken?: string; /** * Pod token expiration timestamp (ISO 8601). * @internal Set by the runtime, not intended for pack code use. */ tokenExpiresAt?: string; /** * Ephemeral data plane instance for transient pod-to-pod communication. * Only available when `metadata.enableEphemeral` is `true` on the pack. * * Provides group membership, fan-out queries, and presence tracking * without requiring persistent state or external dependencies. * * @example * ```typescript * if (context.ephemeral) { * context.ephemeral.joinGroup('room:lobby'); * const members = context.ephemeral.getGroupPods('room:lobby'); * const result = await context.ephemeral.queryPods(members, '/ping'); * } * ``` */ ephemeral?: EphemeralDataPlane; /** * Volume mounts for this pod. * Each entry maps a named volume to a mount path inside the runtime. */ volumeMounts?: VolumeMount[]; /** * Read a file from a volume-backed path. * Only available when the pod has volume mounts and the runtime provides * file I/O for those paths. */ readFile?: (path: string) => Promise; /** * Write a file to a volume-backed path. * Only available when the pod has volume mounts and the runtime provides * file I/O for those paths. */ writeFile?: (path: string, content: string) => Promise; /** * Append content to a file at a volume-backed path. * Only available when the pod has volume mounts and the runtime provides * file I/O for those paths. */ appendFile?: (path: string, content: string) => Promise; /** * Browser-only: register inbound request handlers. * * In Node.js, use standard HTTP servers (Express, Fastify, Koa, etc.) — * Stark intercepts `http.createServer` automatically and routes WebRTC * requests to the pack's server. No explicit handler registration needed. * * In the browser (Web Workers), there is no `http.createServer`, so packs * must use `context.listen` to register handlers explicitly. * * @example * ```typescript * // Browser pack: * context.listen.handle('/greet', async (method, path, body) => { * return { status: 200, body: { message: 'Hello!' } }; * }); * * context.listen.handle('/echo', async (method, path, body) => { * return { status: 200, body: { echo: body } }; * }); * * context.listen.setDefault(async (method, path) => { * return { status: 404, body: { error: `Not found: ${method} ${path}` } }; * }); * ``` */ listen?: { handle: (pathPrefix: string, handler: (method: string, path: string, body: unknown, headers?: Record) => Promise<{ status: number; body?: unknown; headers?: Record; }>) => void; setDefault: (handler: (method: string, path: string, body: unknown, headers?: Record) => Promise<{ status: number; body?: unknown; headers?: Record; }>) => void; }; /** * Stark API — programmatic API for orchestrator operations. * Available in browser runtimes when the pack runs inside a pod. * Provides access to auth, packs, pods, services, volumes, etc. * * @example * ```typescript * // List all packs * const packs = await context.starkAPI.pack.list(); * * // Create a pod * const pod = await context.starkAPI.pod.create('my-pack'); * * // Download a volume * const data = await context.starkAPI.volume.download('my-vol', 'my-node'); * ``` */ starkAPI?: unknown; } /** * Pack execution result. * Shared between Node.js and Browser runtimes. */ interface PackExecutionResult { /** Execution ID */ executionId: string; /** Pod ID */ podId: string; /** Whether execution succeeded */ success: boolean; /** Return value from the pack */ returnValue?: unknown; /** Error message if failed */ error?: string; /** Error stack trace if failed */ errorStack?: string; /** Execution duration in milliseconds */ durationMs: number; /** Memory usage in bytes (if available) */ memoryUsage?: number; /** Exit code (0 for success) */ exitCode: number; } /** * Running execution handle. * Shared between Node.js and Browser runtimes. */ interface ExecutionHandle { /** Execution ID */ executionId: string; /** Pod ID */ podId: string; /** Promise resolving to execution result */ promise: Promise; /** Cancel the execution (cooperative - task may continue until it checks for cancellation) */ cancel: () => void; /** * Gracefully stop the execution - invokes shutdown handlers, waits for graceful timeout, * then force terminates. Allows pack code to clean up before termination. */ gracefulStop?: (reason?: string) => Promise; /** Force terminate the worker executing this task (immediate termination) */ forceTerminate: () => Promise; /** Check if cancelled */ isCancelled: () => boolean; /** Execution start time */ startedAt: Date; } /** * Pod handler configuration shared between runtimes */ interface BasePodHandlerConfig { /** Callback when pod status changes */ onStatusChange?: (podId: string, status: LocalPodStatus, message?: string) => void; } /** * Interface for pack executor (implemented by both Node.js and Browser runtimes) */ interface IPackExecutor { /** Initialize the executor */ initialize(): Promise; /** Check if initialized */ isInitialized(): boolean; /** Execute a pack for a pod */ execute(pack: { id: string; name: string; version: string; runtimeTag: RuntimeTag; bundlePath: string; bundleContent?: string; metadata?: Record; }, pod: { id: string; namespace: string; labels?: Labels; annotations?: Annotations; resourceRequests?: ResourceRequirements; resourceLimits?: ResourceRequirements; }, options?: { env?: Record; timeout?: number; args?: unknown[]; }): ExecutionHandle; /** Shutdown the executor */ shutdown(): Promise; } /** * Map local pod status to orchestrator pod status string */ declare function mapLocalStatusToPodStatus(status: LocalPodStatus): string; /** * Event types for Stark Orchestrator * Events are first-class data for debugging, UI timelines, and audits. * @module @stark-o/shared/types/events */ /** * High-level event categories for filtering */ type EventCategory = 'pod' | 'node' | 'pack' | 'service' | 'system' | 'auth' | 'scheduler'; /** * Event severity levels */ type EventSeverity = 'info' | 'warning' | 'error' | 'critical'; /** * All pod event types */ type PodEventType = 'PodCreated' | 'PodScheduled' | 'PodScheduleFailed' | 'PodStarting' | 'PodStarted' | 'PodRunning' | 'PodStopped' | 'PodFailed' | 'PodRestarted' | 'PodRolledBack' | 'PodEvicted' | 'PodScaled' | 'PodUpdated' | 'PodDeleted' | 'PodStatusChanged'; /** * All node event types */ type NodeEventType = 'NodeRegistered' | 'NodeReady' | 'NodeSuspect' | 'NodeLost' | 'NodeRecovered' | 'NodeDraining' | 'NodeDrained' | 'NodeCordoned' | 'NodeUncordoned' | 'NodeDeleted' | 'NodeStatusChanged' | 'NodeResourcePressure'; /** * All pack event types */ type PackEventType = 'PackPublished' | 'PackUpdated' | 'PackDeleted' | 'PackVersionPublished' | 'PackVersionDeprecated'; /** * All service event types */ type ServiceEventType = 'ServiceCreated' | 'ServiceScaled' | 'ServiceRollingUpdate' | 'ServiceRollback' | 'ServicePaused' | 'ServiceResumed' | 'ServiceCompleted' | 'ServiceFailed' | 'ServiceDeleted'; /** * All system event types */ type SystemEventType = 'ClusterStarted' | 'ClusterStopped' | 'ConfigChanged' | 'SchedulerStarted' | 'SchedulerStopped' | 'GarbageCollectionRun'; /** * All authentication event types */ type AuthEventType = 'UserLoggedIn' | 'UserLoggedOut' | 'TokenRefreshed' | 'PermissionDenied'; /** * All scheduler event types */ type SchedulerEventType = 'SchedulingCycleStarted' | 'SchedulingCycleCompleted' | 'NoNodesAvailable' | 'PreemptionTriggered'; /** * All event types in the system */ type StarkEventType = PodEventType | NodeEventType | PackEventType | ServiceEventType | SystemEventType | AuthEventType | SchedulerEventType; /** * Who or what caused the event */ type EventActorType = 'user' | 'system' | 'scheduler' | 'node'; /** * Where the event originated */ type EventSource = 'server' | 'node' | 'client' | 'cli' | 'scheduler'; /** * Base event metadata */ interface EventMetadata { /** Event source */ source?: EventSource; /** Request correlation ID for tracing */ correlationId?: string; /** Acting user ID */ userId?: string; /** Additional custom metadata */ [key: string]: unknown; } /** * Base Stark event structure */ interface StarkEvent { /** Unique event identifier */ id: string; /** Specific event type */ eventType: StarkEventType; /** High-level category */ category: EventCategory; /** Severity level */ severity: EventSeverity; /** Primary resource ID */ resourceId?: string; /** Resource type (pod, node, pack, etc.) */ resourceType?: string; /** Human-readable resource name */ resourceName?: string; /** Namespace context */ namespace?: string; /** Actor who caused the event */ actorId?: string; /** Actor type */ actorType: EventActorType; /** Short reason code */ reason?: string; /** Human-readable message */ message?: string; /** Previous state snapshot */ previousState?: T; /** New state snapshot */ newState?: T; /** Related resource ID */ relatedResourceId?: string; /** Related resource type */ relatedResourceType?: string; /** Related resource name */ relatedResourceName?: string; /** Additional metadata */ metadata: Record; /** Event source */ source: EventSource; /** Correlation ID for tracing */ correlationId?: string; /** When the event occurred */ timestamp: Date; } /** * Pod state for event tracking */ interface PodEventState { status?: string; version?: string; nodeId?: string; nodeName?: string; } /** * Pod event with typed state */ type PodEvent = StarkEvent & { category: 'pod'; eventType: PodEventType; resourceType: 'pod'; }; /** * Node state for event tracking */ interface NodeEventState { status?: string; runtimeType?: string; runningPods?: number; } /** * Node event with typed state */ type NodeEvent = StarkEvent & { category: 'node'; eventType: NodeEventType; resourceType: 'node'; }; /** * Pack state for event tracking */ interface PackEventState { version?: string; visibility?: string; } /** * Pack event with typed state */ type PackEvent = StarkEvent & { category: 'pack'; eventType: PackEventType; resourceType: 'pack'; }; /** * Service state for event tracking */ interface ServiceEventState { replicas?: number; readyReplicas?: number; version?: string; status?: string; } /** * Service event with typed state */ type ServiceEvent = StarkEvent & { category: 'service'; eventType: ServiceEventType; resourceType: 'service'; }; /** * Input for creating a pod event */ interface EmitPodEventInput { eventType: PodEventType; podId: string; podName?: string; namespace?: string; severity?: EventSeverity; actorId?: string; reason?: string; message?: string; previousStatus?: string; newStatus?: string; nodeId?: string; nodeName?: string; metadata?: Record; correlationId?: string; } /** * Input for creating a node event */ interface EmitNodeEventInput { eventType: NodeEventType; nodeId: string; nodeName?: string; severity?: EventSeverity; actorId?: string; reason?: string; message?: string; previousStatus?: string; newStatus?: string; metadata?: Record; correlationId?: string; } /** * Input for creating a generic event */ interface EmitEventInput { eventType: StarkEventType; category: EventCategory; resourceId?: string; resourceType?: string; resourceName?: string; namespace?: string; severity?: EventSeverity; actorId?: string; actorType?: EventActorType; reason?: string; message?: string; previousState?: Record; newState?: Record; relatedResourceId?: string; relatedResourceType?: string; relatedResourceName?: string; metadata?: Record; source?: EventSource; correlationId?: string; } /** * Options for querying events */ interface EventQueryOptions { /** Filter by category */ category?: EventCategory; /** Filter by event type */ eventType?: StarkEventType; /** Filter by resource type */ resourceType?: string; /** Filter by resource ID */ resourceId?: string; /** Filter by namespace */ namespace?: string; /** Filter by severity */ severity?: EventSeverity | EventSeverity[]; /** Events after this time */ since?: Date; /** Events before this time */ until?: Date; /** Maximum number of results */ limit?: number; /** Offset for pagination */ offset?: number; /** Order direction */ order?: 'asc' | 'desc'; } /** * Paginated event result */ interface EventQueryResult { events: StarkEvent[]; total: number; hasMore: boolean; } /** * Event timeline item (simplified for UI display) */ interface EventTimelineItem { id: string; eventType: StarkEventType; category: EventCategory; severity: EventSeverity; resourceType?: string; resourceName?: string; reason?: string; message?: string; timestamp: Date; } /** * Event subscription filter */ interface EventSubscriptionFilter { /** Filter by categories */ categories?: EventCategory[]; /** Filter by event types */ eventTypes?: StarkEventType[]; /** Filter by resource types */ resourceTypes?: string[]; /** Filter by namespace */ namespace?: string; /** Filter by minimum severity */ minSeverity?: EventSeverity; } /** * Event callback for subscriptions */ type EventCallback = (event: StarkEvent) => void; /** * Common pod event reasons */ declare const PodEventReasons: { readonly Scheduled: "Scheduled"; readonly ScheduleFailed: "ScheduleFailed"; readonly NoNodesAvailable: "NoNodesAvailable"; readonly AffinityNotSatisfied: "AffinityNotSatisfied"; readonly InsufficientResources: "InsufficientResources"; readonly TaintNotTolerated: "TaintNotTolerated"; readonly Created: "Created"; readonly Started: "Started"; readonly Stopped: "Stopped"; readonly Deleted: "Deleted"; readonly Failed: "Failed"; readonly OOMKilled: "OOMKilled"; readonly CrashLoopBackOff: "CrashLoopBackOff"; readonly ImagePullError: "ImagePullError"; readonly StartupFailed: "StartupFailed"; readonly Evicted: "Evicted"; readonly NodeDrain: "NodeDrain"; readonly ResourcePressure: "ResourcePressure"; readonly Preempted: "Preempted"; readonly RolledBack: "RolledBack"; readonly Restarted: "Restarted"; readonly Scaled: "Scaled"; }; /** * Common node event reasons */ declare const NodeEventReasons: { readonly Registered: "Registered"; readonly RegistrationFailed: "RegistrationFailed"; readonly HeartbeatTimeout: "HeartbeatTimeout"; readonly HeartbeatRestored: "HeartbeatRestored"; readonly HealthCheckFailed: "HealthCheckFailed"; readonly Ready: "Ready"; readonly NotReady: "NotReady"; readonly Cordoned: "Cordoned"; readonly Uncordoned: "Uncordoned"; readonly Draining: "Draining"; readonly Drained: "Drained"; readonly DrainFailed: "DrainFailed"; readonly MemoryPressure: "MemoryPressure"; readonly DiskPressure: "DiskPressure"; readonly PodPressure: "PodPressure"; }; /** * Severity levels in order of importance */ declare const SEVERITY_ORDER: Record; /** * Compare severity levels */ declare function compareSeverity(a: EventSeverity, b: EventSeverity): number; /** * Check if severity meets minimum threshold */ declare function meetsMinSeverity(severity: EventSeverity, minSeverity: EventSeverity): boolean; /** * Get default severity for an event type */ declare function getDefaultSeverity(eventType: StarkEventType): EventSeverity; /** * Get category from event type */ declare function getCategoryFromEventType(eventType: StarkEventType): EventCategory; /** * Metrics type definitions * @module @stark-o/shared/types/metrics */ /** * System metrics collected from a node */ interface NodeSystemMetrics { /** Uptime in seconds */ uptimeSeconds: number; /** CPU usage percentage (0-100) */ cpuUsagePercent?: number; /** Memory used in bytes */ memoryUsedBytes?: number; /** Total memory in bytes */ memoryTotalBytes?: number; /** Memory usage percentage (0-100) */ memoryUsagePercent?: number; /** Runtime version (e.g., 'v20.10.0' for Node.js) */ runtimeVersion?: string; } /** * Worker pool statistics (Node.js only) */ interface WorkerPoolStats { /** Total workers in the pool */ totalWorkers: number; /** Workers currently executing */ busyWorkers: number; /** Workers available for work */ idleWorkers: number; /** Tasks waiting in queue */ pendingTasks: number; } /** * Resource allocation metrics */ interface ResourceAllocationMetrics { /** Pods allocated */ podsAllocated: number; /** Pod capacity */ podsCapacity: number; /** CPU allocated (millicores) */ cpuAllocated: number; /** CPU capacity (millicores) */ cpuCapacity: number; /** Memory allocated (bytes) */ memoryAllocatedBytes: number; /** Memory capacity (bytes) */ memoryCapacityBytes: number; } /** * Complete node metrics payload */ interface NodeMetrics { /** Node ID */ nodeId: string; /** Runtime type */ runtimeType: RuntimeType; /** System metrics */ system: NodeSystemMetrics; /** Resource allocation */ resources: ResourceAllocationMetrics; /** Worker pool stats (Node.js only) */ workerPool?: WorkerPoolStats; /** Timestamp when metrics were collected */ timestamp: Date; } /** * Node metrics stored in database */ interface NodeMetricsRecord extends NodeMetrics { /** Record ID */ id: string; /** When the record was created */ recordedAt: Date; createdAt: Date; } /** * Input for creating node metrics */ interface CreateNodeMetricsInput { nodeId: string; runtimeType: RuntimeType; uptimeSeconds: number; cpuUsagePercent?: number; memoryUsedBytes?: number; memoryTotalBytes?: number; memoryUsagePercent?: number; runtimeVersion?: string; podsAllocated: number; podsCapacity: number; cpuAllocated: number; cpuCapacity: number; memoryAllocatedBytes: number; memoryCapacityBytes: number; workerPoolTotal?: number; workerPoolBusy?: number; workerPoolIdle?: number; workerPoolPendingTasks?: number; } /** * Execution statistics for a pod */ interface PodExecutionStats { /** Total execution count */ executionCount: number; /** Successful executions */ successfulExecutions: number; /** Failed executions */ failedExecutions: number; /** Total execution time in ms */ totalExecutionTimeMs: number; /** Average execution time in ms */ avgExecutionTimeMs?: number; /** Last execution timestamp */ lastExecutionAt?: Date; } /** * Complete pod metrics payload */ interface PodMetrics { /** Pod ID */ podId: string; /** Node ID where pod is running */ nodeId?: string; /** Current status */ status: PodStatus; /** Restart count */ restartCount: number; /** Execution statistics */ execution: PodExecutionStats; /** CPU usage (if available) */ cpuUsagePercent?: number; /** Memory used (if available) */ memoryUsedBytes?: number; /** Timestamp */ timestamp: Date; } /** * Pod metrics stored in database */ interface PodMetricsRecord extends PodMetrics { /** Record ID */ id: string; /** When the record was created */ recordedAt: Date; createdAt: Date; } /** * Input for creating pod metrics */ interface CreatePodMetricsInput { podId: string; nodeId?: string; status: PodStatus; restartCount: number; executionCount: number; successfulExecutions: number; failedExecutions: number; totalExecutionTimeMs: number; avgExecutionTimeMs?: number; lastExecutionAt?: Date; cpuUsagePercent?: number; memoryUsedBytes?: number; } /** * Failure reason breakdown */ interface SchedulingFailureReasons { /** No nodes available at all */ noNodesAvailable?: number; /** Insufficient CPU */ insufficientCpu?: number; /** Insufficient memory */ insufficientMemory?: number; /** Insufficient pod capacity */ insufficientPodCapacity?: number; /** Taint/toleration mismatch */ taintMismatch?: number; /** Node selector mismatch */ nodeSelectorMismatch?: number; /** Affinity mismatch */ affinityMismatch?: number; /** Other reasons */ other?: number; /** Custom reasons */ [key: string]: number | undefined; } /** * Scheduling metrics for a time window */ interface SchedulingMetrics { /** Window start time */ windowStart: Date; /** Window end time */ windowEnd: Date; /** Total scheduling attempts */ schedulingAttempts: number; /** Successful schedulings */ schedulingSuccesses: number; /** Failed schedulings */ schedulingFailures: number; /** Failure reasons breakdown */ failureReasons: SchedulingFailureReasons; /** Average scheduling latency in ms */ avgSchedulingLatencyMs?: number; /** Max scheduling latency in ms */ maxSchedulingLatencyMs?: number; /** Min scheduling latency in ms */ minSchedulingLatencyMs?: number; /** Pending pods at window end */ pendingPodsCount: number; } /** * Scheduling metrics stored in database */ interface SchedulingMetricsRecord extends SchedulingMetrics { /** Record ID */ id: string; /** When the record was created */ createdAt: Date; } /** * Node status counts */ interface NodeStatusCounts { total: number; online: number; offline: number; unhealthy: number; draining: number; maintenance: number; } /** * Pod status counts */ interface PodStatusCounts { total: number; pending: number; scheduled: number; starting: number; running: number; stopping: number; stopped: number; failed: number; evicted: number; /** Desired pods from services */ desired: number; } /** * Cluster resource utilization */ interface ClusterResourceUtilization { /** Total CPU capacity (millicores) */ totalCpuCapacity: number; /** Total memory capacity (bytes) */ totalMemoryCapacityBytes: number; /** Total pod capacity */ totalPodsCapacity: number; /** Allocated CPU (millicores) */ totalCpuAllocated: number; /** Allocated memory (bytes) */ totalMemoryAllocatedBytes: number; /** Allocated pods */ totalPodsAllocated: number; /** CPU utilization percentage */ cpuUtilizationPercent: number; /** Memory utilization percentage */ memoryUtilizationPercent: number; /** Pod utilization percentage */ podsUtilizationPercent: number; } /** * Restart statistics */ interface RestartStats { /** Total restarts across all pods */ totalPodRestarts: number; /** Number of pods that have restarted */ podsWithRestarts: number; } /** * Complete cluster metrics */ interface ClusterMetrics { /** Node status counts */ nodes: NodeStatusCounts; /** Pod status counts */ pods: PodStatusCounts; /** Resource utilization */ resources: ClusterResourceUtilization; /** Restart statistics */ restarts: RestartStats; /** Scheduling failures in last hour */ schedulingFailuresLastHour: number; /** Average scheduling latency */ avgSchedulingLatencyMs?: number; /** Timestamp */ timestamp: Date; } /** * Cluster metrics stored in database */ interface ClusterMetricsRecord { /** Record ID */ id: string; /** Node counts */ nodesTotal: number; nodesOnline: number; nodesOffline: number; nodesUnhealthy: number; nodesDraining: number; /** Pod counts */ podsTotal: number; podsPending: number; podsScheduled: number; podsStarting: number; podsRunning: number; podsStopping: number; podsStopped: number; podsFailed: number; podsEvicted: number; podsDesired: number; /** Resource capacity */ totalCpuCapacity: number; totalMemoryCapacityBytes: number; totalPodsCapacity: number; /** Resource allocation */ totalCpuAllocated: number; totalMemoryAllocatedBytes: number; totalPodsAllocated: number; /** Utilization percentages */ cpuUtilizationPercent: number; memoryUtilizationPercent: number; podsUtilizationPercent: number; /** Scheduling health */ schedulingFailuresLastHour: number; avgSchedulingLatencyMs?: number; /** Restart metrics */ totalPodRestarts: number; podsWithRestarts: number; /** Timestamps */ recordedAt: Date; createdAt: Date; } /** * Dashboard metrics summary */ interface MetricsDashboard { /** Latest cluster metrics */ cluster: ClusterMetrics; /** Latest node metrics per node */ nodes: NodeMetricsRecord[]; /** Pods with highest restart counts */ topRestartingPods: Array<{ podId: string; podName?: string; restartCount: number; }>; /** Recent scheduling failures */ recentSchedulingFailures: number; /** Uptime summary */ uptime: { /** Oldest node uptime */ maxNodeUptimeSeconds: number; /** Average node uptime */ avgNodeUptimeSeconds: number; }; } /** * Time range for metrics queries */ interface MetricsTimeRange { /** Start time */ start: Date; /** End time */ end: Date; } /** * Options for metrics queries */ interface MetricsQueryOptions { /** Time range */ timeRange?: MetricsTimeRange; /** Node ID filter */ nodeId?: string; /** Pod ID filter */ podId?: string; /** Maximum number of records */ limit?: number; /** Offset for pagination */ offset?: number; } /** * Base error class with error codes * @module @stark-o/shared/errors/base-error */ /** * Error codes for categorization */ declare enum ErrorCode { UNKNOWN = 1000, INTERNAL = 1001, NOT_IMPLEMENTED = 1002, TIMEOUT = 1003, CANCELLED = 1004, VALIDATION_FAILED = 2000, INVALID_INPUT = 2001, MISSING_REQUIRED_FIELD = 2002, INVALID_FORMAT = 2003, OUT_OF_RANGE = 2004, CONSTRAINT_VIOLATION = 2005, AUTHENTICATION_REQUIRED = 3000, INVALID_CREDENTIALS = 3001, TOKEN_EXPIRED = 3002, TOKEN_INVALID = 3003, SESSION_EXPIRED = 3004, FORBIDDEN = 4000, INSUFFICIENT_PERMISSIONS = 4001, ROLE_REQUIRED = 4002, RESOURCE_ACCESS_DENIED = 4003, NOT_FOUND = 5000, ALREADY_EXISTS = 5001, CONFLICT = 5002, GONE = 5003, RESOURCE_EXHAUSTED = 5004, POD_SCHEDULING_FAILED = 6000, POD_START_FAILED = 6001, POD_EXECUTION_FAILED = 6002, POD_TIMEOUT = 6003, POD_NOT_FOUND = 6004, POD_ALREADY_RUNNING = 6005, POD_EVICTED = 6006, NODE_NOT_FOUND = 7000, NODE_OFFLINE = 7001, NODE_UNHEALTHY = 7002, NODE_CAPACITY_EXCEEDED = 7003, NO_AVAILABLE_NODES = 7004, NODE_REGISTRATION_FAILED = 7005, PACK_NOT_FOUND = 8000, PACK_VERSION_NOT_FOUND = 8001, PACK_ALREADY_EXISTS = 8002, PACK_INVALID_BUNDLE = 8003, PACK_RUNTIME_MISMATCH = 8004, PACK_UPLOAD_FAILED = 8005, NAMESPACE_NOT_FOUND = 9000, NAMESPACE_QUOTA_EXCEEDED = 9001, NAMESPACE_LIMIT_VIOLATION = 9002, NAMESPACE_RESERVED = 9003, NAMESPACE_TERMINATING = 9004, CLUSTER_UNHEALTHY = 10000, CLUSTER_CAPACITY_EXCEEDED = 10001, SCHEDULER_UNAVAILABLE = 10002 } /** * Error metadata for additional context */ interface ErrorMeta { /** Resource type involved */ resourceType?: string; /** Resource ID involved */ resourceId?: string; /** Field that caused the error */ field?: string; /** Additional context */ [key: string]: unknown; } /** * Base error class for all Stark Orchestrator errors */ declare class StarkError extends Error { /** Error code for categorization */ readonly code: ErrorCode; /** HTTP status code equivalent */ readonly statusCode: number; /** Error metadata */ readonly meta: ErrorMeta; /** Timestamp when error occurred */ readonly timestamp: Date; /** Correlation ID for tracing */ correlationId?: string; /** Original error if this wraps another */ readonly cause?: Error; constructor(message: string, code?: ErrorCode, meta?: ErrorMeta, cause?: Error); /** * Map error code to HTTP status code */ private getStatusCode; /** * Set correlation ID for tracing */ withCorrelationId(correlationId: string): this; /** * Convert to JSON for API responses */ toJSON(): Record; /** * Convert to log-friendly format */ toLog(): Record; /** * Check if this is a client error (4xx) */ isClientError(): boolean; /** * Check if this is a server error (5xx) */ isServerError(): boolean; /** * Check if this error is retryable */ isRetryable(): boolean; } /** * Check if an error is a StarkError */ declare function isStarkError(error: unknown): error is StarkError; /** * Wrap an unknown error as a StarkError */ declare function wrapError(error: unknown, code?: ErrorCode): StarkError; /** * Validation error class * @module @stark-o/shared/errors/validation-error */ /** * Validation error detail */ interface ValidationErrorDetail { /** Field that failed validation */ field: string; /** Error message */ message: string; /** Validation rule that failed */ rule?: string; /** Expected value/format */ expected?: string; /** Actual value received */ received?: unknown; } /** * Validation error for input validation failures */ declare class ValidationError$1 extends StarkError { /** Validation error details */ readonly details: ValidationErrorDetail[]; constructor(message: string, details?: ValidationErrorDetail[], meta?: ErrorMeta); /** * Create from a single field error */ static field(field: string, message: string, rule?: string): ValidationError$1; /** * Create for a required field */ static required(field: string): ValidationError$1; /** * Create for an invalid format */ static invalidFormat(field: string, expected: string, received?: unknown): ValidationError$1; /** * Create for an out of range value */ static outOfRange(field: string, min?: number, max?: number, received?: number): ValidationError$1; /** * Create from multiple field errors */ static multiple(errors: ValidationErrorDetail[]): ValidationError$1; /** * Create for a constraint violation */ static constraint(message: string, field?: string): ValidationError$1; /** * Override error code */ private withCode; /** * Add a validation error detail */ addDetail(detail: ValidationErrorDetail): this; /** * Check if a specific field has an error */ hasFieldError(field: string): boolean; /** * Get errors for a specific field */ getFieldErrors(field: string): ValidationErrorDetail[]; /** * Convert to JSON for API responses */ toJSON(): Record; } /** * Check if an error is a ValidationError */ declare function isValidationError(error: unknown): error is ValidationError$1; /** * Validation result type */ type ValidationResult$1 = { valid: true; value: T; } | { valid: false; error: ValidationError$1; }; /** * Create a successful validation result */ declare function validResult(value: T): ValidationResult$1; /** * Create a failed validation result */ declare function invalidResult(error: ValidationError$1): ValidationResult$1; /** * Authentication/Authorization error class * @module @stark-o/shared/errors/auth-error */ /** * Authentication error for login/token failures */ declare class AuthenticationError extends StarkError { constructor(message: string, code?: ErrorCode, meta?: ErrorMeta); /** * Create for missing authentication */ static required(): AuthenticationError; /** * Create for invalid credentials */ static invalidCredentials(): AuthenticationError; /** * Create for expired token */ static tokenExpired(): AuthenticationError; /** * Create for invalid token */ static tokenInvalid(reason?: string): AuthenticationError; /** * Create for expired session */ static sessionExpired(): AuthenticationError; } /** * Authorization error for permission failures */ declare class AuthorizationError extends StarkError { /** Required roles for the action */ readonly requiredRoles?: UserRole[]; /** User's actual roles */ readonly userRoles?: UserRole[]; constructor(message: string, code?: ErrorCode, meta?: ErrorMeta, requiredRoles?: UserRole[], userRoles?: UserRole[]); /** * Create for general forbidden access */ static forbidden(resource?: string): AuthorizationError; /** * Create for insufficient permissions */ static insufficientPermissions(action: string, resource?: string): AuthorizationError; /** * Create for missing required role */ static roleRequired(requiredRoles: UserRole[], userRoles?: UserRole[]): AuthorizationError; /** * Create for resource access denied */ static resourceAccessDenied(resourceType: string, resourceId: string, reason?: string): AuthorizationError; /** * Convert to JSON for API responses */ toJSON(): Record; } /** * Check if an error is an AuthenticationError */ declare function isAuthenticationError(error: unknown): error is AuthenticationError; /** * Check if an error is an AuthorizationError */ declare function isAuthorizationError(error: unknown): error is AuthorizationError; /** * Check if an error is any auth-related error */ declare function isAuthError(error: unknown): error is AuthenticationError | AuthorizationError; /** * Pod-specific error class * @module @stark-o/shared/errors/pod-error */ /** * Pod scheduling failure reason */ interface SchedulingFailureReason { /** Reason type */ type: 'no_nodes' | 'no_compatible_nodes' | 'insufficient_resources' | 'taint_not_tolerated' | 'affinity_not_met' | 'quota_exceeded' | 'scheduler_error'; /** Detailed message */ message: string; /** Nodes that were considered */ consideredNodes?: number; /** Nodes that were filtered out */ filteredNodes?: number; } /** * Pod execution failure details */ interface ExecutionFailureDetails { /** Exit code if available */ exitCode?: number; /** Error output */ stderr?: string; /** Execution duration in ms */ durationMs?: number; /** Memory usage at failure */ memoryUsage?: number; } /** * Pod-specific error class */ declare class PodError extends StarkError { /** Pod ID if available */ readonly podId?: string; /** Pack ID if available */ readonly packId?: string; /** Node ID if available */ readonly nodeId?: string; constructor(message: string, code?: ErrorCode, meta?: ErrorMeta, podId?: string, packId?: string, nodeId?: string); /** * Create for scheduling failure */ static schedulingFailed(reason: SchedulingFailureReason, podId?: string, packId?: string): PodError; /** * Create for no available nodes */ static noAvailableNodes(runtimeType?: string, podId?: string): PodError; /** * Create for start failure */ static startFailed(reason: string, podId: string, nodeId?: string): PodError; /** * Create for execution failure */ static executionFailed(reason: string, details: ExecutionFailureDetails, podId: string, nodeId?: string): PodError; /** * Create for timeout */ static timeout(timeoutMs: number, podId: string, nodeId?: string): PodError; /** * Create for pod not found */ static notFound(podId: string): PodError; /** * Create for already running */ static alreadyRunning(podId: string): PodError; /** * Create for eviction */ static evicted(reason: string, podId: string, nodeId?: string): PodError; /** * Create for runtime mismatch */ static runtimeMismatch(packRuntime: string, nodeRuntime: string, podId?: string, packId?: string): PodError; /** * Convert to JSON for API responses */ toJSON(): Record; } /** * Check if an error is a PodError */ declare function isPodError(error: unknown): error is PodError; /** * Create common scheduling failure reasons */ declare const SchedulingFailures: { readonly noNodes: () => SchedulingFailureReason; readonly noCompatibleNodes: (runtime: string, considered: number) => SchedulingFailureReason; readonly insufficientResources: (considered: number, filtered: number) => SchedulingFailureReason; readonly taintNotTolerated: (taintKey: string, considered: number) => SchedulingFailureReason; readonly affinityNotMet: (considered: number) => SchedulingFailureReason; readonly quotaExceeded: (namespace: string) => SchedulingFailureReason; readonly schedulerError: (message: string) => SchedulingFailureReason; }; /** * Pack registration validation * @module @stark-o/shared/validation/pack-validation */ /** * Validation result */ interface ValidationResult { valid: boolean; errors: ValidationError[]; } /** * Single validation error */ interface ValidationError { field: string; message: string; code: string; } /** * Validate pack name */ declare function validatePackName(name: unknown): ValidationError | null; /** * Validate pack version */ declare function validatePackVersion(version: unknown): ValidationError | null; /** * Validate runtime tag */ declare function validateRuntimeTag(runtimeTag: unknown): ValidationError | null; /** * Validate pack description */ declare function validatePackDescription(description: unknown): ValidationError | null; /** * Validate pack metadata */ declare function validatePackMetadata(metadata: unknown): ValidationError | null; /** * Validate minimum Node.js version requirement * Accepts formats: "22", "22.0", "22.0.0", "22.0.0-beta.1" */ declare function validateMinNodeVersion(minNodeVersion: unknown): ValidationError | null; /** * Validate pack registration input */ declare function validateRegisterPackInput(input: unknown): ValidationResult; /** * Validate pack update input */ declare function validateUpdatePackInput(input: unknown): ValidationResult; /** * Node registration validation * @module @stark-o/shared/validation/node-validation */ /** * Validate node name */ declare function validateNodeName(name: unknown): ValidationError | null; /** * Validate runtime type */ declare function validateRuntimeType(runtimeType: unknown): ValidationError | null; /** * Validate node capabilities */ declare function validateNodeCapabilities(capabilities: unknown): ValidationError | null; /** * Validate a single label key-value pair */ declare function validateLabelEntry(key: string, value: string, fieldPrefix: string): ValidationError | null; /** * Validate labels */ declare function validateLabels(labels: unknown, fieldName?: string): ValidationError[]; /** * Validate annotations */ declare function validateAnnotations(annotations: unknown, fieldName?: string): ValidationError[]; /** * Validate a single taint */ declare function validateTaint(taint: unknown, index: number): ValidationError[]; /** * Validate taints array */ declare function validateTaints(taints: unknown): ValidationError[]; /** * Validate allocatable resources */ declare function validateAllocatableResources(resources: unknown): ValidationError[]; /** * Validate node registration input */ declare function validateRegisterNodeInput(input: unknown): ValidationResult; /** * Validate node update input */ declare function validateUpdateNodeInput(input: unknown): ValidationResult; /** * Pod request validation including runtime compatibility * @module @stark-o/shared/validation/pod-validation */ /** * Validate pack ID */ declare function validatePackId(packId: unknown): ValidationError | null; /** * Validate pack version (optional for pod creation) */ declare function validatePodPackVersion(version: unknown): ValidationError | null; /** * Validate namespace */ declare function validateNamespace(namespace: unknown): ValidationError | null; /** * Validate priority class name */ declare function validatePriorityClassName$1(name: unknown): ValidationError | null; /** * Validate a single toleration */ declare function validateToleration(toleration: unknown, index: number): ValidationError[]; /** * Validate tolerations array */ declare function validateTolerations(tolerations: unknown): ValidationError[]; /** * Validate resource requirements */ declare function validateResourceRequirements(resources: unknown, fieldName: string): ValidationError[]; /** * Validate pod metadata */ declare function validatePodMetadata(metadata: unknown): ValidationError | null; /** * Validate pod creation input */ declare function validateCreatePodInput(input: unknown): ValidationResult; /** * Validate pod status */ declare function validatePodStatus(status: unknown): ValidationError | null; /** * Validate pod update input */ declare function validateUpdatePodInput(input: unknown): ValidationResult; /** * Validate that resource requests don't exceed limits */ declare function validateResourceRequestsVsLimits(requests: Partial | undefined, limits: Partial | undefined): ValidationError[]; /** * Namespace creation/update validation (Kubernetes-like) * @module @stark-o/shared/validation/namespace-validation */ /** * Reserved namespace names that cannot be created by users */ declare const RESERVED_NAMESPACE_NAMES: readonly ["default", "stark-system", "stark-public"]; /** * Validate namespace name */ declare function validateNamespaceName(name: unknown): ValidationError | null; /** * Check if namespace name is reserved */ declare function isReservedNamespaceName(name: string): boolean; /** * Validate resource quota hard limits */ declare function validateResourceQuotaHard(hard: unknown, fieldPrefix?: string): ValidationError[]; /** * Validate resource quota */ declare function validateResourceQuota(quota: unknown): ValidationError[]; /** * Validate resource limit value (cpu/memory) */ declare function validateResourceLimitValue(value: unknown, fieldName: string): ValidationError[]; /** * Validate limit range */ declare function validateLimitRange(limitRange: unknown): ValidationError[]; /** * Validate namespace creation input */ declare function validateCreateNamespaceInput(input: unknown): ValidationResult; /** * Validate namespace update input */ declare function validateUpdateNamespaceInput(input: unknown): ValidationResult; /** * Validate that pod resources fit within namespace limits */ declare function validatePodFitsNamespaceLimits(podCpu: number, podMemory: number, limitRange: LimitRange | undefined): ValidationError[]; /** * Cluster configuration validation (Kubernetes-like) * @module @stark-o/shared/validation/cluster-validation */ /** * Validate scheduling policy */ declare function validateSchedulingPolicy(policy: unknown): ValidationError | null; /** * Validate default resources */ declare function validateDefaultResources(resources: unknown, fieldName: string): ValidationError[]; /** * Validate positive integer */ declare function validatePositiveInteger(value: unknown, fieldName: string): ValidationError | null; /** * Validate non-negative integer */ declare function validateNonNegativeInteger(value: unknown, fieldName: string): ValidationError | null; /** * Validate boolean */ declare function validateBoolean(value: unknown, fieldName: string): ValidationError | null; /** * Validate cluster config update input */ declare function validateUpdateClusterConfigInput(input: unknown): ValidationResult; /** * Validate priority class name */ declare function validatePriorityClassName(name: unknown): ValidationError | null; /** * Validate priority value */ declare function validatePriorityValue(value: unknown): ValidationError | null; /** * Validate preemption policy */ declare function validatePreemptionPolicy(policy: unknown): ValidationError | null; /** * Validate priority class creation input */ declare function validateCreatePriorityClassInput(input: unknown): ValidationResult; /** * Scheduling config, affinity, and toleration validation (Kubernetes-like) * @module @stark-o/shared/validation/scheduling-validation */ /** * Validate node selector requirement */ declare function validateNodeSelectorRequirement(req: unknown, fieldPrefix: string): ValidationError[]; /** * Validate node selector term */ declare function validateNodeSelectorTerm(term: unknown, fieldPrefix: string): ValidationError[]; /** * Validate preferred scheduling term */ declare function validatePreferredSchedulingTerm(term: unknown, fieldPrefix: string): ValidationError[]; /** * Validate node affinity */ declare function validateNodeAffinity(affinity: unknown): ValidationError[]; /** * Validate label selector */ declare function validateLabelSelector(selector: unknown, fieldPrefix: string): ValidationError[]; /** * Validate pod affinity term */ declare function validatePodAffinityTerm(term: unknown, fieldPrefix: string): ValidationError[]; /** * Validate weighted pod affinity term */ declare function validateWeightedPodAffinityTerm(term: unknown, fieldPrefix: string): ValidationError[]; /** * Validate pod affinity */ declare function validatePodAffinity(affinity: unknown): ValidationError[]; /** * Validate pod anti-affinity */ declare function validatePodAntiAffinity(affinity: unknown): ValidationError[]; /** * Validate scheduling configuration */ declare function validateSchedulingConfig(config: unknown): ValidationResult; /** * Service validation * @module @stark-o/shared/validation/service-validation */ /** * Validate service name */ declare function validateServiceName(name: unknown): ValidationError | null; /** * Validate pack ID for service (can be ID or name) */ declare function validateServicePackId(packId: unknown): ValidationError | null; /** * Validate pack name for service */ declare function validateServicePackName(packName: unknown): ValidationError | null; /** * Validate replicas count */ declare function validateReplicas(replicas: unknown): ValidationError | null; /** * Validate namespace */ declare function validateServiceNamespace(namespace: unknown): ValidationError | null; /** * Validate service status */ declare function validateServiceStatus(status: unknown): ValidationError | null; /** * Validate service metadata */ declare function validateServiceMetadata(metadata: unknown): ValidationError | null; /** * Validate ingress port */ declare function validateIngressPort(ingressPort: unknown): ValidationError | null; /** * Validate create service input */ declare function validateCreateServiceInput(input: unknown): ValidationResult; /** * Validate update service input */ declare function validateUpdateServiceInput(input: unknown): ValidationResult; /** * Volume validation * @module @stark-o/shared/validation/volume-validation */ /** * Validate volume name */ declare function validateVolumeName(name: unknown): ValidationError | null; /** * Validate a single volume mount */ declare function validateVolumeMount(mount: unknown, index: number): ValidationError[]; /** * Validate volume mounts array */ declare function validateVolumeMounts(mounts: unknown): ValidationError[]; /** * Validate create volume input */ declare function validateCreateVolumeInput(input: unknown): ValidationResult; /** * Secret validation * * Validates secret creation and update inputs following the same * patterns as other Stark validators (pack, pod, service, etc.). * * @module @stark-o/shared/validation/secret-validation */ /** * Validate secret name */ declare function validateSecretName(name: unknown): ValidationError | null; /** * Validate secret type */ declare function validateSecretType(type: unknown): ValidationError | null; /** * Validate secret data (plaintext key-value pairs) */ declare function validateSecretData(data: unknown, type?: SecretType): ValidationError[]; /** * Validate injection configuration */ declare function validateSecretInjection(injection: unknown): ValidationError[]; /** * Validate secret namespace */ declare function validateSecretNamespace(namespace: unknown): ValidationError | null; /** * Validate a CreateSecretInput */ declare function validateCreateSecretInput(input: unknown): ValidationResult; /** * Validate an UpdateSecretInput */ declare function validateUpdateSecretInput(input: unknown, existingType?: SecretType): ValidationResult; /** * Validate that volume mount paths don't conflict across multiple secrets. * Returns conflicting secret name pairs if any overlap is detected. */ declare function validateMountPathConflicts(secrets: Array<{ name: string; injection: { mode: string; mountPath?: string; }; }>): ValidationError[]; /** * Structured JSON logger with correlation IDs * @module @stark-o/shared/logging/logger */ /** * Log levels */ type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'fatal'; /** * Log entry metadata */ interface LogMeta { /** Correlation ID for request tracing */ correlationId?: string; /** Request ID */ requestId?: string; /** User ID */ userId?: string; /** Service name */ service?: string; /** Component name */ component?: string; /** Additional context */ [key: string]: unknown; } /** * Structured log entry */ interface LogEntry { /** ISO timestamp */ timestamp: string; /** Log level */ level: LogLevel; /** Log message */ message: string; /** Metadata */ meta?: LogMeta; /** Error details */ error?: { name: string; message: string; stack?: string; code?: string | number; }; } /** * Logger configuration */ interface LoggerConfig { /** Minimum log level */ level: LogLevel; /** Service name */ service?: string; /** Component name */ component?: string; /** Pretty print output (development) */ pretty?: boolean; /** Enable timestamps */ timestamps?: boolean; /** Custom output function */ output?: (entry: LogEntry) => void; } /** * Structured JSON logger */ declare class Logger { private config; private meta; constructor(config?: Partial, meta?: LogMeta); /** * Check if a log level is enabled */ private isLevelEnabled; /** * Format and output a log entry */ private log; /** * Default output to console */ private defaultOutput; /** * Format log entry for pretty printing */ private formatPretty; /** * Create a child logger with additional metadata */ child(meta: LogMeta): Logger; /** * Create a child logger with a correlation ID */ withCorrelationId(correlationId: string): Logger; /** * Create a child logger with a request ID */ withRequestId(requestId: string): Logger; /** * Create a child logger with a user ID */ withUserId(userId: string): Logger; /** * Log a debug message */ debug(message: string, meta?: LogMeta): void; /** * Log an info message */ info(message: string, meta?: LogMeta): void; /** * Log a warning message */ warn(message: string, meta?: LogMeta): void; /** * Log an error message */ error(message: string, error?: Error | LogMeta, meta?: LogMeta): void; /** * Log a fatal error message */ fatal(message: string, error?: Error | LogMeta, meta?: LogMeta): void; } /** * Check if running in test environment */ declare function isTestEnvironment(): boolean; /** * Create a new logger instance (basic, does not apply test environment detection) */ declare function createLogger(config?: Partial, meta?: LogMeta): Logger; /** * Create a logger instance with test environment detection * Automatically suppresses output during tests unless LOG_LEVEL is explicitly set */ declare function createServiceLogger(config?: Partial, meta?: LogMeta): Logger; /** * Default logger instance */ declare const logger: Logger; /** * Generate a correlation ID */ declare function generateCorrelationId(): string; /** * Pod Log Sink * @module @stark-o/shared/logging/pod-log-sink * * Routes stdout/stderr from pod execution to console with pod metadata. * This is a kernel-level abstraction - no files, rotation, retention, streaming, * querying, UI, or persistence. Those are policy concerns. */ /** * Stream type for distinguishing stdout vs stderr */ type LogStream = 'out' | 'err'; /** * Pod metadata for log sink */ interface PodLogSinkMeta { podId: string; packId: string; packVersion: string; executionId: string; } /** * PodLogSink routes stdout/stderr from a pod to console with metadata prefix. * * Must be closed when the pod exits or is killed to release resources * and allow cleanup. */ declare class PodLogSink { private readonly meta; private closed; constructor(meta: PodLogSinkMeta); /** * Get the pod ID */ get podId(): string; /** * Check if the sink is closed */ get isClosed(): boolean; /** * Write to stdout stream */ stdout(message: string): void; /** * Write to stderr stream */ stderr(message: string): void; /** * Internal write method */ private write; /** * Close the sink. Must be called when the pod exits or is killed. * After close, all writes are silently dropped. */ close(): void; } /** * Create a PodLogSink for a pod execution */ declare function createPodLogSink(meta: PodLogSinkMeta): PodLogSink; /** * Console-like interface that can be injected into pack execution context. * Routes console methods through the PodLogSink. */ interface PodConsole { log: (...args: unknown[]) => void; info: (...args: unknown[]) => void; warn: (...args: unknown[]) => void; error: (...args: unknown[]) => void; debug: (...args: unknown[]) => void; } /** * Format arguments for logging (exported for reuse in serializable contexts). * Converts unknown values to strings suitable for log output. */ declare function formatLogArgs(args: unknown[]): string; /** * Create a console-like object that routes through a PodLogSink. * Useful for injecting into sandboxed pack execution. */ declare function createPodConsole(sink: PodLogSink): PodConsole; /** * Returns JavaScript code that patches console methods to route through pod logging. * * This is designed for use in serialized worker functions where we can't import modules. * The code is self-contained and can be executed via eval() or new Function(). * * Usage in worker: * const patchCode = getPodConsolePatchCode(podId); * eval(patchCode); // patches console.log, console.error, etc. * * @param podId - The pod ID to include in log prefixes * @returns JavaScript code string that patches console methods */ declare function getPodConsolePatchCode(podId: string): string; /** * Service Registry * * Orchestrator-side registry mapping serviceId → pods. * Isomorphic: can also be used on pods for local cache of registry state. * * @module @stark-o/shared/network/service-registry */ /** * In-memory service registry. */ declare class ServiceRegistry { private registry; /** * Register a pod for a service. * If the pod already exists, updates it. */ register(serviceId: string, podId: string, nodeId: string, status?: RegistryPodStatus): void; /** * Unregister a pod from a service. */ unregister(serviceId: string, podId: string): boolean; /** * Remove a pod from all services (e.g. when pod dies). */ unregisterPod(podId: string): void; /** * Remove all pods belonging to a specific node. * Used when a node reconnects to clear stale pod entries. */ unregisterPodsOnNode(nodeId: string): string[]; /** * Update a pod's status. */ updatePodStatus(serviceId: string, podId: string, status: RegistryPodStatus): void; /** * Get all healthy pods for a service. */ getHealthyPods(serviceId: string): ServiceRegistryEntry[]; /** * Get all pods for a service (any status). */ getAllPods(serviceId: string): ServiceRegistryEntry[]; /** * Select a single pod for a service using round-robin-like selection. * Picks a random healthy pod (simple load balancing). */ selectPod(serviceId: string, excludePodId?: string): ServiceRegistryEntry | null; /** * Check if a specific pod is healthy. */ isPodHealthy(serviceId: string, podId: string): boolean; /** * Get all registered services. */ listServices(): string[]; /** * Mark pods as unhealthy if they haven't sent a heartbeat within the given threshold. */ markStale(heartbeatThresholdMs: number): string[]; /** * Get full registry snapshot (for API/debugging). */ snapshot(): Record; /** * Clear the entire registry. */ clear(): void; /** * Number of services in the registry. */ get serviceCount(): number; /** * Total number of pod entries across all services. */ get podCount(): number; } declare function getServiceRegistry(): ServiceRegistry; /** * Pod Target Cache * * Per-pod local cache of target pods for services the pod communicates with. * Sticky sessions by default: the same target pod is reused until TTL expires * or the pod becomes unavailable. * * @module @stark-o/shared/network/pod-cache */ /** * Local cache of target pods per service. * Lives on each calling pod. */ declare class PodTargetCache { /** serviceId → CachedTargetPod */ private cache; private defaultTtl; constructor(defaultTtl?: number); /** * Get a cached target pod for a service. * Returns null if not cached, expired, or unhealthy. */ get(serviceId: string): CachedTargetPod | null; /** * Set a cached target pod for a service (sticky). */ set(serviceId: string, podId: string, nodeId: string, ttl?: number): CachedTargetPod; /** * Mark a cached pod as unhealthy (triggers re-routing on next call). */ markUnhealthy(serviceId: string): void; /** * Invalidate (remove) the cached pod for a service. */ invalidate(serviceId: string): void; /** * Invalidate all entries pointing to a specific pod * (e.g. when a pod is known to have died). */ invalidatePod(podId: string): void; /** * Clear the entire cache. */ clear(): void; /** * Get all cached entries (for debugging). */ entries(): CachedTargetPod[]; /** * Number of cached entries. */ get size(): number; } /** * WebRTC Connection Manager * * Manages persistent WebRTC peer connections between pods. * Isomorphic: works in both Node.js (via simple-peer) and browser. * * Transport is kept separate from routing logic: * - This module only manages connections (open, close, send, receive). * - Routing decisions are made by the ServiceCaller / orchestrator. * * @module @stark-o/shared/network/webrtc-manager */ /** * Thin wrapper around a single WebRTC peer connection to a target pod. */ interface PeerConnection { targetPodId: string; state: PeerConnectionState; createdAt: number; lastActivity: number; /** Send a serialised message over the data channel. */ send(data: string): void; /** Close the connection and clean up. */ close(): void; } /** * Callback to deliver a signalling message to the remote pod * (typically relayed via the orchestrator's WebSocket). */ type SignalSender = (message: SignallingMessage) => void; /** * Callback invoked when a message is received from a peer. */ type MessageHandler = (fromPodId: string, data: string) => void; /** * Manages all WebRTC connections for a single pod. * * Usage: * ```ts * const mgr = new WebRTCConnectionManager({ * localPodId: 'pod-1', * signalSender: (msg) => ws.send(JSON.stringify(msg)), * onMessage: (from, data) => handleIncoming(from, data), * peerFactory: (initiator) => new SimplePeer({ initiator }), * }); * * // To connect to a target pod (initiator side): * await mgr.connect('pod-2'); * * // To send data: * mgr.send('pod-2', JSON.stringify(request)); * * // When a signalling message arrives from the WebSocket: * mgr.handleSignal(signallingMessage); * ``` */ declare class WebRTCConnectionManager { private localPodId; private connections; private signalSender; private onMessage; private peerFactory; private config; private pendingConnections; /** Optional callback invoked when a peer-gone notification is received. */ private onPeerGone?; constructor(opts: { localPodId: string; signalSender: SignalSender; onMessage: MessageHandler; /** Factory to create a simple-peer instance. Keeps this module peer-library agnostic. */ peerFactory: PeerFactory; config?: WebRTCConfig; /** Called when a remote peer is reported dead by the orchestrator. */ onPeerGone?: (deadPodId: string) => void; }); /** * Open a connection to a target pod (initiator side). * If a healthy connection already exists, returns it immediately. * Retries up to {@link MAX_CONNECT_RETRIES} times with a short delay on timeout. */ connect(targetPodId: string): Promise; /** * Send data to a connected peer. * Throws if no connection exists or the connection is not open. */ send(targetPodId: string, data: string): void; /** * Handle an incoming signalling message from the WebSocket relay. * If no connection exists for the source pod, creates one (responder side). */ handleSignal(message: SignallingMessage): void; /** * Handle a `network:peer-gone` notification from the orchestrator. * Tears down the PeerConnection for the dead pod and invokes the optional * callback so higher layers (e.g. ServiceCaller) can invalidate caches. */ handlePeerGone(deadPodId: string): void; /** * Check if a connection to a target pod is healthy. */ isConnected(targetPodId: string): boolean; /** * Get the connection state for a target pod. */ getState(targetPodId: string): PeerConnectionState; /** * Close a specific peer connection. */ disconnect(targetPodId: string): void; /** * Close all peer connections. */ disconnectAll(): void; /** * Get all active connections. */ listConnections(): Array<{ targetPodId: string; state: PeerConnectionState; lastActivity: number; }>; /** * Number of active (connected) peers. */ get activeCount(): number; private createPeer; private destroyPeer; } /** * A SimplePeer-like interface. We don't import simple-peer directly * so this module stays dependency-free and isomorphic. */ interface SimplePeerLike { signal(data: unknown): void; send(data: string | Uint8Array): void; destroy(): void; on(event: 'signal', cb: (data: unknown) => void): void; on(event: 'connect', cb: () => void): void; on(event: 'data', cb: (data: Uint8Array | string) => void): void; on(event: 'error', cb: (err: Error) => void): void; on(event: 'close', cb: () => void): void; on(event: string, cb: (...args: unknown[]) => void): void; } /** * Factory function to create a SimplePeer-like instance. * Implementations differ between Node.js (simple-peer with wrtc) and browser (simple-peer native). */ type PeerFactory = (initiator: boolean, config: Required) => SimplePeerLike; /** * Service Caller * * Pod-side wrapper for making inter-service calls. * Implements the full routing flow: * 1. Parse virtual URL → serviceId + path * 2. Check network policy * 3. Check sticky cache for cached target pod * 4. If cache miss or non-sticky → query orchestrator * 5. Open/reuse WebRTC connection → send request → await response * * Sticky sessions are the **default**. Non-sticky is opt-in per request. * * @module @stark-o/shared/network/service-caller */ /** * Function to request a routing decision from the orchestrator. * Implementations differ per runtime (WS message in Node, postMessage in browser, etc.). */ type OrchestratorRouter = (request: RoutingRequest) => Promise; interface ServiceCallerConfig { /** This pod's ID */ podId: string; /** This pod's service ID */ serviceId: string; /** WebRTC connection manager for sending/receiving */ connectionManager: WebRTCConnectionManager; /** Function to ask the orchestrator for a target pod */ orchestratorRouter: OrchestratorRouter; /** Network policy engine (optional — if omitted, all traffic is allowed) */ policyEngine?: NetworkPolicyEngine; /** Pod target cache (optional — a default one is created) */ cache?: PodTargetCache; /** Default TTL for cached targets in ms */ cacheTtl?: number; /** Default request timeout in ms */ defaultTimeout?: number; } declare class ServiceCaller { private podId; private serviceId; private connMgr; private router; private policy; private cache; private defaultTimeout; /** Pending responses keyed by requestId */ private pending; private requestCounter; constructor(config: ServiceCallerConfig); /** * Make a service call using a virtual internal URL. * * @example * ```ts * const res = await caller.call('http://users-service.internal/api/users/123'); * const res = await caller.call('http://auth.internal/validate', { method: 'POST', body: { token } }); * // Non-sticky (fresh pod selection): * const res = await caller.call('http://workers.internal/process', { nonSticky: true }); * ``` */ call(url: string, options?: ServiceCallOptions): Promise; /** * Handle an incoming response message from a peer. * Called by the WebRTC connection manager's onMessage callback. */ handleResponse(data: string): boolean; /** * Notify that a pod has become unavailable (e.g. pod churn). * Invalidates cache entries and closes the connection. */ notifyPodDead(podId: string): void; /** * Get the underlying cache (for inspection/testing). */ getCache(): PodTargetCache; private routeViaOrchestrator; private nextRequestId; } declare class NetworkPolicyError extends Error { readonly sourceService: string; readonly targetService: string; constructor(sourceService: string, targetService: string, reason?: string); } /** * Orchestrator Routing * * Server-side handler for pod routing requests. * When a pod has a cache miss (or non-sticky request), it asks the * orchestrator to select a target pod for the requested service. * * The orchestrator: * 1. Checks network policies (if any are configured). * 2. Selects a healthy pod from the service registry. * 3. Returns the selected pod's ID and node ID to the caller. * * The orchestrator **never proxies traffic**. It only assists with routing. * * @module @stark-o/shared/network/orchestrator-router */ interface OrchestratorRouterConfig { /** The service registry (maps serviceId → pods) */ registry: ServiceRegistry; /** The network policy engine (allow/deny rules) */ policyEngine?: NetworkPolicyEngine; /** * Lookup function for service network metadata (visibility/exposed/allowedSources). * Used for visibility-based policy evaluation. */ networkMetaLookup?: ServiceNetworkMetaLookup; } /** * Handle a routing request from a caller pod. * * Policy evaluation order: * 1. Visibility-based check (public allows all; private/system checks allowedSources) * 2. Policy engine check (explicit allow/deny rules supplement visibility) * * For private/system services, traffic is allowed if the caller is in * allowedSources OR has an explicit allow policy. Both systems are part * of the same unified access-control model. * * @returns A RoutingResponse with the selected target pod, * or a denied response if a network policy blocks it. * @throws If no healthy pods are available for the target service. */ declare function handleRoutingRequest(request: RoutingRequest, config: OrchestratorRouterConfig): RoutingResponse; /** * Service Request Handler (pod-side) * * Handles incoming ServiceRequests on the target pod. * This is a minimal router that dispatches the request to registered handlers. */ type RequestHandler = (method: string, path: string, body: unknown, headers?: Record) => Promise<{ status: number; body?: unknown; headers?: Record; }>; /** * Create a request handler registry for a pod. * Pods register handlers for paths, and incoming ServiceRequests are dispatched. */ declare class PodRequestRouter { private handlers; private defaultHandler; /** * Register a handler for a specific path prefix. */ handle(pathPrefix: string, handler: RequestHandler): void; /** * Set a default handler for unmatched paths. */ setDefault(handler: RequestHandler): void; /** * Dispatch an incoming request to the appropriate handler. */ dispatch(method: string, path: string, body: unknown, headers?: Record): Promise<{ status: number; body?: unknown; headers?: Record; }>; } /** * HTTP Interceptor for Transparent Inter-Service Communication * * Monkey-patches `globalThis.fetch` and provides Axios interceptor adapters * so that pods can use any HTTP client/library to make service calls to * `*.internal` URLs without needing explicit `context.serviceCall()`. * * Outgoing requests to `http://{serviceId}.internal/{path}` are transparently * routed through the Stark networking layer (ServiceCaller → WebRTC). * * Works in both Node.js and browser environments (isomorphic). * * @module @stark-o/shared/network/http-interceptor */ /** * Check if a URL targets a Stark internal service. */ declare function isInternalUrl(url: string): boolean; /** * Monkey-patch `globalThis.fetch` to intercept `*.internal` URLs. * Non-internal URLs pass through to the original fetch unchanged. * * @example * ```ts * interceptFetch(serviceCaller); * * // This now routes transparently through Stark: * const res = await fetch('http://users-service.internal/api/users'); * const data = await res.json(); * * // This still goes to the real internet: * const ext = await fetch('https://api.example.com/data'); * ``` */ declare function interceptFetch(serviceCaller: ServiceCaller): void; /** * Restore the original `globalThis.fetch` function. */ declare function restoreFetch(): void; /** * Create an Axios request interceptor configuration that transparently routes * `*.internal` URLs through the Stark ServiceCaller. * * Usage with a per-pod Axios instance: * ```ts * import axios from 'axios'; * const interceptor = createAxiosStarkInterceptor(serviceCaller); * axios.interceptors.request.use(interceptor.requestInterceptor); * ``` * * Usage with the global Axios instance (patches all requests): * ```ts * installAxiosInterceptor(axios, serviceCaller); * ``` * * After installation, any Axios request to `*.internal` is routed through Stark: * ```ts * const res = await axios.post('http://echo.internal/echo', { hello: 'world' }); * // Transparently goes through WebRTC pod-to-pod communication * ``` */ declare function createAxiosStarkInterceptor(serviceCaller: ServiceCaller): { /** * Axios request interceptor. Detects `.internal` URLs and short-circuits * the request by overriding the adapter to return the ServiceCaller response. */ requestInterceptor: (config: Record) => Promise>; }; /** * Install the Stark interceptor on an Axios instance. * Returns the interceptor ID so it can be removed later. * * @example * ```ts * import axios from 'axios'; * const id = installAxiosInterceptor(axios, serviceCaller); * // Later: * axios.interceptors.request.eject(id); * ``` */ declare function installAxiosInterceptor(axiosInstance: { interceptors: { request: { use: (fn: Function) => number; }; }; }, serviceCaller: ServiceCaller): number; interface InterceptorHandles { /** Restore fetch to its original implementation */ restoreFetch: () => void; /** Axios interceptor ID (if installed) — eject with `axios.interceptors.request.eject(id)` */ axiosInterceptorId?: number; } /** * Install all outbound HTTP interceptors for a pod. * Patches `globalThis.fetch` and optionally installs an Axios interceptor. * * @param serviceCaller - The pod's ServiceCaller instance * @param axiosInstance - Optional Axios instance to patch * @returns Handles for tearing down interceptors */ declare function installOutboundInterceptors(serviceCaller: ServiceCaller, axiosInstance?: { interceptors: { request: { use: (fn: Function) => number; }; }; }): InterceptorHandles; /** * Node.js Server Interceptor for Inbound Inter-Service Communication * * Patches Node.js `http.createServer` / `http.Server` so that when a pack * starts an HTTP server (Express, Fastify, Koa, plain http, etc.), incoming * WebRTC ServiceRequests are automatically forwarded to it by emitting * synthetic 'request' events directly on the server. * * This makes `context.router.handle()` unnecessary in Node.js — * packs can use any HTTP framework and Stark will route traffic to them. * * If no HTTP server is captured (e.g. the pack doesn't start one), * falls back to the PodRequestRouter for handler-based dispatch. * * @module @stark-o/shared/network/server-interceptor */ /** * Minimal interface for the Node.js `http` module. * We accept it as a parameter to avoid importing `http` directly * (keeping this module importable in browser bundles that never call `install()`). */ interface HttpModuleLike { createServer: (...args: unknown[]) => HttpServerLike; request: (options: Record, cb: (res: IncomingMessageLike) => void) => WritableLike; Server?: { prototype: Record; }; } interface HttpServerLike { listen: (...args: unknown[]) => HttpServerLike; address: () => { port: number; address: string; family: string; } | string | null; on: (event: string, listener: (...args: unknown[]) => void) => HttpServerLike; once: (event: string, listener: (...args: unknown[]) => void) => HttpServerLike; emit: (event: string, ...args: unknown[]) => boolean; } interface IncomingMessageLike { statusCode?: number; headers: Record; on: (event: string, cb: (...args: unknown[]) => void) => void; } interface WritableLike { write: (data: string | Buffer) => boolean; end: (data?: string | Buffer) => void; on: (event: string, cb: (...args: unknown[]) => void) => void; } /** * StarkServerInterceptor * * Captures HTTP servers created by pack code and forwards incoming * WebRTC ServiceRequests to them as real HTTP loopback requests. * * Usage (in the runtime, before pack code runs): * ```ts * import http from 'http'; * const interceptor = new StarkServerInterceptor(podRequestRouter); * interceptor.install(http); * * // ... pack code runs, creates Express/Fastify/etc. server ... * * // When a ServiceRequest arrives via WebRTC: * const response = await interceptor.dispatch(serviceRequest, http); * * // Cleanup: * interceptor.uninstall(http); * ``` */ declare class StarkServerInterceptor { /** Captured servers: port → server instance */ private capturedServers; /** All captured servers (for immediate use before port is known) */ private allServers; /** Server that had listen() called (primary target for synthetic requests) */ private primaryServer; /** Fallback router for when no HTTP server is available */ private router; /** Original createServer function for http module */ private _originalHttpCreateServer; /** Original createServer function for https module */ private _originalHttpsCreateServer; constructor(router: PodRequestRouter); /** * Create a wrapped createServer function that captures servers. */ private wrapCreateServer; /** * Patch `http.createServer` and `server.listen` to capture HTTP servers * started by pack code. Call this BEFORE the pack code runs. */ install(httpModule: HttpModuleLike): void; /** * Patch `https.createServer` to capture HTTPS servers. * Call this in addition to install() if you want to capture HTTPS servers. */ installHttps(httpsModule: HttpModuleLike): void; /** * Restore the original `http.createServer` function. */ uninstall(httpModule: HttpModuleLike): void; /** * Restore the original `https.createServer` function. */ uninstallHttps(httpsModule: HttpModuleLike): void; /** * Check if any HTTP servers have been captured. */ get hasCapturedServers(): boolean; /** * Get the port of the first captured server (for debugging). */ get capturedPort(): number | null; /** * Dispatch a ServiceRequest to the pack's HTTP server. * * - If a primary server is available, emits a synthetic 'request' event directly. * - Otherwise falls back to the PodRequestRouter. * * @param request - The incoming ServiceRequest from WebRTC * @param _httpModule - Unused (kept for API compatibility) */ dispatch(request: ServiceRequest, _httpModule?: HttpModuleLike): Promise; private dispatchToRouter; /** * Emit a synthetic 'request' event on the server with mock req/res objects. * This works because Node.js HTTP servers (and frameworks like Express) * listen for 'request' events and handle them via their request listeners. */ private forwardViaSyntheticEvent; } /** * Browser Listener for Inbound Inter-Service Communication * * In browser environments (Web Workers), there is no `http.createServer`. * Packs must explicitly register request handlers using this listener. * * This is the **one exception** to Stark's transparent HTTP interception: * browser packs need a special listen/handle function for inbound traffic. * * Wraps PodRequestRouter with a friendlier API. * * @module @stark-o/shared/network/browser-listener */ /** * StarkBrowserListener * * Provides an explicit handler registration API for browser-based packs. * * @example * ```ts * // In a browser pack: * module.exports.default = async function(context) { * // context.listen is a StarkBrowserListener * * context.listen.handle('/greet', async (method, path, body) => { * return { status: 200, body: { message: 'Hello!' } }; * }); * * context.listen.handle('/echo', async (method, path, body) => { * return { status: 200, body: { echo: body } }; * }); * * context.listen.setDefault(async (method, path) => { * return { status: 404, body: { error: `Not found: ${method} ${path}` } }; * }); * }; * ``` */ declare class StarkBrowserListener { private router; constructor(router?: PodRequestRouter); /** * Register a handler for a specific path prefix. * * @param pathPrefix - Path prefix to match (e.g. '/api/users') * @param handler - Handler function: (method, path, body, headers?) => { status, body?, headers? } */ handle(pathPrefix: string, handler: RequestHandler): void; /** * Set a default handler for paths that don't match any registered prefix. */ setDefault(handler: RequestHandler): void; /** * Dispatch an incoming ServiceRequest to the registered handlers. * Called by the browser runtime when a WebRTC request arrives. */ dispatch(request: ServiceRequest): Promise; /** * Get the underlying PodRequestRouter (for advanced use or testing). */ getRouter(): PodRequestRouter; } /** * Default PeerFactory implementation using `simple-peer`. * * Isomorphic — works in both Node.js and browsers. * In Node.js, pass the `@roamhq/wrtc` package to enable WebRTC support. * In browsers, native WebRTC APIs are used automatically. * * @module @stark-o/shared/network/peer-factory */ /** * Options for createSimplePeerFactory. */ interface SimplePeerFactoryOptions { /** * The wrtc module for Node.js environments. * Required in Node.js; not needed in browsers. * Install with: npm install @roamhq/wrtc */ wrtc?: any; } /** * Create a PeerFactory backed by `simple-peer`. * * Usage (Browser): * ```ts * const factory = createSimplePeerFactory(); * ``` * * Usage (Node.js): * ```ts * import wrtc from '@roamhq/wrtc'; * const factory = createSimplePeerFactory({ wrtc }); * ``` */ declare function createSimplePeerFactory(options?: SimplePeerFactoryOptions): PeerFactory; /** * Pure utility functions (uuid generation, date formatting) * @module @stark-o/shared/utils */ /** * Generate a UUID v4 * Uses crypto.randomUUID if available, otherwise fallback to manual generation */ declare function generateUUID(): string; /** * Check if a string is a valid UUID */ declare function isValidUUID(value: string): boolean; /** * Format a date to ISO string */ declare function formatISODate(date: Date): string; /** * Format a date to a human-readable string */ declare function formatDate(date: Date, options?: Intl.DateTimeFormatOptions): string; /** * Format a relative time (e.g., "5 minutes ago") */ declare function formatRelativeTime(date: Date, baseDate?: Date): string; /** * Parse an ISO date string to a Date object */ declare function parseISODate(isoString: string): Date; /** * Get current timestamp in ISO format */ declare function nowISO(): string; /** * Get current timestamp as Date */ declare function now(): Date; /** * Sleep for a specified duration */ declare function sleep(ms: number): Promise; /** * Retry a function with exponential backoff */ declare function retry(fn: () => Promise, options?: { maxRetries?: number; initialDelayMs?: number; maxDelayMs?: number; backoffFactor?: number; }): Promise; /** * Deep clone an object */ declare function deepClone(obj: T): T; /** * Deep merge two objects */ declare function deepMerge>(target: T, source: Partial): T; /** * Pick specified keys from an object */ declare function pick, K extends keyof T>(obj: T, keys: K[]): Pick; /** * Omit specified keys from an object */ declare function omit, K extends keyof T>(obj: T, keys: K[]): Omit; /** * Check if two objects are deeply equal */ declare function deepEqual(a: unknown, b: unknown): boolean; /** * Debounce a function */ declare function debounce unknown>(fn: T, delayMs: number): (...args: Parameters) => void; /** * Throttle a function */ declare function throttle unknown>(fn: T, limitMs: number): (...args: Parameters) => void; /** * Capitalize the first letter of a string */ declare function capitalize(str: string): string; /** * Convert a string to kebab-case */ declare function toKebabCase(str: string): string; /** * Convert a string to camelCase */ declare function toCamelCase(str: string): string; /** * Truncate a string to a maximum length */ declare function truncate(str: string, maxLength: number, suffix?: string): string; /** * Generate a random string of specified length */ declare function randomString(length: number): string; /** * Check if a value is a plain object */ declare function isPlainObject(value: unknown): value is Record; /** * Compact an array (remove null/undefined values) */ declare function compact(arr: (T | null | undefined)[]): T[]; /** * Group an array by a key */ declare function groupBy(arr: T[], keyFn: (item: T) => K): Record; /** * Sort an array by a key (ascending) */ declare function sortBy(arr: T[], keyFn: (item: T) => string | number): T[]; /** * CLI Command Data Types * * Data-driven command definitions that can be consumed by * both Node.js CLI (commander) and browser CLI implementations. * @module @stark-o/shared/cli/types */ /** * Describes a single CLI option (flag) */ interface CliOptionDef { /** Short and long flag, e.g. '-n, --name ' */ flags: string; /** Human-readable description */ description: string; /** Default value (if any) */ defaultValue?: string | boolean | number; /** Whether this option is required */ required?: boolean; /** Env variable fallback */ envVar?: string; } /** * Describes a single subcommand */ interface CliSubcommandDef { /** Command name, e.g. 'list' */ name: string; /** Positional argument(s), e.g. '[name]' or '' */ argument?: string; /** Argument description */ argumentDescription?: string; /** Command alias, e.g. 'ls' */ alias?: string; /** Human-readable description */ description: string; /** Options for this subcommand */ options?: CliOptionDef[]; /** API method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' */ apiMethod?: string; /** API path template (may include :params), e.g. '/api/pods' */ apiPath?: string; /** Whether authentication is required */ requiresAuth?: boolean; /** Nested subcommands (e.g., node agent start) */ subcommands?: CliSubcommandDef[]; } /** * Top-level command group definition */ interface CliCommandDef { /** Command name, e.g. 'pack' */ name: string; /** Command alias, e.g. 'ns' for namespace */ alias?: string; /** Human-readable description */ description: string; /** Subcommands */ subcommands: CliSubcommandDef[]; } /** * Complete CLI definition — all command groups */ interface CliDefinition { /** Program name */ name: string; /** Program version */ version: string; /** Program description */ description: string; /** Global options */ globalOptions: CliOptionDef[]; /** Command groups */ commands: CliCommandDef[]; } /** * CLI Command Definitions — Auth * * Data-driven definition for the `auth` command group. * @module @stark-o/shared/cli/commands/auth */ declare const authCommandDef: CliCommandDef; /** * CLI Command Definitions — Pack * * Data-driven definition for the `pack` command group. * @module @stark-o/shared/cli/commands/pack */ declare const packCommandDef: CliCommandDef; /** * CLI Command Definitions — Node * * Data-driven definition for the `node` command group. * @module @stark-o/shared/cli/commands/node */ declare const nodeCommandDef: CliCommandDef; /** * CLI Command Definitions — Pod * * Data-driven definition for the `pod` command group. * @module @stark-o/shared/cli/commands/pod */ declare const podCommandDef: CliCommandDef; /** * CLI Command Definitions — Service * * Data-driven definition for the `service` command group. * @module @stark-o/shared/cli/commands/service */ declare const serviceCommandDef: CliCommandDef; /** * CLI Command Definitions — Namespace * * Data-driven definition for the `namespace` command group. * @module @stark-o/shared/cli/commands/namespace */ declare const namespaceCommandDef: CliCommandDef; /** * CLI Command Definitions — Secret * * Data-driven definition for the `secret` command group. * @module @stark-o/shared/cli/commands/secret */ declare const secretCommandDef: CliCommandDef; /** * CLI Command Definitions — Volume * * Data-driven definition for the `volume` command group. * @module @stark-o/shared/cli/commands/volume */ declare const volumeCommandDef: CliCommandDef; /** * CLI Command Definitions — Chaos * * Data-driven definition for the `chaos` command group. * @module @stark-o/shared/cli/commands/chaos */ declare const chaosCommandDef: CliCommandDef; /** * CLI Command Definitions — Network * * Data-driven definition for the `network` command group. * @module @stark-o/shared/cli/commands/network */ declare const networkCommandDef: CliCommandDef; /** * CLI Command Definitions — Server * * Data-driven definition for the `server` command group. * @module @stark-o/shared/cli/commands/server */ declare const serverCommandDef: CliCommandDef; /** * CLI Command Definitions — Server Config * * Data-driven definition for the `server-config` command group. * @module @stark-o/shared/cli/commands/server-config */ declare const serverConfigCommandDef: CliCommandDef; /** * Complete Stark CLI Definition * * Assembles all command definitions into a single CLI definition * that can be used to build both Node.js and browser CLIs. * @module @stark-o/shared/cli/definition */ /** * Complete CLI definition for the Stark Orchestrator */ declare const starkCliDefinition: CliDefinition; /** * Portable Stark API * * Runtime-agnostic programmatic API for orchestrator operations. * Works in Node.js, browsers, and Web Workers — uses only `fetch` * (no localStorage, no JSZip). * * Browser-specific features (volume zip operations) are NOT included here; * they live in `@stark-o/browser-runtime/api`. * * @module @stark-o/shared/api/stark-api */ /** * Minimal config needed to create a StarkAPI in any runtime environment. */ interface StarkAPIConfig { /** Base HTTP URL of the orchestrator (e.g. https://localhost:443) */ apiUrl?: string; /** Bearer token for authenticated requests */ accessToken?: string; } /** * Standard Stark API interface. * Available to packs via `context.starkAPI`. */ interface StarkAPI { auth: { login(email: string, password: string): Promise<{ user: { id: string; email: string; }; accessToken: string; }>; logout(): void; whoami(): { email: string; userId: string; } | null; isAuthenticated(): boolean; status(): { authenticated: boolean; email?: string; expiresAt?: string; }; /** Update the in-memory access token (called by runtime on auth:token-refreshed) */ updateAccessToken(token: string): void; setup(email: string, password: string, displayName?: string): Promise<{ user: { id: string; email: string; }; accessToken: string; }>; setupStatus(): Promise<{ needsSetup: boolean; }>; addUser(email: string, password: string, options?: { displayName?: string; roles?: string[]; }): Promise<{ user: { id: string; email: string; roles?: string[]; }; }>; listUsers(): Promise; }; pack: { list(): Promise; versions(name: string): Promise; info(name: string): Promise; delete(name: string): Promise; }; node: { list(): Promise; status(nameOrId: string): Promise; }; pod: { list(options?: { namespace?: string; status?: string; }): Promise; status(podId: string): Promise; create(packName: string, options?: { namespace?: string; packVersion?: string; nodeId?: string; }): Promise; stop(podId: string): Promise; rollback(podId: string): Promise; history(podId: string): Promise; }; service: { list(options?: { namespace?: string; }): Promise; status(name: string): Promise; create(packName: string, options?: { namespace?: string; replicas?: number; visibility?: string; }): Promise; }; namespace: { list(): Promise; get(name: string): Promise; create(name: string): Promise; delete(name: string): Promise; current(): string; use(name: string): void; }; secret: { list(options?: { namespace?: string; }): Promise; get(name: string, namespace?: string): Promise; }; volume: { list(options?: { nodeNameOrId?: string; }): Promise; create(name: string, nodeNameOrId: string): Promise; download(name: string, nodeNameOrId: string): Promise<{ files: Array<{ path: string; data: string; }>; }>; }; chaos: { status(): Promise; enable(): Promise; disable(): Promise; scenarios(): Promise; connections(): Promise; nodes(): Promise; events(): Promise; reset(): Promise; }; network: { policies(): Promise; registry(): Promise; }; serverConfig: { get(): Promise; }; } /** * Creates a portable StarkAPI instance. * * Unlike the browser-runtime's version, this does NOT use localStorage. * Auth tokens and API URL must be provided explicitly (or derived from * the global `__STARK_CONTEXT__`). * * @param config - API URL and/or access token * @returns StarkAPI object suitable for `context.starkAPI` */ declare function createStarkAPI(config?: StarkAPIConfig): StarkAPI; export { ALL_CAPABILITIES, ALL_NAMESPACE_PHASES, ALL_NODE_STATUSES, ALL_POD_ACTIONS, ALL_POD_STATUSES, ALL_ROLES, ALL_RUNTIME_TAGS, ALL_RUNTIME_TYPES, ALL_SCHEDULING_POLICIES, ALL_TAINT_EFFECTS, ALL_TERMINATION_REASONS, ALL_TOLERATION_OPERATORS, APPLICATION_TERMINATION_REASONS, type AgentEvent, type AgentEventHandler, type AllocatableResources, type Annotations, type AppConfig, type AuthEventType, AuthenticationError, AuthorizationError, BUILTIN_PRIORITY_CLASSES, type BaseAgentEvent, type BasePodHandlerConfig, type CachedTargetPod, type Capability, type CapabilityGrantContext, type CapabilityGrantResult, type CliCommandDef, type CliDefinition, type CliOptionDef, type CliSubcommandDef, type ClusterConfig, type ClusterHealth, type ClusterHealthStatus, type ClusterMetrics, type ClusterMetricsRecord, type ClusterResourceUtilization, type ClusterStats, CommonTaints, CommonTolerations, type ConnectionState, type CreateNamespaceInput, type CreateNetworkPolicyInput, type CreateNodeMetricsInput, type CreatePodInput, type CreatePodMetricsInput, type CreatePriorityClassInput, type CreateSecretInput, type CreateServiceInput, type CreateUserInput, type CreateVolumeInput, DEFAULT_ALLOCATABLE, DEFAULT_ALLOCATED, DEFAULT_APP_CONFIG, DEFAULT_CACHE_TTL, DEFAULT_CAPABILITIES, DEFAULT_CLUSTER_CONFIG, DEFAULT_CONNECTION_TIMEOUT, DEFAULT_EPHEMERAL_QUERY_TIMEOUT, DEFAULT_MEMBERSHIP_TTL, DEFAULT_REAP_INTERVAL, DEFAULT_RESOURCE_LIMITS, DEFAULT_RESOURCE_REQUESTS, DEFAULT_RESOURCE_USAGE, DEFAULT_SERVICE_CALL_TIMEOUT, DEFAULT_SERVICE_RESOURCE_LIMITS, DEFAULT_SERVICE_RESOURCE_REQUESTS, DOCKER_REGISTRY_REQUIRED_KEYS, type DefaultResources, type DirectoryEntry, type EmitEventInput, type EmitNodeEventInput, type EmitPodEventInput, type EphemeralAuditHook, EphemeralDataPlane, type EphemeralDataPlaneConfig, type EphemeralDataPlaneOptions, type EphemeralEvent, type EphemeralEventType, type EphemeralQuery, type EphemeralQueryHandler, type EphemeralQueryResult, type EphemeralResponse, type EphemeralTransport, ErrorCode, type ErrorMeta, type EventActorType, type EventCallback, type EventCategory, type EventMetadata, type EventQueryOptions, type EventQueryResult, type EventSeverity, type EventSource, type EventSubscriptionFilter, type EventTimelineItem, type ExecutionFailureDetails, type ExecutionHandle, type FileStats, type GroupTransport, type HttpAdapterConfig, HttpAdapterError, type HttpAdapterErrorOptions, type HttpMethod, type HttpModuleLike, type HttpRequestOptions, type HttpResponse, type HttpServerLike, type IHttpAdapter, INFRASTRUCTURE_TERMINATION_REASONS, INTERNAL_URL_SUFFIX, type IPackExecutor, type IStorageAdapter, type ISyncStorageAdapter, type IWorkerAdapter, type InterceptorHandles, type LabelSelector, type LabelSelectorMatchExpression, type LabelSelectorOperator, type Labels, type LimitRange, type LocalPodStatus, type LogEntry, type LogLevel, type LogMeta, type LogStream, Logger, type LoggerConfig, MAX_SECRET_DATA_SIZE, MAX_SECRET_KEYS, MAX_SECRET_NAME_LENGTH, type MessageHandler, type MetricsDashboard, type MetricsQueryOptions, type MetricsTimeRange, type Namespace, type NamespaceListItem, type NamespacePhase, type NetworkEventType, type NetworkPolicy, type NetworkPolicyAction, NetworkPolicyEngine, NetworkPolicyError, type Node, type NodeAffinity, type NodeCapabilities, type NodeEvent, NodeEventReasons, type NodeEventState, type NodeEventType, type NodeHeartbeat, type NodeListItem, type NodeMetrics, type NodeMetricsRecord, type NodeSelectorRequirement, type NodeSelectorTerm, type NodeStatus, type NodeStatusCounts, type NodeSystemMetrics, OPERATOR_TERMINATION_REASONS, type OrchestratorRouter, type OrchestratorRouterConfig, type Pack, type PackDataMessage, type PackEvent, type PackEventState, type PackEventType, type PackExecutionContext, type PackExecutionResult, type PackListItem, type PackMessageHandler, type PackMetadata, type PackNamespace, type PackVersionSummary, type PackVisibility, type PeerConnection, type PeerConnectionState, type PeerFactory, type Pod, type PodAction, type PodAffinity, type PodAffinityTerm, type PodAgentEvent, type PodAntiAffinity, type PodConsole, type PodDeployPayload, PodError, type PodEvent, PodEventReasons, type PodEventState, type PodEventType, type PodExecutionStats, type PodGroup, PodGroupHandle, type PodGroupHandleOptions, type PodGroupMembership, type PodGroupPlaneRef, PodGroupStore, type PodHistoryEntry, type PodLifecycleFacts, type PodLifecyclePhase, type PodListItem, PodLogSink, type PodLogSinkMeta, type PodMetrics, type PodMetricsRecord, type PodOperationResult, PodRequestRouter, type PodSchedulingConfig, type PodSecretPayload, type PodStatus, type PodStatusCounts, type PodStopPayload, PodTargetCache, type PodTerminationReason, type PolicyEvaluationRequest, type PolicyEvaluationResult, type PoolStats, type PreferredSchedulingTerm, type PriorityClass, RESERVED_NAMESPACES, RESERVED_NAMESPACE_NAMES, type RTCIceServerInit, type RegisterNodeInput, type RegisterPackInput, type RegistryPodStatus, type RequestHandler, type ResolvedSecretMaterial, type ResourceAllocationMetrics, type ResourceLimitValue, type ResourceQuota, type ResourceQuotaHard, type ResourceRequirements, type ResourceUsage, type RestartStats, type RoutingRequest, type RoutingResponse, type RuntimeTag, type RuntimeType, SECRET_NAME_PATTERN, SEVERITY_ORDER, SYSTEM_ONLY_CAPABILITIES, type SchedulerEventType, type SchedulingConfig, type SchedulingFailureReason, type SchedulingFailureReasons, SchedulingFailures, type SchedulingMetrics, type SchedulingMetricsRecord, type SchedulingPolicy, type Secret, type SecretEnvBundle, type SecretEnvInjection, type SecretInjection, type SecretInjectionMode, type SecretListItem, type SecretType, type SecretVolumeInjection, type SecretVolumeMount, type SemVer, type Service, type ServiceCallOptions, ServiceCaller, type ServiceCallerConfig, type ServiceEvent, type ServiceEventState, type ServiceEventType, type ServiceListItem, type ServiceNetworkMeta, type ServiceNetworkMetaLookup, ServiceNetworkMetaStore, ServiceRegistry, type ServiceRegistryEntry, type ServiceRequest, type ServiceResponse, type ServiceStatus, type ServiceVisibility, type ShutdownHandler, type SignalSender, type SignallingMessage, type SignallingMessageType, type SimplePeerFactoryOptions, type SimplePeerLike, type StarkAPI, type StarkAPIConfig, StarkBrowserListener, StarkError, type StarkEvent, type StarkEventType, StarkServerInterceptor, type StorageAdapterConfig, type SystemEventType, TLS_REQUIRED_KEYS, type Taint, type TaintEffect, TaskCancelledError, type TaskHandle, type TaskOptions, type TaskResult, TaskTimeoutError, type Toleration, type TolerationOperator, type TransferableObject, UI_PACK_CAPABILITIES, type UpdateAppConfigInput, type UpdateClusterConfigInput, type UpdateNamespaceInput, type UpdateNodeInput, type UpdatePackInput, type UpdatePodInput, type UpdateSecretInput, type UpdateServiceInput, type UpdateUserInput, type User, type UserRole, type UserSession, VALID_INJECTION_MODES, VALID_SECRET_TYPES, VALID_SERVICE_VISIBILITY_VALUES, ValidationError$1 as ValidationError, type ValidationErrorDetail, type ValidationResult$1 as ValidationResult, type Volume, type VolumeDownloadRequest, type VolumeDownloadResponse, type VolumeFileEntry, type VolumeListItem, type VolumeMount, type WebRTCConfig, WebRTCConnectionManager, type WeightedPodAffinityTerm, type WorkerAdapterConfig, WorkerNotInitializedError, type WorkerPoolStats, WorkerScriptRequiredError, type WsMessage, applyLimitRangeDefaults, authCommandDef, calculateAffinityScore, canManageResources, canRunSystemPacks, capitalize, chaosCommandDef, compact, compareSemVer, compareSeverity, createAxiosStarkInterceptor, createEphemeralDataPlane, createLogger, createPodConsole, createPodLogSink, createStarkAPI as createPortableStarkAPI, createSelector, createServiceLogger, createSimplePeerFactory, debounce, deepClone, deepEqual, deepMerge, effectiveCapabilities, evaluateNetworkPolicy, formatDate, formatISODate, formatLogArgs, formatRelativeTime, generateCorrelationId, generateUUID, getAvailableResources, getCategoryFromEventType, getClusterHealthStatus, getDefaultSeverity, getEvictionTaints, getNetworkPolicyEngine, getPodConsolePatchCode, getPodGroupStore, getRemainingQuota, getRequiredKeysForType, getResourceUtilization, getServiceNetworkMetaStore, getServiceRegistry, getUntoleratedPreferNoScheduleTaints, grantCapabilities, groupBy, handleRoutingRequest, hasAllCapabilities, hasAllRoles, hasAnyCapability, hasAnyRole, hasAvailableResources, hasCapability, hasQuotaAvailable, hasRole, installAxiosInterceptor, installOutboundInterceptors, interceptFetch, invalidResult, isAuthError, isAuthenticationError, isAuthorizationError, isInternalUrl, isNodeAgent, isNodeSchedulable, isNodeVersionCompatible, isPlainObject, isPodActive, isPodError, isPodRunning, isPodSchedulable, isPodTerminated, isReservedNamespace, isReservedNamespaceName, isRuntimeCompatible, isServiceActive, isServiceCallAllowed, isServiceDaemonSet, isServiceReady, isStarkError, isTestEnvironment, isValidCapability, isValidLabelKey, isValidLabelValue, isValidUUID, isValidationError, logger, mapLocalStatusToPodStatus, matchesExpression, matchesLabels, matchesNodeSelectorTerm, matchesRequirement, matchesSelector, meetsMinSeverity, mergeLabels, namespaceCommandDef, networkCommandDef, nodeCommandDef, now, nowISO, omit, packCommandDef, parseISODate, parseInternalUrl, parseSemVer, pick, podCommandDef, randomString, requiresMainThread, requiresSystemNamespace, resetPodGroupStore, restoreFetch, retry, secretCommandDef, serverCommandDef, serverConfigCommandDef, serviceCommandDef, shouldCountTowardCrashLoop, sleep, sortBy, starkCliDefinition, throttle, toCamelCase, toKebabCase, toleratesBlockingTaints, toleratesTaints, tolerationMatchesTaint, truncate, validResult, validateAgainstLimitRange, validateAllocatableResources, validateAnnotations, validateBoolean, validateCapabilities, validateSchedulingPolicy as validateClusterSchedulingPolicyInput, validateCreateNamespaceInput, validateCreatePodInput, validateCreatePriorityClassInput, validateCreateSecretInput, validateCreateServiceInput, validateCreateVolumeInput, validateDefaultResources, validateIngressPort, validateLabelEntry, validateLabelSelector, validateLabels$1 as validateLabels, validateLimitRange, validateMinNodeVersion, validateMountPathConflicts, validateNamespace, validateNamespaceName, validateNodeAffinity as validateNodeAffinityInput, validateNodeCapabilities, validateLabels as validateNodeLabels, validateNodeName, validateNodeSelectorRequirement, validateNodeSelectorTerm, validateNonNegativeInteger, validatePackDescription, validatePackId, validatePackMetadata, validatePackName, validatePackVersion, validatePodAffinity as validatePodAffinityInput, validatePodAffinityTerm, validatePodAntiAffinity, validatePodFitsNamespaceLimits, validatePodMetadata, validatePodPackVersion, validatePodStatus, validatePositiveInteger, validatePreemptionPolicy, validatePreferredSchedulingTerm, validatePriorityClassName$1 as validatePriorityClassName, validatePriorityClassName as validatePriorityClassNameForClass, validatePriorityValue, validateRegisterNodeInput, validateRegisterPackInput, validateReplicas, validateResourceLimitValue, validateResourceQuota, validateResourceQuotaHard, validateResourceRequestsVsLimits, validateResourceRequirements, validateRuntimeTag, validateRuntimeType, validateSchedulingConfig, validateSecretData, validateSecretInjection, validateSecretName, validateSecretNamespace, validateSecretType, validateServiceMetadata, validateServiceName, validateServiceNamespace, validateServicePackId, validateServicePackName, validateServiceStatus, validateTaint, validateTaints, validateToleration, validateTolerations, validateUpdateClusterConfigInput, validateUpdateNamespaceInput, validateUpdateNodeInput, validateUpdatePackInput, validateUpdatePodInput, validateUpdateSecretInput, validateUpdateServiceInput, validateVolumeMount, validateVolumeMounts, validateVolumeName, validateWeightedPodAffinityTerm, volumeCommandDef, wrapError };