type AnyObject = {
    [key: string | number]: any;
};
interface ThrottleHandle {
    /** Stop the repeating emission */
    clear(): void;
}

/**
 * Represents a context object used within a graph system.
 * Contexts are essentially a container for data that is relevant to a specific task or routine.
 * They are passed down the graph and can be used to store and manipulate data during the execution process.
 * The context is divided into full context, user data, and metadata.
 * Provides methods for accessing, cloning, mutating, combining, and exporting the context data.
 */
declare class GraphContext {
    readonly id: string;
    readonly fullContext: AnyObject;
    readonly userData: AnyObject;
    readonly metadata: AnyObject;
    constructor(context: AnyObject);
    /**
     * Gets frozen user data (read-only, no clone).
     * @returns Frozen user context.
     */
    getContext(): AnyObject;
    /**
     * Clones the current user context data and returns a deep-cloned copy of it.
     *
     * @return {AnyObject} A deep-cloned copy of the user context data.
     */
    getClonedContext(): AnyObject;
    /**
     * Gets full raw context (cloned for safety).
     * @returns Cloned full context.
     */
    getFullContext(): AnyObject;
    /**
     * Creates and returns a deep-cloned version of the fullContext object.
     *
     * @return {AnyObject} A deep copy of the fullContext instance, preserving all nested structures and data.
     */
    getClonedFullContext(): AnyObject;
    /**
     * Gets frozen metadata (read-only).
     * @returns Frozen metadata object.
     */
    getMetadata(): AnyObject;
    /**
     * Combines the current GraphContext with another GraphContext, merging their user data
     * and full context into a new GraphContext instance.
     *
     * @param {GraphContext} otherContext - The other GraphContext to combine with the current one.
     * @return {GraphContext} A new GraphContext instance containing merged data from both contexts.
     */
    combine(otherContext: GraphContext): GraphContext;
    /**
     * Exports the context.
     * @returns Exported object.
     */
    export(): {
        id: string;
        context: AnyObject;
    };
}

/**
 * Abstract class representing an iterator for traversing a collection of elements.
 * Subclasses must implement core methods to allow iteration and may optionally implement additional methods for extended functionality.
 */
declare abstract class Iterator {
    abstract hasNext(): boolean;
    abstract hasPrevious?(): boolean;
    abstract next(): any;
    abstract previous?(): any;
    abstract getFirst?(): any;
    abstract getLast?(): any;
}

/**
 * Represents an abstract base class for a graph node or task.
 * This class provides the foundation for graph-related operations such as traversal,
 * exportation, logging, and execution. It must be extended by concrete implementations.
 */
declare abstract class Graph {
    /**
     * Executes this graph node/task.
     * @param args Execution args (e.g., context).
     * @returns Result.
     */
    abstract execute(...args: any[]): unknown;
    /**
     * Logs the graph node (debugging).
     */
    abstract log(): void;
    /**
     * Destroys the graph node.
     */
    abstract destroy(): void;
    /**
     * Exports the graph node.
     * @returns Exported data.
     */
    abstract export(): any;
    /**
     * Accepts a visitor for traversal (e.g., debugging/exporters).
     * @param visitor The visitor.
     * @note Non-runtime use; pairs with iterator for data extraction.
     */
    abstract accept(visitor: GraphVisitor): void;
    /**
     * Gets an iterator for graph traversal (e.g., BFS/DFS).
     * @returns Iterator.
     * @note For debugging/exporters.
     */
    abstract getIterator(): Iterator;
}

/**
 * Represents an iterator for traversing nodes in a graph structure.
 * Implements the Iterator interface and allows traversal of nodes layer by layer.
 */
declare class GraphNodeIterator implements Iterator {
    currentNode: GraphNode | undefined;
    currentLayer: GraphNode[];
    nextLayer: GraphNode[];
    index: number;
    constructor(node: GraphNode);
    hasNext(): boolean;
    next(): any;
}

/**
 * Represents an abstract chain of execution, where each instance can be
 * connected to a succeeding or preceding instance to form a chain of steps.
 * Provides methods to manage the links between instances in the chain.
 */
declare abstract class ExecutionChain {
    next: ExecutionChain | undefined;
    previous: ExecutionChain | undefined;
    setNext(next: ExecutionChain): void;
    get hasNext(): boolean;
    get hasPreceding(): boolean;
    getNext(): ExecutionChain | undefined;
    getPreceding(): ExecutionChain | undefined;
    decouple(): void;
}

/**
 * The `GraphLayerIterator` class provides an iterator for traversing through
 * layers of a `GraphLayer` data structure. It allows sequential and bi-directional
 * iteration, as well as access to the first and last layers in the graph.
 *
 * @implements {Iterator}
 */
declare class GraphLayerIterator implements Iterator {
    graph: GraphLayer;
    currentLayer: GraphLayer | undefined;
    constructor(graph: GraphLayer);
    hasNext(): boolean;
    hasPrevious(): boolean;
    next(): GraphLayer;
    previous(): GraphLayer;
    getFirst(): GraphLayer;
    getLast(): GraphLayer;
}

/**
 * Represents an abstract layer in a graph, handling nodes and their execution.
 * A `GraphLayer` can manage execution states, debug states, and relationships with other layers in the graph.
 * This class is designed to be extended and requires the implementation of the `execute` method.
 *
 * @abstract
 * @class GraphLayer
 * @extends ExecutionChain
 * @implements Graph
 */
declare abstract class GraphLayer extends ExecutionChain implements Graph {
    readonly index: number;
    nodes: GraphNode[];
    executionTime: number;
    executionStart: number;
    debug: boolean;
    constructor(index: number);
    /**
     * Sets the debug mode for the current instance and all associated nodes.
     *
     * @param {boolean} value - A boolean value to enable (true) or disable (false) debug mode.
     * @return {void} No return value.
     */
    setDebug(value: boolean): void;
    /**
     * Abstract method to execute a specific operation given a context.
     *
     * @param {GraphContext} [context] - Optional parameter representing the execution context, which contains relevant data for performing the operation.
     * @return {unknown} - Returns the result of the operation, its type may vary depending on the implementation.
     */
    abstract execute(context?: GraphContext): unknown;
    /**
     * Checks if the current layer has a preceding layer.
     *
     * @return {boolean} True if the current layer has a preceding layer that is an instance of GraphLayer; otherwise, false.
     */
    get hasPreceding(): boolean;
    getNumberOfNodes(): number;
    /**
     * Retrieves a list of nodes that match the given routine execution ID.
     *
     * @param {string} routineExecId - The ID of the routine execution to filter nodes by.
     * @return {Array} An array of nodes that have the specified routine execution ID.
     */
    getNodesByRoutineExecId(routineExecId: string): GraphNode[];
    /**
     * Finds and returns all nodes in the graph that are identical to the given node.
     * Two nodes are considered identical if they share the same routine execution ID
     * and share a task with each other.
     *
     * @param {GraphNode} node - The reference node to compare against other nodes in the graph.
     * @return {GraphNode[]} An array of nodes that are identical to the given node.
     */
    getIdenticalNodes(node: GraphNode): GraphNode[];
    /**
     * Checks whether all nodes in the collection have been processed.
     *
     * @return {boolean} Returns true if all nodes are processed, otherwise false.
     */
    isProcessed(): boolean;
    /**
     * Checks whether all layers in the graph have been processed.
     *
     * @return {boolean} Returns true if all graph layers are processed; otherwise, returns false.
     */
    graphDone(): boolean;
    /**
     * Sets the next GraphLayer in the sequence if it has a higher index than the current layer.
     * Updates the previous property if the given next layer has an existing previous layer.
     *
     * @param {GraphLayer} next - The next GraphLayer to be linked in the sequence.
     * @return {void} Does not return a value. Modifies the current layer's state.
     */
    setNext(next: GraphLayer): void;
    /**
     * Adds a node to the graph.
     *
     * @param {GraphNode} node - The node to be added to the graph.
     * @return {void}
     */
    add(node: GraphNode): void;
    /**
     * Starts the execution timer if it has not been started already.
     * Records the current timestamp as the start time.
     *
     * @return {number} The timestamp representing the start time in milliseconds.
     */
    start(): number;
    /**
     * Marks the end of a process by capturing the current timestamp and calculating the execution time if a start time exists.
     *
     * @return {number} The timestamp at which the process ended, or 0 if the start time is not defined.
     */
    end(): number;
    /**
     * Destroys the current graph layer and its associated resources.
     * This method recursively destroys all nodes in the current layer, clears the node list,
     * and ensures that any connected subsequent graph layers are also destroyed.
     * Additionally, it calls the decoupling logic to disconnect the current layer from its dependencies.
     *
     * @return {void} Does not return any value.
     */
    destroy(): void;
    /**
     * Returns an iterator for traversing through the graph layers.
     *
     * @return {GraphLayerIterator} An instance of GraphLayerIterator to traverse graph layers.
     */
    getIterator(): GraphLayerIterator;
    /**
     * Accepts a visitor object to traverse or perform operations on the current graph layer and its nodes.
     *
     * @param {GraphVisitor} visitor - The visitor instance implementing the visitLayer and visitNode behavior.
     * @return {void} Returns nothing.
     */
    accept(visitor: GraphVisitor): void;
    export(): {
        __index: number;
        __executionTime: number;
        __numberOfNodes: number;
        __hasNextLayer: boolean;
        __hasPrecedingLayer: boolean;
        __nodes: string[];
    };
    log(): void;
}

/**
 * Represents a synchronous graph layer derived from the GraphLayer base class.
 * This class is designed to execute graph nodes in a strictly synchronous manner.
 * Asynchronous functions are explicitly disallowed, ensuring consistency and predictability.
 */
declare class SyncGraphLayer extends GraphLayer {
    /**
     * Executes the processing logic of the current set of graph nodes. Iterates through all
     * nodes, skipping any that have already been processed, and executes their respective
     * logic to generate new nodes. Asynchronous functions are not supported and will
     * trigger an error log.
     *
     * @return {GraphNode[]} An array of newly generated graph nodes after executing the logic of each unprocessed node.
     */
    execute(): GraphNode[];
}

/**
 * An abstract class representing a GraphExporter.
 * This class defines a structure for exporting graph data in different formats,
 * depending on the implementations provided by subclasses.
 */
declare abstract class GraphExporter {
    abstract exportGraph(graph: SyncGraphLayer): any;
    abstract exportStaticGraph(graph: Task[]): any;
}

/**
 * GraphBuilder is an abstract base class designed to construct and manage a graph structure
 * composed of multiple layers. Subclasses are expected to implement the `compose` method
 * based on specific requirements. This class provides methods for adding nodes, managing
 * layers, and resetting the graph construction process.
 *
 * This class supports creating layered graph structures, dynamically adding layers and nodes,
 * and debugging graph-building operations.
 */
declare abstract class GraphBuilder {
    graph: GraphLayer | undefined;
    topLayerIndex: number;
    layers: GraphLayer[];
    debug: boolean;
    setDebug(value: boolean): void;
    getResult(): GraphLayer;
    /**
     * Composes a series of functions or operations.
     * This method should be implemented in the child class
     * to define custom composition logic.
     *
     * @return {any} The result of the composed operations or functions
     * when implemented in the child class.
     */
    compose(): void;
    /**
     * Adds a node to the appropriate layer of the graph.
     *
     * @param {GraphNode} node - The node to be added to the graph. The node contains
     *                           layer information that determines which layer it belongs to.
     * @return {void} Does not return a value.
     */
    addNode(node: GraphNode): void;
    /**
     * Adds multiple nodes to the graph.
     *
     * @param {GraphNode[]} nodes - An array of nodes to be added to the graph.
     * @return {void} This method does not return a value.
     */
    addNodes(nodes: GraphNode[]): void;
    /**
     * Adds a new layer to the graph at the specified index. If the graph does not exist,
     * it creates the graph using the specified index. Updates the graph's top layer index
     * and maintains the order of layers.
     *
     * @param {number} index - The index at which the new layer should be added to the graph.
     * @return {void} This method does not return a value.
     */
    addLayer(index: number): void;
    /**
     * Creates a new layer for the graph at the specified index.
     *
     * @param {number} index - The index of the layer to be created.
     * @return {GraphLayer} A new instance of the graph layer corresponding to the provided index.
     */
    createLayer(index: number): GraphLayer;
    /**
     * Retrieves a specific layer from the current set of layers.
     *
     * @param {number} layerIndex - The index of the layer to retrieve.
     * @return {*} The layer corresponding to the given index.
     */
    getLayer(layerIndex: number): GraphLayer;
    reset(): void;
}

/**
 * Abstract class representing a strategy for configuring and executing graph operations.
 * Provides a structure for managing graph builders, altering strategies, and updating the execution context.
 *
 * This class cannot be instantiated directly and must be extended by concrete implementations.
 */
declare abstract class GraphRunStrategy {
    graphBuilder: GraphBuilder;
    runInstance?: GraphRun;
    constructor();
    setRunInstance(runInstance: GraphRun): void;
    changeStrategy(builder: GraphBuilder): void;
    reset(): void;
    addNode(node: GraphNode): void;
    updateRunInstance(): void;
    abstract run(): void;
    abstract export(): any;
}

interface RunJson {
    __id: string;
    __label: string;
    __graph: any;
    __data: any;
}
/**
 * Represents a GraphRun instance which manages the execution of a graph-based workflow.
 * It utilizes a specific strategy and export mechanism to manage, execute, and export the graph data.
 */
declare class GraphRun {
    readonly id: string;
    graph: GraphLayer | undefined;
    strategy: GraphRunStrategy;
    exporter: GraphExporter | undefined;
    constructor(strategy: GraphRunStrategy);
    setGraph(graph: GraphLayer): void;
    addNode(node: GraphNode): void;
    run(): void | Promise<void>;
    destroy(): void;
    log(): void;
    export(): RunJson;
    setExporter(exporter: GraphExporter): void;
}

/**
 * Represents a routine in a graph structure with tasks and signal observation capabilities.
 * Routines are named entrypoint for a sub-graph, describing the purpose for the subsequent flow.
 * Since Task names are specific to the task it performs, it doesn't describe the overall flow.
 * Routines, therefore are used to assign names to sub-flows that can be referenced using that name instead of the name of the task(s).
 * Extends SignalEmitter to emit and handle signals related to the routine's lifecycle and tasks.
 */
declare class GraphRoutine extends SignalEmitter {
    readonly name: string;
    version: number;
    readonly description: string;
    readonly isMeta: boolean;
    tasks: Set<Task>;
    registered: boolean;
    registeredTasks: Set<Task>;
    observedSignals: Set<string>;
    constructor(name: string, tasks: Task[], description: string, isMeta?: boolean);
    /**
     * Iterates over each task in the `tasks` collection and applies the provided callback function.
     * If the callback returns a Promise, resolves all Promises concurrently.
     *
     * @param {function} callBack - A function to be executed on each task from the `tasks` collection.
     *                              The callback receives the current task as its argument.
     * @return {Promise<void>} A Promise that resolves once all callback executions, including asynchronous ones, are complete.
     */
    forEachTask(callBack: (task: Task) => any): Promise<void>;
    /**
     * Sets global Version.
     * @param version The Version.
     */
    setVersion(version: number): void;
    /**
     * Subscribes the current instance to the specified signals, enabling it to observe them.
     *
     * @param {...string} signals - The names of the signals to observe.
     * @return {this} Returns the instance to allow for method chaining.
     */
    doOn(...signals: string[]): this;
    /**
     * Unsubscribes from all observed signals and clears the internal collection
     * of observed signals. This ensures that the instance is no longer listening
     * or reacting to any previously subscribed signals.
     *
     * @return {this} Returns the current instance for chaining purposes.
     */
    unsubscribeAll(): this;
    /**
     * Unsubscribes the current instance from the specified signals.
     *
     * @param {...string} signals - The signals to unsubscribe from.
     * @return {this} The current instance for method chaining.
     */
    unsubscribe(...signals: string[]): this;
    /**
     * Cleans up resources and emits an event indicating the destruction of the routine.
     *
     * This method unsubscribes from all events, clears the tasks list,
     * and emits a "meta.routine.destroyed" event with details of the destruction.
     *
     * @return {void}
     */
    destroy(): void;
}

