/**
 * WorkflowEngine 工作流引擎
 * 支持结构化工作流定义和执行
 */
const { EventEmitter } = require('../utils/event-emitter');
const { Plugin } = require('../core/plugin-base');
const { logger } = require('../utils/logger');
const log = logger.child('Workflow');
const { z } = require('zod');
const { runScriptSafely, evaluateInSandbox, runWorkflowFileSafely, runWorkflowSafely } = require('../utils/sandbox');
const fs = require('fs');
const crypto = require('crypto');
const path = require('path');
/**
 * 工作流步骤类型
 */
const StepType = {
  AGENT: 'agent',
  SCRIPT: 'script',
  CONDITION: 'condition',
  SWITCH: 'switch',
  TRY: 'try',
  PARALLEL: 'parallel',
  SEQUENTIAL: 'sequential',
  LOOP: 'loop',
  DELAY: 'delay',
  TOOL: 'tool',
  INPUT: 'input',
  OUTPUT: 'output',
  MESSAGE: 'message',
  THINK: 'think',
  WORKFLOW: 'workflow', // 嵌套工作流
};
/**
 * StepExecutor - 统一的步骤执行器
 * 同时被 WorkflowEngine 和 ExplorerLoop 使用
 */
class StepExecutor {
  constructor(framework) {
    this.framework = framework;
    this._log = logger.child('StepExecutor');
  }
  /**
   * 执行单个步骤
   */
  async executeStep(step, context) {
    const handler = this._getStepHandler(step.type);
    if (!handler) {
      throw new Error(`Unknown step type: ${step.type}`);
    }
    return await handler.call(this, step, context);
  }
  /**
   * 执行多个步骤（顺序）
   */
  async executeSteps(steps, context) {
    const results = [];
    for (const step of steps) {
      const result = await this.executeStep(step, context);
      results.push(result);
    }
    return results;
  }
  /**
   * 获取步骤类型处理器
   */
  _getStepHandler(type) {
    const handlers = {
      [StepType.TOOL]: this.executeTool,
      [StepType.SCRIPT]: this.executeScript,
      [StepType.CONDITION]: this.executeCondition,
      [StepType.SWITCH]: this.executeSwitch,
      [StepType.TRY]: this.executeTry,
      [StepType.PARALLEL]: this.executeParallel,
      [StepType.LOOP]: this.executeLoop,
      [StepType.DELAY]: this.executeDelay,
      [StepType.SEQUENTIAL]: this.executeSequential,
      [StepType.MESSAGE]: this.executeMessage,
      [StepType.THINK]: this.executeThink,
      [StepType.WORKFLOW]: this.executeWorkflowStep,
    };
    return handlers[type];
  }
  /**
   * 执行 switch 步骤
   */
  async executeSwitch(step, context) {
    this._log.debug(` Executing switch: ${step.name || step.id}`);
    const value = this._resolveValue(step.value, context);
    const branches = step.branches || [];
    for (const branch of branches) {
      const caseValue = this._resolveValue(branch.case, context);
      if (value === caseValue) {
        this._log.debug(` Switch matched case: ${caseValue}`);
        if (branch.steps && branch.steps.length > 0) {
          return await this.executeSteps(branch.steps, context);
        }
        return { matched: caseValue };
      }
    }
    // 默认分支
    if (step.default && step.default.steps) {
      this._log.debug(` Executing switch default branch`);
      return await this.executeSteps(step.default.steps, context);
    }
    return { matched: null, value };
  }
  /**
   * 执行 try-catch 步骤
   */
  async executeTry(step, context) {
    this._log.debug(` Executing try-catch: ${step.name || step.id}`);
    try {
      if (step.try && step.try.steps) {
        const result = await this.executeSteps(step.try.steps, context);
        return { success: true, result };
      }
      return { success: true };
    } catch (err) {
      this._log.debug(` Try block failed, executing catch: ${err.message}`);
      if (step.catch && step.catch.steps) {
        const catchResult = await this.executeSteps(step.catch.steps, context);
        return { success: false, error: err.message, caught: catchResult };
      }
      return { success: false, error: err.message };
    }
  }
  /**
   * 执行嵌套工作流步骤
   */
  async executeWorkflowStep(step, context) {
    this._log.debug(` Executing nested workflow: ${step.name || step.id}`);
    if (!step.workflow) {
      throw new Error('Workflow step requires a workflow definition');
    }
    // 执行嵌套工作流
    const result = await this.framework.pluginManager
      .get('workflow')
      .executeWorkflow(step.workflow, step.input || {}, context.variables._sessionId);
    // 将嵌套工作流的输出合并到当前上下文
    if (result.output) {
      for (const [key, value] of Object.entries(result.output)) {
        context.variables[key] = value;
      }
    }
    return result;
  }
  /**
   * 执行并行步骤
   */
  async executeParallel(step, context) {
    this._log.debug(` Executing parallel: ${step.name || step.id}`);
    const steps = step.steps || [];
    if (steps.length === 0) {
      return [];
    }
    // 并行执行所有步骤
    const promises = steps.map((stepConfig) => {
      return this.executeStep(stepConfig, context);
    });
    const results = await Promise.all(promises);
    return results;
  }
  /**
   * 执行工具步骤
   */
  async executeTool(step, context) {
    if (!step.tool) {
      throw new Error('Tool step requires a tool name');
    }
    this._log.debug(` Executing tool: ${step.tool}`);
    // 解析工具参数，支持变量引用
    let resolvedArgs = this._resolveArgs(step.args || {}, context);
    // 兼容旧格式：处理 step.input 字段（${stepId.output} 引用）
    // 将 input 注入到 args.input_data，供 python-execute 使用
    if (step.input) {
      const resolvedInput = this._resolveArgs(step.input, context);
      resolvedArgs.input_data = resolvedInput;
    }
    // 获取当前 sessionId
    let sessionId = context.variables?._sessionId;
    if (!sessionId && this.framework.getExecutionContext) {
      const ctx = this.framework.getExecutionContext();
      sessionId = ctx?.sessionId;
    }
    // 执行工具
    let result;
    if (sessionId && this.framework.runWithContext) {
      result = await this.framework.runWithContext(
        { sessionId },
        async () => await this.framework.executeTool(step.tool, resolvedArgs)
      );
    } else {
      result = await this.framework.executeTool(step.tool, resolvedArgs);
    }
    // 保存结果到变量
    // 支持 output 作为 outputVariable 的别名
    const outputVar = step.outputVariable || step.output;
    if (outputVar) {
      context.variables[outputVar] = result;
    }
    context.lastResult = result;
    if (result && result.error) {
      this._log.warn(` Tool ${step.tool} returned error: ${result.error}`);
    }
    return result;
  }
  /**
   * 执行脚本步骤
   */
  async executeScript(step, context) {
    this._log.debug(` Executing script step: ${step.name || step.id}`);
    // 安全警告：使用 new Function() 执行用户脚本存在风险
    if (typeof step.script === 'string') {
      this._log.warn(
        ` [SECURITY WARNING] Executing user script via new Function() - ensure script is from trusted source`
      );
    }
    try {
      // 兼容旧格式：处理 step.input 字段（${stepId.output} 引用）
      let resolvedInput = context.input || {};
      if (step.input && typeof step.input === 'object') {
        resolvedInput = this._resolveArgs(step.input, context);
      }
      const scriptContext = {
        input: resolvedInput,
        input_data: resolvedInput, // 兼容 input_data 变量名
        variables: context.variables,
        previousResult: context.lastResult,
        console: {
          log: (...args) => {
            const s = logger.child('Script');
            s.debug(`[\${step.id}]`, ...args);
          },
        },
      };
      let result;
      if (typeof step.script === 'function') {
        result = await step.script(scriptContext);
      } else if (typeof step.script === 'string') {
        // 使用沙箱执行用户脚本，防止恶意代码执行
        result = await runScriptSafely(step.script, scriptContext, { timeout: 10000 });
      }
      // 支持 output 作为 outputVariable 的别名
      const outputVar = step.outputVariable || step.output;
      if (outputVar) {
        context.variables[outputVar] = result;
      }
      context.lastResult = result;
      return result;
    } catch (err) {
      throw new Error(`Script execution failed: ${err.message}`);
    }
  }
  /**
   * 执行条件步骤
   */
  async executeCondition(step, context) {
    this._log.debug(` Evaluating condition: ${step.name || step.id}`);
    for (const branch of step.branches || []) {
      try {
        let conditionValue;
        if (typeof branch.condition === 'function') {
          conditionValue = branch.condition(context);
        } else if (typeof branch.condition === 'string') {
          // 使用沙箱评估条件，防止恶意代码执行
          conditionValue = await evaluateInSandbox(branch.condition, context, { timeout: 5000 });
        }
        if (conditionValue) {
          this._log.debug(` Condition matched: ${branch.name || branch.stepId}`);
          if (branch.steps && branch.steps.length > 0) {
            await this.executeSteps(branch.steps, context);
          }
          return branch.stepId || branch.name;
        }
      } catch (err) {
        this._log.warn(` Branch condition error:`, err.message);
      }
    }
    // 执行默认分支
    if (step.defaultBranch && step.defaultBranch.steps) {
      this._log.debug(` Executing default branch`);
      await this.executeSteps(step.defaultBranch.steps, context);
    }
    return null;
  }
  /**
   * 执行循环步骤
   */
  async executeLoop(step, context) {
    this._log.debug(` Executing loop: ${step.name || step.id}`);
    const results = [];
    const maxIterations = step.maxIterations || 10;
    const loopVariable = step.loopVariable || 'loopIndex';
    for (let i = 0; i < maxIterations; i++) {
      context.variables[loopVariable] = i;
      this._log.debug(` Loop iteration ${i}`);
      const iterationResults = [];
      for (const stepConfig of step.steps || []) {
        const result = await this.executeStep(stepConfig, context);
        iterationResults.push(result);
      }
      results.push(iterationResults);
      // 检查终止条件
      if (step.until) {
        let shouldStop = false;
        if (typeof step.until === 'function') {
          shouldStop = step.until(context);
        } else if (typeof step.until === 'string') {
          // 使用沙箱评估循环条件，防止恶意代码执行
        shouldStop = await evaluateInSandbox(step.until, context, { timeout: 5000 });
        }
        if (shouldStop) {
          this._log.debug(` Loop terminated at iteration ${i}`);
          break;
        }
      }
    }
    return results;
  }
  /**
   * 执行延迟步骤
   */
  async executeDelay(step, context) {
    const delayMs = step.delayMs || 1000;
    this._log.debug(` Delaying ${delayMs}ms`);
    await new Promise((resolve) => setTimeout(resolve, delayMs));
    return null;
  }
  /**
   * 执行顺序步骤
   */
  async executeSequential(step, context) {
    this._log.debug(` Executing sequential: ${step.name || step.id}`);
    return await this.executeSteps(step.steps || [], context);
  }
  /**
   * 执行消息步骤（ExplorerLoop 专用）
   */
  async executeMessage(step, context) {
    this._log.debug(` Executing message step`);
    // 使用子Agent处理消息，避免阻塞主agent
    const messageAgent = this.framework.createSubAgent({
      name: 'workflow_message',
      role: '工作流任务执行助手，专注于处理工作流中的消息任务',
    });
    let content = step.content || '';
    // 支持变量引用
    content = this._resolveValue(content, context);
    // 如果有事件上下文，附加到消息
    if (context.variables?._event) {
      content = `${content}\n\n[事件上下文: ${JSON.stringify(context.variables._event)}]`;
    }
    const result = await messageAgent.chat(content);
    return { success: true, result };
  }
  /**
   * 执行思考步骤（ExplorerLoop 专用）
   */
  async executeThink(step, context) {
    this._log.debug(` Executing think step`);
    const thinkPlugin = this.framework.pluginManager?.get('think');
    if (!thinkPlugin) {
      return { success: false, error: '思考插件不可用' };
    }
    let topic = step.topic || 'Ambient代理反思';
    topic = this._resolveValue(topic, context);
    if (context.variables?._event) {
      topic = `${topic}\n\n[事件上下文: ${JSON.stringify(context.variables._event)}]`;
    }
    const result = await thinkPlugin._triggerThinking({
      topic,
      mode: step.mode || 'reflect',
      depth: step.depth || 2,
    });
    return result;
  }
  /**
   * 获取活跃代理
   */
  _getActiveAgent() {
    if (this.framework._mainAgent) {
      return this.framework._mainAgent;
    }
    const agents = this.framework._agents || [];
    return agents.length > 0 ? agents[agents.length - 1] : null;
  }
  /**
   * 解析参数中的变量引用
   */
  _resolveArgs(args, context) {
    const resolved = {};
    for (const [key, value] of Object.entries(args)) {
      resolved[key] = this._resolveValue(value, context);
    }
    return resolved;
  }
  _resolveValue(value, context) {
    if (typeof value === 'string') {
      // 支持多种引用格式：
      // {{result}} - 上一步结果 (lastResult)
      // {{result.body.ip}} - 从上一步结果提取嵌套字段
      // {{variables.xxx}} - 显式引用 context.variables
      // {{context.xxx}} - 显式引用 context 根属性
      // {{lastResult}} - 上一步结果（result 的别名）
      // ${stepId.output} - 引用指定 id 步骤的输出（兼容旧格式）
      // ${stepId.output.path} - 从指定步骤输出提取字段
      let result = value;
      // 先处理 ${stepId.output} 格式（兼容旧格式）
      result = result.replace(/\$\{([^}]+)\}/g, (match, path) => {
        const stepOutputs = context.variables._stepOutputs || {};
        if (path === 'output') {
          // ${output} 等同于 ${stepId.output} 引用上一步
          return context.lastResult ?? match;
        }
        if (path.includes('.')) {
          // ${stepId.output.field} 格式
          const [stepId, ...fieldParts] = path.split('.');
          const stepOutput = stepOutputs[stepId];
          if (stepOutput !== undefined) {
            const val = this._getNestedValue(stepOutput, fieldParts.join('.'));
            if (val !== undefined) return val;
          }
        } else {
          // ${stepId.output} 格式
          const stepOutput = stepOutputs[path];
          if (stepOutput !== undefined) return stepOutput;
        }
        return match;
      });
      // 再处理 {{...}} 格式（支持 _event.email.from 等嵌套属性）
      result = result.replace(/\{\{([^}]+)\}\}/g, (match, path) => {
        // result 和 lastResult 都指向 context.lastResult
        if (path === 'result' || path === 'lastResult') {
          return context.lastResult ?? match;
        }
        if (path.startsWith('result.') || path.startsWith('lastResult.')) {
          const nestedPath = path.replace(/^(result|lastResult)\./, '');
          const val = this._getNestedValue(context.lastResult, nestedPath);
          if (val !== undefined) return val;
          return match;
        }
        if (path.startsWith('variables.')) {
          return this._getNestedValue(context, path) ?? match;
        } else if (path.startsWith('context.')) {
          return this._getNestedValue(context, path) ?? match;
        } else {
          // 先从 variables 查找，再从 context 根属性查找
          const val = this._getNestedValue(context.variables, path);
          if (val !== undefined) return val;
          return this._getNestedValue(context, path) ?? match;
        }
      });
      return result;
    } else if (Array.isArray(value)) {
      return value.map((v) => this._resolveValue(v, context));
    } else if (typeof value === 'object' && value !== null) {
      const resolved = {};
      for (const [k, v] of Object.entries(value)) {
        resolved[k] = this._resolveValue(v, context);
      }
      return resolved;
    }
    return value;
  }
  _getNestedValue(obj, path) {
    if (!obj) return undefined;
    const parts = path.split('.');
    let current = obj;
    for (const part of parts) {
      if (current === null || current === undefined) return undefined;
      // 如果当前值是字符串，尝试解析为 JSON
      if (typeof current === 'string' && part !== '0' && part !== 'length') {
        try {
          current = JSON.parse(current);
        } catch {
          // 解析失败，继续用原值
        }
      }
      current = current[part];
    }
    return current;
  }
}
/**
 * 工作流步骤基类
 */
