All files / src/modules workflow.ts

81.12% Statements 159/196
72.13% Branches 44/61
83.33% Functions 10/12
81.12% Lines 159/196

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319                    1x                                                                                                                                                                                         5x 5x 5x 5x   2x 2x 2x 2x 2x 2x       2x 2x   1x 1x 1x 2x 2x 2x 1x 1x 1x 1x                         14x 14x 1x   14x   18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x   14x 14x 14x 14x 14x   14x 14x 16x 16x 16x 3x 3x 2x 2x 2x 3x 16x 3x 3x       1x 9x 9x 16x 16x   9x 9x 1x 1x 1x 1x 1x 1x       1x         1x 1x 1x   9x 9x 9x 9x 9x 9x 9x 9x   9x 9x 9x 9x   9x 15x 15x   14x 14x 14x   14x 14x     15x 13x 13x   13x 13x 13x 13x 13x 13x     15x 2x 15x 11x 11x 15x 1x 1x 1x 1x 1x 1x   1x 1x 1x                 1x 15x   8x 8x 8x 8x 8x 8x 8x 9x 9x 9x         1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 2x 2x 2x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x  
/**
 * AgentKits — Workflow Engine
 *
 * Define and execute multi-step workflows with LLM calls, tool calls,
 * conditional branches, parallel execution, retry, and fallback.
 *
 * Usage:
 *   import { createWorkflow, runWorkflow } from 'agentkits/workflow';
 */
 
import { createChat } from '../llm/index.js';
import type { ChatConfig } from '../llm/index.js';
 
// ── Types ──────────────────────────────────────────────────────────
 
export type StepType = 'llm' | 'tool' | 'condition' | 'parallel' | 'transform' | 'delay';
 
export interface RetryPolicy {
  maxRetries?: number;
  delayMs?: number;
  backoff?: 'fixed' | 'exponential';
}
 
export interface WorkflowStep {
  id: string;
  type: StepType;
  /** For 'llm': chat config */
  llm?: ChatConfig & { prompt?: string; systemPrompt?: string };
  /** For 'tool': function to call */
  tool?: {
    name: string;
    handler: (input: any, context: WorkflowContext) => Promise<any>;
  };
  /** For 'condition': branch based on result */
  condition?: {
    /** Expression evaluated against context.variables — or a function */
    check: string | ((context: WorkflowContext) => boolean);
    ifTrue: string;   // step id
    ifFalse: string;  // step id
  };
  /** For 'parallel': run multiple steps concurrently */
  parallel?: string[]; // step ids
  /** For 'transform': transform data */
  transform?: (input: any, context: WorkflowContext) => any;
  /** For 'delay': wait ms */
  delayMs?: number;
  /** Next step id (for linear flows) */
  next?: string;
  /** Retry policy */
  retry?: RetryPolicy;
  /** Fallback step id on error */
  fallback?: string;
  /** Input mapping: keys from context.variables */
  input?: string | ((context: WorkflowContext) => any);
  /** Output variable name to store result */
  output?: string;
}
 
export interface WorkflowDefinition {
  name: string;
  description?: string;
  version?: string;
  /** First step id */
  startStep: string;
  steps: WorkflowStep[];
  /** Global variables / initial context */
  variables?: Record<string, any>;
}
 
export interface WorkflowContext {
  variables: Record<string, any>;
  stepResults: Record<string, any>;
  currentStep: string;
  history: Array<{ stepId: string; status: 'success' | 'error' | 'skipped'; result?: any; error?: string; durationMs: number }>;
}
 
export interface WorkflowResult {
  success: boolean;
  context: WorkflowContext;
  finalOutput: any;
  totalDurationMs: number;
  stepsExecuted: number;
}
 
export interface WorkflowEngine {
  /** Run the workflow */
  run(initialVars?: Record<string, any>): Promise<WorkflowResult>;
  /** Validate workflow definition */
  validate(): string[];
}
 
// ── Step Executors ─────────────────────────────────────────────────
 