/**
 * Represents a runner for managing and executing tasks or routines within a graph.
 * The `GraphRunner` extends `SignalEmitter` to include signal-based event-driven mechanisms.
 */
declare class GraphRunner extends SignalEmitter {
    currentRun: GraphRun;
    debug: boolean;
    verbose: boolean;
    isRunning: boolean;
    readonly isMeta: boolean;
    strategy: GraphRunStrategy;
    /**
     * Constructs a runner.
     * @param isMeta Meta flag (default false).
     * @edge Creates 'Start run' meta-task chained to registry gets.
     */
    constructor(isMeta?: boolean);
    /**
     * Adds tasks or routines to the current execution pipeline. Supports both individual tasks,
     * routines, or arrays of tasks and routines. Handles metadata and execution context management.
     *
     * @param {Task|GraphRoutine|(Task|GraphRoutine)[]} tasks - The task(s) or routine(s) to be added.
     * It can be a single task, a single routine, or an array of tasks and routines.
     * @param {AnyObject} [context={}] - Optional context object to provide execution trace and metadata.
     * Used to propagate information across task or routine executions.
     * @return {void} - This method does not return a value.
     */
    addTasks(tasks: Task | GraphRoutine | (Task | GraphRoutine)[], context?: AnyObject): void;
    /**
     * Executes the provided tasks or routines. Maintains the execution state
     * and handles synchronous or asynchronous processing.
     *
     * @param {Task|GraphRoutine|(Task|GraphRoutine)[]} [tasks] - A single task, a single routine, or an array of tasks or routines to execute. Optional.
     * @param {AnyObject} [context] - An optional context object to be used during task execution.
     * @return {GraphRun|Promise<GraphRun>} - Returns a `GraphRun` instance if the execution is synchronous, or a `Promise` resolving to a `GraphRun` for asynchronous execution.
     */
    run(tasks?: Task | GraphRoutine | (Task | GraphRoutine)[], context?: AnyObject): GraphRun | Promise<GraphRun>;
    /**
     * Executes the provided asynchronous operation and resets the state afterwards.
     *
     * @param {Promise<void>} run - A promise representing the asynchronous operation to execute.
     * @return {Promise<GraphRun>} A promise that resolves to the result of the reset operation after the asynchronous operation completes.
     */
    runAsync(run: Promise<void>): Promise<GraphRun>;
    /**
     * Resets the current state of the graph, creating a new GraphRun instance
     * and returning the previous run instance.
     * If the debug mode is not enabled, it will destroy the existing resources.
     *
     * @return {GraphRun} The last GraphRun instance before the reset.
     */
    reset(): GraphRun;
    setDebug(value: boolean): void;
    setVerbose(value: boolean): void;
    destroy(): void;
    /**
     * Sets the strategy to be used for running the graph and initializes
     * the current run with the provided strategy if no process is currently running.
     *
     * @param {GraphRunStrategy} strategy - The strategy to use for running the graph.
     * @return {void}
     */
    setStrategy(strategy: GraphRunStrategy): void;
}

interface EmitOptions {
    squash?: boolean;
    squashId?: string | null;
    groupId?: string | null;
    mergeFunction?: ((oldContext: AnyObject, ...newContext: AnyObject[]) => AnyObject) | null;
    debounce?: boolean;
    throttle?: boolean;
    delayMs?: number;
    schedule?: boolean;
    exactDateTime?: Date | null;
    throttleBatch?: number;
    flushStrategy?: string;
}
type SignalDeliveryMode = "single" | "broadcast";
type SignalReceiverFilter = {
    serviceNames?: string[];
    serviceInstanceIds?: string[];
    origins?: string[];
    roles?: string[];
    protocols?: string[];
    runtimeStates?: string[];
};
type SignalMetadata = {
    deliveryMode?: SignalDeliveryMode;
    broadcastFilter?: SignalReceiverFilter | null;
};
type PassiveSignalListener = (signal: string, context: AnyObject, metadata: SignalMetadata | null) => void;
type SignalDefinitionInput = string | ({
    name: string;
} & SignalMetadata);
type FlushStrategyName = string;
interface FlushStrategy {
    intervalMs: number;
    maxBatchSize: number;
}
/**
 * This class manages signals and observers, enabling communication across different parts of an application.
 * It follows a singleton design pattern, allowing for centralized signal management.
 */
declare class SignalBroker {
    static instance_: SignalBroker;
    static get instance(): SignalBroker;
    debug: boolean;
    verbose: boolean;
    setDebug(value: boolean): void;
    setVerbose(value: boolean): void;
    runner: GraphRunner | undefined;
    metaRunner: GraphRunner | undefined;
    throttleEmitters: Map<string, any>;
    throttleQueues: Map<string, any>;
    getSignalsTask: Task | undefined;
    registerSignalTask: Task | undefined;
    signalObservers: Map<string, {
        fn: (runner: GraphRunner, tasks: (Task | GraphRoutine)[], context: AnyObject) => void;
        tasks: Set<Task | GraphRoutine>;
        registered: boolean;
    }>;
    emittedSignalsRegistry: Set<string>;
    signalMetadataRegistry: Map<string, SignalMetadata>;
    passiveSignalListeners: Map<string, PassiveSignalListener>;
    private flushStrategies;
    private strategyData;
    private strategyTimers;
    private isStrategyFlushing;
    private readonly defaultStrategyName;
    constructor();
    private resolveSignalMetadataKey;
    private normalizeSignalMetadata;
    setSignalMetadata(signal: string, metadata?: SignalMetadata | null): void;
    getSignalMetadata(signal: string): SignalMetadata | undefined;
    logMemoryFootprint(label?: string): void;
    /**
     * Validates the provided signal name string to ensure it adheres to specific formatting rules.
     * Throws an error if any of the validation checks fail.
     *
     * @param {string} signalName - The signal name to be validated.
     * @return {void} - Returns nothing if the signal name is valid.
     * @throws {Error} - Throws an error if the signal name is longer than 100 characters, contains spaces,
     *                   contains backslashes, or contains uppercase letters in restricted parts of the name.
     */
    validateSignalName(signalName: string): void;
    /**
     * Initializes with runners.
     * @param runner Standard runner for user signals.
     * @param metaRunner Meta runner for 'meta.' signals (suppresses further meta-emits).
     */
    bootstrap(runner: GraphRunner, metaRunner: GraphRunner): void;
    /**
     * Initializes and sets up the various tasks for managing and processing signals.
     *
     * @return {void} This method does not return a value.
     */
    init(): void;
    setFlushStrategy(name: FlushStrategyName, config: {
        intervalMs: number;
        maxBatchSize?: number;
    }): void;
    updateFlushStrategy(name: FlushStrategyName, config: FlushStrategy): void;
    removeFlushStrategy(name: FlushStrategyName): void;
    getFlushStrategies(): Record<FlushStrategyName, FlushStrategy>;
    private readonly MAX_FLUSH_DURATION_MS;
    squash(signal: string, context: AnyObject, options?: EmitOptions): void;
    private flushGroup;
    private flushStrategy;
    clearSquashState(): void;
    private clearScheduledState;
    private scheduledBuckets;
    private scheduleTimer;
    schedule(signal: string, context: AnyObject, options?: EmitOptions): AbortController;
    private flushScheduled;
    private debouncedEmitters;
    private readonly MAX_DEBOUNCERS;
    private clearDebounceState;
    private clearThrottleState;
    debounce(signal: string, context: any, options?: {
        delayMs: number;
    }): void;
    throttle(signal: string, context: any, options?: EmitOptions): void;
    /**
     * Emits `signal` repeatedly with a fixed interval.
     *
     * @param signal
     * @param context
     * @param intervalMs
     * @param leading  If true, emits immediately (unless a startDateTime is given and we are before it).
     * @param startDateTime  Optional absolute Date when the *first* emission after `leading` should occur.
     * @returns a handle with `clear()` to stop the loop.
     */
    interval(signal: string, context: AnyObject, intervalMs?: number, leading?: boolean, startDateTime?: Date): ThrottleHandle;
    /**
     * Emits a signal with the specified context, triggering any associated handlers for that signal.
     *
     * @param {string} signal - The name of the signal to emit.
     * @param {AnyObject} [context={}] - An optional context object containing additional information or metadata
     * associated with the signal. If the context includes a `__routineExecId`, it will be handled accordingly.
     * @param options
     * @return {void} This method does not return a value.
     */
    emit(signal: string, context?: AnyObject, options?: EmitOptions): void;
    /**
     * Executes a signal by emitting events, updating context, and invoking listeners.
     * Creates a new execution trace if necessary and updates the context with relevant metadata.
     * Handles specific, hierarchy-based, and wildcard signals.
     *
     * @param {string} signal - The signal name to be executed, potentially including namespaces or tags (e.g., "meta.*" or "signal:type").
     * @param {AnyObject} context - An object containing relevant metadata and execution details used for handling the signal.
     * @return {boolean} Returns true if any listeners were successfully executed, otherwise false.
     */
    execute(signal: string, context: AnyObject): boolean;
    /**
     * Executes the tasks associated with a given signal and context.
     * It processes both normal and meta tasks depending on the signal type
     * and the availability of the appropriate runner.
     *
     * @param {string} signal - The signal identifier that determines which tasks to execute.
     * @param {AnyObject} context - The context object passed to the task execution function.
     * @return {boolean} - Returns true if tasks were executed; otherwise, false.
     */
    executeListener(signal: string, context: AnyObject): boolean;
    /**
     * Adds a signal to the signalObservers for tracking and execution.
     * Performs validation on the signal name and emits a meta signal event when added.
     * If the signal contains a namespace (denoted by a colon ":"), its base signal is
     * also added if it doesn't already exist.
     *
     * @param {string} signal - The name of the signal to be added.
     * @return {void} This method does not return any value.
     */
    addSignal(signal: string, metadata?: SignalMetadata | null): void;
    /**
     * Observes a signal with a routine/task.
     * @param signal The signal (e.g., 'domain.action', 'domain.*' for wildcards).
     * @param routineOrTask The observer.
     * @edge Duplicates ignored; supports wildcards for broad listening.
     */
    observe(signal: string, routineOrTask: Task | GraphRoutine, metadata?: SignalMetadata | null): void;
    addPassiveSignalListener(listener: PassiveSignalListener): () => void;
    private notifyPassiveSignalListeners;
    registerEmittedSignal(signal: string, metadata?: SignalMetadata | null): void;
    /**
     * Unsubscribes a routine/task from a signal.
     * @param signal The signal.
     * @param routineOrTask The observer.
     * @edge Removes all instances if duplicate; deletes if empty.
     */
    unsubscribe(signal: string, routineOrTask: Task | GraphRoutine): void;
    /**
     * Lists all observed signals.
     * @returns Array of signals.
     */
    listObservedSignals(): string[];
    listEmittedSignals(): string[];
    reset(): void;
    shutdown(): void;
}

/**
 * Abstract class representing a signal emitter.
 * Allows emitting events or signals, with the option to suppress emissions if desired.
 */
declare abstract class SignalEmitter {
    silent: boolean;
    /**
     * Constructor for signal emitters.
     * @param silent If true, suppresses all emissions (e.g., for meta-runners to avoid loops; affects all emits).
     */
    constructor(silent?: boolean);
    /**
     * Emits a signal via the broker.
     * @param signal The signal name.
     * @param data Optional payload (defaults to empty object).
     * @param options
     */
    emit(signal: string, data?: AnyObject, options?: EmitOptions): void;
    /**
     * Emits a signal via the broker if not silent.
     * @param signal The signal name.
     * @param data Optional payload (defaults to empty object).
     * @param options
     */
    emitMetrics(signal: string, data?: AnyObject, options?: EmitOptions): void;
}

type SchemaType = "string" | "number" | "boolean" | "array" | "object" | "any";
type SchemaConstraints = {
    min?: number;
    max?: number;
    minLength?: number;
    maxLength?: number;
    pattern?: string;
    enum?: any[];
    multipleOf?: number;
    format?: "email" | "url" | "date-time" | "uuid" | "custom";
    oneOf?: any[];
};
type SchemaDefinition = {
    type: SchemaType;
    required?: string[];
    properties?: {
        [key: string]: Schema;
    };
    items?: Schema;
    constraints?: SchemaConstraints;
    description?: string;
    strict?: boolean;
};
type SchemaMap = Record<string, SchemaDefinition>;
type Schema = SchemaDefinition | SchemaMap;

interface Intent {
    name: string;
    description?: string;
    input?: SchemaDefinition;
    output?: SchemaDefinition;
}
interface InquiryOptions {
    timeout?: number;
    rejectOnTimeout?: boolean;
    includePendingTasks?: boolean;
    requireComplete?: boolean;
}
declare class InquiryBroker extends SignalEmitter {
    static instance_: InquiryBroker;
    static get instance(): InquiryBroker;
    debug: boolean;
    verbose: boolean;
    setDebug(value: boolean): void;
    setVerbose(value: boolean): void;
    validateInquiryName(inquiryName: string): void;
    runner: GraphRunner | undefined;
    metaRunner: GraphRunner | undefined;
    inquiryObservers: Map<string, {
        fn: (runner: GraphRunner, tasks: Task[], context: AnyObject) => void;
        tasks: Set<Task>;
        registered: boolean;
    }>;
    intents: Map<string, Intent>;
    /**
     * Initializes with runners.
     * @param runner Standard runner for user signals.
     * @param metaRunner Meta runner for 'meta.' signals (suppresses further meta-emits).
     */
    bootstrap(runner: GraphRunner, metaRunner: GraphRunner): void;
    init(): void;
    /**
     * Observes an inquiry with a routine/task.
     * @param inquiry The inquiry (e.g., 'domain.action', 'domain.*' for wildcards).
     * @param task The observer.
     * @edge Duplicates ignored; supports wildcards for broad listening.
     */
    observe(inquiry: string, task: Task): void;
    /**
     * Unsubscribes a routine/task from an inquiry.
     * @param inquiry The inquiry.
     * @param task The observer.
     * @edge Removes all instances if duplicate; deletes if empty.
     */
    unsubscribe(inquiry: string, task: Task): void;
    addInquiry(inquiry: string): void;
    addIntent(intent: Intent): void;
    inquire(inquiry: string, context: AnyObject, options?: InquiryOptions): Promise<AnyObject>;
    reset(): void;
}

/**
 * Represents a node in a graph structure used for executing tasks.
 * A Node is a container for a task and its associated context, providing
 * methods for executing the task and managing its lifecycle.
 *
 * It extends the SignalEmitter class to emit and handle signals related to
 * the node's lifecycle, such as "meta.node.started" and "meta.node.completed".
 *
 * It also implements the Graph interface, allowing it to be used as a part of
 * a graph structure, such as a GraphLayer or GraphRoutine.
 *
 * @extends SignalEmitter
 * @implements Graph
 */