class WorkflowStep {
  constructor(config) {
    this.id = config.id || `step_${Date.now()}_${crypto.randomBytes(6).toString('base64url')}`;
    this.type = config.type;
    this.name = config.name || '';
    this.description = config.description || '';
    this.condition = config.condition || null;
    this.timeout = config.timeout || 30000;
    this.retry = config.retry || { enabled: false, maxAttempts: 3, delay: 1000 };
    this.onSuccess = config.onSuccess || null;
    this.onFailure = config.onFailure || null;
  }
  async execute(context, engine) {
    throw new Error('execute() must be implemented by subclass');
  }
  validate() {
    if (!this.type) {
      throw new Error('Step must have a type');
    }
    return true;
  }
}
/**
 * 脚本步骤
 */
class ScriptStep extends WorkflowStep {
  constructor(config) {
    super({ ...config, type: StepType.SCRIPT });
    this.script = config.script;
    this.outputVariable = config.outputVariable || null;
  }
  async execute(context, engine) {
    // 使用 StepExecutor 执行脚本逻辑
    const executor = new StepExecutor(engine.framework);
    const stepConfig = {
      id: this.id,
      name: this.name,
      type: StepType.SCRIPT,
      script: this.script,
      outputVariable: this.outputVariable,
    };
    return await executor.executeScript(stepConfig, context);
  }
}
/**
 * 条件步骤
 */
