import { IScopedLogger, ModelDownloadOptions, ModelDownloadResult, IAddonModelManager, ModelCatalogEntry, ModelFormat, IPythonEnvironment, PythonProbeResult, PythonEnvReady, PipelineConfig, ValidationResult, FrameInput, PipelineResult, AudioChunkInput, PipelineNode, ElementState as ElementState$1, LoggerFactory, ProcessConfig, ManagedProcessStatus, INetworkQualityTracker, ClientNetworkStats, DeviceNetworkStats, ReplResult, AgentInfo, AgentEntry, AgentStatus, AgentTask, TaskDispatchOptions, AgentTaskResult, LogEntry, LogFilter, AgentRegistrationInfo, AgentToHubMessage, HubToAgentMessage, AgentRuntimeStatus, ITaskHandler, TaskContext, IEventBus, FeatureManifest, FeatureFlag, SystemEvent, EventFilter, IStorageProvider as IStorageProvider$1, ISettingsBackend, TokenScope, ScopedToken, TokenPayload, UserRole, UserRecord, INotificationOutput, Notification, Toast, IAddonRouteProvider, IAddonHttpRoute, PlatformCapabilities, HardwareInfo, PlatformScore, ModelRequirement, ResolvedInferenceConfig, ProviderListItem } from '@camstack/types';
export { AgentEntry, AgentInfo, AgentResources, AgentStatus, AgentTask, AgentTaskResult, BackupManifest, ClientNetworkStats, DeviceNetworkStats, EventFilter, EventSource, FeatureFlag, FeatureManifest, INetworkQualityTracker, IScopedLogger, LogEntry, LogFilter, LogLevel, ManagedProcessStatus, ProcessConfig, ProcessStats, ProviderListItem, ReplResult, StreamNetworkStats, SystemEvent, TaskDispatchOptions, TokenPayload, UserRecord, UserRole, ValidationIssue, ValidationResult } from '@camstack/types';
import { ChildProcess } from 'node:child_process';
import { AddonLoader, AddonEngineManager, CapabilityRegistry } from '@camstack/kernel';
export { A as AddonTableSchema, C as CORE_TABLE_DDL, F as FileSystemStorage, S as SettingsStore, a as SqliteStorageAddon, b as SqliteStorageProvider, c as addonTableToDdl } from './sql-schema-CKz78rId.js';
export { WinstonDestination, WinstonLoggingAddon } from './builtins/winston-logging/index.js';
export { BackupConfig, LocalBackupAddon, LocalBackupService } from './builtins/local-backup/index.js';

interface PlatformInfo {
    readonly platform: NodeJS.Platform;
    readonly arch: NodeJS.Architecture;
}
declare function getPlatformInfo(): PlatformInfo;
declare function buildBinaryPath(dataDir: string, name: string, platform?: string): string;
/** Check if a binary exists in PATH */
declare function findInPath(name: string): string | null;
interface DownloadOptions {
    readonly name: string;
    readonly url: string;
    readonly targetDir: string;
    readonly targetName: string;
    readonly logger: IScopedLogger;
    readonly isArchive?: boolean;
    readonly archiveFormat?: 'zip' | 'tar.gz' | 'tar.xz';
    /** Relative path within archive to the binary (e.g., 'ffmpeg-6.1/bin/ffmpeg') */
    readonly archiveInnerPath?: string;
}
/**
 * Download a binary to the target directory.
 * Handles archives (zip, tar.gz, tar.xz) and raw binaries.
 */
declare function downloadBinary(opts: DownloadOptions): Promise<string>;
/**
 * Ensure a binary is available. Checks:
 * 1. Target path (already downloaded)
 * 2. System PATH
 * 3. Download from URL
 */
declare function ensureBinary(opts: {
    readonly name: string;
    readonly targetDir: string;
    readonly downloadUrl: string;
    readonly logger: IScopedLogger;
    readonly isArchive?: boolean;
    readonly archiveFormat?: 'zip' | 'tar.gz' | 'tar.xz';
    readonly archiveInnerPath?: string;
}): Promise<string>;

declare function getFfmpegDownloadUrl(platform: string, arch: string): string;
/**
 * Ensure ffmpeg binary is available.
 * Checks: deps dir → system PATH → download.
 */
declare function ensureFfmpeg(dataDir: string, logger: IScopedLogger): Promise<string>;

declare const PYTHON_VERSION = "3.12.12";
declare function getPythonDownloadUrl(platform: string, arch: string): string;
/**
 * Ensure a portable Python is available.
 * Checks: embedded python → system PATH → download portable.
 *
 * Returns the path to the python3 binary.
 */
declare function ensurePython(dataDir: string, logger: IScopedLogger): Promise<string | null>;
/**
 * Install Python packages into the portable Python environment.
 */
declare function installPythonPackages(pythonPath: string, packages: readonly string[], logger: IScopedLogger): Promise<void>;

type EventCallback<T = unknown> = (data: T) => void;
declare class EventBus {
    private listeners;
    on<T = unknown>(event: string, callback: EventCallback<T>): () => void;
    emit<T = unknown>(event: string, data: T): void;
    once<T = unknown>(event: string, callback: EventCallback<T>): () => void;
    removeAllListeners(event?: string): void;
    listenerCount(event: string): number;
}

/**
 * Download a single file from a URL to a destination path.
 * Uses native fetch() (Node 22+) which handles redirects natively.
 * Streams to disk with optional progress callback.
 * Returns the destination path. Skips download if file already exists.
 */