declare class GraphNode extends SignalEmitter implements Graph {
    id: string;
    routineExecId: string;
    executionTraceId: string;
    task: Task;
    context: GraphContext;
    layer: GraphLayer | undefined;
    divided: boolean;
    splitGroupId: string;
    processing: boolean;
    subgraphComplete: boolean;
    graphComplete: boolean;
    result: TaskResult;
    retryCount: number;
    retryDelay: number;
    retries: number;
    previousNodes: GraphNode[];
    nextNodes: GraphNode[];
    executionTime: number;
    executionStart: number;
    failed: boolean;
    errored: boolean;
    destroyed: boolean;
    debug: boolean;
    verbose: boolean;
    constructor(task: Task, context: GraphContext, routineExecId: string, prevNodes?: GraphNode[], debug?: boolean, verbose?: boolean);
    setDebug(value: boolean): void;
    isUnique(): boolean;
    isMeta(): boolean;
    isProcessed(): boolean;
    isProcessing(): boolean;
    subgraphDone(): boolean;
    graphDone(): boolean;
    /**
     * Compares the current GraphNode instance with another GraphNode to determine if they are considered equal.
     *
     * @param {GraphNode} node - The GraphNode object to compare with the current instance.
     * @return {boolean} Returns true if the nodes share the same task, context, and belong to the same graph; otherwise, false.
     */
    isEqualTo(node: GraphNode): boolean;
    /**
     * Determines if the given node is part of the same graph as the current node.
     *
     * @param {GraphNode} node - The node to compare with the current node.
     * @return {boolean} Returns true if the provided node is part of the same graph
     *                   (i.e., has the same routineExecId), otherwise false.
     */
    isPartOfSameGraph(node: GraphNode): boolean;
    /**
     * Determines whether the current instance shares a task with the provided node.
     *
     * @param {GraphNode} node - The graph node to compare with the current instance.
     * @return {boolean} Returns true if the task names of both nodes match, otherwise false.
     */
    sharesTaskWith(node: GraphNode): boolean;
    /**
     * Determines whether the current node shares the same context as the specified node.
     *
     * @param {GraphNode} node - The graph node to compare with the current node's context.
     * @return {boolean} True if both nodes share the same context; otherwise, false.
     */
    sharesContextWith(node: GraphNode): boolean;
    getLayerIndex(): number;
    getConcurrency(): number;
    /**
     * Retrieves the tag associated with the current task and context.
     *
     * @return {string} The tag retrieved from the task within the given context.
     */
    getTag(): string;
    private classifyBusinessRoutineLifecycle;
    private getBusinessRoutineLifecycleDecision;
    private rememberBusinessRoutineLifecycleDecision;
    /**
     * Schedules the current node/task on the specified graph layer if applicable.
     *
     * This method assesses whether the current node/task should be scheduled
     * on the given graph layer. It ensures that tasks are only scheduled
     * under certain conditions, such as checking if the task shares
     * execution contexts or dependencies with other nodes, and handles
     * various metadata emissions and context updates during the scheduling process.
     *
     * @param {GraphLayer} layer - The graph layer on which the current task should be scheduled.
     * @returns {void} Does not return a value.
     */
    scheduleOn(layer: GraphLayer): void;
    /**
     * Starts the execution process by initializing the execution start timestamp,
     * emitting relevant metadata, and logging debug information if applicable.
     *
     * The method performs the following actions:
     * 1. Sets the execution start timestamp if it's not already initialized.
     * 2. Emits metrics with metadata about the routine execution starting, including additional data if there are no previous nodes.
     * 3. Optionally logs debug or verbose information based on the current settings.
     * 4. Emits additional metrics to indicate that the execution has started.
     *
     * @return {number} The timestamp indicating when the execution started.
     */
    start(): number;
    /**
     * Marks the end of an execution process, performs necessary cleanup, emits
     * metrics with associated metadata, and signals the completion of execution.
     * Also handles specific cases when the graph completes.
     *
     * @return {number} The timestamp corresponding to the end of execution. If execution
     * was not started, it returns 0.
     */
    end(): number;
    /**
     * Executes the main logic of the task, including input validation, processing, and post-processing.
     * Handles both synchronous and asynchronous workflows.
     *
     * @return {Array|Promise|undefined} Returns the next nodes to process if available.
     * If asynchronous processing is required, it returns a Promise that resolves to the next nodes.
     * Returns undefined in case of an error during input validation or preconditions that prevent processing.
     */
    execute(): GraphNode[] | Promise<GraphNode[]>;
    /**
     * Executes an asynchronous workflow that processes a result and retries on errors.
     * The method handles different result states, checks for error properties, and invokes
     * error handling when necessary.
     *
     * @return {Promise<void>} A promise that resolves when the operation completes successfully,
     * or rejects if an unhandled error occurs.
     */
    workAsync(): Promise<void>;
    /**
     * Executes an asynchronous operation, processes the result, and determines the next nodes to execute.
     * This method will manage asynchronous work, handle post-processing of results, and ensure proper handling of both synchronous and asynchronous next node configurations.
     *
     * @return {Promise<any>} A promise resolving to the next nodes to be executed. Can be the result of post-processing or a directly resolved next nodes object.
     */
    executeAsync(): Promise<GraphNode[]>;
    /**
     * Executes the task associated with the current instance, using the given context,
     * progress callback, and metadata. If the task fails or an error occurs, it attempts
     * to retry the execution. If the retry is not successful, it propagates the error and
     * returns the result.
     *
     * @return {TaskResult | Promise<TaskResult>} The result of the task execution, or a
     * promise that resolves to the task result. This includes handling for retries on
     * failure and error propagation.
     */
    work(): TaskResult | Promise<TaskResult>;
    inquire(inquiry: string, context: AnyObject, options: InquiryOptions): Promise<any>;
    /**
     * Emits a signal along with its associated metadata. The metadata includes
     * task-specific information such as task name, version, execution ID, and
     * additional context metadata like routine execution ID and execution trace ID.
     * This method is designed to enrich emitted signals with relevant details
     * before broadcasting them.
     *
     * @param {string} signal - The name of the signal to be emitted.
     * @param {AnyObject} data - The data object to be sent along with the signal. Metadata
     * will be injected into this object before being emitted.
     * @param options
     * @return {void} No return value.
     */
    emitWithMetadata(signal: string, data: AnyObject, options?: EmitOptions): void;
    /**
     * Emits metrics with additional metadata describing the task execution and context.
     *
     * @param {string} signal - The signal name being emitted.
     * @param {AnyObject} data - The data associated with the signal emission, enriched with metadata.
     * @param options
     * @return {void} Emits the signal with enriched data and does not return a value.
     */
    emitMetricsWithMetadata(signal: string, data: AnyObject, options?: EmitOptions): void;
    /**
     * Updates the progress of a task and emits metrics with associated metadata.
     *
     * @param {number} progress - A number representing the progress value, which will be clamped between 0 and 1.
     * @return {void} This method does not return a value.
     */
    onProgress(progress: number): void;
    /**
     * Processes the result of the current operation, validates it, and determines the next set of nodes.
     *
     * This method ensures that results of certain types such as strings or arrays
     * are flagged as errors. It divides the current context into subsequent nodes
     * for further processing. If the division returns a promise, it delegates the
     * processing to `postProcessAsync`. For synchronous division, it sets the
     * `nextNodes` and finalizes the operation.
     *
     * @return {(Array|undefined)} Returns an array of next nodes for further processing,
     * or undefined if no further processing is required.
     */
    postProcess(): GraphNode[] | Promise<GraphNode[]>;
    /**
     * Asynchronously processes and finalizes the provided graph nodes.
     *
     * @param {Promise<GraphNode[]>} nextNodes A promise that resolves to an array of graph nodes to be processed.
     * @return {Promise<GraphNode[]>} A promise that resolves to the processed array of graph nodes.
     */
    postProcessAsync(nextNodes: Promise<GraphNode[]>): Promise<GraphNode[]>;
    /**
     * Finalizes the current task execution by determining if the task is complete, handles any errors or failures,
     * emits relevant signals based on the task outcomes, and ensures proper end of the task lifecycle.
     *
     * @return {void} Does not return a value.
     */
    finalize(): void;
    /**
     * Handles an error event, processes the error, and updates the state accordingly.
     *
     * @param {unknown} error - The error object or message that occurred.
     * @param {AnyObject} [errorData={}] - Additional error data to include in the result.
     * @return {void} This method does not return any value.
     */
    onError(error: unknown, errorData?: AnyObject): void;
    /**
     * Retries a task based on the defined retry count and delay time. If the retry count is 0, it immediately resolves with the provided previous result.
     *
     * @param {any} [prevResult] - The result from a previous attempt, if any, to return when no retries are performed.
     * @return {Promise<TaskResult>} - A promise that resolves with the result of the retried task or the previous result if no retries occur.
     */
    retry(prevResult?: any): Promise<TaskResult>;
    /**
     * Retries an asynchronous operation and returns its result.
     * If the retry count is zero, the method immediately returns the provided previous result.
     *
     * @param {any} [prevResult] - The optional result from a previous operation attempt, if applicable.
     * @return {Promise<TaskResult>} A promise that resolves to the result of the retried operation.
     */
    retryAsync(prevResult?: any): Promise<TaskResult>;
    delayRetry(): Promise<void>;
    /**
     * Processes the result of a task by generating new nodes based on the task output.
     * The method handles synchronous and asynchronous generators, validates task output,
     * and creates new nodes accordingly. If errors occur, the method attempts to handle them
     * by generating alternative task nodes.
     *
     * @return {GraphNode[] | Promise<GraphNode[]>} Returns an array of generated GraphNode objects
     * (synchronously or wrapped in a Promise) based on the task result, or propagates errors if validation fails.
     */
    divide(): GraphNode[] | Promise<GraphNode[]>;
    /**
     * Processes an asynchronous iterator result, validates its output, and generates new graph nodes accordingly.
     * Additionally, continues to process and validate results from an asynchronous generator.
     *
     * @param {Promise<IteratorResult<any>>} current - A promise resolving to the current step result from an asynchronous iterator.
     * @return {Promise<GraphNode[]>} A promise resolving to an array of generated GraphNode objects based on validated outputs.
     */
    divideAsync(current: Promise<IteratorResult<any>>): Promise<GraphNode[]>;
    /**
     * Generates new nodes based on the provided result and task configuration.
     *
     * @param {any} result - The result of the previous operation, which determines the configuration and context for new nodes. It can be a boolean or an object containing details like failure, errors, or metadata.
     * @return {GraphNode[]} An array of newly generated graph nodes configured based on the task and context.
     */
    generateNewNodes(result: any): GraphNode[];
    /**
     * Executes the differentiation process based on a given task and updates the instance properties accordingly.
     *
     * @param {Task} task - The task object containing information such as retry count, retry delay, and metadata status.
     * @return {GraphNode} The updated instance after processing the task.
     */
    differentiate(task: Task): GraphNode;
    /**
     * Migrates the current instance to a new context and returns the updated instance.
     *
     * @param {any} ctx - The context data to be used for migration.
     * @return {GraphNode} The updated instance after migration.
     */
    migrate(ctx: any): GraphNode;
    /**
     * Splits the current node into a new group identified by the provided ID.
     *
     * @param {string} id - The unique identifier for the new split group.
     * @return {GraphNode} The current instance of the GraphNode with the updated split group ID.
     */
    split(id: string): GraphNode;
    /**
     * Creates a new instance of the GraphNode with the current node's properties.
     * This method allows for duplicating the existing graph node.
     *
     * @return {GraphNode} A new instance of GraphNode that is a copy of the current node.
     */
    clone(): GraphNode;
    /**
     * Consumes the given graph node by combining contexts, merging previous nodes,
     * and performing associated operations on the provided node.
     *
     * @param {GraphNode} node - The graph node to be consumed.
     * @return {void} This method does not return a value.
     */
    consume(node: GraphNode): void;
    /**
     * Changes the identity of the current instance by updating the `id` property.
     *
     * @param {string} id - The new identity value to be assigned.
     * @return {void} Does not return a value.
     */
    changeIdentity(id: string): void;
    /**
     * Completes the subgraph for the current node and recursively for its previous nodes
     * once all next nodes have their subgraphs marked as done. If there are no previous nodes,
     * it completes the entire graph.
     *
     * @return {void} Does not return a value.
     */
    completeSubgraph(): void;
    /**
     * Completes the current graph by setting a flag indicating the graph has been completed
     * and recursively completes all subsequent nodes in the graph.
     *
     * @return {void} Does not return a value.
     */
    completeGraph(): void;
    /**
     * Destroys the current instance by releasing resources, breaking references,
     * and resetting properties to ensure proper cleanup.
     *
     * @return {void} No return value.
     */
    destroy(): void;
    /**
     * Retrieves an iterator for traversing through the graph nodes.
     *
     * @return {GraphNodeIterator} An iterator instance specific to this graph node.
     */
    getIterator(): GraphNodeIterator;
    /**
     * Applies a callback function to each node in the `nextNodes` array and returns
     * the resulting array from the map operation.
     *
     * @param {function} callback - A function to execute on each `GraphNode` in the `nextNodes` array.
     * The function receives a `GraphNode` as its argument.
     * @return {Array} The resulting array after applying the callback function to each node in `nextNodes`.
     */
    mapNext(callback: (node: GraphNode) => any): any[];
    /**
     * Accepts a visitor object and calls its visitNode method with the current instance.
     *
     * @param {GraphVisitor} visitor - The visitor instance implementing the GraphVisitor interface.
     * @return {void} This method does not return a value.
     */
    accept(visitor: GraphVisitor): void;
    /**
     * Exports the current object's state and returns it in a serialized format.
     * The exported object contains metadata, task details, context information, execution times, node relationships, routine execution status, and other state information.
     *
     * @return {Object} An object representing the current state.
     */
    export(): {
        __id: string;
        __task: AnyObject;
        __context: {
            id: string;
            context: AnyObject;
        };
        __result: TaskResult;
        __executionTime: number;
        __executionStart: number;
        __executionEnd: number;
        __nextNodes: string[];
        __previousNodes: string[];
        __routineExecId: string;
        __isProcessing: boolean;
        __isMeta: boolean;
        __graphComplete: boolean;
        __failed: boolean;
        __errored: boolean;
        __isUnique: boolean;
        __splitGroupId: string;
        __tag: string;
    };
    lightExport(): {
        __id: string;
        __task: {
            __name: string;
            __version: number;
        };
        __context: {
            id: string;
            context: AnyObject;
        };
        __executionTime: number;
        __executionStart: number;
        __nextNodes: string[];
        __previousNodes: string[];
        __routineExecId: string;
        __isProcessing: boolean;
        __graphComplete: boolean;
        __isMeta: boolean;
        __failed: boolean;
        __errored: boolean;
        __isUnique: boolean;
        __splitGroupId: string;
        __tag: string;
    };
    log(): void;
}

declare abstract class GraphVisitor {
    abstract visitLayer(layer: GraphLayer): any;
    abstract visitNode(node: GraphNode): any;
    abstract visitTask(task: Task): any;
}

/**
 * TaskIterator is a custom iterator for traversing over a set of tasks.
 * It provides mechanisms to iterate through tasks in a layered manner,
 * where each task can branch out to other tasks forming multiple layers.
 */