class ConditionStep extends WorkflowStep {
  constructor(config) {
    super({ ...config, type: StepType.CONDITION });
    this.branches = config.branches || [];
    this.defaultBranch = config.defaultBranch || null;
  }
  async execute(context, engine) {
    const executor = new StepExecutor(engine.framework);
    const stepConfig = {
      id: this.id,
      name: this.name,
      type: StepType.CONDITION,
      branches: this.branches,
      defaultBranch: this.defaultBranch,
    };
    return await executor.executeCondition(stepConfig, context);
  }
}
/**
 * 并行步骤
 */
class ParallelStep extends WorkflowStep {
  constructor(config) {
    super({ ...config, type: StepType.PARALLEL });
    this.steps = config.steps || [];
  }
  async execute(context, engine) {
    const executor = new StepExecutor(engine.framework);
    const stepConfig = {
      id: this.id,
      name: this.name,
      type: StepType.PARALLEL,
      steps: this.steps,
    };
    return await executor.executeParallel(stepConfig, context);
  }
}
/**
 * Switch 步骤
 */
class SwitchStep extends WorkflowStep {
  constructor(config) {
    super({ ...config, type: StepType.SWITCH });
    this.value = config.value;
    this.branches = config.branches || [];
    this.default = config.default || null;
  }
  async execute(context, engine) {
    const executor = new StepExecutor(engine.framework);
    const stepConfig = {
      id: this.id,
      name: this.name,
      type: StepType.SWITCH,
      value: this.value,
      branches: this.branches,
      default: this.default,
    };
    return await executor.executeSwitch(stepConfig, context);
  }
}
/**
 * Try-Catch 步骤
 */