declare function downloadFile(url: string, destPath: string, onProgress?: (downloaded: number, total: number) => void): Promise<string>;
/**
 * Fetch JSON from a URL using native fetch().
 */
declare function fetchJson(url: string): Promise<unknown>;
/**
 * Download a model with fallback URLs and optional SHA256 verification.
 * Legacy API preserved for backward compatibility -- delegates to downloadFile().
 */
declare function downloadModel(options: ModelDownloadOptions): Promise<ModelDownloadResult>;

/**
 * Unified model download service.
 *
 * Handles downloading model files and extra files (labels, dicts) from a
 * catalog of ModelCatalogEntry items. Supports single-file models and
 * directory bundles (e.g., .mlpackage for CoreML).
 *
 * Addons use this via `context.models.ensure(modelId, format)`.
 */
declare class ModelDownloadService implements IAddonModelManager {
    private readonly modelsDir;
    private readonly onProgress?;
    private readonly catalog;
    constructor(modelsDir: string, catalog: readonly ModelCatalogEntry[], onProgress?: ((modelId: string, downloaded: number, total: number) => void) | undefined);
    /**
     * Ensure a model (and its extra files) is downloaded.
     * Returns the local filesystem path to the model file/directory.
     */
    ensure(modelId: string, format?: ModelFormat): Promise<string>;
    /**
     * Ensure extra files for a model are downloaded.
     * Returns the local paths of all extra files.
     */
    ensureExtraFiles(modelId: string): Promise<readonly string[]>;
    /** Absolute path to the shared models directory. */
    getModelsDir(): string;
    /** Check if a model file is already present on disk. */
    isDownloaded(modelId: string, format?: ModelFormat): boolean;
    /**
     * Legacy API: download a model by ID (delegates to ensure with default format).
     * Required by IAddonModelManager interface.
     */
    downloadModel(id: string): Promise<string>;
    /** Get the catalog entry for a model by ID. */
    getEntry(modelId: string): ModelCatalogEntry | undefined;
    private pickDefaultFormat;
    private modelFilePath;
    /**
     * Download a directory bundle (e.g., .mlpackage) from HuggingFace.
     * ATOMIC: downloads to temp dir, renames only on complete success.
     */
    private downloadDirectory;
    /** Recursively list all files in a HuggingFace directory via API. */
    private listHfFiles;
}

declare class PythonEnvManager implements IPythonEnvironment {
    private readonly dataDir;
    private venvPath;
    private cachedProbe;
    constructor(dataDir: string);
    probe(): Promise<PythonProbeResult>;
    ensure(options: {
        packages: readonly string[];
    }): Promise<PythonEnvReady>;
    spawn(script: string, args: readonly string[]): ChildProcess;
}

declare class PipelineValidator {
    private readonly loader;
    constructor(loader: AddonLoader);
    validate(config: PipelineConfig): ValidationResult;
    private validateNode;
}

declare class PipelineRunner {
    private readonly engineManager;
    private readonly addonConfigs;
    constructor(engineManager: AddonEngineManager, addonConfigs: Map<string, Record<string, unknown>>);
    run(frame: FrameInput, config: PipelineConfig): Promise<PipelineResult>;
    /**
     * Run only the audio classification node on an audio chunk.
     * Used by the audio path in DetectionWiringService (separate from video pipeline).
     */
    runAudioNode(chunk: AudioChunkInput, audioNode: PipelineNode): Promise<PipelineResult>;
    private executeNode;
    private executeChildren;
}

type ProcessState = ElementState$1;

/** Event emitter for process lifecycle events */
type ProcessEventEmitter = {
    emitProcessCrashed(processId: string, code: number | null, signal: string | null, restartCount: number): void;
    emitProcessRestartScheduled(processId: string, restartCount: number, delayMs: number): void;
    emitProcessRestarted(processId: string, restartCount: number): void;
};
/** Re-export LoggerFactory as ProcessLoggerFactory for backward compatibility */
type ProcessLoggerFactory = LoggerFactory;

declare class ManagedProcess {
    private readonly config;
    private readonly events;
    private readonly logger;
    private childProcess;
    private _state;
    private _startedAt?;
    private restartTimer?;
    private _restartCount;
    private _lastCrashAt?;
    private _lastCrashError?;
    constructor(config: ProcessConfig, events: ProcessEventEmitter, logger: IScopedLogger);
    get state(): ProcessState;
    start(): Promise<void>;
    stop(): Promise<void>;
    getStatus(): ManagedProcessStatus;
    private scheduleRestart;
    private getStats;
    private getNextRestartTime;
}

declare class ProcessManager {
    private readonly events;
    private readonly loggerFactory;
    private readonly processes;
    constructor(events: ProcessEventEmitter, loggerFactory: ProcessLoggerFactory);
    register(config: ProcessConfig): ManagedProcess;
    start(id: string): Promise<void>;
    stop(id: string): Promise<void>;
    restart(id: string): Promise<void>;
    get(id: string): ManagedProcess;
    listAll(): readonly ManagedProcessStatus[];
    shutdownAll(): Promise<void>;
}

declare class NetworkQualityTracker implements INetworkQualityTracker {
    private readonly devices;
    private static readonly MAX_SAMPLES;
    reportStreamStats(deviceId: string, streamId: string, bitrateKbps: number, packetLoss?: number): void;
    reportClientStats(deviceId: string, stats: Omit<ClientNetworkStats, 'lastUpdated'>): void;
    getDeviceStats(deviceId: string): DeviceNetworkStats | null;
    getAllStats(): readonly DeviceNetworkStats[];
    private getOrCreateDevice;
}

