import type { FlowRecovery } from './host/flow-recovery.js'; export type { FlowRecovery } from './host/flow-recovery.js'; import type { IntentStageRequest } from './host/intent-stages.js'; /** * Pure JS parser for .tools file content (string or object) * @param input JSON string or parsed object * @returns tools array */ export declare function parseTools(input: string | object): any[]; /** * Pure JS parser for .flows file content (string or object) * @param input JSON string or parsed object * @returns flows array */ export declare function parseFlows(input: string | object): any[]; /** * Logger interface for use with WorkflowEngine. * * Any logger passed to initSession must implement these four methods. * * @example * class MyLogger implements Logger { * info(msg: string) { ... } * warn(msg: string) { ... } * error(msg: string) { ... } * debug(msg: string) { ... } * } */ export declare class JSFEExecutionError extends Error { readonly cause?: Error | undefined; constructor(message: string, cause?: Error | undefined); } export interface Logger { info(message: string, ...args: unknown[]): void; warn(message: string, ...args: unknown[]): void; error(message: string, ...args: unknown[]): void; debug(message: string, ...args: unknown[]): void; setLevel?(level: string): void; } export type MessageTemplates = Record; export type MessageRegistry = Record; export interface GuidanceConfig { enabled: boolean; mode: 'append' | 'prepend' | 'template' | 'none'; template?: string; separator?: string; contextSelector?: 'general' | 'payment' | 'auto'; guidanceMessages?: { general?: string; payment?: string; } | MessageRegistry; } export declare const GUIDANCE_CONFIG_EXAMPLES: { append: { enabled: boolean; mode: "append"; separator: string; contextSelector: "auto"; }; elegant: { enabled: boolean; mode: "template"; template: string; contextSelector: "auto"; }; integrated: { enabled: boolean; mode: "template"; template: string; separator: string; contextSelector: "auto"; guidanceMessages: { general: string; payment: string; }; }; compact: { enabled: boolean; mode: "template"; template: string; contextSelector: "auto"; }; silent: { enabled: boolean; mode: "none"; }; automation: { enabled: boolean; mode: "none"; }; disabled: { enabled: boolean; mode: "none"; }; multilingual: { enabled: boolean; mode: "template"; template: string; contextSelector: "auto"; guidanceMessages: { en: { general: string; payment: string; }; es: { general: string; payment: string; }; }; }; }; export declare function getSystemMessage(engine: Engine, messageId: string, context?: Record): string; export declare function getFlowPrompt(engine: Engine, flowName: string): string; export type StepType = 'SAY' | 'SAY-GET' | 'SET' | 'CALL-TOOL' | 'FLOW' | 'SWITCH' | 'CASE' | 'RETURN' | 'END' | 'DISPATCH'; export interface ContextEntry { role: 'user' | 'assistant' | 'system' | 'tool'; content: string | Record | unknown; timestamp: number; stepId?: string; toolName?: string; metadata?: Record; start?: { flow: string; arguments?: Record; }; } export type AiCallbackFunction = ((systemInstruction: string, userMessage: string, jsonSchema?: string, request?: AiCallbackRequest) => Promise) | null; /** A flow parameter as the intent-detection call sees it. */ export interface FlowParameterDefinition { name: string; description: string; type?: string; enum?: string[]; jsonSchema?: Record; internal?: boolean; } /** Structured form of the intent-detection call; see AiCallbackFunction. */ export interface DetectFlowRequest { task: 'detect_flow'; input: string; conversation: { role: 'user' | 'assistant'; content: string; }[]; flows: { id: string; name: string; description: string; parameters: FlowParameterDefinition[]; }[]; } export type AiCallbackRequest = DetectFlowRequest | IntentStageRequest; /** * @interface EngineSessionContext * @property {string} sessionId - Unique identifier for the session * @property {string} userId - Identifier for the user * @property {Date} createdAt - Timestamp when the session was created * @property {Date} lastActivity - Timestamp of the last activity in the session * @property {FlowFrame[][]} flowStacks - Stack of active flows (can be nested) * @property {string[]} globalAccumulatedMessages - All messages exchanged in the session * @property {{ user?: ContextEntry; assistant?: ContextEntry }} lastChatTurn - Last user and assistant messages * @property {Record} globalVariables - Global variables accessible across flows * @property {string | null} [response] - Latest response from flow processing * @property {TransactionData[]} [completedTransactions] - Completed transactions for host access * @property {Record | undefined} cargo - Additional session data for host use * @property {FlowOutcome} [lastFlowOutcome] - Declared outcome of a flow that TERMINATED this turn (one-shot, cleared at the start of each updateActivity) * @property {DispatchRecord} [lastTurnDispatch] - Set when a DISPATCH step re-routed this turn's input (one-shot, cleared at the start of each updateActivity) */ export interface EngineSessionContext { /** Persistence policy is pinned to an action-enabled conversation, including snapshots before its first effect. */ actionPersistence?: 'durable' | 'session-only'; continuationSafetyRevisions?: Record; continuationSafetyHold?: { reason: string; flowId?: string; }; actionRecoveryIdentity?: { protocol: number; runtime: string; definitions: string; }; actionRecoveryProgress?: number; actionRecoveryEpoch?: string | null; actionRecoveryPolicy?: { revision: number; paths: Record; }; lastTurnRecovery?: { key: string; sequence: number; deferredInput: ContextEntry; status?: string; hold?: boolean; reason?: string; }; sessionId: string; userId: string; createdAt: Date; lastActivity: Date; flowStacks: FlowFrame[][]; globalAccumulatedMessages: string[]; lastChatTurn: { user?: ContextEntry; assistant?: ContextEntry; }; globalVariables: Record; response?: string | null; completedTransactions?: TransactionData[]; cargo: Record | undefined; language?: string; hasTentativeFlowInit?: boolean; lastFlowRecovery?: FlowRecovery; lastFlowOutcome?: FlowOutcome; lastTurnToolCalls?: ToolCallRecord[]; lastTurnDispatch?: DispatchRecord; } /** * Host-facing record of a DISPATCH: the flow whose DISPATCH step ended every flow, and the flow * intent detection then started with the same input — or null when none matched, in which case * the engine returned no response and the host answers the turn itself. */ export interface DispatchRecord { fromFlow: string; matchedFlow: string | null; } /** * One tool call the engine ATTEMPTED during an updateActivity call — see * EngineSessionContext.lastTurnToolCalls and "Host Responsibilities" in the README. * * Recorded at the entry of callTool, BEFORE anything is sent, for every attempt including * internal retries. It is deliberately an attempt and not a success: a call that timed out * or threw may still have taken effect on the remote side (a card charged, an SMS sent), so * the host must treat any record here as "an external action may have happened". */ export interface ToolCallRecord { tool: string; implementation: string; transactionId: string | null; at: number; } /** * Host-facing outcome a flow declares about its own ending, via an optional * `outcome` (+ `reason`) attribute on a terminal step (RETURN / END / final SAY): * * { "type": "RETURN", "value": "''", "outcome": "unresolved", "reason": "otp_retries_exhausted" } * * Semantics: * - 'unresolved': the flow ended WITHOUT resolving the user's need — its * transaction is marked failed (not completed) and the host can run a * recovery/post-mortem turn. * - 'deflected': a decoy ("fake flow") absorbed an intent-detection false * positive by design — transaction completes; hosts should NOT treat it as * a user struggle (stats only). * - 'resolved' (or any other value): informational; transaction completes. * * Flows that declare nothing behave exactly as before. */ export interface FlowOutcome { flowName: string; outcome: string; reason?: string; endedBy: 'return' | 'completion' | 'dispatch'; } export interface FlowStep { id?: string; type: StepType; recovery?: { version: 1; mode: string; reason: string; form?: string; flow?: string; }; responseParameters?: FlowParameterDefinition[]; responseVariable?: string; tool?: string; args?: Record; variable?: string; value?: string; digits?: unknown; asSpoken?: boolean | string; pii?: boolean | string; [key: string]: unknown; name?: string; callType?: 'call' | 'replace' | 'reboot'; initializeDefaults?: boolean; keepSay?: boolean; discardSay?: boolean; branches?: Record; _branchOrder?: string[]; onFail?: FlowStep; retryCount?: number; maxRetries?: number; retryDelay?: number; retryStrategy?: 'immediate' | 'exponential' | 'linear' | 'manual'; retryOnConditions?: Array<{ errorPattern: string; action: 'retry' | 'skip' | 'ask_user' | 'fallback'; fallbackStep?: FlowStep; }>; inputValidation?: { patterns?: Array<{ field: string; pattern: string; message: string; }>; customValidator?: string; }; } export interface TransactionStep { stepId: string; stepType: StepType; tool?: string; result?: unknown; error?: string; duration: number; status: 'success' | 'error'; timestamp: Date; retryCount?: number; } export interface TransactionData { id: string; flowName: string; initiator: string; userId: string; steps: TransactionStep[]; state: 'active' | 'completed' | 'failed' | 'rolled_back' | 'yielded'; createdAt: Date; completedAt?: Date; failedAt?: Date; rolledBackAt?: Date; failureReason?: string; metadata: Record; } export declare class TransactionManager { static create(flowName: string, initiator: string, userId: string): TransactionData; static addStep(transaction: TransactionData, step: FlowStep, result: unknown, duration: number, status?: 'success' | 'error'): void; static addError(transaction: TransactionData, step: FlowStep, error: Error, duration: number): void; static sanitizeForLog(data: unknown): unknown; static rollback(transaction: TransactionData): void; static complete(transaction: TransactionData): void; static yield(transaction: TransactionData): void; static fail(transaction: TransactionData, reason: string): void; } export interface FlowFrame { flowName: string; flowId: string; flowVersion: string; safetyRevision?: string; flowStepsStack: FlowStep[]; contextStack: ContextEntry[]; inputStack: unknown[]; variables: Record; transaction: TransactionData; userId: string; startTime: number; pendingVariable?: string; pendingVariableContext?: string; pendingVariableAsSpoken?: boolean; pendingVariablePii?: boolean; lastSayMessage?: string; pendingInterruption?: Record; declaredOutcome?: { outcome: string; reason?: string; }; accumulatedMessages?: string[]; parentTransaction?: string; justResumed?: boolean; isolatedScope?: boolean; } export type Engine = WorkflowEngine; /** Explicit JSON authoring input. The constructor lowers version 1 and 2 declarations (2: one parameter contract, shared functions). */ export interface FlowDeclaration { declarationVersion: 1 | 2; id: string; [key: string]: unknown; } export interface FlowDefinition { id: string; name: string; prompt?: string; prompt_en?: string; prompt_es?: string; prompt_pt?: string; prompt_fr?: string; prompt_de?: string; [key: `prompt_${string}`]: string | undefined; description: string; version: string; safetyRevision?: string; primary?: boolean; wraps?: string; interruptable?: boolean; scope?: 'shared' | 'isolated'; parameters?: FlowParameterDefinition[]; parameterInstructions?: string; steps: FlowStep[]; variables?: Record; metadata?: { riskLevel?: string; category?: string; [key: string]: unknown; }; } export type ArgsType = Record; export interface ToolDefinition { id: string; name: string; description: string; schema?: { required?: string[]; properties?: Record; }; parameters?: { type: string; properties?: Record; required?: string[]; additionalProperties?: boolean; }; implementation?: { type: 'local' | 'http'; function?: string; url?: string; method?: HttpMethod; contentType?: string; pathParams?: string[]; queryParams?: string[]; headers?: Record; responseMapping?: MappingConfig; timeout?: number; retries?: number; acceptStatus?: number[]; authentication?: AuthConfig; }; security?: { rateLimit?: { requests: number; window: number; }; }; apiKey?: string; riskLevel?: 'low' | 'medium' | 'high'; category?: string; /** * Optional JSON Schema of the value this tool hands the flow — the CALL-TOOL `variable`, i.e. after * `responseMapping` when there is one. The tool's output contract, as `parameters` is its input * contract: flow authors and AI co-pilots read result paths from it instead of guessing them. * * The engine never changes, blocks or re-shapes a result because of it. Only when the host opts in * with `engine.validateToolReturns = true` is each result checked against it, and a mismatch (or a * schema that does not compile) is logged as a warning — the result is still delivered unchanged. */ returns?: Record; } export interface PropertySchema { type: 'string' | 'number' | 'boolean' | 'object' | 'array'; description?: string; enum?: (string | number)[]; minimum?: number; maximum?: number; minLength?: number; maxLength?: number; pattern?: string; items?: PropertySchema; properties?: Record; required?: string[]; default?: unknown; } export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS'; export interface AuthConfig { type: 'bearer' | 'basic' | 'apikey' | 'hmac'; token?: string; username?: string; password?: string; key?: string; secret?: string; header?: string; } export interface ApprovedFunctions { [functionName: string]: ((...args: unknown[]) => unknown) | undefined; } export interface SystemContext { [key: string]: string | number | boolean | null | undefined; } export interface ValidationResult { isValid: boolean; errors: string[]; warnings: string[]; } export type JsonPathMappingConfig = { type: 'jsonPath'; mappings: Record; strict?: boolean; }; export type ObjectMappingConfig = { type: 'object'; mappings: Record; strict?: boolean; }; export type ArrayMappingConfig = { type: 'array'; source?: string; filter?: ConditionConfig; itemMapping?: MappingConfig; sort?: { field: string; order?: 'asc' | 'desc'; }; offset?: number; limit?: number; fallback?: unknown[]; }; export type TemplateMappingConfig = { type: 'template'; template: string; dataPath?: string; }; export type ConditionalMappingConfig = { type: 'conditional'; conditions: Array<{ if: ConditionConfig; then: MappingConfig; }>; else?: MappingConfig; }; export type PathConfig = { path: string; transform?: ValueTransformConfig; fallback?: unknown; }; export interface ValueTransformConfig { type: 'parseInt' | 'parseFloat' | 'toLowerCase' | 'toUpperCase' | 'trim' | 'replace' | 'concat' | 'regex' | 'date' | 'default' | 'conditional' | 'substring' | 'split' | 'join' | 'abs' | 'round' | 'floor' | 'ceil' | 'template' | 'sum' | 'average' | 'count' | 'min' | 'max' | 'multiply' | 'divide' | 'percentage' | 'add' | 'subtract' | 'currentYear' | 'yearDifference' | 'handlebars' | 'custom'; fallback?: unknown; prefix?: string; suffix?: string; pattern?: string; replacement?: string; group?: number; start?: number; end?: number; delimiter?: string; index?: number; template?: string; calculation?: string; condition?: ConditionConfig; conditions?: Array<{ if: ConditionConfig; then: unknown; }>; trueValue?: unknown; falseValue?: unknown; value?: unknown; flags?: string; else?: unknown; field?: string; precision?: number; divisor?: number; multiplier?: number; addend?: number; subtrahend?: number; fromYear?: number; dataPath?: string; } export interface ConditionConfig { field: string; operator: 'equals' | 'eq' | 'notEquals' | 'ne' | 'contains' | 'exists' | 'notExists' | 'greaterThan' | 'gt' | 'lessThan' | 'lt' | 'greaterThanOrEqual' | 'gte' | 'lessThanOrEqual' | 'lte' | 'startsWith' | 'endsWith' | 'matches' | 'in' | 'hasLength' | 'isArray' | 'isObject' | 'isString' | 'isNumber'; value?: unknown; } export type MappingConfig = JsonPathMappingConfig | ObjectMappingConfig | ArrayMappingConfig | TemplateMappingConfig | ConditionalMappingConfig | PathConfig | string | Record; /** * Represents any object that can be traversed by path * Object with string keys for safe path traversal */ export interface PathTraversableObject { [key: string]: unknown; } /** Intrinsic admission marker for generators and hosts. Absent safetyRevision retains legacy behavior. */ export { continuationSafetyProtocol } from './forms/continuation-safety.js'; export declare function getFlowForInput(input: string, engine: Engine): Promise; export declare function detectFlowWithParameters(input: string, engine: Engine, continuation?: FlowDefinition, responseContext?: string): Promise<{ flow: FlowDefinition; parameters?: Record; } | null>; /** * The root names a template expression reads — `{{ ... }}` without the braces — for the validator's * undefined-variable check. String literals are removed first; a name after `.` is a property, a name before a * `:` that follows `{` or `,` is an object key, and names the expression declares itself (function parameters, * var/let/const) are local. What is left are the variables and functions the expression needs from its scope. * Exported for tests. */ export declare function templateExpressionNames(expression: string): string[]; /** * Thin wrappers (flow attribute `wraps`). A flow that wraps another (named by id or name) becomes the entry point in its * place: the wrapped flow loses `primary` and stays callable as a worker, and the wrapper takes the wrapped flow's * description, parameters, prompts and primary flag unless it declares its own, so intent detection reads one * description kept in one place. Copies are returned; the host's flow objects are not changed. A `wraps` that names no * flow in the menu is logged and ignored. Without any `wraps`, the menu is returned as given. */ export declare function applyWraps(flowsMenu: FlowDefinition[]): FlowDefinition[]; export declare class WorkflowEngine implements Engine { private _actionPersistence; /** Native actions require durable storage unless the host deliberately selects session-only guards. */ get actionPersistence(): 'durable' | 'session-only'; set actionPersistence(mode: 'durable' | 'session-only'); /** Host-injected durable action journal. Missing storage never implicitly enables session-only actions. */ actionJournal?: { claim(input: { sessionId: string; record: any; action: any; checkpoint?: any; }): Promise; complete(input: { sessionId: string; record: any; action: any; outcome: any; checkpoint?: any; }): Promise; checkpoint(input: { sessionId: string; keys?: string[]; receipts?: Array<{ key: string; sequence: number; }>; }): Promise; pending(input: { sessionId: string; }): Promise; }; private actionRecoveryIdentityPromise?; /** Loaded definitions are immutable after activation. Hot reload constructs a new engine. */ getActionRecoveryIdentity(): Promise<{ protocol: number; runtime: string; definitions: string; }>; cargo: Record | undefined; flowsMenu: FlowDefinition[]; private readonly sourceFlowDeclarations; private readonly namedFunctionNamespaces; /** The flow set's shared data, read in expressions as $data.: deep-frozen, never persisted in session variables. */ sharedData?: Record; /** A detached authoring copy; engine compilation and validation never become editor source. */ getFlowDeclarations(): Array; /** Engine-only lexical helpers for the current definition, never persisted in session variables. */ getNamedFunctionNamespace(): Record | undefined; toolsRegistry: ToolDefinition[]; APPROVED_FUNCTIONS: ApprovedFunctions; sessionId: string; createdAt: Date; lastActivity: Date; language?: string; messageRegistry?: MessageRegistry; guidanceConfig?: GuidanceConfig; globalVariables?: Record; aiCallback: AiCallbackFunction; aiTimeOut: number; /** * Opt-in (default false): check every tool result against its tool's `returns` schema and log a * warning on a mismatch. Diagnostic only — a result is never altered or withheld because of it. */ validateToolReturns: boolean; /** * Opt-in (default 'single-call'): how intent detection asks aiCallback. 'two-stage': stage 1 picks the flow * (from the primaries' descriptions only), stage 2 extracts the SELECTED flow's parameters; each call carries * both executors' instructions (`llm`, `systemOne`) as its 4th argument — see jsfe/host intent-stages. * 'single-call': the original one call that picks a flow and extracts parameters for every flow at once. */ intentDetection: 'single-call' | 'two-stage'; /** This turn's host start (ContextEntry.start), or null. */ hostStart: { flow: string; arguments?: Record; } | null; /** * Opt-in (default false): log one warning when a tool returns a failure (`success: false` or a * non-zero `error`), with the tool and its message, digit runs masked. Diagnostic only. */ logToolFailures: boolean; /** * Set by a DISPATCH step to the name of the flow that dispatched; processActivity consumes it * within the same call and routes the turn's input to intent detection. Never persisted. */ pendingDispatchFrom: string | null; /** Internal per-turn routing callback; never serialized or retained across updateActivity calls. */ dispatchIfMatched: ((frame: FlowFrame, step: any) => Promise) | null; private enabledCommands; private commandsEnabled; private sessionContext; set logger(value: Logger); get logger(): Logger; get flowStacks(): FlowFrame[][]; get globalAccumulatedMessages(): string[]; get lastChatTurn(): { user?: ContextEntry; assistant?: ContextEntry; }; /** * Engine-internal: note a tool call about to be attempted on the current session. * Called by callTool before anything is sent. Public only so the module-level tool * executor can reach the private session; hosts READ the result from * `engineSessionContext.lastTurnToolCalls` and never call this. */ recordToolCall(record: ToolCallRecord): void; /** * Initialize a new EngineSessionContext for a user session. * If hostLogger is null, uses the global default logger. * @param hostLogger - Logger instance for this session. Must implement info, warn, error, and debug methods. * @param aiCallback - Callback function for AI operations * @param flowsMenu - List of available flow definitions * @param toolsRegistry - List of available tool definitions * @param APPROVED_FUNCTIONS - Approved functions for the engine * @param globalVariables - Optional global variables shared across all new flows * @param validateOnInit - Whether to perform validation on initialization (default: true) * @param language - Optional language code for localization * @param aiTimeOut - Optional timeout in milliseconds for AI calls (default: 2000ms) * @param messageRegistry - Optional message registry for custom messages * @param guidanceConfig - Optional guidance configuration for AI interactions * @example * const engine = new WorkflowEngine(logger, aiCallback, flowsMenu, toolsRegistry, APPROVED_FUNCTIONS); * // With custom timeout: * const engine = new WorkflowEngine(logger, aiCallback, flowsMenu, toolsRegistry, APPROVED_FUNCTIONS, [], true, 'en', 1000); */ constructor(hostLogger: Logger | null, aiCallback: AiCallbackFunction, flowsMenu: Array, toolsRegistry: ToolDefinition[], APPROVED_FUNCTIONS: ApprovedFunctions, globalVariables?: Record, // Optional global variables shared across all new flows validateOnInit?: boolean, language?: string, aiTimeOut?: number, // Optional AI timeout in milliseconds (default 2000ms) messageRegistry?: MessageRegistry, guidanceConfig?: GuidanceConfig); /** * Initialize a new session context for a user session. * * @param userId - User identifier for this session * @param sessionId - Unique identifier for the session * @param language - Optional language code for this session (defaults to engine's language) * @returns EngineSessionContext object that should be persisted by the host * @throws Error if logger does not implement all required methods * * @example * const engine = new WorkflowEngine(...); * const session = engine.initSession('user-123', 'session-456', 'en'); */ initSession(userId: string, sessionId: string, language?: string): EngineSessionContext; updateActivity(contextEntry: ContextEntry, engineSessionContext: EngineSessionContext): Promise; /** * Enable specific system commands or all commands if none specified. * Useful for voice applications that want to limit command availability. * * @param commands - Array of command names to enable, or empty/null to enable all * * @example * ```typescript * // Enable only help and status commands (disable cancel for voice apps) * engine.enableCommands(['help', 'status']); * * // Enable all commands * engine.enableCommands(); * ``` */ enableCommands(commands?: string[]): void; /** * Disable specific system commands or all commands if none specified. * Useful for automation flows that should not be interruptible. * * @param commands - Array of command names to disable, or empty/null to disable all * * @example * ```typescript * // Disable only cancel command (allow help/status for voice apps) * engine.disableCommands(['cancel']); * * // Disable all commands for automation flows * engine.disableCommands(); * ``` */ disableCommands(commands?: string[]): void; /** * Check if a specific system command is currently enabled. * * @param command - The command to check * @returns true if the command is enabled, false otherwise * * @example * ```typescript * if (engine.isCommandEnabled('cancel')) { * // Show cancel option in UI * } * ``` */ isCommandEnabled(command: string): boolean; /** * Get the current session language */ getSessionLanguage(): string | undefined; /** * Set the session language */ setSessionLanguage(language: string): void; /** * Get list of currently enabled commands. * * @returns Array of enabled command names * * @example * ```typescript * const enabledCommands = engine.getEnabledCommands(); * console.log('Available commands:', enabledCommands); * ``` */ getEnabledCommands(): string[]; /** * Reconstruct variable references after JSON deserialization. * This fixes the issue where JSON.stringify/parse breaks shared object references * that are crucial for variable inheritance between flows. */ reconstructVariableReferences(): void; addAccumulatedMessage(message: string): void; getAndClearAccumulatedMessages(): string[]; hasAccumulatedMessages(): boolean; setTentativeFlowInit(value: boolean): void; getSessionContext(): EngineSessionContext; /** * The session as a host should store it (jsfe 1.9.1): a copy without the form-instance definition copies that the * loaded flows reproduce exactly, and with revision hashes only for open form instances. updateActivity restores it. * The session passed in is not changed. */ storedSession(session: EngineSessionContext): EngineSessionContext; stampFlowRecovery(recovery: FlowRecovery): void; stampFlowOutcome(outcome: FlowOutcome): void; getTentativeFlowInit(): boolean; initializeFlowStacks(): void; resetFlowState(): void; clearFlowOutcome(): void; recordDispatch(record: DispatchRecord): void; getCurrentStack(): FlowFrame[]; getCurrentStackLength(): number; getCurrentFlowFrame(): FlowFrame; createNewStack(): void; pushToCurrentStack(flowFrame: FlowFrame): void; popFromCurrentStack(): FlowFrame; getFlowForInput(input: string): Promise; /** * Performs comprehensive validation of all flows during engine initialization * This catches configuration errors early and provides immediate feedback */ performInitializationValidation(): void; /** * Walks ALL flows in flowsMenu and sets _branchOrder on every CASE/SWITCH step. * This ensures branch evaluation order survives unordered serialization (e.g. DynamoDB Maps). * * Called automatically after performInitializationValidation(), but hosts MUST call this * after adding flows to flowsMenu post-construction (e.g. flowsMenu.unshift(...systemFlows)). */ ensureBranchOrder(): void; /** * Validates a single flow and all its dependencies recursively * @param flowName - Name of the flow to validate * @param options - Validation options * @returns Validation result with errors, warnings, and flow graph */ validateFlow(flowName: string, options?: any): any; /** * Recursively validates a flow and its sub-flows */ private _validateFlowRecursive; /** * Validates flow metadata and basic structure */ private _validateFlowMetadata; /** * Validates the parameters intent detection extracts: unique names, and a well-formed enum. * An enum is a non-empty list of unique, non-empty strings, allowed only on a string parameter - * values are matched as strings, so on any other type it could never match. */ private _validateFlowParameters; /** * Validates flow variable definitions */ private _validateFlowVariables; /** * Validates a single step within a flow */ private _validateFlowStep; /** * Validates SAY and SAY-GET steps */ private _validateSayStep; /** * Validates SET steps */ private _validateSetStep; /** * Validates SWITCH steps */ private _validateSwitchStep; /** * Validates CASE steps */ private _validateCaseStep; /** * Validates CALL-TOOL steps */ private _validateCallToolStep; /** * Validates FLOW steps (sub-flow calls) */ private _validateSubFlowStep; /** * Validates onFail handlers */ private _validateOnFailHandler; /** * Checks for circular references in the flow call graph */ private _checkCircularReferences; /** * Validates all flows in the flowsMenu * @param options - Validation options * @returns Summary of validation results */ validateAllFlows(options?: any): any; /** * Gets the current variable scope available at a specific step * This includes variables defined in flow definition + variables created by previous steps + parent flow variables */ private _getCurrentStepScope; /** * Updates the variable scope after a step executes * This tracks what variables a step creates for subsequent validation */ private _updateScopeAfterStep; /** * Determines what variables a step creates/defines */ private _addStepVariablesToScope; /** * Validates tool arguments against tool schema */ private _validateToolArguments; /** * Validates variable references in arguments, values, etc. */ private _validateVariableReferences; /** * Validates response mapping configurations */ private _validateResponseMapping; /** * Validates argument type against schema */ private _validateArgumentType; private _validateJsonPathMapping; private _validateObjectMapping; private _validateArrayMapping; private _validateTemplateMapping; private _validateConditionalMapping; } //# sourceMappingURL=index.d.ts.map