class TryStep extends WorkflowStep {
  constructor(config) {
    super({ ...config, type: StepType.TRY });
    this.try = config.try || {};
    this.catch = config.catch || {};
  }
  async execute(context, engine) {
    const executor = new StepExecutor(engine.framework);
    const stepConfig = {
      id: this.id,
      name: this.name,
      type: StepType.TRY,
      try: this.try,
      catch: this.catch,
    };
    return await executor.executeTry(stepConfig, context);
  }
}
/**
 * 嵌套工作流步骤
 */
class NestedWorkflowStep extends WorkflowStep {
  constructor(config) {
    super({ ...config, type: StepType.WORKFLOW });
    this.workflow = config.workflow;
    this.input = config.input || {};
  }
  async execute(context, engine) {
    const executor = new StepExecutor(engine.framework);
    const stepConfig = {
      id: this.id,
      name: this.name,
      type: StepType.WORKFLOW,
      workflow: this.workflow,
      input: this.input,
    };
    return await executor.executeWorkflowStep(stepConfig, context);
  }
}
/**
 * 顺序步骤
 */
class SequentialStep extends WorkflowStep {
  constructor(config) {
    super({ ...config, type: StepType.SEQUENTIAL });
    this.steps = config.steps || [];
  }
  async execute(context, engine) {
    const executor = new StepExecutor(engine.framework);
    const stepConfig = {
      id: this.id,
      name: this.name,
      type: StepType.SEQUENTIAL,
      steps: this.steps,
    };
    return await executor.executeSequential(stepConfig, context);
  }
}
/**
 * 循环步骤
 */