interface ReplScope {
    readonly type: 'system' | 'provider' | 'device' | 'addon';
    readonly providerId?: string;
    readonly deviceId?: string;
    readonly addonId?: string;
}
interface ReplSessionContext {
    readonly scope: ReplScope;
    /** Pre-populated variables available in the REPL session */
    readonly variables: Record<string, unknown>;
}

interface IReplEngine {
    execute(code: string, context: ReplSessionContext): Promise<ReplResult>;
    getCompletions(partial: string, context: ReplSessionContext): Promise<string[]>;
}
/**
 * Context provider that the server kernel implements.
 * The REPL engine calls this to build the sandbox for each scope type.
 */
interface IReplContextProvider {
    getSystemSandbox(): Record<string, unknown>;
    getDeviceSandbox(deviceId: string): Record<string, unknown>;
    getProviderSandbox(providerId: string): Record<string, unknown>;
    getAddonSandbox(addonId: string): Record<string, unknown>;
}

declare class ReplEngine implements IReplEngine {
    private readonly contextProvider;
    constructor(contextProvider: IReplContextProvider);
    execute(code: string, context: ReplSessionContext): Promise<ReplResult>;
    getCompletions(partial: string, context: ReplSessionContext): Promise<string[]>;
    private buildSandbox;
}

/** Event emitter for agent lifecycle and task events */
type AgentEventEmitter = {
    emitAgentRegistered(agentId: string, capabilities: readonly string[]): void;
    emitAgentUnregistered(agentId: string): void;
    emitAgentOnline(agentId: string): void;
    emitAgentOffline(agentId: string): void;
    emitTaskDispatched(taskId: string, agentId: string, capability: string): void;
};

declare class AgentRegistry {
    private readonly events;
    private readonly heartbeatTimeoutMs;
    private readonly heartbeatCheckIntervalMs;
    private readonly agents;
    private readonly heartbeatIntervals;
    constructor(events: AgentEventEmitter, heartbeatTimeoutMs?: number, heartbeatCheckIntervalMs?: number);
    /** Register a new agent */
    registerAgent(info: AgentInfo): void;
    /** Remove agent */
    unregisterAgent(id: string): void;
    /** Update heartbeat timestamp */
    heartbeat(id: string): void;
    /** Find agents with a specific capability */
    getAgentsWithCapability(capability: string): readonly AgentEntry[];
    /** Get best agent for a task (least loaded) */
    selectAgent(capability: string, preferredId?: string): AgentEntry | null;
    /** List all agents with status */
    listAgents(): readonly AgentStatus[];
    /** Get single agent */
    getAgent(id: string): AgentEntry | null;
    /** Destroy all heartbeat intervals */
    destroy(): void;
    private startHeartbeatCheck;
}

declare class TaskDispatcher {
    private readonly agentRegistry;
    private readonly events;
    private readonly pendingTasks;
    private readonly localExecutors;
    constructor(agentRegistry: AgentRegistry, events: AgentEventEmitter);
    /** Dispatch a task to the best available agent */
    dispatch(task: AgentTask, options?: TaskDispatchOptions): Promise<AgentTaskResult>;
    /** Register a local executor for a capability (in-process fallback) */
    registerLocalExecutor(capability: string, executor: (input: Record<string, unknown>) => Promise<Record<string, unknown>>): void;
    /** Called when an agent returns a result */
    handleTaskResult(result: AgentTaskResult): void;
    private executeLocally;
    private sendToAgent;
}

declare class LogRingBuffer {
    private readonly capacity;
    private readonly buffer;
    private head;
    private count;
    constructor(capacity?: number);
    push(entry: LogEntry): void;
    getAll(): LogEntry[];
    query(filter: LogFilter): LogEntry[];
}

declare class ScopedLogger implements IScopedLogger {
    private readonly scope;
    private readonly writeFn;
    constructor(scope: string[], writeFn: (entry: LogEntry) => void);
    debug(message: string, meta?: Record<string, unknown>): void;
    info(message: string, meta?: Record<string, unknown>): void;
    warn(message: string, meta?: Record<string, unknown>): void;
    error(message: string, meta?: Record<string, unknown>): void;
    child(childScope: string): IScopedLogger;
    private write;
}

interface AgentClientConfig {
    readonly hubUrl: string;
    readonly token?: string;
    readonly logger: IScopedLogger;
    readonly registrationInfo: AgentRegistrationInfo;
}
type MessageHandler = (msg: HubToAgentMessage) => void;
type BinaryHandler = (data: Buffer) => void;
type ConnectionHandler = () => void;
/**
 * WebSocket client for agent mode. Framework-agnostic (no NestJS).
 * Connects to the hub, sends registration, handles messages,
 * reconnects with exponential backoff.
 */
declare class AgentClient {
    private ws;
    private reconnectAttempt;
    private reconnectTimer;
    private heartbeatTimer;
    private destroyed;
    private readonly messageHandlers;
    private readonly binaryHandlers;
    private readonly connectHandlers;
    private readonly disconnectHandlers;
    private readonly logger;
    private readonly hubUrl;
    private readonly token?;
    private readonly registrationInfo;
    private runtimeStatus;
    constructor(config: AgentClientConfig);
    /** Connect to the hub WebSocket */
    connect(): Promise<void>;
    /** Disconnect and stop reconnecting */
    disconnect(): void;
    /** Send a JSON control message to the hub */
    send(msg: AgentToHubMessage): void;
    /** Send a binary frame to the hub */
    sendBinary(data: Buffer): void;
    /** Register a handler for JSON messages from hub */
    onMessage(handler: MessageHandler): void;
    /** Register a handler for binary frames from hub */
    onBinaryFrame(handler: BinaryHandler): void;
    /** Register a handler for successful connection */
    onConnect(handler: ConnectionHandler): void;
    /** Register a handler for disconnection */
    onDisconnect(handler: ConnectionHandler): void;
    /** Update the runtime status (used in heartbeat) */
    updateStatus(status: AgentRuntimeStatus): void;
    /** Whether currently connected */
    get connected(): boolean;
    private doConnect;
    private handleBuiltinMessage;
    private scheduleReconnect;
    private startHeartbeat;
    private stopHeartbeat;
    private clearTimers;
}