declare class TaskIterator implements Iterator {
    currentTask: Task | undefined;
    currentLayer: Set<Task>;
    nextLayer: Set<Task>;
    iterator: {
        next: () => {
            value: Task | undefined;
        };
    };
    constructor(task: Task);
    hasNext(): boolean;
    next(): Task | undefined;
}

interface RuntimeTools {
    helpers: Record<string, HelperInvoker>;
    globals: Record<string, unknown>;
}
type HelperFunction = (context: AnyObject, emit: (signal: string, context: AnyObject) => void, inquire: (inquiry: string, context: AnyObject, options: InquiryOptions) => Promise<AnyObject>, tools: RuntimeTools, progressCallback: (progress: number) => void) => TaskResult;
type HelperInvoker = (context?: AnyObject) => TaskResult | Promise<TaskResult>;
interface ToolDependencyOwner {
    readonly isMeta: boolean;
    helperAliases: Map<string, string>;
    globalAliases: Map<string, string>;
}
declare class GlobalDefinition {
    readonly name: string;
    readonly description: string;
    readonly version: number;
    readonly isMeta: boolean;
    readonly value: unknown;
    destroyed: boolean;
    constructor(name: string, value: unknown, description?: string, isMeta?: boolean);
    destroy(): void;
    export(): Record<string, unknown>;
}
declare class HelperDefinition implements ToolDependencyOwner {
    readonly name: string;
    readonly description: string;
    readonly version: number;
    readonly isMeta: boolean;
    readonly helperFunction: HelperFunction;
    readonly helperAliases: Map<string, string>;
    readonly globalAliases: Map<string, string>;
    destroyed: boolean;
    constructor(name: string, helperFunction: HelperFunction, description?: string, isMeta?: boolean);
    usesHelpers(helpers: Record<string, HelperDefinition | undefined>): this;
    usesGlobals(globals: Record<string, GlobalDefinition | undefined>): this;
    execute(context: AnyObject, emit: (signal: string, context: AnyObject) => void, inquire: (inquiry: string, context: AnyObject, options: InquiryOptions) => Promise<AnyObject>, progressCallback: (progress: number) => void): TaskResult;
    destroy(): void;
    export(): Record<string, unknown>;
}

type TaskFunction = (context: AnyObject, emit: (signal: string, context: AnyObject) => void, inquire: (inquiry: string, context: AnyObject, options: InquiryOptions) => Promise<AnyObject>, tools: RuntimeTools, progressCallback: (progress: number) => void) => TaskResult;
type TaskResult = boolean | AnyObject | Generator | Promise<any> | void;
type ThrottleTagGetter = (context?: AnyObject, task?: Task) => string;
/**
 * Represents a task with a specific behavior, configuration, and lifecycle management.
 * Tasks are used to define units of work that can be executed and orchestrated.
 * Tasks can specify input/output validation, concurrency, retry policies, and more.
 * This class extends SignalEmitter and implements Graph, allowing tasks to emit and observe signals.
 */
declare class Task extends SignalEmitter implements Graph, ToolDependencyOwner {
    readonly name: string;
    readonly description: string;
    version: number;
    concurrency: number;
    timeout: number;
    readonly isMeta: boolean;
    readonly isSubMeta: boolean;
    readonly isHidden: boolean;
    readonly isUnique: boolean;
    readonly throttled: boolean;
    readonly isSignal: boolean;
    readonly isDeputy: boolean;
    readonly isEphemeral: boolean;
    readonly isDebounce: boolean;
    inputContextSchema: Schema;
    hasExplicitInputContextSchema: boolean;
    validateInputContext: boolean;
    outputContextSchema: Schema;
    hasExplicitOutputContextSchema: boolean;
    validateOutputContext: boolean;
    readonly retryCount: number;
    readonly retryDelay: number;
    readonly retryDelayMax: number;
    readonly retryDelayFactor: number;
    layerIndex: number;
    progressWeight: number;
    nextTasks: Set<Task>;
    predecessorTasks: Set<Task>;
    destroyed: boolean;
    register: boolean;
    registered: boolean;
    registeredSignals: Set<string>;
    taskMapRegistration: Set<string>;
    emitsSignals: Set<string>;
    signalsToEmitAfter: Set<string>;
    signalsToEmitOnFail: Set<string>;
    observedSignals: Set<string>;
    handlesIntents: Set<string>;
    inquiresIntents: Set<string>;
    helperAliases: Map<string, string>;
    globalAliases: Map<string, string>;
    readonly taskFunction: TaskFunction;
    /**
     * Constructs an instance of the task with the specified properties and configuration options.
     *
     * @param {string} name - The name of the task.
     * @param {TaskFunction} task - The function that represents the task logic.
     * @param {string} [description=""] - A description of the task.
     * @param {number} [concurrency=0] - The number of concurrent executions allowed for the task.
     * @param {number} [timeout=0] - The maximum execution time for the task in milliseconds.
     * @param {boolean} [register=true] - Indicates if the task should be registered or not.
     * @param {boolean} [isUnique=false] - Specifies if the task should only allow one instance to exist at any time.
     * @param {boolean} [isMeta=false] - Indicates if the task is a meta-task.
     * @param {boolean} [isSubMeta=false] - Indicates if the task is a sub-meta-task.
     * @param {boolean} [isHidden=false] - Determines if the task is hidden and not exposed publicly.
     * @param {ThrottleTagGetter} [getTagCallback=undefined] - A callback to generate a throttle tag for the task.
     * @param {Schema} [inputSchema=undefined] - The input schema for validating the task's input context.
     * @param {boolean} [validateInputContext=false] - Specifies if the input context should be validated against the input schema.
     * @param {Schema} [outputSchema=undefined] - The output schema for validating the task's output context.
     * @param {boolean} [validateOutputContext=false] - Specifies if the output context should be validated against the output schema.
     * @param {number} [retryCount=0] - The number of retry attempts allowed for the task in case of failure.
     * @param {number} [retryDelay=0] - The initial delay (in milliseconds) between retry attempts.
     * @param {number} [retryDelayMax=0] - The maximum delay (in milliseconds) allowed between retries.
     * @param {number} [retryDelayFactor=1] - The factor by which the retry delay increases after each attempt.
     */
    constructor(name: string, task: TaskFunction, description?: string, concurrency?: number, timeout?: number, register?: boolean, isUnique?: boolean, isMeta?: boolean, isSubMeta?: boolean, isHidden?: boolean, getTagCallback?: ThrottleTagGetter | undefined, inputSchema?: Schema, validateInputContext?: boolean, outputSchema?: Schema, validateOutputContext?: boolean, retryCount?: number, retryDelay?: number, retryDelayMax?: number, retryDelayFactor?: number);
    clone(traverse?: boolean, includeSignals?: boolean): Task;
    /**
     * Retrieves the tag associated with the instance.
     * Can be overridden by subclasses.
     *
     * @param {AnyObject} [context] - Optional context parameter that can be provided.
     * @return {string} The tag value of the instance.
     */
    getTag(context?: AnyObject): string;
    setVersion(version: number): void;
    setTimeout(timeout: number): void;
    setConcurrency(concurrency: number): void;
    setProgressWeight(weight: number): void;
    setInputContextSchema(schema: Schema): void;
    setOutputContextSchema(schema: Schema): void;
    setValidateInputContext(value: boolean): void;
    setValidateOutputContext(value: boolean): void;
    /**
     * Emits a signal along with metadata if certain conditions are met.
     *
     * This method sends a signal with optional context data and adds metadata
     * to the emitted data if the instance is not hidden and not a subordinate metadata object.
     *
     * @param {string} signal - The name of the signal to emit.
     * @param {AnyObject} [ctx={}] - Additional context data to include with the emitted signal.
     * @return {void} Does not return a value.
     */
    emitWithMetadata(signal: string, ctx?: AnyObject): void;
    /**
     * Emits metrics with additional metadata enhancement based on the context and the state of the instance.
     * This is used to prevent loops on the meta layer in debug mode.
     *
     * @param {string} signal - The signal identifier for the metric being emitted.
     * @param {AnyObject} [ctx={}] - Optional context object to provide additional information with the metric.
     * @return {void} This method does not return any value.
     */
    emitMetricsWithMetadata(signal: string, ctx?: AnyObject): void;
    private isSchemaDefinition;
    private isDefaultAnyObjectSchema;
    private mergeSchemaVariant;
    private validateValueAgainstSchema;
    /**
     * Validates a data object against a specified schema definition and returns validation results.
     *
     * @param {any} data - The target object to validate against the schema.
     * @param {Schema | undefined} schema - The schema definition describing the expected structure and constraints of the data.
     * @param {string} [path="context"] - The base path or context for traversing the data, used in generating error messages.
     * @return {{ valid: boolean, errors: Record<string, string> }} - An object containing a validity flag (`valid`)
     * and a map (`errors`) of validation error messages keyed by property paths.
     */
    validateSchema(data: any, schema: Schema | undefined, path?: string): {
        valid: boolean;
        errors: Record<string, string>;
    };
    validateProp(prop: SchemaDefinition, key: string, value?: any, path?: string): Record<string, string>;
    /**
     * Validates the input context against the predefined schema and emits metadata if validation fails.
     *
     * @param {AnyObject} context - The input context to validate.
     * @return {true | AnyObject} - Returns `true` if validation succeeds, otherwise returns an error object containing details of the validation failure.
     */
    private getEffectiveValidationMode;
    private warnMissingSchema;
    private logValidationFailure;
    validateInput(context: AnyObject, metadata?: AnyObject): true | AnyObject;
    /**
     * Validates the output context using the provided schema and emits metadata if validation fails.
     *
     * @param {AnyObject} context - The output context to validate.
     * @return {true | AnyObject} Returns `true` if the output context is valid; otherwise, returns an object
     * containing error information when validation fails.
     */
    validateOutput(context: AnyObject, metadata?: AnyObject): true | AnyObject;
    /**
     * Executes a task within a given context, optionally emitting signals and reporting progress.
     *
     * @param {GraphContext} context The execution context which provides data and functions necessary for the task.
     * @param {function(string, AnyObject): void} emit A function to emit signals and communicate intermediate results or states.
     * @param {function(string, AnyObject, InquiryOptions): Promise<AnyObject>} inquire A function to inquire something from another task.
     * @param {function(number): void} progressCallback A callback function used to report task progress as a percentage (0 to 100).
     * @param {{ nodeId: string; routineExecId: string }} nodeData An object containing identifiers related to the node and execution routine.
     * @return {TaskResult} The result of the executed task.
     */
    execute(context: GraphContext, emit: (signal: string, context: AnyObject) => void, inquire: (inquiry: string, context: AnyObject, options: InquiryOptions) => Promise<AnyObject>, progressCallback: (progress: number) => void, nodeData: {
        nodeId: string;
        routineExecId: string;
    }): TaskResult;
    /**
     * Adds tasks as predecessors to the current task and establishes dependencies between them.
     * Ensures that adding predecessors does not create cyclic dependencies.
     * Updates task relationships, progress weights, and emits relevant metrics after operations.
     *
     * @param {Task[]} tasks - An array of tasks to be added as predecessors to the current task.
     * @return {this} The current task instance for method chaining.
     * @throws {Error} Throws an error if adding a predecessor creates a cycle in the task structure.
     */
    doAfter(...tasks: (Task | undefined)[]): this;
    /**
     * Adds a sequence of tasks as successors to the current task, ensuring no cyclic dependencies are introduced.
     * Metrics are emitted when a relationship is successfully added.
     *
     * @param {...Task} tasks - The tasks to be added as successors to the current task.
     * @return {this} Returns the current task instance for method chaining.
     * @throws {Error} Throws an error if adding a task causes a cyclic dependency.
     */
    then(...tasks: (Task | undefined)[]): this;
    /**
     * Decouples the current task from the provided task by removing mutual references.
     *
     * @param {Task} task - The task to decouple from the current task.
     * @return {void} This method does not return a value.
     */
    decouple(task: Task): void;
    /**
     * Updates the progress weights for tasks within each layer of the subgraph.
     * The progress weight for each task is calculated based on the inverse proportion
     * of the number of layers and the number of tasks in each layer. This ensures an
     * even distribution of progress weight across the tasks in the layers.
     *
     * @return {void} Does not return a value.
     */
    updateProgressWeights(): void;
    /**
     * Retrieves a mapping of layer indices to sets of tasks within each layer of a subgraph.
     * This method traverses the task dependencies and organizes tasks by their respective layer indices.
     *
     * @return {Map<number, Set<Task>>} A map where the key is the layer index (number) and the value is a set of tasks (Set<Task>) belonging to that layer.
     */
    getSubgraphLayers(): Map<number, Set<Task>>;
    /**
     * Updates the `layerIndex` of the current task based on the maximum layer index of its predecessors
     * and propagates the update recursively to all subsequent tasks. If the `layerIndex` changes,
     * emits a metric event with metadata about the change.
     *
     * @return {void} This method does not return a value.
     */
    updateLayerFromPredecessors(): void;
    /**
     * Determines whether there is a cycle in the tasks graph.
     * This method performs a depth-first search (DFS) to detect cycles.
     *
     * @return {boolean} - Returns true if a cycle is found in the graph, otherwise false.
     */
    hasCycle(): boolean;
    /**
     * Maps over the next set of tasks or failed tasks if specified, applying the provided callback function.
     *
     * @param {Function} callback A function that will be called with each task, transforming the task as needed. It receives a single parameter of type Task.
     * @return {any[]} An array of transformed tasks resulting from applying the callback function.
     */
    mapNext(callback: (task: Task) => any): any[];
    /**
     * Maps through each task in the set of predecessor tasks and applies the provided callback function.
     *
     * @param {function} callback - A function to execute on each task in the predecessor tasks. The function receives a `Task` object as its argument and returns any value.
     * @return {any[]} An array containing the results of applying the callback function to each predecessor task.
     */
    mapPrevious(callback: (task: Task) => any): any[];
    makeRoutine(name: string, description: string): this;
    /**
     * Adds the specified signals to the current instance, making it observe them.
     * If the instance is already observing a signal, it will be skipped.
     * The method also emits metadata information if the `register` property is set.
     *
     * @param {...string[]} signals - The array of signal names to observe.
     * @return {this} The current instance after adding the specified signals.
     */
    doOn(...signals: SignalDefinitionInput[]): this;
    /**
     * Registers the specified signals to be emitted after the Task executes successfully and attaches them for further processing.
     *
     * @param {...string} signals - The list of signals to be registered for emission.
     * @return {this} The current instance for method chaining.
     */
    emits(...signals: SignalDefinitionInput[]): this;
    /**
     * Configures the instance to emit specified signals when the task execution fails.
     * A failure is defined as anything that does not return a successful result.
     *
     * @param {...string} signals - The names of the signals to emit upon failure.
     * @return {this} Returns the current instance for chaining.
     */
    emitsOnFail(...signals: SignalDefinitionInput[]): this;
    /**
     * Attaches a signal to the current context and emits metadata if the register flag is set.
     *
     * @param {...string} signals - The names of the signals to attach.
     * @return {void} This method does not return a value.
     */
    attachSignal(...signals: SignalDefinitionInput[]): Task;
    /**
     * Unsubscribes the current instance from the specified signals.
     * This method removes the signals from the observedSignals set, unsubscribes
     * from the underlying broker, and emits metadata for the unsubscription if applicable.
     *
     * @param {string[]} signals - The list of signal names to unsubscribe from.
     * @return {this} Returns the current instance for method chaining.
     */
    unsubscribe(...signals: string[]): this;
    /**
     * Unsubscribes from all currently observed signals and clears the list of observed signals.
     *
     * @return {this} The instance of the class to allow method chaining.
     */
    unsubscribeAll(): this;
    /**
     * Detaches the specified signals from being emitted after execution and optionally emits metadata for each detached signal.
     *
     * @param {...string} signals - The list of signal names to be detached. Signals can be in the format "namespace:signalName".
     * @return {this} Returns the current instance of the object for method chaining.
     */
    detachSignals(...signals: string[]): this;
    /**
     * Detaches all signals associated with the object by invoking the `detachSignals` method
     * and clearing the `signalsToEmitAfter` collection.
     *
     * @return {this} Returns the current instance to allow method chaining.
     */
    detachAllSignals(): this;
    respondsTo(...inquires: string[]): this;
    usesHelpers(helpers: Record<string, HelperDefinition | undefined>): this;
    usesGlobals(globals: Record<string, GlobalDefinition | undefined>): this;
    attachIntents(...intentNames: string[]): this;
    detachIntents(...intentNames: string[]): this;
    detachAllIntents(): this;
    /**
     * Maps over the signals in the `signalsToEmitAfter` set and applies a callback function to each signal.
     *
     * @param {function(string): void} callback - A function that is called with each signal
     *   in the `signalsToEmitAfter` set, providing the signal as an argument.
     * @return {Array<any>} An array containing the results of applying the callback
     *   function to each signal.
     */
    mapSignals(callback: (signal: string) => void): void[];
    /**
     * Maps over the signals in `signalsToEmitOnFail` and applies the provided callback to each signal.
     *
     * @param {function(string): void} callback - A function that receives each signal as a string and performs an operation or transformation on it.
     * @return {Array} The array resulting from applying the callback to each signal in `signalsToEmitOnFail`.
     */
    mapOnFailSignals(callback: (signal: string) => void): void[];
    /**
     * Maps over the observed signals with the provided callback function.
     *
     * @param {function(string): void} callback - A function to execute on each signal in the observed signals array.
     * @return {Array} A new array containing the results of calling the callback function on each observed signal.
     */
    mapObservedSignals(callback: (signal: string) => void): void[];
    /**
     * Emits a collection of signals stored in the `signalsToEmitAfter` array.
     *
     * @param {GraphContext} context - The context object containing data or state to be passed to the emitted signals.
     * @return {void} This method does not return a value.
     */
    emitSignals(context: GraphContext): void;
    /**
     * Emits registered signals when an operation fails.
     *
     * @param {GraphContext} context - The context from which the full context is derived and passed to the signals being emitted.
     * @return {void} This method does not return any value.
     */
    emitOnFailSignals(context: GraphContext): void;
    /**
     * Cleans up and destroys the task instance, detaching it from other tasks and
     * performing necessary cleanup operations.
     *
     * This method:
     * - Unsubscribes from all signals and events.
     * - Detaches all associated signal handlers.
     * - Removes the task from successor and predecessor task mappings.
     * - Clears all task relationships and marks the task as destroyed.
     * - Emits destruction metrics, if applicable.
     *
     * @return {void} No value is returned because the function performs clean-up operations.
     */
    destroy(): void;
    /**
     * Exports the current state of the object as a structured plain object.
     *
     * @return {AnyObject} An object containing the serialized properties of the current instance. The exported object includes various metadata, schema information, task attributes, and related tasks, such as:
     * - Name and description of the task.
     * - Layer index, uniqueness, meta, and signal-related flags.
     * - Event triggers and attached signals.
     * - Throttling, concurrency, timeout settings, and ephemeral flag.
     * - Task function as a string.
     * - Serialization of getter callbacks and schemas for input/output validation.
     * - Relationships such as next tasks, failure tasks, and predecessor tasks.
     */
    export(): AnyObject;
    /**
     * Returns an iterator for iterating over tasks associated with this instance.
     *
     * @return {TaskIterator} An iterator instance for tasks.
     */
    getIterator(): TaskIterator;
    /**
     * Accepts a visitor object to perform operations on the current instance.
     *
     * @param {GraphVisitor} visitor - The visitor object implementing operations for this instance.
     * @return {void} This method does not return a value.
     */
    accept(visitor: GraphVisitor): void;
    log(): void;
}