class LoopStep extends WorkflowStep {
  constructor(config) {
    super({ ...config, type: StepType.LOOP });
    this.maxIterations = config.maxIterations || 10;
    this.loopVariable = config.loopVariable || 'loopIndex';
    this.steps = config.steps || [];
    this.until = config.until || null;
  }
  async execute(context, engine) {
    const executor = new StepExecutor(engine.framework);
    const stepConfig = {
      id: this.id,
      name: this.name,
      type: StepType.LOOP,
      maxIterations: this.maxIterations,
      loopVariable: this.loopVariable,
      steps: this.steps,
      until: this.until,
    };
    return await executor.executeLoop(stepConfig, context);
  }
}
/**
 * 延迟步骤
 */
class DelayStep extends WorkflowStep {
  constructor(config) {
    super({ ...config, type: StepType.DELAY });
    this.delayMs = config.delayMs || 1000;
  }
  async execute(context, engine) {
    const executor = new StepExecutor(engine.framework);
    const stepConfig = {
      id: this.id,
      name: this.name,
      type: StepType.DELAY,
      delayMs: this.delayMs,
    };
    return await executor.executeDelay(stepConfig, context);
  }
}
/**
 * 工具步骤
 */
class ToolStep extends WorkflowStep {
  constructor(config) {
    super({ ...config, type: StepType.TOOL });
    this.tool = config.tool;
    this.args = config.args || {};
    this.outputVariable = config.outputVariable || null;
    this.output = config.output || null; // 兼容旧格式
    this.input = config.input || null; // 兼容旧格式：input 字段
  }
  async execute(context, engine) {
    const executor = new StepExecutor(engine.framework);
    const stepConfig = {
      id: this.id,
      name: this.name,
      type: StepType.TOOL,
      tool: this.tool,
      args: this.args,
      outputVariable: this.outputVariable,
      output: this.output, // 传递 output
      input: this.input, // 传递 input
    };
    return await executor.executeTool(stepConfig, context);
  }
}
/**
 * 工作流引擎
 */