/**
 * Receives task assignments from hub, routes to registered ITaskHandler instances.
 * Maintains handler registry, manages task lifecycle.
 * Framework-agnostic (no NestJS).
 */
declare class AgentTaskRunner {
    private readonly agentId;
    private readonly client;
    private readonly handlers;
    private readonly runningTasks;
    private readonly logger;
    constructor(agentId: string, client: AgentClient, logger: IScopedLogger);
    /** Register a task handler for a given task type */
    registerHandler(handler: ITaskHandler): void;
    /** Unregister a task handler */
    unregisterHandler(taskType: string): void;
    /** Get all registered task types */
    getTaskTypes(): readonly string[];
    /** Get a handler by task type */
    getHandler(taskType: string): ITaskHandler | undefined;
    /**
     * Execute a task dispatched from the hub.
     * Sends result or error back to hub via the AgentClient.
     */
    executeTask(taskId: string, taskType: string, payload: unknown): Promise<void>;
    /** Cancel a running task */
    cancelTask(taskId: string): Promise<void>;
    /** Number of currently running tasks */
    get activeTaskCount(): number;
    /** Destroy: cancel all running tasks */
    destroy(): Promise<void>;
}

/**
 * Stub task handler for pipeline.decode.
 * In the full implementation, this would start a StreamBroker for a camera
 * and send decoded frames to the hub via the AgentClient.
 */
declare class DecodeTaskHandler implements ITaskHandler {
    readonly taskType = "pipeline.decode";
    readonly description = "Decode an RTSP stream and produce JPEG frames";
    handle(payload: unknown, context: TaskContext): Promise<unknown>;
    cancel(): Promise<void>;
}
/**
 * Stub task handler for pipeline.detect.
 * In the full implementation, this would receive frames (via binary WS),
 * run them through the detection engine, and send results back.
 */
declare class DetectTaskHandler implements ITaskHandler {
    readonly taskType = "pipeline.detect";
    readonly description = "Run object detection on received frames";
    handle(payload: unknown, context: TaskContext): Promise<unknown>;
    cancel(): Promise<void>;
}
/**
 * Stub task handler for pipeline.record.
 * In the full implementation, this would start recording an RTSP stream
 * to disk in segments and report segment metadata back to the hub.
 */
declare class RecordTaskHandler implements ITaskHandler {
    readonly taskType = "pipeline.record";
    readonly description = "Record an RTSP stream to disk segments";
    handle(payload: unknown, context: TaskContext): Promise<unknown>;
    cancel(): Promise<void>;
}

type ElementState = 'stopped' | 'starting' | 'running' | 'stopping' | 'error' | 'disabled';
interface ElementStatus {
    state: ElementState;
    error?: string;
    startedAt?: number;
    stoppedAt?: number;
    restartCount: number;
    uptime: number;
}
declare class LifecycleStateMachine {
    private readonly elementId;
    private readonly elementType;
    private readonly eventBus;
    private readonly logger;
    private _state;
    private _error?;
    private _startedAt?;
    private _stoppedAt?;
    private _restartCount;
    private _hasStartedOnce;
    constructor(elementId: string, elementType: 'provider' | 'device' | 'addon' | 'process', eventBus: IEventBus, logger: IScopedLogger);
    get state(): ElementState;
    getStatus(): ElementStatus;
    transition(to: ElementState, error?: string): boolean;
    incrementRestartCount(): void;
    private isValidTransition;
}

type FeatureConfigReader = {
    readonly features: FeatureManifest;
};
declare class FeatureManager {
    private readonly configReader;
    constructor(configReader: FeatureConfigReader);
    isEnabled(flag: FeatureFlag): boolean;
    getManifest(): FeatureManifest;
}

declare class SystemEventBus implements IEventBus {
    private readonly ringBuffer;
    private readonly subscribers;
    constructor(bufferSize?: number);
    emit(event: SystemEvent): void;
    subscribe(filter: EventFilter, handler: (event: SystemEvent) => void): () => void;
    getRecent(filter?: EventFilter, limit?: number): readonly SystemEvent[];
}

interface ILogDestination {
    initialize(): Promise<void>;
    shutdown(): Promise<void>;
    write(entry: LogEntry): void;
    query?(filter: LogFilter): Promise<readonly LogEntry[]>;
}
declare class LogManager {
    private readonly ringBuffer;
    private readonly destinations;
    constructor(bufferSize?: number);
    createLogger(scope: string): IScopedLogger;
    addDestination(dest: ILogDestination): void;
    removeDestination(dest: ILogDestination): void;
    query(filter: LogFilter): LogEntry[];
}