async function executeLLMStep(step: WorkflowStep, context: WorkflowContext): Promise<any> {
  const cfg = step.llm!;
  const chat = createChat({ provider: cfg.provider, model: cfg.model, apiKey: cfg.apiKey, baseUrl: cfg.baseUrl, temperature: cfg.temperature, maxTokens: cfg.maxTokens });
  const prompt = resolveTemplate(cfg.prompt ?? '', context);
  const messages: Array<{ role: 'system' | 'user'; content: string }> = [];
  if (cfg.systemPrompt) messages.push({ role: 'system', content: resolveTemplate(cfg.systemPrompt, context) });
  messages.push({ role: 'user', content: prompt });
  return await chat.chat(messages);
}
 
async function executeToolStep(step: WorkflowStep, context: WorkflowContext): Promise<any> {
  const input = resolveInput(step, context);
  return await step.tool!.handler(input, context);
}
 
async function executeConditionStep(step: WorkflowStep, context: WorkflowContext): Promise<string> {
  const cond = step.condition!;
  let result: boolean;
  if (typeof cond.check === 'function') {
    result = cond.check(context);
  } else {
    // Simple expression: check if variable is truthy
    result = !!context.variables[cond.check];
  }
  return result ? cond.ifTrue : cond.ifFalse;
}
 
async function executeParallelStep(step: WorkflowStep, allSteps: Map<string, WorkflowStep>, context: WorkflowContext): Promise<any> {
  const results = await Promise.all(
    step.parallel!.map(async (stepId) => {
      const s = allSteps.get(stepId);
      if (!s) throw new Error(`Parallel step not found: ${stepId}`);
      return executeStep(s, allSteps, context);
    })
  );
  return results;
}
 
function resolveTemplate(template: string, context: WorkflowContext): string {
  return template.replace(/\{\{(\w+(?:\.\w+)*)\}\}/g, (_, key) => {
    const parts = key.split('.');
    let val: any = { ...context.variables, ...context.stepResults };
    for (const p of parts) {
      val = val?.[p];
    }
    return val !== undefined ? String(val) : `{{${key}}}`;
  });
}
 
function resolveInput(step: WorkflowStep, context: WorkflowContext): any {
  if (!step.input) return context.variables;
  if (typeof step.input === 'function') return step.input(context);
  return context.variables[step.input] ?? context.stepResults[step.input];
}
 
async function executeStep(step: WorkflowStep, allSteps: Map<string, WorkflowStep>, context: WorkflowContext): Promise<any> {
  switch (step.type) {
    case 'llm': return executeLLMStep(step, context);
    case 'tool': return executeToolStep(step, context);
    case 'transform': return step.transform!(resolveInput(step, context), context);
    case 'delay': await new Promise(r => setTimeout(r, step.delayMs ?? 1000)); return null;
    case 'parallel': return executeParallelStep(step, allSteps, context);
    case 'condition': return executeConditionStep(step, context);
    default: throw new Error(`Unknown step type: ${step.type}`);
  }
}
 
async function executeWithRetry(step: WorkflowStep, allSteps: Map<string, WorkflowStep>, context: WorkflowContext): Promise<any> {
  const policy = step.retry ?? { maxRetries: 0 };
  const maxRetries = policy.maxRetries ?? 0;
  const delayMs = policy.delayMs ?? 1000;
  const backoff = policy.backoff ?? 'exponential';
 
  let lastError: Error | null = null;
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      return await executeStep(step, allSteps, context);
    } catch (e: any) {
      lastError = e;
      if (attempt < maxRetries) {
        const wait = backoff === 'exponential' ? delayMs * Math.pow(2, attempt) : delayMs;
        await new Promise(r => setTimeout(r, wait));
      }
    }
  }
  throw lastError;
}
 
// ── Factory ────────────────────────────────────────────────────────
 