class WorkflowEngine extends EventEmitter {
  constructor(framework) {
    super();
    this.framework = framework;
    this._steps = new Map();
  }
  /**
   * 注册自定义步骤类型
   */
  registerStepType(type, StepClass) {
    this._steps.set(type, StepClass);
  }
  /**
   * 创建步骤实例
   * 自动推断步骤类型：
   * - 有 tool 字段 -> tool 类型
   * - 有 code/script 字段 -> script 类型
   * - 有 branches 字段 -> condition 类型
   * - 有 value + branches -> switch 类型
   * - 有 try/catch 字段 -> try 类型
   * - 有 parallel 属性 -> parallel 类型
   * - 有 steps 字段 + loopVariable/maxIterations -> loop 类型
   * - 有 steps 字段 -> sequential 类型
   * - 有 delayMs 字段 -> delay 类型
   * - 有 workflow 字段 -> workflow 类型
   */
  createStep(config) {
    let type = config.type;
    // 自动推断类型
    if (!type) {
      if (config.tool) {
        type = StepType.TOOL;
      } else if (config.code || config.script) {
        type = StepType.SCRIPT;
      } else if (config.try || config.catch) {
        type = StepType.TRY;
      } else if (config.value !== undefined && config.branches) {
        type = StepType.SWITCH;
      } else if (config.parallel === true || config.mode === 'parallel') {
        type = StepType.PARALLEL;
      } else if (config.workflow) {
        type = StepType.WORKFLOW;
      } else if (config.branches) {
        type = StepType.CONDITION;
      } else if (config.steps && (config.loopVariable || config.maxIterations)) {
        type = StepType.LOOP;
      } else if (config.steps) {
        type = StepType.SEQUENTIAL;
      } else if (config.delayMs !== undefined) {
        type = StepType.DELAY;
      } else if (config.message) {
        type = StepType.MESSAGE;
      } else if (config.topic) {
        type = StepType.THINK;
      }
    }
    if (!type) {
      throw new Error(
        `Cannot infer step type for step: ${JSON.stringify(config).substring(0, 100)}`
      );
    }
    const StepClass = this._steps.get(type);
    if (!StepClass) {
      throw new Error(`Unknown step type: ${type}`);
    }
    // 确保配置有 type 字段
    return new StepClass({ ...config, type });
  }
  /**
   * 创建工作流上下文
   */
  createContext(input = {}, variables = {}) {
    return {
      input,
      variables,
      lastResult: null,
      results: [],
    };
  }
}
/**
 * WorkflowManagerPlugin
 */