interface IStorageBackend {
    /** Backend type identifier */
    readonly type: string;
    /** Base path of this backend */
    readonly basePath: string;
    /** Resolve a subpath to an absolute path */
    resolve(subpath: string): string;
    /** Check if the backend path exists and is writable */
    isAvailable(): boolean;
    /** Ensure base directory exists (mkdir -p equivalent) */
    initialize(): Promise<void>;
}
declare class FsStorageBackend implements IStorageBackend {
    readonly type = "local";
    readonly basePath: string;
    constructor(basePath: string);
    resolve(subpath: string): string;
    isAvailable(): boolean;
    initialize(): Promise<void>;
}

type StorageLocationName = 'data' | 'media' | 'recordings' | 'models' | 'cache' | 'logs';
declare class StorageLocationManager {
    private readonly backends;
    private readonly dataPath;
    constructor(dataPath: string);
    /** Initialize all locations with default paths */
    initializeDefaults(): Promise<void>;
    /** Override a specific location's backend path */
    setLocationPath(name: StorageLocationName, basePath: string): Promise<void>;
    /** Get the backend for a location */
    getBackend(name: StorageLocationName): IStorageBackend;
    /** Resolve a path within a location */
    resolve(location: StorageLocationName, subpath: string): string;
    /** Check if all locations are available */
    getStatus(): Array<{
        name: StorageLocationName;
        available: boolean;
        path: string;
    }>;
    /** All location names */
    getLocationNames(): StorageLocationName[];
}

interface IStorageProvider {
    initialize(): Promise<void>;
    shutdown(): Promise<void>;
    getLocation(name: StorageLocationName): IStorageLocation;
    export?(locationName: StorageLocationName): Promise<Buffer>;
    import?(locationName: StorageLocationName, data: Buffer): Promise<void>;
}
interface QueryFilter {
    where?: Record<string, unknown>;
    whereIn?: Record<string, unknown[]>;
    whereBetween?: Record<string, [unknown, unknown]>;
    orderBy?: {
        field: string;
        direction: 'asc' | 'desc';
    };
    limit?: number;
    offset?: number;
}
interface StorageRecord {
    collection: string;
    id: string;
    data: Record<string, unknown>;
}
interface IStructuredStorage {
    query(collection: string, filter?: QueryFilter): Promise<readonly StorageRecord[]>;
    insert(record: StorageRecord): Promise<StorageRecord>;
    update(collection: string, id: string, data: Record<string, unknown>): Promise<StorageRecord>;
    delete(collection: string, id: string): Promise<void>;
    count(collection: string, filter?: QueryFilter): Promise<number>;
}
interface IFileStorage {
    readFile(path: string): Promise<Buffer>;
    writeFile(path: string, data: Buffer): Promise<void>;
    deleteFile(path: string): Promise<void>;
    listFiles(prefix?: string): Promise<readonly string[]>;
    getFileUrl(path: string): Promise<string>;
    exists(path: string): Promise<boolean>;
}
interface IStorageLocation {
    structured?: IStructuredStorage;
    files?: IFileStorage;
}
/**
 * StorageManager — bridge between legacy code (getLocation/getLocationPath)
 * and the new capability-based storage system.
 *
 * Legacy consumers call getLocation('addon', namespace) to get structured + file storage.
 * This manager builds the response from:
 *   - SettingsBackend (for structured queries) — provided by sqlite-settings addon
 *   - LocationManager (for file paths) — set during Phase 2 boot
 */
declare class StorageManager {
    private legacyProvider;
    private locationManager;
    private newStorageProvider;
    private settingsBackend;
    /** @deprecated Set by legacy capability consumer — use setNewStorageProvider instead */
    setProvider(provider: IStorageProvider | IStorageProvider$1): void;
    setNewStorageProvider(provider: IStorageProvider$1): void;
    setSettingsBackend(backend: ISettingsBackend): void;
    getProvider(): IStorageProvider;
    setLocationManager(manager: StorageLocationManager): void;
    getLocationManager(): StorageLocationManager;
    initializeLocations(dataPath: string): Promise<void>;
    getLocationPath(name: StorageLocationName): string;
    /**
     * Get a storage location with optional namespace scoping.
     * Builds IStorageLocation from settingsBackend (structured) + locationManager (files).
     */
    getLocation(name: StorageLocationName | string, namespace?: string): IStorageLocation;
    private createLegacyShim;
    private createNamespacedLocation;
}

/**
 * Manages scoped API tokens with restricted addon/route/capability access.
 * Framework-agnostic — dependencies injected via constructor.
 */
declare class ScopedTokenManager {
    private readonly storage;
    constructor(storage: IStructuredStorage);
    /**
     * Create a new scoped token. Returns the raw token string (shown once)
     * and the stored record (with hash, not the raw token).
     */
    create(userId: string, name: string, scopes: TokenScope[], expiresAt?: number): Promise<{
        token: string;
        record: ScopedToken;
    }>;
    /**
     * Validate a raw token string. Returns the token record if valid, null otherwise.
     */
    validate(rawToken: string): Promise<ScopedToken | null>;
    /**
     * Check whether a token's scopes grant access to the given addon, route, or capability.
     */
    matchesScope(token: ScopedToken, addonId?: string, routePath?: string, capability?: string): boolean;
    /**
     * Revoke a token by ID.
     */
    revoke(tokenId: string): Promise<void>;
    /**
     * List all tokens for a user (without exposing the raw token).
     */
    listForUser(userId: string): Promise<ScopedToken[]>;
    /**
     * Update the lastUsedAt timestamp for a token.
     */
    updateLastUsed(tokenId: string): Promise<void>;
}