/**
 * This class serves as a registry for managing tasks and routines within a graph-based execution model.
 * It provides functionalities to register, update, retrieve, delete, and iterate over tasks and routines.
 */
declare class GraphRegistry {
    static _instance: GraphRegistry;
    static get instance(): GraphRegistry;
    tasks: Map<string, Task>;
    routines: Map<string, GraphRoutine>;
    registerTask: Task;
    updateTaskInputSchema: Task;
    updateTaskOutputSchema: Task;
    getTaskByName: Task;
    getTasksByLayer: Task;
    getAllTasks: Task;
    doForEachTask: Task;
    deleteTask: Task;
    registerRoutine: Task;
    getRoutineByName: Task;
    getAllRoutines: Task;
    doForEachRoutine: Task;
    deleteRoutine: Task;
    /**
     * Constructs a new instance and sets up various meta tasks and routines.
     *
     * This constructor initializes several predefined tasks for managing operations
     * like registering tasks, updating schemas for tasks, fetching tasks or routines,
     * and performing actions on all tasks or routines. It also initializes routines
     * to handle similar operations and hardcodes the initial meta tasks and routines.
     *
     * It initializes the instance state by setting up tasks and routines.
     */
    constructor();
    reset(): void;
}

interface DebounceOptions {
    leading?: boolean;
    trailing?: boolean;
    maxWait?: number;
}
/**
 * Class representing a debounced task, inheriting from the `Task` class.
 * This class allows tasks to be executed with debounce behavior, controlling
 * the frequency at which the task function is triggered.
 */
declare class DebounceTask extends Task {
    readonly debounceTime: number;
    leading: boolean;
    trailing: boolean;
    maxWait: number;
    timer: NodeJS.Timeout | null;
    maxTimer: NodeJS.Timeout | null;
    hasLaterCall: boolean;
    lastResolve: ((value: unknown) => void) | null;
    lastReject: ((reason?: any) => void) | null;
    lastContext: GraphContext | null;
    lastTimeout: NodeJS.Timeout | null;
    lastProgressCallback: ((progress: number) => void) | null;
    lastEmitFunction: ((signal: string, context: any) => void) | null;
    lastInquireFunction: ((inquiry: string, context: AnyObject, options: InquiryOptions) => Promise<AnyObject>) | null;
    constructor(name: string, task: TaskFunction, description?: string, debounceTime?: number, leading?: boolean, trailing?: boolean, maxWait?: number, concurrency?: number, timeout?: number, register?: boolean, isUnique?: boolean, isMeta?: boolean, isSubMeta?: boolean, isHidden?: boolean, inputSchema?: Schema | undefined, validateInputSchema?: boolean, outputSchema?: Schema | undefined, validateOutputSchema?: boolean);
    /**
     * Executes the taskFunction with the provided context, emit function, and progress callback.
     * It clears any existing timeout before execution.
     * Handles synchronous and asynchronous results from taskFunction.
     * If an error occurs during execution, it resolves with the error.
     *
     * @return {void} This method does not return any value.
     */
    executeFunction(): void;
    /**
     * Executes a debounced operation, ensuring controlled execution of functions
     * over a specified debounce time and maximum wait time. This method handles
     * both leading and trailing edge executions and invokes callbacks accordingly.
     *
     * @param {Function} resolve - The function to call when the operation is successfully resolved.
     * @param {Function} reject - The function to call with an error or reason if the operation fails.
     * @param {GraphContext} context - The execution context for the operation.
     * @param {NodeJS.Timeout} timeout - A timeout object for managing execution delays.
     * @param {Function} emit - A callback function to emit signals with a specific context.
     * @param inquire
     * @param {Function} progressCallback - A callback function to report progress during operation execution.
     * @return {void} Does not return a value but sets internal timers and invokes provided callbacks.
     */
    debouncedTrigger(resolve: (value: unknown) => void, reject: (reason?: any) => void, context: GraphContext, timeout: NodeJS.Timeout, emit: (signal: string, context: any) => void, inquire: (inquiry: string, context: AnyObject, options: InquiryOptions) => Promise<AnyObject>, progressCallback: (progress: number) => void): void;
    /**
     * Executes a task with a debounced trigger mechanism.
     *
     * @param {GraphContext} context - The context containing relevant graph data for the execution.
     * @param {function(string, any): void} emit - A function used to emit signals with associated context.
     * @param inquire
     * @param {function(number): void} progressCallback - A callback function to report the progress of the task as a number between 0 and 1.
     * @return {Promise<TaskResult>} A promise that resolves with the task result upon completion or rejects on failure.
     */
    execute(context: GraphContext, emit: (signal: string, context: any) => void, inquire: (inquiry: string, context: AnyObject, options: InquiryOptions) => Promise<AnyObject>, progressCallback: (progress: number) => void): TaskResult;
}

type EphemeralTaskOptions = {
    once?: boolean;
    destroyCondition?: (context: any) => boolean;
};
/**
 * Represents a transient task that executes and may optionally self-destruct
 * based on given conditions.
 *
 * EphemeralTask extends the standard Task class and introduces additional
 * features for managing tasks that are intended to run only once, or under
 * certain conditions. This class is particularly useful when you want a task
 * to clean up after itself and not persist within the system indefinitely.
 */
declare class EphemeralTask extends Task {
    readonly once: boolean;
    readonly condition: (context: any) => boolean;
    readonly isEphemeral: boolean;
    constructor(name: string, task: TaskFunction, description?: string, once?: boolean, condition?: (context: any) => boolean, concurrency?: number, timeout?: number, register?: boolean, isUnique?: boolean, isMeta?: boolean, isSubMeta?: boolean, isHidden?: boolean, getTagCallback?: ThrottleTagGetter | undefined, inputSchema?: Schema | undefined, validateInputContext?: boolean, outputSchema?: Schema | undefined, validateOutputContext?: boolean, retryCount?: number, retryDelay?: number, retryDelayMax?: number, retryDelayFactor?: number);
    /**
     * Executes the process logic with the provided context, emit function, progress callback, and node data.
     *
     * @param {any} context - The execution context, carrying necessary parameters or states for the operation.
     * @param {function(string, AnyObject): void} emit - A function to emit signals with a string identifier and associated context.
     * @param inquire
     * @param {function(number): void} progressCallback - A callback function to report the progress of the execution as a numerical value.
     * @param {{ nodeId: string, routineExecId: string }} nodeData - An object containing details about the node ID and routine execution ID.
     * @return {any} The result of the execution, returned from the base implementation or processed internally.
     */
    execute(context: any, emit: (signal: string, context: AnyObject) => void, inquire: (inquiry: string, context: AnyObject, options: InquiryOptions) => Promise<AnyObject>, progressCallback: (progress: number) => void, nodeData: {
        nodeId: string;
        routineExecId: string;
    }): boolean | void | AnyObject | Generator<unknown, any, any> | Promise<any>;
}

/**
 * The GraphAsyncRun class extends GraphRunStrategy to implement an asynchronous
 * graph execution strategy. It utilizes a GraphAsyncQueueBuilder for building
 * and composing the graph asynchronously before execution.
 */
declare class GraphAsyncRun extends GraphRunStrategy {
    constructor();
    /**
     * Executes the run operation, which involves composing the graph builder,
     * updating the run instance, and resetting the state.
     *
     * @return {Promise<void>} A promise that resolves when the operation completes.
     */
    run(): Promise<void>;
    reset(): void;
    export(): any;
}

/**
 * The GraphStandardRun class extends the GraphRunStrategy and provides
 * a concrete implementation of methods to manage and execute a graph run.
 * This class is responsible for orchestrating the graph composition,
 * updating the run instance, and resetting its state after execution.
 */
declare class GraphStandardRun extends GraphRunStrategy {
    /**
     * Executes the sequence of operations involving graph composition,
     * instance updating, and reset mechanisms.
     *
     * @return {void} Does not return a value.
     */
    run(): void;
    export(): any;
}

/**
 * Determines when an actor key should be materialized in memory.
 * - `eager`: creates the default key record immediately.
 * - `lazy`: creates key records on first access.
 */
type ActorLoadPolicy = "eager" | "lazy";
/**
 * Defines how durable writes should be interpreted by actor tasks.
 * - `overwrite`: replace full durable state.
 * - `patch`: shallow-merge object fields.
 * - `reducer`: allow reducer-return handlers.
 */
type ActorWriteContract = "overwrite" | "patch" | "reducer";
/**
 * Declares the intent of an actor task.
 * - `read`: no state writes allowed.
 * - `write`: durable/runtime writes allowed.
 * - `meta`: write semantics with forced meta task registration.
 */
type ActorTaskMode = "read" | "write" | "meta";
/**
 * Actor classification.
 * Meta actors are internal/framework-level actors and force bound tasks to meta.
 */
type ActorKind = "standard" | "meta";
/**
 * Optional runtime read protection policy.
 */
type ActorRuntimeReadGuard = "none" | "freeze-shallow";
/**
 * Consistency profile hint used primarily by distributed/service extensions.
 */
type ActorConsistencyProfileName = "strict" | "balanced" | "cached" | "async";
/**
 * Per-invocation actor options accepted via `context.__actorOptions`.
 * Only key targeting and idempotency are overridable at invocation level.
 */
interface ActorInvocationOptions {
    actorKey?: string;
    idempotencyKey?: string;
}
/**
 * Session expiry/touch behavior for actor keys.
 */
interface SessionPolicy {
    enabled?: boolean;
    idleTtlMs?: number;
    absoluteTtlMs?: number;
    extendIdleTtlOnRead?: boolean;
    persistDurableState?: boolean;
    persistenceTimeoutMs?: number;
}
/**
 * Task retry policy metadata for actor definitions/specs.
 */
interface RetryPolicy {
    attempts?: number;
    delayMs?: number;
    maxDelayMs?: number;
    factor?: number;
}
/**
 * Idempotency policy for actor task execution.
 */
interface IdempotencyPolicy {
    enabled?: boolean;
    mode?: "required" | "optional";
    rerunOnFailedDuplicate?: boolean;
    ttlMs?: number;
}
/**
 * Declarative actor-key resolution configuration.
 */
type ActorKeyDefinition = {
    source: "path";
    path: string;
} | {
    source: "field";
    field: string;
} | {
    source: "template";
    template: string;
};
/**
 * Serializable metadata describing a task bound to an actor.
 */
interface ActorTaskBindingDefinition {
    taskName: string;
    mode?: ActorTaskMode;
    description?: string;
}
/**
 * Declarative state schema/configuration for an actor.
 *
 * Durable state uses `initState` for bootstrap defaults.
 * Runtime state is intentionally task-driven (no actor-level init lifecycle hook).
 */
interface ActorStateDefinition<D extends Record<string, any>, R = AnyObject> {
    durable?: {
        /**
         * Initial durable state. Prefer static values for simple cases.
         * Function form is intended for advanced computed initialization.
         */
        initState?: D | (() => D);
        schema?: AnyObject;
        description?: string;
    };
    runtime?: {
        schema?: AnyObject;
        description?: string;
    };
}
/**
 * Serializable actor definition used for persistence/round-tripping.
 */
