/** * Workflows - Pipeline and orchestration patterns */ import { type FlowStep } from './patterns'; export { Loop, loop as loopPattern, type LoopConfig, type LoopResult } from './loop'; export { Repeat, repeat as repeatPattern, type RepeatConfig, type RepeatResult, type RepeatContext } from './repeat'; export { If, Parallel, Route, Include, when, if_, ifStep, include, routePattern, parallelPattern, MAX_NESTING_DEPTH, DEFAULT_MAX_PARALLEL_WORKERS, PARALLEL_ON_FAILURE_MODES, WorkflowStepError, NestingDepthError, evaluateWorkflowCondition, substituteWorkflowVariables, setRecipeResolver, getRecipeResolver, isControlFlowPattern, type FlowStep, type AgentLikeStep, type IncludableWorkflow, type RecipeResolver, type ParallelOnFailure, type ParallelBranchError, } from './patterns'; export type StepStatus = 'pending' | 'running' | 'completed' | 'failed' | 'skipped'; export interface StepResult { stepId: string; stepName: string; status: StepStatus; output?: T; error?: Error; duration: number; startedAt: number; completedAt?: number; } export interface WorkflowContext { workflowId: string; stepResults: Map; metadata: Record; /** The original input handed to `AgentFlow.run()` (Python: WorkflowContext.input). */ input?: any; get(stepName: string): T | undefined; set(key: string, value: any): void; } export type StepFunction = (input: TInput, context: WorkflowContext) => Promise | TOutput; /** * Context configuration - controls how step accesses and modifies context */ export interface StepContextConfig { /** Get context from specific step(s) */ contextFrom?: string | string[]; /** Retain full context from previous steps */ retainFullContext?: boolean; /** Additional context variables to inject */ inject?: Record; } /** * Output configuration - controls where step output goes */ export interface StepOutputConfig { /** Store output in this context variable */ outputVariable?: string; /** Write output to file */ outputFile?: string; /** Parse output as JSON */ outputJson?: boolean; /** Transform output before storing */ transform?: (output: any) => any; } /** * Execution configuration - controls how step executes */ export interface StepExecutionConfig { /** Run asynchronously (non-blocking) */ async?: boolean; /** Enable quality check after execution */ qualityCheck?: boolean | ((output: any) => boolean); /** Rerun if quality check fails */ rerun?: boolean; /** Maximum rerun attempts */ maxRerunAttempts?: number; /** Delay between retries in ms */ retryDelay?: number; } /** * Routing configuration - controls workflow branching */ export interface StepRoutingConfig { /** Next step(s) to execute (overrides default sequential flow) */ nextSteps?: string | string[]; /** Condition for branching */ branchCondition?: (output: any, context: WorkflowContext) => string | string[] | null; /** Skip to step if condition met */ skipTo?: string; /** Early exit condition */ exitIf?: (output: any, context: WorkflowContext) => boolean; } export interface TaskConfig { name: string; execute: StepFunction; condition?: (context: WorkflowContext) => boolean; onError?: 'fail' | 'skip' | 'retry'; maxRetries?: number; timeout?: number; context?: StepContextConfig; output?: StepOutputConfig; execution?: StepExecutionConfig; routing?: StepRoutingConfig; } /** * Workflow Step - Enhanced with Python-parity configuration */ export declare class Task { readonly id: string; readonly name: string; readonly execute: StepFunction; readonly condition?: (context: WorkflowContext) => boolean; readonly onError: 'fail' | 'skip' | 'retry'; readonly maxRetries: number; readonly timeout?: number; readonly contextConfig?: StepContextConfig; readonly outputConfig?: StepOutputConfig; readonly executionConfig?: StepExecutionConfig; readonly routingConfig?: StepRoutingConfig; constructor(config: TaskConfig); /** * Get input based on context configuration */ private getInputFromContext; /** * Store output based on output configuration */ private storeOutput; /** * Determine next step based on routing configuration */ getNextSteps(output: TOutput, context: WorkflowContext): string[] | null; run(input: TInput, context: WorkflowContext): Promise>; private delay; private executeWithTimeout; } /** * Options accepted by `AgentFlow.run()`. */ export interface AgentFlowRunOptions { /** Seed values for `context.metadata` (Python: Workflow.variables). */ variables?: Record; /** * Recipes/workflows already on the include stack. Set automatically when a * workflow is run through an `Include` step so circular includes are caught * across nested runs. */ includeChain?: Set; } /** * Object form of the `AgentFlow` constructor (Python: AgentFlow(name, description, steps, variables)). */ export interface AgentFlowConfig { name?: string; description?: string; steps?: FlowStep[]; variables?: Record; } /** * AgentFlow - Sequential pipeline execution (renamed from Workflow for Python parity) * * Steps may be `Task`s, plain functions, agents (anything with `chat()`), or * control-flow patterns: `If`, `Parallel`, `Route`, `Include`, `Loop`, `Repeat`. * * @example * ```typescript * import { Agent, AgentFlow } from 'praisonai'; * * const researcher = new Agent({ instructions: "Research the topic" }); * const writer = new Agent({ instructions: "Write based on research" }); * * const flow = new AgentFlow("Research Pipeline") * .agent(researcher, "Research AI trends") * .agent(writer, "Write article based on research"); * * await flow.run("AI in 2025"); * ``` * * @example Patterns * ```typescript * const flow = new AgentFlow({ * name: 'review', * variables: { score: 90 }, * steps: [ * new Parallel([summarise, factCheck], 2, 'fail_all'), * when('{{score}} > 80', [approve], [reject]), * ], * }); * ``` */ export declare class AgentFlow { readonly id: string; readonly name: string; readonly description: string; /** Default variables seeded into `context.metadata` on every run. */ readonly variables: Record; private steps; constructor(nameOrConfig?: string | AgentFlowConfig); /** * Add a step to the workflow. * * Accepts a `TaskConfig` (wrapped in a `Task`), a ready `Task`, a function, * an agent, or any control-flow pattern (`If`, `Parallel`, `Route`, * `Include`, `Loop`, `Repeat`). */ addStep(config: TaskConfig): this; addStep(step: FlowStep): this; /** Add several steps at once (Python: AgentFlow(steps=[...])). */ addSteps(steps: FlowStep[]): this; private static isTaskConfig; /** True for anything `run()` can execute without wrapping in a `Task` first. */ private static isRunnableStep; /** * Add a step using a simpler syntax */ step(name: string, execute: StepFunction): this; /** * Add an agent step to the workflow * * @example * ```typescript * import { Agent, Workflow } from 'praisonai'; * * const researcher = new Agent({ instructions: "Research the topic" }); * const writer = new Agent({ instructions: "Write based on research" }); * * const workflow = new Workflow("Research Pipeline") * .agent(researcher, "Research AI trends") * .agent(writer, "Write article based on research"); * * await workflow.run("AI in 2025"); * ``` */ agent(agentInstance: { chat: (prompt: string) => Promise; name?: string; }, task?: string): this; /** * Run the workflow */ run(input: TInput, options?: AgentFlowRunOptions): Promise<{ output: TOutput | undefined; results: StepResult[]; context: WorkflowContext; }>; /** * Get step count */ get stepCount(): number; /** * Execute one step at a given nesting depth. Patterns recurse with depth + 1; * anything deeper than MAX_NESTING_DEPTH throws (Python parity). */ private executeStep; /** Run `steps` one after another, chaining outputs. Stops at the first `stop`. */ private executeSequence; /** Normalise a leaf (Task / function / agent) and run it. Python: _normalize_single_step */ private executeLeaf; private normalizeLeaf; /** Variables visible to `If` conditions: step outputs by name, then metadata, then the specials. */ private conditionVariables; /** Python: _execute_route */ private executeRoute; /** Python: _execute_if */ private executeIf; /** Python: _execute_parallel */ private executeParallel; /** Python: _execute_loop (driven here so nested patterns and `parallel` work). */ private executeLoop; /** Python: _execute_repeat — feeds each iteration the previous iteration's output. */ private executeRepeat; /** Python: _execute_include */ private executeInclude; } /** * Workflow - Silent alias for AgentFlow (backward compatibility) * @deprecated Use AgentFlow instead */ export declare const Workflow: typeof AgentFlow; /** * Pipeline - Silent alias for AgentFlow (backward compatibility) * @deprecated Use AgentFlow instead */ export declare const Pipeline: typeof AgentFlow; /** * Parallel execution helper */ export declare function parallel(tasks: Array<() => Promise>): Promise; /** * Route helper - Execute based on condition */ export declare function route(conditions: Array<{ condition: () => boolean; execute: () => Promise; }>, defaultExecute?: () => Promise): Promise; /** * Loop helper - Repeat until condition */ export declare function loop(execute: (iteration: number) => Promise, shouldContinue: (result: T, iteration: number) => boolean, maxIterations?: number): Promise; /** * Repeat helper - Execute N times */ export declare function repeat(execute: (iteration: number) => Promise, times: number): Promise; /** * ifThen - Callback-style conditional execution. * * Formerly exported as `If`; that name now belongs to the `If` step class * (Python parity). Behaviour is unchanged. * * @example * ```typescript * import { ifThen } from 'praisonai'; * * const result = await ifThen( * () => userType === 'premium', * async () => premiumAgent.chat(query), * async () => basicAgent.chat(query) * ); * ``` */ export declare function ifThen(condition: boolean | (() => boolean) | (() => Promise), thenExecute: () => Promise | T, elseExecute?: () => Promise | T): Promise; /** * IfConfig for declarative conditional workflows */ export interface IfConfig { /** Condition to evaluate */ condition: boolean | (() => boolean) | (() => Promise); /** Execute if condition is true */ then: () => Promise | T; /** Execute if condition is false */ else?: () => Promise | T; } /** * whenValue - Pattern-matching style conditional on a value. * * Formerly exported as `when`; that name now belongs to the `when()` factory * that builds an `If` step (Python parity). Behaviour is unchanged. * * @example * ```typescript * import { whenValue } from 'praisonai'; * * const result = await whenValue(userIntent, { * 'search': async () => searchAgent.chat(query), * 'create': async () => createAgent.chat(query), * 'delete': async () => deleteAgent.chat(query), * }, async () => defaultAgent.chat(query)); * ``` */ export declare function whenValue(value: TValue, cases: Record Promise | TResult>, defaultCase?: () => Promise | TResult): Promise; /** * WhenConfig for declarative pattern matching */ export interface WhenConfig { /** Value to match against */ value: TValue; /** Cases to match */ cases: Record Promise | TResult>; /** Default case if no match */ default?: () => Promise | TResult; } /** * Switch - Multi-condition branching (Python parity) * * @example * ```typescript * import { Switch } from 'praisonai'; * * const result = await Switch([ * { when: () => score > 90, then: () => 'A' }, * { when: () => score > 80, then: () => 'B' }, * { when: () => score > 70, then: () => 'C' }, * ], () => 'F'); * ``` */ export declare function Switch(cases: Array<{ when: boolean | (() => boolean) | (() => Promise); then: () => Promise | T; }>, defaultCase?: () => Promise | T): Promise; /** * Guard - Execute only if all guards pass (Python parity) * * @example * ```typescript * import { Guard } from 'praisonai'; * * const result = await Guard( * [ * () => user.isAuthenticated, * () => user.hasPermission('write'), * () => !rateLimiter.isLimited(user.id), * ], * async () => agent.chat(query), * async (failedGuardIndex) => `Guard ${failedGuardIndex} failed` * ); * ``` */ export declare function Guard(guards: Array boolean) | (() => Promise)>, execute: () => Promise | T, onFail?: (failedGuardIndex: number) => Promise | T): Promise;