export function createWorkflow(definition: WorkflowDefinition): WorkflowEngine {
  const stepMap = new Map<string, WorkflowStep>();
  for (const step of definition.steps) {
    stepMap.set(step.id, step);
  }
 
  return {
    validate(): string[] {
      const errors: string[] = [];
      if (!stepMap.has(definition.startStep)) errors.push(`Start step '${definition.startStep}' not found`);
      for (const step of definition.steps) {
        if (step.next && !stepMap.has(step.next)) errors.push(`Step '${step.id}' references unknown next '${step.next}'`);
        if (step.fallback && !stepMap.has(step.fallback)) errors.push(`Step '${step.id}' references unknown fallback '${step.fallback}'`);
        if (step.condition) {
          if (!stepMap.has(step.condition.ifTrue)) errors.push(`Condition step '${step.id}' references unknown ifTrue '${step.condition.ifTrue}'`);
          if (!stepMap.has(step.condition.ifFalse)) errors.push(`Condition step '${step.id}' references unknown ifFalse '${step.condition.ifFalse}'`);
        }
        if (step.parallel) {
          for (const pid of step.parallel) {
            if (!stepMap.has(pid)) errors.push(`Parallel step '${step.id}' references unknown step '${pid}'`);
          }
        }
      }
      return errors;
    },
 
    async run(initialVars?: Record<string, any>): Promise<WorkflowResult> {
      const startTime = Date.now();
      const context: WorkflowContext = {
        variables: { ...definition.variables, ...initialVars },
        stepResults: {},
        currentStep: definition.startStep,
        history: [],
      };
 
      let currentStepId: string | undefined = definition.startStep;
      let stepsExecuted = 0;
      let finalOutput: any = null;
      const maxSteps = 100; // safety limit
 
      while (currentStepId && stepsExecuted < maxSteps) {
        const step = stepMap.get(currentStepId);
        if (!step) throw new Error(`Step '${currentStepId}' not found`);
 
        context.currentStep = currentStepId;
        const stepStart = Date.now();
        stepsExecuted++;
 
        try {
          const result = await executeWithRetry(step, stepMap, context);
 
          // Store result
          if (step.output) context.variables[step.output] = result;
          context.stepResults[step.id] = result;
          finalOutput = result;
 
          context.history.push({
            stepId: step.id,
            status: 'success',
            result,
            durationMs: Date.now() - stepStart,
          });
 
          // Determine next step
          if (step.type === 'condition') {
            currentStepId = result as string; // condition returns next step id
          } else {
            currentStepId = step.next;
          }
        } catch (e: any) {
          context.history.push({
            stepId: step.id,
            status: 'error',
            error: e.message,
            durationMs: Date.now() - stepStart,
          });
 
          if (step.fallback) {
            currentStepId = step.fallback;
          } else {
            return {
              success: false,
              context,
              finalOutput: null,
              totalDurationMs: Date.now() - startTime,
              stepsExecuted,
            };
          }
        }
      }
 
      return {
        success: true,
        context,
        finalOutput,
        totalDurationMs: Date.now() - startTime,
        stepsExecuted,
      };
    },
  };
}
 
// ── YAML/JSON Definition Parser ────────────────────────────────────
 
/** Parse a workflow from a JSON object (e.g., loaded from YAML/JSON file) */
export function parseWorkflowJSON(json: any, toolHandlers?: Record<string, (input: any, ctx: WorkflowContext) => Promise<any>>): WorkflowDefinition {
  const steps: WorkflowStep[] = (json.steps ?? []).map((s: any) => {
    const step: WorkflowStep = {
      id: s.id,
      type: s.type,
      next: s.next,
      output: s.output,
      input: s.input,
      retry: s.retry,
      fallback: s.fallback,
      delayMs: s.delayMs,
    };
    if (s.type === 'llm') step.llm = s.llm;
    if (s.type === 'tool' && toolHandlers?.[s.tool]) {
      step.tool = { name: s.tool, handler: toolHandlers[s.tool] };
    }
    if (s.type === 'condition') step.condition = s.condition;
    if (s.type === 'parallel') step.parallel = s.parallel;
    return step;
  });
 
  return {
    name: json.name ?? 'unnamed',
    description: json.description,
    version: json.version,
    startStep: json.startStep ?? steps[0]?.id,
    steps,
    variables: json.variables,
  };
}