interface ActorDefinition<D extends Record<string, any>, R = AnyObject> {
    name: string;
    description: string;
    defaultKey: string;
    kind?: ActorKind;
    loadPolicy?: ActorLoadPolicy;
    writeContract?: ActorWriteContract;
    consistencyProfile?: ActorConsistencyProfileName;
    retry?: RetryPolicy;
    idempotency?: IdempotencyPolicy;
    session?: SessionPolicy;
    runtimeReadGuard?: ActorRuntimeReadGuard;
    key?: ActorKeyDefinition;
    state?: ActorStateDefinition<D, R>;
    tasks?: ActorTaskBindingDefinition[];
}
/**
 * Runtime actor specification used by `Cadenza.createActor(...)`.
 */
interface ActorSpec<D extends Record<string, any>, R = AnyObject> {
    name: string;
    description?: string;
    state?: ActorStateDefinition<D, R>;
    /**
     * Shortcut durable bootstrap state when `state.durable.initState` is not supplied.
     */
    initState?: D | (() => D);
    defaultKey: string;
    key?: ActorKeyDefinition;
    keyResolver?: (input: Record<string, any>) => string | undefined;
    loadPolicy?: ActorLoadPolicy;
    writeContract?: ActorWriteContract;
    kind?: ActorKind;
    retry?: RetryPolicy;
    idempotency?: IdempotencyPolicy;
    session?: SessionPolicy;
    consistencyProfile?: ActorConsistencyProfileName;
    runtimeReadGuard?: ActorRuntimeReadGuard;
    taskBindings?: ActorTaskBindingDefinition[];
}
/**
 * Optional actor creation flags.
 */
interface ActorFactoryOptions<D extends Record<string, any> = Record<string, any>, R = AnyObject> {
    isMeta?: boolean;
    definitionSource?: ActorDefinition<D, R>;
    hydrateDurableState?: (actorKey: string) => Promise<ActorDurableStateHydration<D> | null>;
}
/**
 * Optional per-binding behavior when wrapping actor handlers.
 */
interface ActorTaskBindingOptions {
    mode?: ActorTaskMode;
    touchSession?: boolean;
}
/**
 * Reducer function used for state transitions.
 */
type ActorStateReducer<S> = (state: S, input: AnyObject) => S;
/**
 * Fully resolved invocation options used during actor task execution.
 */
interface ActorResolvedInvocationOptions {
    actorKey?: string;
    loadPolicy: ActorLoadPolicy;
    writeContract: ActorWriteContract;
    consistencyProfile?: ActorConsistencyProfileName;
    idempotencyKey?: string;
    touchSession: boolean;
}
/**
 * Durable/runtime mutator helpers exposed to actor handlers.
 */
interface ActorStateMutators<D extends Record<string, any>, R = AnyObject> {
    setDurable: (next: D | ActorStateReducer<D>) => void;
    patchDurable: (partial: Partial<D>) => void;
    reduceDurable: (reducer: ActorStateReducer<D>) => void;
    setRuntime: (next: R | ActorStateReducer<R>) => void;
    patchRuntime: (partial: Partial<R>) => void;
    reduceRuntime: (reducer: ActorStateReducer<R>) => void;
}
/**
 * Combined actor state snapshot and mutators exposed to handlers.
 */
interface ActorStateStore<D extends Record<string, any>, R = AnyObject> extends ActorStateMutators<D, R> {
    durable: D;
    runtime: R;
    version: number;
    durableVersion: number;
    runtimeVersion: number;
}
/**
 * Context injected into `actor.task(...)` handlers.
 */
interface ActorTaskContext<D extends Record<string, any>, R = AnyObject> {
    /**
     * Durable state alias retained for backwards ergonomics.
     */
    state: D;
    durableState: D;
    runtimeState: R;
    store: ActorStateStore<D, R>;
    input: AnyObject;
    actor: {
        name: string;
        description?: string;
        key: string;
        version: number;
        durableVersion: number;
        runtimeVersion: number;
        kind: ActorKind;
    };
    options: ActorResolvedInvocationOptions;
    setState: (next: D | ActorStateReducer<D>) => void;
    patchState: (partial: Partial<D>) => void;
    reduceState: (reducer: ActorStateReducer<D>) => void;
    setDurableState: (next: D | ActorStateReducer<D>) => void;
    patchDurableState: (partial: Partial<D>) => void;
    reduceDurableState: (reducer: ActorStateReducer<D>) => void;
    setRuntimeState: (next: R | ActorStateReducer<R>) => void;
    patchRuntimeState: (partial: Partial<R>) => void;
    reduceRuntimeState: (reducer: ActorStateReducer<R>) => void;
    emit: (signal: string, payload?: AnyObject) => void;
    inquire: (inquiry: string, context?: AnyObject, options?: InquiryOptions) => Promise<AnyObject>;
    tools: RuntimeTools;
}
/**
 * Handler signature used by `actor.task(...)`.
 */
type ActorTaskHandler<D extends Record<string, any>, R = AnyObject> = (context: ActorTaskContext<D, R>, emit: (signal: string, payload?: AnyObject) => void, inquire: (inquiry: string, context?: AnyObject, options?: InquiryOptions) => Promise<AnyObject>, tools: RuntimeTools, progressCallback: (progress: number) => void) => TaskResult | ActorStateReducer<D> | Promise<TaskResult | ActorStateReducer<D>>;
interface ActorDurableStateHydration<D extends Record<string, any>> {
    durableState: D;
    durableVersion: number;
}
/**
 * Metadata attached to wrapped actor task functions.
 */
interface ActorTaskRuntimeMetadata {
    actorName: string;
    actorDescription?: string;
    actorKind: ActorKind;
    mode: ActorTaskMode;
    forceMeta: boolean;
}
declare const META_ACTOR_SESSION_STATE_PERSIST_INTENT = "meta-actor-session-state-persist";
/**
 * Reads actor metadata from a wrapped task function if available.
 */
declare function getActorTaskRuntimeMetadata(taskFunction: TaskFunction): ActorTaskRuntimeMetadata | undefined;
/**
 * In-memory actor runtime.
 *
 * Actors keep durable and runtime state per resolved actor key.
 * Durable defaults are loaded from `initState`.
 * Runtime state is intentionally initialized/updated by normal actor write tasks.
 */
declare class Actor<D extends Record<string, any> = AnyObject, R = AnyObject> {
    readonly spec: ActorSpec<D, R>;
    readonly kind: ActorKind;
    private readonly sourceDefinition?;
    private readonly hydrateDurableState?;
    private readonly stateByKey;
    private readonly sessionByKey;
    private readonly idempotencyByKey;
    private readonly pendingHydrationByKey;
    private readonly writeQueueByKey;
    private nextTaskBindingIndex;
    /**
     * Creates an actor instance and optionally materializes the default key.
     */
    constructor(spec: ActorSpec<D, R>, options?: ActorFactoryOptions<D, R>);
    /**
     * Wraps an actor-aware handler into a standard Cadenza task function.
     */
    task(handler: ActorTaskHandler<D, R>, bindingOptions?: ActorTaskBindingOptions): TaskFunction;
    /**
     * Returns durable state snapshot for the resolved key.
     */
    getState(actorKey?: string): D;
    /**
     * Returns durable state snapshot for the resolved key.
     */
    getDurableState(actorKey?: string): D;
    /**
     * Returns runtime state reference for the resolved key.
     */
    getRuntimeState(actorKey?: string): R;
    /**
     * Lists all currently materialized actor keys.
     */
    listActorKeys(): string[];
    /**
     * Alias of `getDurableVersion`.
     */
    getVersion(actorKey?: string): number;
    /**
     * Returns durable state version for the resolved key.
     */
    getDurableVersion(actorKey?: string): number;
    /**
     * Returns runtime state version for the resolved key.
     */
    getRuntimeVersion(actorKey?: string): number;
    /**
     * Exports this actor as a serializable definition.
     */
    toDefinition(): ActorDefinition<D, R>;
    /**
     * Resets one actor key or all keys.
     */
    reset(actorKey?: string): void;
    private applyRuntimeReadGuard;
    private normalizeInputContext;
    private resolveInvocationOptions;
    private resolveActorKey;
    private resolveActorKeyFromDefinition;
    private resolveInitialDurableState;
    private resolveInitialRuntimeState;
    private ensureStateRecord;
    private maybeHydrateStateRecord;
    private touchSession;
    private pruneExpiredActorKeys;
    private isSessionExpired;
    private runWithOptionalIdempotency;
    private runWithPerKeyWriteSerialization;
    private getActiveIdempotencyRecord;
    private persistDurableStateIfConfigured;
    private emitActorCreatedSignal;
}

type RuntimeHandlerLanguage = "js" | "ts";
type RuntimeTaskDefinitionKind = "task" | "metaTask";
type RuntimeHelperDefinitionKind = "helper" | "metaHelper";
type RuntimeGlobalDefinitionKind = "global" | "metaGlobal";
type RuntimeSignalEmissionMode = "attach" | "after" | "onFail";
type RuntimeSharingMode = "isolated" | "shared";
type RuntimeSessionRole = "owner" | "writer" | "observer";
type RuntimeTaskOptions = Omit<TaskOptions, "getTagCallback">;
interface RuntimeTaskDefinition {
    name: string;
    description?: string;
    handlerSource: string;
    language: RuntimeHandlerLanguage;
    kind?: RuntimeTaskDefinitionKind;
    options?: RuntimeTaskOptions;
}
interface RuntimeHelperDefinition {
    name: string;
    description?: string;
    handlerSource: string;
    language: RuntimeHandlerLanguage;
    kind?: RuntimeHelperDefinitionKind;
}
interface RuntimeGlobalDefinition {
    name: string;
    description?: string;
    value: unknown;
    kind?: RuntimeGlobalDefinitionKind;
}
interface RuntimeRoutineDefinition {
    name: string;
    description?: string;
    startTaskNames: string[];
    isMeta?: boolean;
}
interface RuntimeActorTaskDefinition {
    actorName: string;
    taskName: string;
    description?: string;
    mode?: ActorTaskMode;
    handlerSource: string;
    language: RuntimeHandlerLanguage;
    options?: RuntimeTaskOptions;
}
interface RuntimeTaskLinkDefinition {
    predecessorTaskName: string;
    successorTaskName: string;
}
interface RuntimeSnapshotTask {
    name: string;
    version: number;
    description: string;
    kind: "task" | "metaTask" | "actorTask";
    runtimeOwned: boolean;
    language: RuntimeHandlerLanguage | null;
    handlerSource: string | null;
    concurrency: number;
    timeout: number;
    retryCount: number;
    retryDelay: number;
    retryDelayMax: number;
    retryDelayFactor: number;
    validateInputContext: boolean;
    validateOutputContext: boolean;
    inputContextSchema: Record<string, unknown>;
    outputContextSchema: Record<string, unknown>;
    nextTaskNames: string[];
    predecessorTaskNames: string[];
    signals: {
        emits: string[];
        emitsAfter: string[];
        emitsOnFail: string[];
        observed: string[];
    };
    intents: {
        handles: string[];
        inquires: string[];
    };
    tools: {
        helpers: Record<string, string>;
        globals: Record<string, string>;
    };
    actorName: string | null;
    actorMode: ActorTaskMode | null;
}
interface RuntimeSnapshotHelper {
    name: string;
    version: number;
    description: string;
    kind: "helper" | "metaHelper";
    runtimeOwned: boolean;
    language: RuntimeHandlerLanguage | null;
    handlerSource: string | null;
    tools: {
        helpers: Record<string, string>;
        globals: Record<string, string>;
    };
}
interface RuntimeSnapshotGlobal {
    name: string;
    version: number;
    description: string;
    kind: "global" | "metaGlobal";
    runtimeOwned: boolean;
    value: unknown;
}
interface RuntimeSnapshotRoutine {
    name: string;
    version: number;
    description: string;
    isMeta: boolean;
    runtimeOwned: boolean;
    startTaskNames: string[];
    observedSignals: string[];
}
interface RuntimeSnapshotIntent extends Intent {
    runtimeOwned: boolean;
}
interface RuntimeSnapshotSignal {
    name: string;
    metadata: SignalMetadata | null;
}
interface RuntimeSnapshotActorKeyState {
    actorKey: string;
    durableState: unknown;
    runtimeState: unknown;
    durableVersion: number;
    runtimeVersion: number;
}
interface RuntimeSnapshotActor {
    name: string;
    description: string;
    runtimeOwned: boolean;
    definition: ActorDefinition<Record<string, any>, AnyObject>;
    actorKeys: RuntimeSnapshotActorKeyState[];
}
interface RuntimeSnapshotActorTask {
    actorName: string;
    taskName: string;
    description: string;
    mode: ActorTaskMode;
    language: RuntimeHandlerLanguage;
    handlerSource: string;
    runtimeOwned: boolean;
}
interface RuntimeSnapshot {
    runtimeMode: "core";
    bootstrapped: boolean;
    mode: string;
    tasks: RuntimeSnapshotTask[];
    helpers: RuntimeSnapshotHelper[];
    globals: RuntimeSnapshotGlobal[];
    routines: RuntimeSnapshotRoutine[];
    intents: RuntimeSnapshotIntent[];
    signals: RuntimeSnapshotSignal[];
    actors: RuntimeSnapshotActor[];
    actorTasks: RuntimeSnapshotActorTask[];
    links: RuntimeTaskLinkDefinition[];
}
interface RuntimeSubscription {
    subscriptionId: string;
    signalPatterns: string[];
    maxQueueSize: number;
    createdAt: string;
    pendingEvents: number;
}
interface RuntimeSignalEventSource {
    taskName: string | null;
    taskVersion: number | null;
    taskExecutionId: string | null;
    routineName: string | null;
    routineVersion: number | null;
    routineExecutionId: string | null;
    executionTraceId: string | null;
    consumed: boolean;
    consumedBy: string | null;
}
interface RuntimeSignalEvent {
    id: string;
    subscriptionId: string;
    sequence: number;
    type: "signal";
    signal: string;
    signalName: string;
    signalTag: string | null;
    emittedAt: string | null;
    isMeta: boolean;
    isSubMeta: boolean;
    metadata: SignalMetadata | null;
    source: RuntimeSignalEventSource;
    context: Record<string, unknown>;
}
interface RuntimeNextEventResult {
    subscriptionId: string;
    event: RuntimeSignalEvent | null;
    timedOut: boolean;
    pendingEvents: number;
}
interface RuntimePollEventsResult {
    subscriptionId: string;
    events: RuntimeSignalEvent[];
    pendingEvents: number;
}
interface RuntimeInfo {
    runtimeMode: "core";
    runtimeSharing: RuntimeSharingMode;
    runtimeName: string | null;
    sessionId: string | null;
    sessionRole: RuntimeSessionRole | null;
    activeSessionCount: number;
    daemonProcessId: number | null;
    bootstrapped: boolean;
    mode: string;
}
type RuntimeProtocolOperation = "runtime.bootstrap" | "runtime.info" | "runtime.detach" | "runtime.shutdown" | "runtime.reset" | "runtime.snapshot" | "runtime.subscribe" | "runtime.unsubscribe" | "runtime.nextEvent" | "runtime.pollEvents" | "task.upsert" | "helper.upsert" | "global.upsert" | "task.link" | "task.observeSignal" | "task.emitSignal" | "task.respondToIntent" | "task.useHelper" | "task.useGlobal" | "helper.useHelper" | "helper.useGlobal" | "routine.upsert" | "routine.observeSignal" | "intent.upsert" | "actor.upsert" | "actorTask.upsert" | "run" | "emit" | "inquire";
interface RuntimeProtocolRequest<TPayload = AnyObject> {
    id?: string | number;
    operation: RuntimeProtocolOperation;
    payload?: TPayload;
}
interface RuntimeProtocolError {
    code: string;
    message: string;
    details?: AnyObject;
}
interface RuntimeProtocolResponse<TResult = unknown> {
    id?: string | number;
    operation: RuntimeProtocolOperation;
    ok: boolean;
    result?: TResult;
    error?: RuntimeProtocolError;
}
interface RuntimeProtocolHandshake {
    ready: true;
    protocol: "cadenza-runtime-jsonl";
    protocolVersion: "1";
    runtimeMode: "core";
    runtimeSharing: RuntimeSharingMode;
    runtimeName: string | null;
    sessionId: string | null;
    sessionRole: RuntimeSessionRole | null;
    supportedOperations: RuntimeProtocolOperation[];
}