class WorkflowPlugin extends Plugin {
  constructor(config = {}) {
    super();
    this.name = 'workflow';
    this.version = '1.0.0';
    this.description = '工作流引擎，支持结构化工作流定义和执行';
    this.priority = 6;
    this.system = true;
    this._framework = null;
    this._engine = null;
    this._workflowsDir = config.workflowsDir || '.agent/workflows';
    this._workflows = new Map();
    this._workflowTools = new Map();
  }
  install(framework) {
    this._framework = framework;
    this._engine = new WorkflowEngine(framework);
    // 注册内置步骤类型
    this._engine.registerStepType(StepType.SCRIPT, ScriptStep);
    this._engine.registerStepType(StepType.CONDITION, ConditionStep);
    this._engine.registerStepType(StepType.SWITCH, SwitchStep);
    this._engine.registerStepType(StepType.TRY, TryStep);
    this._engine.registerStepType(StepType.PARALLEL, ParallelStep);
    this._engine.registerStepType(StepType.SEQUENTIAL, SequentialStep);
    this._engine.registerStepType(StepType.LOOP, LoopStep);
    this._engine.registerStepType(StepType.DELAY, DelayStep);
    this._engine.registerStepType(StepType.TOOL, ToolStep);
    this._engine.registerStepType(StepType.WORKFLOW, NestedWorkflowStep);
    // 注册工作流执行工具
    framework.registerTool({
      name: 'execute_workflow',
      description: '执行指定的工作流',
      inputSchema: z.object({
        workflow: z.string().describe('工作流定义（JSON 或 JavaScript 代码）'),
        input: z.object({}).optional().describe('工作流输入参数'),
      }),
      execute: async (args, framework) => {
        // 获取当前 sessionId
        let sessionId = null;
        const ctx = framework.getExecutionContext();
        if (ctx?.sessionId) {
          sessionId = ctx.sessionId;
        }
        return await this.executeWorkflow(args.workflow, args.input || {}, sessionId);
      },
    });
    return this;
  }
  start(framework) {
    this._loadWorkflows();
    this._registerWorkflowTools();
    // 注册 reloadWorkflows 工具
    framework.registerTool({
      name: 'reloadWorkflows',
      description: '重载所有工作流，当用户添加或修改工作流后调用此工具',
      inputSchema: z.object({}),
      execute: async () => {
        this.reload(this._framework);
        return {
          success: true,
          message: `Workflows reloaded. Total: ${this._workflows.size}`,
          workflows: Array.from(this._workflows.keys()),
        };
      },
    });
    return this;
  }
  /**
   * 加载目录中的工作流定义
   */
  _loadWorkflows() {
    const dir = path.resolve(process.cwd(), this._workflowsDir);
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
      log.info(` Created workflows directory: ${dir}`);
      return;
    }
    try {
      const files = fs.readdirSync(dir);
      for (const file of files) {
        if (!file.endsWith('.json') && !file.endsWith('.js')) continue;
        const filePath = path.join(dir, file);
        const workflowName = path.basename(file, path.extname(file));
        // 跳过已存在的工作流
        if (this._workflows.has(workflowName)) continue;
        try {
          const content = fs.readFileSync(filePath, 'utf-8');
          let workflowDef;
          if (file.endsWith('.js')) {
            // 执行 JS 文件获取工作流定义
            // 使用沙箱加载工作流文件，防止恶意代码执行
            workflowDef = runWorkflowFileSafely(content, { timeout: 10000 });
            if (typeof workflowDef === 'function') {
              workflowDef = workflowDef(this._engine || {});
            }
            workflowDef = workflowDef.default || workflowDef;
          } else {
            workflowDef = JSON.parse(content);
          }
          if (workflowDef && workflowDef.steps) {
            this._workflows.set(workflowName, workflowDef);
            //log.info(` Loaded: ${workflowName}`)
          }
        } catch (err) {
          log.error(` Failed to load ${file}:`, err.message);
        }
      }
    } catch (err) {
      log.error(' Failed to read workflows directory:', err.message);
    }
  }
  /**
   * 注册工作流为工具
   */
  _registerWorkflowTools() {
    for (const [name, workflow] of this._workflows) {
      if (this._workflowTools.has(name)) continue;
      const toolName = `workflow_${name}`;
      const description = workflow.description || `执行工作流: ${name}`;
      this._framework.registerTool({
        name: toolName,
        description,
        inputSchema: z.object({
          input: z.object({}).optional().describe('工作流输入参数'),
        }),
        execute: async (args, framework) => {
          // Get current sessionId to ensure notifications reach the correct session
          let sessionId = null;
          const ctx = framework?.getExecutionContext?.();
          if (ctx?.sessionId) {
            sessionId = ctx.sessionId;
          }
          return await this.executeWorkflow(workflow, args.input || {}, sessionId);
        },
      });
      this._workflowTools.set(name, toolName);
      log.info(` Registered tool: ${toolName}`);
    }
  }
  /**
   * 重载工作流
   */
  reload(framework) {
    // 清除模块缓存，确保重新加载最新代码
    const modulePath = require.resolve('./src/capabilities/workflow-engine');
    if (require.cache[modulePath]) {
      delete require.cache[modulePath];
    }
    log.info(' Reloading...');
    this._framework = framework;
    // 重新创建 engine（确保使用最新代码）
    this._engine = new (require('./src/capabilities/workflow-engine').WorkflowEngine)(framework);
    // 注册内置步骤类型
    this._engine.registerStepType(
      require('./src/capabilities/workflow-engine').StepType.SCRIPT,
      require('./src/capabilities/workflow-engine').ScriptStep
    );
    this._engine.registerStepType(
      require('./src/capabilities/workflow-engine').StepType.TOOL,
      require('./src/capabilities/workflow-engine').ToolStep
    );
    this._engine.registerStepType(
      require('./src/capabilities/workflow-engine').StepType.CONDITION,
      require('./src/capabilities/workflow-engine').ConditionStep
    );
    this._engine.registerStepType(
      require('./src/capabilities/workflow-engine').StepType.SWITCH,
      require('./src/capabilities/workflow-engine').SwitchStep
    );
    this._engine.registerStepType(
      require('./src/capabilities/workflow-engine').StepType.TRY,
      require('./src/capabilities/workflow-engine').TryStep
    );
    this._engine.registerStepType(
      require('./src/capabilities/workflow-engine').StepType.PARALLEL,
      require('./src/capabilities/workflow-engine').ParallelStep
    );
    this._engine.registerStepType(
      require('./src/capabilities/workflow-engine').StepType.SEQUENTIAL,
      require('./src/capabilities/workflow-engine').SequentialStep
    );
    this._engine.registerStepType(
      require('./src/capabilities/workflow-engine').StepType.LOOP,
      require('./src/capabilities/workflow-engine').LoopStep
    );
    this._engine.registerStepType(
      require('./src/capabilities/workflow-engine').StepType.DELAY,
      require('./src/capabilities/workflow-engine').DelayStep
    );
    this._engine.registerStepType(
      require('./src/capabilities/workflow-engine').StepType.WORKFLOW,
      require('./src/capabilities/workflow-engine').NestedWorkflowStep
    );
    // 清除已注册的工具
    for (const toolName of this._workflowTools.values()) {
      // 工具注销需要框架支持，这里只清理内部状态
    }
    this._workflowTools.clear();
    this._workflows.clear();
    // 重新加载
    this._loadWorkflows();
    this._registerWorkflowTools();
    log.info(` Reloaded. Total workflows: ${this._workflows.size}`);
  }
  /**
   * 执行工作流
   */
  async executeWorkflow(workflowDef, input = {}, sessionId = null) {
    try {
      let workflow;
      if (typeof workflowDef === 'string') {
        // 尝试作为工作流名称加载（先检查是否已加载的工作流）
        const workflowName = workflowDef.trim();
        if (this._workflows.has(workflowName)) {
          workflow = this._workflows.get(workflowName);
        } else {
          // 尝试解析 JSON 或执行代码
          try {
            workflow = JSON.parse(workflowDef);
          } catch {
            // 使用沙箱解析工作流定义，防止恶意代码执行
            workflow = runWorkflowSafely(workflowDef, this._engine, { timeout: 5000 });
          }
        }
      } else {
        workflow = workflowDef;
      }
      const context = this._engine.createContext(input, {});
      // 将 sessionId 存储到上下文变量，供工具步骤使用
      if (sessionId) {
        context.variables._sessionId = sessionId;
      }
      // 执行工作流步骤
      if (workflow.steps && Array.isArray(workflow.steps)) {
        const results = [];
        // 按 id 存储步骤输出，供 ${id.output} 引用
        context.variables._stepOutputs = {};
        for (const stepConfig of workflow.steps) {
          const step = this._engine.createStep(stepConfig);
          const result = await step.execute(context, this._engine);
          results.push(result);
          // 如果步骤有 id，存储其输出
          if (stepConfig.id) {
            context.variables._stepOutputs[stepConfig.id] = result;
          }
        }
        // 只返回最后一步的结果（包含最终输出）和成功状态
        // 不返回所有中间结果，避免上下文超限
        const lastResult = results.length > 0 ? results[results.length - 1] : null;
        // 从 context.variables 中提取非下划线开头的用户变量
        // 下划线开头的是内部变量（如 _stepOutputs），不需要返回
        const userVariables = {};
        for (const [key, value] of Object.entries(context.variables)) {
          if (!key.startsWith('_')) {
            userVariables[key] = value;
          }
        }
        return {
          success: true,
          stepCount: workflow.steps.length,
          result: lastResult,
          output: userVariables,
        };
      }
      return { success: true, output: {} };
    } catch (err) {
      return { success: false, error: err.message };
    }
  }
  /**
   * 获取引擎
   */
  getEngine() {
    return this._engine;
  }
  uninstall(framework) {
    this._engine = null;
    this._framework = null;
  }
}
module.exports = {
  WorkflowPlugin,
  WorkflowEngine,
  WorkflowStep,
  StepType,
  StepExecutor,
  ScriptStep,
  ConditionStep,
  ParallelStep,
  SwitchStep,
  TryStep,
  NestedWorkflowStep,
  SequentialStep,
  LoopStep,
  DelayStep,
  ToolStep,
};