type AuthConfigReader = {
    get<T>(path: string): T;
    update(section: string, data: Record<string, unknown>): void;
};
declare class AuthManager {
    private readonly config;
    private readonly jwtSecret;
    private scopedTokenManager;
    constructor(config: AuthConfigReader);
    signToken(payload: Omit<TokenPayload, 'iat' | 'exp'>): string;
    verifyToken(token: string): TokenPayload;
    hashPassword(password: string): Promise<string>;
    comparePassword(password: string, hash: string): Promise<boolean>;
    generateApiKey(): {
        token: string;
        hash: string;
        prefix: string;
    };
    validateApiKey(token: string, storedHash: string): boolean;
    /**
     * Create a service token for agent/worker authentication.
     * Used when forking workers or when agents register.
     */
    createServiceToken(opts: {
        readonly agentId: string;
        readonly role?: string;
        readonly expiresIn?: string;
    }): string;
    /**
     * Set the scoped token manager for the auth chain.
     */
    setScopedTokenManager(manager: ScopedTokenManager): void;
    /**
     * Validate a scoped token string.
     * Returns the token record if valid, null otherwise.
     */
    validateScopedToken(rawToken: string): Promise<ScopedToken | null>;
    /**
     * Check whether a scoped token grants access to a given addon/route/capability.
     */
    matchesScopedTokenScope(token: ScopedToken, addonId?: string, routePath?: string, capability?: string): boolean;
}

interface ApiKeyRecord {
    id: string;
    label: string;
    role: UserRole;
    allowedProviders: string[] | '*';
    allowedDevices: Record<string, string[] | '*'>;
    tokenHash: string;
    tokenPrefix: string;
    createdAt: number;
    lastUsedAt?: number;
}
interface CreateApiKeyInput {
    label: string;
    role: UserRole;
    allowedProviders?: string[] | '*';
    allowedDevices?: Record<string, string[] | '*'>;
}
type ApiKeyStorageAccess = {
    getStructuredStorage(): IStructuredStorage;
};
declare class ApiKeyManager {
    private readonly storageAccess;
    private readonly auth;
    constructor(storageAccess: ApiKeyStorageAccess, auth: AuthManager);
    private get structured();
    create(input: CreateApiKeyInput): Promise<{
        record: ApiKeyRecord;
        token: string;
    }>;
    validateToken(token: string): Promise<ApiKeyRecord | null>;
    listAll(): Promise<Omit<ApiKeyRecord, 'tokenHash'>[]>;
    revoke(id: string): Promise<void>;
    findById(id: string): Promise<ApiKeyRecord | null>;
}

interface CreateUserInput {
    username: string;
    password: string;
    role: UserRole;
    allowedProviders?: string[] | '*';
    allowedDevices?: Record<string, string[] | '*'>;
}
type UpdatableUserFields = Partial<Pick<UserRecord, 'role' | 'allowedProviders' | 'allowedDevices'>>;
type UserStorageAccess = {
    getStructuredStorage(): IStructuredStorage;
};
type UserConfigReader = {
    get<T>(path: string): T;
};
declare class UserManager {
    private readonly storageAccess;
    private readonly auth;
    private readonly config;
    constructor(storageAccess: UserStorageAccess, auth: AuthManager, config: UserConfigReader);
    private get structured();
    create(input: CreateUserInput): Promise<UserRecord>;
    findByUsername(username: string): Promise<UserRecord | null>;
    findById(id: string): Promise<UserRecord | null>;
    validateCredentials(username: string, password: string): Promise<UserRecord | null>;
    listAll(): Promise<Omit<UserRecord, 'passwordHash'>[]>;
    update(id: string, data: UpdatableUserFields): Promise<void>;
    delete(id: string): Promise<void>;
    resetPassword(id: string, newPassword: string): Promise<void>;
    ensureAdminExists(): Promise<void>;
}

/**
 * Central notification service that routes notifications to configured outputs.
 * Framework-agnostic — dependencies injected via constructor.
 *
 * Outputs are resolved from the CapabilityRegistry's 'notification-output'
 * collection on each call (proxy pattern). Falls back to a local map
 * when no registry is provided (backward compat).
 */
declare class NotificationService {
    private readonly logger;
    private readonly localOutputs;
    private readonly routing;
    private readonly rateLimits;
    private readonly lastSent;
    private registry;
    constructor(logger: IScopedLogger);
    /** Set the registry for live output lookup. Called once during boot. */
    setRegistry(registry: CapabilityRegistry): void;
    /** Resolve all outputs — prefers registry, falls back to local map */
    private get outputs();
    /** @deprecated Use registry-based resolution. Kept for backward compat only. */
    addOutput(output: INotificationOutput): void;
    /** @deprecated Use registry-based resolution. Kept for backward compat only. */
    removeOutput(id: string): void;
    setRouting(category: string, outputIds: string[]): void;
    setRateLimit(category: string, minIntervalMs: number): void;
    notify(notification: Notification): Promise<void>;
    getOutputs(): ReadonlyArray<{
        id: string;
        name: string;
        icon: string;
    }>;
    getRouting(): ReadonlyMap<string, string[]>;
    getOutput(id: string): INotificationOutput | undefined;
}

type Unsubscribe = () => void;
/**
 * Service for broadcasting toast notifications to connected UI clients.
 * Framework-agnostic — integrates with tRPC subscriptions via subscribe().
 */
declare class ToastService {
    private readonly listeners;
    /**
     * Subscribe to toast events for a specific user.
     * Returns an unsubscribe function.
     */
    subscribe(connectionId: string, userId: string, callback: (toast: Toast) => void): Unsubscribe;
    /**
     * Broadcast a toast to all connected clients.
     */
    broadcast(toast: Toast): void;
    /**
     * Send a toast to a specific user's connections only.
     */
    sendToUser(userId: string, toast: Toast): void;
}