interface TaskOptions {
    concurrency?: number;
    timeout?: number;
    register?: boolean;
    isUnique?: boolean;
    isMeta?: boolean;
    isSubMeta?: boolean;
    isHidden?: boolean;
    getTagCallback?: ThrottleTagGetter;
    inputSchema?: Schema;
    validateInputContext?: boolean;
    outputSchema?: Schema;
    validateOutputContext?: boolean;
    retryCount?: number;
    retryDelay?: number;
    retryDelayMax?: number;
    retryDelayFactor?: number;
}
type CadenzaMode = "dev" | "debug" | "verbose" | "production";
type RuntimeValidationMode = "off" | "warn" | "enforce";
interface RuntimeValidationPolicy {
    metaInput?: RuntimeValidationMode;
    metaOutput?: RuntimeValidationMode;
    businessInput?: RuntimeValidationMode;
    businessOutput?: RuntimeValidationMode;
    warnOnMissingMetaInputSchema?: boolean;
    warnOnMissingMetaOutputSchema?: boolean;
    warnOnMissingBusinessInputSchema?: boolean;
    warnOnMissingBusinessOutputSchema?: boolean;
}
interface RuntimeValidationScope {
    id: string;
    active?: boolean;
    startTaskNames?: string[];
    startRoutineNames?: string[];
    policy?: RuntimeValidationPolicy;
}
interface ResolvedRuntimeValidationPolicy {
    layer: "meta" | "business";
    inputMode: RuntimeValidationMode;
    outputMode: RuntimeValidationMode;
    warnOnMissingInputSchema: boolean;
    warnOnMissingOutputSchema: boolean;
    activeScopeIds: string[];
}
type RuntimeInquiryDelegate = (inquiry: string, context: AnyObject, options?: InquiryOptions) => Promise<any>;
/**
 * Represents the core class of the Cadenza framework managing tasks, meta-tasks, signal emissions, and execution strategies.
 * All core components such as SignalBroker, GraphRunner, and GraphRegistry are initialized through this class, and it provides
 * utility methods to create, register, and manage various task types.
 */
declare class Cadenza {
    static signalBroker: SignalBroker;
    static inquiryBroker: InquiryBroker;
    static runner: GraphRunner;
    static metaRunner: GraphRunner;
    static registry: GraphRegistry;
    private static taskCache;
    private static routineCache;
    private static actorCache;
    private static helperCache;
    private static globalCache;
    private static runtimeInquiryDelegate;
    private static runtimeValidationPolicy;
    private static runtimeValidationScopes;
    private static emittedMissingSchemaWarnings;
    private static helperExecutionDepth;
    static isBootstrapped: boolean;
    static mode: CadenzaMode;
    /**
     * Initializes the system by setting up the required components such as the
     * signal broker, runners, and graph registry. Ensures the initialization
     * happens only once. Configures debug settings if applicable.
     *
     * @return {void} No value is returned.
     */
    static bootstrap(): void;
    /**
     * Retrieves the available strategies for running graphs.
     *
     * @return {Object} An object containing the available run strategies, where:
     *                  - PARALLEL: Executes graph runs asynchronously.
     *                  - SEQUENTIAL: Executes graph runs in a sequential order.
     */
    static get runStrategy(): {
        PARALLEL: GraphAsyncRun;
        SEQUENTIAL: GraphStandardRun;
    };
    /**
     * Sets the mode for the application and configures the broker and runner settings accordingly.
     *
     * @param {CadenzaMode} mode - The mode to set. It can be one of the following:
     *                             "debug", "dev", "verbose", or "production".
     *                             Each mode adjusts debug and verbosity settings.
     * @return {void} This method does not return a value.
     */
    static setMode(mode: CadenzaMode): void;
    /**
     * Validates the given name to ensure it is a non-empty string.
     * Throws an error if the validation fails.
     *
     * @param {string} name - The name to validate.
     * @return {void} This method does not return anything.
     * @throws {Error} If the name is not a non-empty string.
     */
    static validateName(name: string): void;
    static assertGraphMutationAllowed(operationName: string): void;
    static executeHelper(helper: HelperDefinition, context: AnyObject, emit: (signal: string, context: AnyObject) => void, inquire: (inquiry: string, context: AnyObject, options: InquiryOptions) => Promise<AnyObject>, progressCallback: (progress: number) => void): TaskResult;
    static resolveToolsForOwner(owner: ToolDependencyOwner, context: AnyObject, emit: (signal: string, context: AnyObject) => void, inquire: (inquiry: string, context: AnyObject, options: InquiryOptions) => Promise<AnyObject>, progressCallback: (progress: number) => void): RuntimeTools;
    private static resolveTaskOptionsForActorTask;
    private static registerActor;
    static getHelper(name: string): HelperDefinition | undefined;
    static getAllHelpers(): HelperDefinition[];
    static getGlobal(name: string): GlobalDefinition | undefined;
    static getAllGlobals(): GlobalDefinition[];
    /**
     * Executes the specified task or GraphRoutine with the given context using an internal runner.
     *
     * @param {Task | GraphRoutine} task - The task or GraphRoutine to be executed.
     * @param {AnyObject} context - The context in which the task or GraphRoutine should be executed.
     * @return {void}
     *
     * @example
     * ```ts
     * const task = Cadenza.createTask('My task', (ctx) => {
     *   console.log('My task executed with context:', ctx);
     * });
     *
     * Cadenza.run(task, { foo: 'bar' });
     *
     * const routine = Cadenza.createRoutine('My routine', [task], 'My routine description');
     *
     * Cadenza.run(routine, { foo: 'bar' });
     * ```
     */
    static run(task: Task | GraphRoutine, context: AnyObject): void;
    /**
     * Emits an event with the specified name and data payload to the broker.
     *
     * @param {string} event - The name of the event to emit.
     * @param {AnyObject} [data={}] - The data payload associated with the event.
     * @param options
     * @return {void} - No return value.
     *
     * @example
     * This is meant to be used as a global event emitter.
     * If you want to emit an event from within a task, you can use the `emit` method provided to the task function. See {@link TaskFunction}.
     * ```ts
     * Cadenza.emit('main.my_event', { foo: 'bar' });
     * ```
     */
    static emit(event: string, data?: AnyObject, options?: EmitOptions): void;
    static schedule(signalName: string, context: AnyObject, delayMs: number, exactDateTime?: Date): void;
    static interval(taskName: string, context: AnyObject, intervalMs: number, leading?: boolean, startDateTime?: Date): void;
    static debounce(signalName: string, context: any, delayMs: number): void;
    static get(taskName: string): Task | undefined;
    static forgetTask(taskName: string): void;
    static getActor<D extends Record<string, any> = AnyObject, R = AnyObject>(actorName: string): Actor<D, R> | undefined;
    static getAllActors<D extends Record<string, any> = AnyObject, R = AnyObject>(): Actor<D, R>[];
    static getRoutine(routineName: string): GraphRoutine | undefined;
    static defineIntent(intent: Intent): Intent;
    static inquire(inquiry: string, context: AnyObject, options?: InquiryOptions): Promise<any>;
    static setRuntimeInquiryDelegate(delegate?: RuntimeInquiryDelegate): void;
    static resolveRuntimeInquiryDelegate(): RuntimeInquiryDelegate;
    static getRuntimeValidationPolicy(): RuntimeValidationPolicy;
    static setRuntimeValidationPolicy(policy?: RuntimeValidationPolicy): RuntimeValidationPolicy;
    static replaceRuntimeValidationPolicy(policy?: RuntimeValidationPolicy): RuntimeValidationPolicy;
    static clearRuntimeValidationPolicy(): void;
    static getRuntimeValidationScopes(): RuntimeValidationScope[];
    static upsertRuntimeValidationScope(scope: RuntimeValidationScope): RuntimeValidationScope;
    static removeRuntimeValidationScope(id: string): void;
    static clearRuntimeValidationScopes(): void;
    static applyRuntimeValidationScopesToContext(context: AnyObject, routineName: string, tasks: Task[]): AnyObject;
    static resolveRuntimeValidationPolicyForTask(task: Task, metadata?: AnyObject): ResolvedRuntimeValidationPolicy;
    static shouldEmitMissingSchemaWarning(cacheKey: string): boolean;
    /**
     * Creates an in-memory actor runtime instance.
     *
     * Actors are not graph nodes. Use `actor.task(...)` to produce standard tasks that
     * participate in the graph like any other task.
     */
    static createActor<D extends Record<string, any> = AnyObject, R = AnyObject>(spec: ActorSpec<D, R>, options?: ActorFactoryOptions): Actor<D, R>;
    /**
     * Creates an actor from a serializable actor definition.
     *
     * Durable bootstrap state is resolved from `state.durable.initState`.
     * For backwards compatibility, legacy `state.durable.initialState` is also accepted.
     */
    static createActorFromDefinition<D extends Record<string, any> = AnyObject, R = AnyObject>(definition: ActorDefinition<D, R>, options?: ActorFactoryOptions<D, R>): Actor<D, R>;
    /**
     * Creates and registers a new task with the specified parameters and options.
     * Tasks are the basic building blocks of Cadenza graphs and are responsible for executing logic.
     * See {@link Task} for more information.
     *
     * @param {string} name - The unique name of the task.
     * @param {TaskFunction} func - The function to be executed by the task.
     * @param {string} [description] - An optional description for the task.
     * @param {TaskOptions} [options={}] - Configuration options for the task, such as concurrency, timeout, and retry settings.
     * @return {Task} The created task instance.
     *
     * @example
     * You can use arrow functions to create tasks.
     * ```ts
     * const task = Cadenza.createTask('My task', (ctx) => {
     *   console.log('My task executed with context:', ctx);
     * }, 'My task description');
     * ```
     *
     * You can also use named functions to create tasks.
     * This is the preferred way to create tasks since it allows for code inspection in the CadenzaUI.
     * ```ts
     * function myTask(ctx) {
     *   console.log('My task executed with context:', ctx);
     * }
     *
     * const task = Cadenza.createTask('My task', myTask);
     * ```
     *
     * ** Use the TaskOptions object to configure the task. **
     *
     * With concurrency limit, timeout limit and retry settings.
     * ```ts
     * Cadenza.createTask('My task', (ctx) => {
     *   console.log('My task executed with context:', ctx);
     * }, 'My task description', {
     *   concurrency: 10,
     *   timeout: 10000,
     *   retryCount: 3,
     *   retryDelay: 1000,
     *   retryDelayFactor: 1.5,
     * });
     * ```
     *
     * You can specify the input and output context schemas for the task.
     * ```ts
     * Cadenza.createTask('My task', (ctx) => {
     *   return { bar: 'foo' + ctx.foo };
     * }, 'My task description', {
     *   inputContextSchema: {
     *     type: 'object',
     *     properties: {
     *       foo: {
     *         type: 'string',
     *       },
     *     },
     *   required: ['foo'],
     *   },
     *   validateInputContext: true, // default is false
     *   outputContextSchema: {
     *     type: 'object',
     *     properties: {
     *       bar: {
     *         type: 'string',
     *       },
     *     },
     *     required: ['bar'],
     *   },
     *   validateOutputContext: true, // default is false
     * });
     * ```
     */
    static createTask(name: string, func: TaskFunction, description?: string, options?: TaskOptions): Task;
    static createTaskFromDefinition(definition: RuntimeTaskDefinition): Task;
    static createHelper(name: string, func: HelperFunction, description?: string): HelperDefinition;
    static createMetaHelper(name: string, func: HelperFunction, description?: string): HelperDefinition;
    static createHelperFromDefinition(definition: RuntimeHelperDefinition): HelperDefinition;
    static createGlobal(name: string, value: unknown, description?: string): GlobalDefinition;
    static createMetaGlobal(name: string, value: unknown, description?: string): GlobalDefinition;
    static createGlobalFromDefinition(definition: RuntimeGlobalDefinition): GlobalDefinition;
    /**
     * Creates a meta task with the specified name, functionality, description, and options.
     * This is used for creating tasks that lives on the meta layer.
     * The meta layer is a special layer that is executed separately from the business logic layer and is used for extending Cadenzas core functionality.
     * See {@link Task} or {@link createTask} for more information.
     *
     * @param {string} name - The name of the meta task.
     * @param {TaskFunction} func - The function to be executed by the meta task.
     * @param {string} [description] - An optional description of the meta task.
     * @param {TaskOptions} [options={}] - Additional optional task configuration. Automatically sets `isMeta` to true.
     * @return {Task} A task instance configured as a meta task.
     */
    static createMetaTask(name: string, func: TaskFunction, description?: string, options?: TaskOptions): Task;
    /**
     * Creates a unique task by wrapping the provided task function with a uniqueness constraint.
     * Unique tasks are designed to execute once per execution ID, merging parents. This is useful for
     * tasks that require fan-in/joins after parallel branches.
     * See {@link Task} for more information.
     *
     * @param {string} name - The name of the task to be created.
     * @param {TaskFunction} func - The function that contains the logic for the task. It receives joinedContexts as a list in the context (context.joinedContexts).
     * @param {string} [description] - An optional description of the task.
     * @param {TaskOptions} [options={}] - Optional configuration for the task, such as additional metadata or task options.
     * @return {Task} The task instance that was created with a uniqueness constraint.
     *
     * @example
     * ```ts
     * const splitTask = Cadenza.createTask('Split foos', function* (ctx) {
     *   for (const foo of ctx.foos) {
     *     yield { foo };
     *   }
     * }, 'Splits a list of foos into multiple sub-branches');
     *
     * const processTask = Cadenza.createTask('Process foo', (ctx) => {
     *  return { bar: 'foo' + ctx.foo };
     * }, 'Process a foo');
     *
     * const uniqueTask = Cadenza.createUniqueTask('Gather processed foos', (ctx) => {
     *   // A unique task will always be provided with a list of contexts (ctx.joinedContexts) from its predecessors.
     *   const processedFoos = ctx.joinedContexts.map((c) => c.bar);
     *   return { foos: processedFoos };
     * }, 'Gathers together the processed foos.');
     *
     * splitTask.then(
     *   processTask.then(
     *     uniqueTask,
     *   ),
     * );
     *
     * // Give the flow a name using a routine
     * Cadenza.createRoutine(
     *   'Process foos',
     *   [splitTask],
     *   'Processes a list of foos'
     * ).doOn('main.received_foos'); // Subscribe to a signal
     *
     * // Trigger the flow from anywhere
     * Cadenza.emit('main.received_foos', { foos: ['foo1', 'foo2', 'foo3'] });
     * ```
     *
     */
    static createUniqueTask(name: string, func: TaskFunction, description?: string, options?: TaskOptions): Task;
    /**
     * Creates a unique meta task with the specified name, function, description, and options.
     * See {@link createUniqueTask} and {@link createMetaTask} for more information.
     *
     * @param {string} name - The name of the task to create.
     * @param {TaskFunction} func - The function to execute when the task is run.
     * @param {string} [description] - An optional description of the task.
     * @param {TaskOptions} [options={}] - Optional settings for the task. Defaults to an empty object. Automatically sets `isMeta` and `isUnique` to true.
     * @return {Task} The created unique meta task.
     */
    static createUniqueMetaTask(name: string, func: TaskFunction, description?: string, options?: TaskOptions): Task;
    /**
     * Creates a throttled task with a concurrency limit of 1, ensuring that only one instance of the task can run at a time for a specific throttle tag.
     * This is useful for ensuring execution order and preventing race conditions.
     * See {@link Task} for more information.
     *
     * @param {string} name - The name of the task.
     * @param {TaskFunction} func - The function to be executed when the task runs.
     * @param {ThrottleTagGetter} [throttledIdGetter=() => "default"] - A function that generates a throttle tag identifier to group tasks for throttling.
     * @param {string} [description] - An optional description of the task.
     * @param {TaskOptions} [options={}] - Additional options to customize the task behavior.
     * @return {Task} The created throttled task.
     *
     * @example
     * ```ts
     * const task = Cadenza.createThrottledTask(
     *   'My task',
     *   async (ctx) => {
     *      await new Promise((resolve) => setTimeout(resolve, 1000));
     *      console.log('My task executed with context:', ctx);
     *   },
     *   // Will throttle by the value of ctx.foo to make sure tasks with the same value are executed sequentially
     *   (ctx) => ctx.foo,
     * );
     *
     * Cadenza.run(task, { foo: 'bar' }); // (First execution)
     * Cadenza.run(task, { foo: 'bar' }); // This will be executed after the first execution is finished
     * Cadenza.run(task, { foo: 'baz' }); // This will be executed in parallel with the first execution
     * ```
     */
    static createThrottledTask(name: string, func: TaskFunction, throttledIdGetter?: ThrottleTagGetter, description?: string, options?: TaskOptions): Task;
    /**
     * Creates a throttled meta task with the specified configuration.
     * See {@link createThrottledTask} and {@link createMetaTask} for more information.
     *
     * @param {string} name - The name of the throttled meta task.
     * @param {TaskFunction} func - The task function to be executed.
     * @param {ThrottleTagGetter} throttledIdGetter - A function to retrieve the throttling identifier.
     * @param {string} [description] - An optional description of the task.
     * @param {TaskOptions} [options={}] - Additional options for configuring the task.
     * @return {Task} The created throttled meta task.
     */
    static createThrottledMetaTask(name: string, func: TaskFunction, throttledIdGetter: ThrottleTagGetter, description?: string, options?: TaskOptions): Task;
    /**
     * Creates and returns a new debounced task with the specified parameters.
     * This is useful to prevent rapid execution of tasks that may be triggered by multiple events within a certain time frame.
     * See {@link DebounceTask} for more information.
     *
     * @param {string} name - The unique name of the task to be created.
     * @param {TaskFunction} func - The function to be executed by the task.
     * @param {string} [description] - An optional description of the task.
     * @param {number} [debounceTime=1000] - The debounce time in milliseconds to delay the execution of the task.
     * @param {TaskOptions & DebounceOptions} [options={}] - Additional configuration options for the task, including debounce behavior and other task properties.
     * @return {DebounceTask} A new instance of the DebounceTask with the specified configuration.
     *
     * @example
     * ```ts
     * const task = Cadenza.createDebounceTask(
     *   'My debounced task',
     *   (ctx) => {
     *      console.log('My task executed with context:', ctx);
     *   },
     *   'My debounced task description',
     *   100, // Debounce time in milliseconds. Default is 1000
     *   {
     *     leading: false, // Should the first execution of a burst be executed immediately? Default is false
     *     trailing: true, // Should the last execution of a burst be executed? Default is true
     *     maxWait: 1000, // Maximum time in milliseconds to wait for the next execution. Default is 0
     *   },
     * );
     *
     * Cadenza.run(task, { foo: 'bar' }); // This will not be executed
     * Cadenza.run(task, { foo: 'bar' }); // This will not be executed
     * Cadenza.run(task, { foo: 'baz' }); // This execution will be delayed by 100ms
     * ```
     */
    static createDebounceTask(name: string, func: TaskFunction, description?: string, debounceTime?: number, options?: TaskOptions & DebounceOptions): DebounceTask;
    /**
     * Creates a debounced meta task with the specified parameters.
     * See {@link createDebounceTask} and {@link createMetaTask} for more information.
     *
     * @param {string} name - The name of the task.
     * @param {TaskFunction} func - The function to be executed by the task.
     * @param {string} [description] - Optional description of the task.
     * @param {number} [debounceTime=1000] - The debounce delay in milliseconds.
     * @param {TaskOptions & DebounceOptions} [options={}] - Additional configuration options for the task.
     * @return {DebounceTask} Returns an instance of the debounced meta task.
     */
    static createDebounceMetaTask(name: string, func: TaskFunction, description?: string, debounceTime?: number, options?: TaskOptions & DebounceOptions): DebounceTask;
    /**
     * Creates an ephemeral task with the specified configuration.
     * Ephemeral tasks are designed to self-destruct after execution or a certain condition is met.
     * This is useful for transient tasks such as resolving promises or performing cleanup operations.
     * They are not registered by default.
     * See {@link EphemeralTask} for more information.
     *
     * @param {string} name - The name of the task to be created.
     * @param {TaskFunction} func - The function that defines the logic of the task.
     * @param {string} [description] - An optional description of the task.
     * @param {TaskOptions & EphemeralTaskOptions} [options={}] - The configuration options for the task, including concurrency, timeouts, and retry policies.
     * @return {EphemeralTask} The created ephemeral task instance.
     *
     * @example
     * By default, ephemeral tasks are executed once and destroyed after execution.
     * ```ts
     * const task = Cadenza.createEphemeralTask('My ephemeral task', (ctx) => {
     *   console.log('My task executed with context:', ctx);
     * });
     *
     * Cadenza.run(task); // Executes the task once and destroys it after execution
     * Cadenza.run(task); // Does nothing, since the task is destroyed
     * ```
     *
     * Use destroy condition to conditionally destroy the task
     * ```ts
     * const task = Cadenza.createEphemeralTask(
     *   'My ephemeral task',
     *   (ctx) => {
     *      console.log('My task executed with context:', ctx);
     *   },
     *   'My ephemeral task description',
     *   {
     *     once: false, // Should the task be executed only once? Default is true
     *     destroyCondition: (ctx) => ctx.foo > 10, // Should the task be destroyed after execution? Default is undefined
     *   },
     * );
     *
     * Cadenza.run(task, { foo: 5 }); // The task will not be destroyed and can still be executed
     * Cadenza.run(task, { foo: 10 }); // The task will not be destroyed and can still be executed
     * Cadenza.run(task, { foo: 20 }); // The task will be destroyed after execution and cannot be executed anymore
     * Cadenza.run(task, { foo: 30 }); // This will not be executed
     * ```
     *
     * A practical use case for ephemeral tasks is to resolve a promise upon some external event.
     * ```ts
     * const task = Cadenza.createTask('Confirm something', (ctx, emit) => {
     *   return new Promise((resolve) => {
     *     ctx.foo = uuid();
     *
     *     Cadenza.createEphemeralTask(`Resolve promise of ${ctx.foo}`, (c) => {
     *       console.log('My task executed with context:', ctx);
     *       resolve(c);
     *     }).doOn(`socket.confirmation_received:${ctx.foo}`);
     *
     *     emit('this_domain.confirmation_requested', ctx);
     *   });
     * });
     * ```
     */
    static createEphemeralTask(name: string, func: TaskFunction, description?: string, options?: TaskOptions & EphemeralTaskOptions): EphemeralTask;
    /**
     * Creates an ephemeral meta task with the specified name, function, description, and options.
     * See {@link createEphemeralTask} and {@link createMetaTask} for more details.
     *
     * @param {string} name - The name of the task to be created.
     * @param {TaskFunction} func - The function to be executed as part of the task.
     * @param {string} [description] - An optional description of the task.
     * @param {TaskOptions & EphemeralTaskOptions} [options={}] - Additional options for configuring the task.
     * @return {EphemeralTask} The created ephemeral meta task.
     */
    static createEphemeralMetaTask(name: string, func: TaskFunction, description?: string, options?: TaskOptions & EphemeralTaskOptions): EphemeralTask;
    /**
     * Creates a new routine with the specified name, tasks, and an optional description.
     * Routines are named entry points to starting tasks and are registered in the GraphRegistry.
     * They are used to group tasks together and provide a high-level structure for organizing and managing the execution of a set of tasks.
     * See {@link GraphRoutine} for more information.
     *
     * @param {string} name - The name of the routine to create.
     * @param {Task[]} tasks - A list of tasks to include in the routine.
     * @param {string} [description=""] - An optional description for the routine.
     * @return {GraphRoutine} A new instance of the GraphRoutine containing the specified tasks and description.
     *
     * @example
     * ```ts
     * const task1 = Cadenza.createTask("Task 1", () => {});
     * const task2 = Cadenza.createTask("Task 2", () => {});
     *
     * task1.then(task2);
     *
     * const routine = Cadenza.createRoutine("Some routine", [task1]);
     *
     * Cadenza.run(routine);
     *
     * // Or, routines can be triggered by signals
     * routine.doOn("some.signal");
     *
     * Cadenza.emit("some.signal", {});
     * ```
     */
    static createRoutine(name: string, tasks: Task[], description?: string): GraphRoutine;
    static createRoutineFromDefinition(definition: RuntimeRoutineDefinition): GraphRoutine;
    /**
     * Creates a meta routine with a given name, tasks, and optional description.
     * Routines are named entry points to starting tasks and are registered in the GraphRegistry.
     * They are used to group tasks together and provide a high-level structure for organizing and managing the execution of a set of tasks.
     * See {@link GraphRoutine} and {@link createRoutine} for more information.
     *
     * @param {string} name - The name of the routine to be created.
     * @param {Task[]} tasks - An array of tasks that the routine will consist of.
     * @param {string} [description=""] - An optional description for the routine.
     * @return {GraphRoutine} A new instance of the `GraphRoutine` representing the created routine.
     * @throws {Error} If no starting tasks are provided.
     */
    static createMetaRoutine(name: string, tasks: Task[], description?: string): GraphRoutine;
    static snapshotRuntime(): RuntimeSnapshot;
    static reset(): void;
}

type RuntimeControlAction = "detach" | "shutdown";
interface RuntimeHostOptions {
    runtimeSharing?: RuntimeSharingMode;
    runtimeName?: string | null;
    sessionId?: string | null;
    sessionRole?: RuntimeSessionRole | null;
    activeSessionCountProvider?: () => number;
    daemonProcessId?: number | null;
    onResetRuntime?: () => void;
}
declare class RuntimeHost {
    private readonly subscriptionManager;
    private readonly runtimeSharing;
    private readonly runtimeName;
    private readonly sessionId;
    private readonly sessionRole;
    private readonly activeSessionCountProvider;
    private readonly daemonProcessId;
    private readonly onResetRuntime;
    private pendingControlAction;
    constructor(options?: RuntimeHostOptions);
    dispose(): void;
    resetSubscriptions(): void;
    consumeControlAction(): RuntimeControlAction | null;
    handshake(): RuntimeProtocolHandshake;
    handle(request: RuntimeProtocolRequest): Promise<RuntimeProtocolResponse>;
    private normalizeError;
    private dispatch;
    private assertOperationAllowed;
    private bootstrapRuntime;
    private runtimeInfo;
    private detachRuntime;
    private shutdownRuntime;
    private resetRuntime;
    private subscribe;
    private unsubscribe;
    private nextEvent;
    private pollEvents;
    private upsertTask;
    private upsertHelper;
    private upsertGlobal;
    private linkTasks;
    private observeTaskSignal;
    private emitTaskSignal;
    private bindTaskIntent;
    private bindTaskHelper;
    private bindTaskGlobal;
    private bindHelperHelper;
    private bindHelperGlobal;
    private upsertRoutine;
    private observeRoutineSignal;
    private upsertIntent;
    private upsertActor;
    private upsertActorTask;
    private runTarget;
    private emitSignal;
    private inquireIntent;
    private requireTask;
    private requireRoutine;
    private applyTaskDecorations;
    private applyHelperDecorations;
    private applyAllTaskLinks;
    private applyRoutineDecorations;
    private rematerializeRoutinesStartingWith;
    private rematerializeActorTasksFor;
    private materializeActorTask;
    private snapshotTask;
    private snapshotHelper;
    private snapshotGlobal;
    private snapshotRoutine;
    private parseSignalPatterns;
    private parsePositiveInteger;
    private parseNonNegativeInteger;
}

export { Actor, type ActorConsistencyProfileName, type ActorDefinition, type ActorFactoryOptions, type ActorInvocationOptions, type ActorKeyDefinition, type ActorKind, type ActorLoadPolicy, type ActorRuntimeReadGuard, type ActorSpec, type ActorStateDefinition, type ActorStateReducer, type ActorStateStore, type ActorTaskBindingDefinition, type ActorTaskBindingOptions, type ActorTaskContext, type ActorTaskHandler, type ActorTaskMode, type ActorTaskRuntimeMetadata, type ActorWriteContract, type AnyObject, type CadenzaMode, type DebounceOptions, DebounceTask, type EmitOptions, EphemeralTask, type EphemeralTaskOptions, GlobalDefinition, GraphContext, GraphRegistry, GraphRoutine, GraphRun, GraphRunner, HelperDefinition, type HelperFunction, type IdempotencyPolicy, InquiryBroker, type InquiryOptions, type Intent, META_ACTOR_SESSION_STATE_PERSIST_INTENT, type ResolvedRuntimeValidationPolicy, type RetryPolicy, type RuntimeActorTaskDefinition, type RuntimeGlobalDefinition, type RuntimeHandlerLanguage, type RuntimeHelperDefinition, RuntimeHost, type RuntimeInfo, type RuntimeNextEventResult, type RuntimePollEventsResult, type RuntimeProtocolError, type RuntimeProtocolHandshake, type RuntimeProtocolOperation, type RuntimeProtocolRequest, type RuntimeProtocolResponse, type RuntimeRoutineDefinition, type RuntimeSessionRole, type RuntimeSharingMode, type RuntimeSignalEmissionMode, type RuntimeSignalEvent, type RuntimeSnapshot, type RuntimeSubscription, type RuntimeTaskDefinition, type RuntimeTaskOptions, type RuntimeTools, type RuntimeValidationMode, type RuntimeValidationPolicy, type RuntimeValidationScope, type Schema, type SchemaConstraints, type SchemaDefinition, type SchemaType, type SessionPolicy, SignalBroker, type SignalDefinitionInput, type SignalDeliveryMode, SignalEmitter, type SignalMetadata, type SignalReceiverFilter, Task, type TaskFunction, type TaskOptions, type TaskResult, type ThrottleTagGetter, Cadenza as default, getActorTaskRuntimeMetadata };