interface RouteMatch {
    readonly route: IAddonHttpRoute;
    readonly addonId: string;
    readonly params: Record<string, string>;
}
/**
 * Registry for dynamic HTTP routes registered by addons.
 * Framework-agnostic — the server HTTP layer queries this registry to dispatch requests.
 */
declare class AddonRouteRegistry {
    private readonly routes;
    /**
     * Register all routes from an addon's route provider.
     */
    registerRoutes(addonId: string, provider: IAddonRouteProvider): void;
    /**
     * Unregister all routes for an addon.
     */
    unregisterRoutes(addonId: string): void;
    /**
     * Match an incoming request method + path to a registered route.
     * Supports simple path parameters (e.g., /items/:id).
     */
    matchRoute(method: string, path: string): RouteMatch | null;
    /**
     * List all registered routes across all addons.
     */
    listRoutes(): ReadonlyArray<{
        addonId: string;
        method: string;
        path: string;
        access: string;
        description?: string;
    }>;
}

interface IRegisteredDevice {
    readonly id: string;
    readonly name: string;
    readonly providerId: string;
    readonly capabilities: readonly string[];
}
declare class DeviceRegistry<T extends IRegisteredDevice = IRegisteredDevice> {
    private readonly eventBus;
    private readonly devices;
    private readonly logger;
    constructor(eventBus: IEventBus, loggingService: LoggerFactory);
    registerDevice(device: T): void;
    unregisterDevice(id: string): void;
    getDevice(id: string): T | null;
    listDevices(): T[];
    getDevicesByProvider(providerId: string): T[];
    getDevicesWithCapability(cap: string): T[];
    registerProviderDevices(providerId: string, devices: readonly T[]): void;
    unregisterProviderDevices(providerId: string): void;
}

interface IDeviceCapability {
    kind: string;
}
interface CapabilityBinding {
    source: 'native' | 'addon' | 'disabled';
    addonId?: string;
    config?: Record<string, unknown>;
}
interface IResolvableDevice {
    readonly id: string;
    readonly capabilities: string[];
    getCapability<T extends IDeviceCapability>(cap: string): T | null;
}
interface IAddonRegistryAccess {
    getAddon(addonId: string): unknown | null;
}
declare class CapabilityResolver {
    private readonly addonRegistry;
    private readonly bindings;
    constructor(addonRegistry: IAddonRegistryAccess);
    resolve<T extends IDeviceCapability>(device: IResolvableDevice, cap: string): T | null;
    setBinding(deviceId: string, cap: string, binding: CapabilityBinding): void;
    removeBinding(deviceId: string, cap: string): void;
    getBindings(deviceId: string): Partial<Record<string, CapabilityBinding>>;
    getEffectiveCapabilities(device: IResolvableDevice): string[];
}

interface TlsCertPair {
    readonly cert: Buffer;
    readonly key: Buffer;
}
interface EnsureTlsResult {
    readonly certPath: string;
    readonly keyPath: string;
    readonly generated: boolean;
}
interface CertOptions {
    /** Common Name for the cert (default: 'camstack.local') */
    readonly commonName?: string;
    /** Validity in days (default: 825 — max for browsers) */
    readonly validDays?: number;
    /** Additional SANs (DNS names or IPs) */
    readonly extraSans?: readonly string[];
}
/**
 * Ensure a self-signed TLS certificate exists in the given directory.
 * Generates one if missing. Returns paths to cert and key files.
 */
declare function ensureTlsCert(dataDir: string, options?: CertOptions): Promise<EnsureTlsResult>;
/**
 * Load TLS cert+key from files. Returns Buffers suitable for Node.js TLS options.
 */
declare function loadTlsCert(certPath: string, keyPath: string): TlsCertPair;

/**
 * Factory for creating tRPC clients for addons.
 *
 * Two modes:
 * - Direct caller (in-process): zero overhead, uses createCallerFactory
 * - WSS client (worker/agent): real WebSocket connection to the server
 */
interface DirectCallerOptions {
    /** The tRPC router instance (from buildAppRouter) */
    readonly router: unknown;
    /** Context for the caller (user identity, etc.) */
    readonly context: {
        readonly user: {
            readonly id: string;
            readonly username: string;
            readonly role: string;
        };
    };
}
interface WssClientOptions {
    /** WebSocket URL (e.g., wss://localhost:4443/trpc) */
    readonly url: string;
    /** Auth token for the connection */
    readonly token: string;
}
declare class AddonApiFactory {
    /**
     * Build a WSS URL from host and port.
     */
    buildWssUrl(host: string, port: number): string;
    /**
     * Create a direct caller -- calls tRPC procedures directly in-process.
     * Zero network overhead. Used for in-process addons and dev mode.
     *
     * @param options.router - The tRPC router from buildAppRouter()
     * @param options.context - The auth context (service account)
     * @returns A tRPC caller that can be used as context.api
     */
    createDirectCaller(options: DirectCallerOptions): unknown;
    /**
     * Create a WSS tRPC client -- connects to the server via WebSocket.
     * Used for forked workers and remote agents.
     *
     * @param options.url - WSS URL (e.g., wss://localhost:4443/trpc)
     * @param options.token - Bearer token for authentication
     * @returns A tRPC client that can be used as context.api
     */
    createWssClient(options: WssClientOptions): Promise<{
        readonly client: unknown;
        readonly close: () => void;
    }>;
}

declare class PlatformScorer {
    private cached;
    /** Probe hardware + runtimes and score all backend combos. Cached after first call. */
    probe(): Promise<PlatformCapabilities>;
    probeHardware(): Promise<HardwareInfo>;
    private probeNodeBackends;
    private probePythonBackends;
    private scoreBackends;
}

declare class InferenceConfigResolver {
    private readonly scores;
    private readonly hardware;
    constructor(scores: readonly PlatformScore[], hardware: HardwareInfo);
    /**
     * Compute accuracy/backend weights based on available system RAM.
     * availableRAM_MB is now sourced from systeminformation (reliable cross-platform),
     * not os.freemem() which is broken on macOS.
     *
     * - > 16 GB available: prefer larger, more accurate models (accuracy 0.6, backend 0.4)
     * - > 8 GB available:  balanced (accuracy 0.5, backend 0.5)
     * - <= 8 GB available: prefer speed (accuracy 0.4, backend 0.6)
     */
    private getWeights;
    /**
     * Given an addon's model requirements, pick the best model + runtime + backend.
     *
     * Algorithm:
     * 1. Filter models by available RAM (minRAM_MB < 25% of available RAM)
     * 2. For each remaining model, find the best platform score whose format
     *    is available in the model's formats
     * 3. Pick the model with the highest combined score using RAM-adaptive weights:
     *    - High RAM (>16 GB): accuracy × 0.6 + backend × 0.4  (prefer accuracy)
     *    - Mid RAM  (>8 GB):  accuracy × 0.5 + backend × 0.5  (balanced)
     *    - Low RAM  (<=8 GB): accuracy × 0.4 + backend × 0.6  (prefer speed)
     */
    resolve(requirements: readonly ModelRequirement[]): ResolvedInferenceConfig;
}

/** Minimal device registry interface for provider management */
type ProviderDeviceRegistry = {
    registerProviderDevices(providerId: string, devices: readonly IRegistrableDevice[]): void;
    unregisterProviderDevices(providerId: string): void;
};
interface IRegistrableDevice {
    readonly id: string;
    readonly name: string;
    readonly providerId: string;
    readonly capabilities: readonly string[];
}
interface ProviderStatus {
    connected: boolean;
    error?: string;
    deviceCount: number;
}
interface LiveEvent {
    type: string;
    camera: string;
    timestamp: number;
    data: Record<string, unknown>;
}
interface IManagedProvider {
    readonly id: string;
    readonly type: string;
    readonly name: string;
    start(): Promise<void>;
    stop(): Promise<void>;
    getStatus(): ProviderStatus;
    getDevices(): readonly IRegistrableDevice[];
    subscribeLiveEvents(callback: (event: LiveEvent) => void): () => void;
}

declare class ProviderManager<P extends IManagedProvider = IManagedProvider> {
    private readonly deviceRegistry;
    private readonly eventBus;
    private readonly loggingService;
    private readonly providers;
    private readonly logger;
    constructor(deviceRegistry: ProviderDeviceRegistry, eventBus: IEventBus, loggingService: LoggerFactory);
    registerProvider(provider: P): void;
    startProvider(id: string): Promise<void>;
    stopProvider(id: string): Promise<void>;
    disableProvider(id: string): Promise<void>;
    enableProvider(id: string): Promise<void>;
    restartProvider(id: string): Promise<void>;
    getProvider(id: string): P | null;
    getProviderStatus(id: string): ElementStatus | null;
    listProviders(): readonly ProviderListItem[];
    shutdownAll(): Promise<void>;
}

export { AddonApiFactory, AddonRouteRegistry, AgentClient, type AgentClientConfig, type AgentEventEmitter, AgentRegistry, AgentTaskRunner, ApiKeyManager, type ApiKeyRecord, type ApiKeyStorageAccess, type AuthConfigReader, AuthManager, type BinaryHandler, type CapabilityBinding, CapabilityResolver, type CertOptions, type ConnectionHandler, DecodeTaskHandler, DetectTaskHandler, DeviceRegistry, type DirectCallerOptions, type ElementState, type ElementStatus, type EnsureTlsResult, EventBus, type FeatureConfigReader, FeatureManager, FsStorageBackend, type IAddonRegistryAccess, type IStorageProvider as ICoreStorageProvider, type IDeviceCapability, type IFileStorage, type ILogDestination, type IManagedProvider, type IRegisteredDevice, type IReplContextProvider, type IReplEngine, type IResolvableDevice, type IStorageBackend, type IStorageLocation, type IStructuredStorage, InferenceConfigResolver, LifecycleStateMachine, LogManager, LogRingBuffer, ManagedProcess, type MessageHandler, ModelDownloadService, NetworkQualityTracker, NotificationService, PYTHON_VERSION, PipelineRunner, PipelineValidator, PlatformScorer, type ProcessEventEmitter, type ProcessLoggerFactory, ProcessManager, type ProcessState, type ProviderDeviceRegistry, ProviderManager, PythonEnvManager, type QueryFilter, RecordTaskHandler, ReplEngine, type ReplScope, type ReplSessionContext, ScopedLogger, ScopedTokenManager, StorageLocationManager, type StorageLocationName, StorageManager, type StorageRecord, SystemEventBus, TaskDispatcher, type TlsCertPair, ToastService, type Unsubscribe, type UserConfigReader, UserManager, type UserStorageAccess, type WssClientOptions, buildBinaryPath, downloadBinary, downloadFile, downloadModel, ensureBinary, ensureFfmpeg, ensurePython, ensureTlsCert, fetchJson, findInPath, getFfmpegDownloadUrl, getPlatformInfo, getPythonDownloadUrl, installPythonPackages, loadTlsCert };
