Appearance
AgentNode V2 设计方案 - 第三部分:监听器实现
四、监听器实现
4.1 AI 任务创建监听器
文件: core/listener/AiAgentTaskCreateListener.java
java
package com.pig4cloud.pigx.wflow.core.listener;
import cn.hutool.core.util.StrUtil;
import com.pig4cloud.pigx.wflow.service.AiAgentService;
import com.pig4cloud.pigx.wflow.utils.SpringBeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.ExtensionElement;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.UserTask;
import org.flowable.engine.delegate.DelegateTask;
import org.flowable.engine.delegate.TaskListener;
import org.flowable.engine.impl.util.ProcessDefinitionUtil;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
/**
* AI Agent 任务创建监听器
* 当 AI 审批任务创建时触发,负责:
* 1. 设置 AI Agent 为候选人
* 2. 初始化流程变量
* 3. 异步触发 AI 分析
*
* @author willian fu
* @since 2026-01-09
*/
@Slf4j
@Component("aiAgentTaskCreateListener")
public class AiAgentTaskCreateListener implements TaskListener {
@Override
public void notify(DelegateTask delegateTask) {
String processInstanceId = delegateTask.getProcessInstanceId();
String taskId = delegateTask.getId();
String taskDefinitionKey = delegateTask.getTaskDefinitionKey();
log.info("AI Agent 任务创建: processInstanceId={}, taskId={}, taskDefinitionKey={}",
processInstanceId, taskId, taskDefinitionKey);
try {
// 1. 获取 AI 配置
Map<String, String> aiConfig = extractAiConfig(delegateTask);
// 2. 初始化流程变量
initializeProcessVariables(delegateTask);
// 3. 检查是否需要 AI 处理
Boolean aiProcessing = (Boolean) delegateTask.getVariable("aiProcessing");
if (aiProcessing == null || aiProcessing) {
// 4. 异步触发 AI 分析
triggerAiAnalysis(delegateTask, aiConfig);
}
log.info("AI Agent 任务创建完成: taskId={}", taskId);
} catch (Exception e) {
log.error("AI Agent 任务创建失败: taskId={}, error={}", taskId, e.getMessage(), e);
// 设置错误标记,但不中断流程
delegateTask.setVariable("aiProcessingError", e.getMessage());
delegateTask.setVariable("aiProcessing", false);
}
}
/**
* 提取 AI 配置
*/
private Map<String, String> extractAiConfig(DelegateTask delegateTask) {
String processDefinitionId = delegateTask.getProcessDefinitionId();
String taskDefinitionKey = delegateTask.getTaskDefinitionKey();
FlowElement flowElement = ProcessDefinitionUtil.getBpmnModel(processDefinitionId)
.getFlowElement(taskDefinitionKey);
if (flowElement instanceof UserTask) {
UserTask userTask = (UserTask) flowElement;
Map<String, List<ExtensionElement>> extensionElements = userTask.getExtensionElements();
// 提取 AI 服务配置
return extractExtensionConfig(extensionElements, "aiService");
}
return Map.of();
}
/**
* 提取扩展配置
*/
private Map<String, String> extractExtensionConfig(
Map<String, List<ExtensionElement>> extensionElements, String namespace) {
Map<String, String> config = new java.util.HashMap<>();
List<ExtensionElement> elements = extensionElements.get(namespace);
if (elements != null) {
for (ExtensionElement element : elements) {
String name = element.getName();
String value = element.getElementText();
if (StrUtil.isNotBlank(value)) {
config.put(name, value);
}
}
}
return config;
}
/**
* 初始化流程变量
*/
private void initializeProcessVariables(DelegateTask delegateTask) {
// 设置 AI 处理标记
if (delegateTask.getVariable("aiProcessing") == null) {
delegateTask.setVariable("aiProcessing", true);
}
// 设置人工干预标记
if (delegateTask.getVariable("humanInterruptRequested") == null) {
delegateTask.setVariable("humanInterruptRequested", false);
}
// 设置当前审批步骤
if (delegateTask.getVariable("currentApprovalStep") == null) {
delegateTask.setVariable("currentApprovalStep", 1);
}
// 初始化 AI 分析结果
delegateTask.setVariable("aiAnalysisStartTime", System.currentTimeMillis());
}
/**
* 触发 AI 分析
*/
private void triggerAiAnalysis(DelegateTask delegateTask, Map<String, String> aiConfig) {
String processInstanceId = delegateTask.getProcessInstanceId();
String taskId = delegateTask.getId();
// 获取业务数据
Map<String, Object> processVariables = delegateTask.getVariables();
// 获取 AI Agent 服务
AiAgentService aiAgentService = SpringBeanUtil.getBean(AiAgentService.class);
// 异步调用 AI 分析
aiAgentService.analyzeAsync(processInstanceId, taskId, aiConfig, processVariables);
log.info("已触发 AI 异步分析: processInstanceId={}, taskId={}", processInstanceId, taskId);
}
}4.2 AI 任务分配监听器
文件: core/listener/AiAgentTaskAssignListener.java
java
package com.pig4cloud.pigx.wflow.core.listener;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.delegate.DelegateTask;
import org.flowable.engine.delegate.TaskListener;
import org.springframework.stereotype.Component;
/**
* AI Agent 任务分配监听器
* 当任务被分配给具体用户时触发
*
* @author willian fu
* @since 2026-01-09
*/
@Slf4j
@Component("aiAgentTaskAssignListener")
public class AiAgentTaskAssignListener implements TaskListener {
@Override
public void notify(DelegateTask delegateTask) {
String assignee = delegateTask.getAssignee();
String taskId = delegateTask.getId();
log.info("AI Agent 任务已分配: taskId={}, assignee={}", taskId, assignee);
// 记录分配时间
delegateTask.setVariable("taskAssignTime", System.currentTimeMillis());
// 判断是 AI 还是人工
if ("ai-agent-user".equals(assignee)) {
delegateTask.setVariable("assigneeType", "AI");
log.info("任务分配给 AI Agent: taskId={}", taskId);
} else {
delegateTask.setVariable("assigneeType", "HUMAN");
log.info("任务分配给人工: taskId={}, user={}", taskId, assignee);
}
}
}4.3 AI 任务完成监听器
文件: core/listener/AiAgentTaskCompleteListener.java
java
package com.pig4cloud.pigx.wflow.core.listener;
import com.pig4cloud.pigx.wflow.dal.ext.WflowAiDecisionRecordDo;
import com.pig4cloud.pigx.wflow.service.AiDecisionRecordService;
import com.pig4cloud.pigx.wflow.utils.SpringBeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.delegate.DelegateTask;
import org.flowable.engine.delegate.TaskListener;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
* AI Agent 任务完成监听器
* 当 AI 审批任务完成时触发,负责:
* 1. 记录 AI 决策结果
* 2. 更新审计日志
* 3. 清理临时变量
*
* @author willian fu
* @since 2026-01-09
*/
@Slf4j
@Component("aiAgentTaskCompleteListener")
public class AiAgentTaskCompleteListener implements TaskListener {
@Override
public void notify(DelegateTask delegateTask) {
String taskId = delegateTask.getId();
String processInstanceId = delegateTask.getProcessInstanceId();
log.info("AI Agent 任务完成: taskId={}, processInstanceId={}", taskId, processInstanceId);
try {
// 1. 获取任务完成信息
String operation = (String) delegateTask.getVariable("operation");
String assigneeType = (String) delegateTask.getVariable("assigneeType");
Object aiSuggestion = delegateTask.getVariable("aiSuggestion");
Object aiConfidence = delegateTask.getVariable("aiConfidence");
// 2. 记录 AI 决策
if ("AI".equals(assigneeType)) {
recordAiDecision(delegateTask, operation, aiSuggestion, aiConfidence);
}
// 3. 计算任务耗时
Long startTime = (Long) delegateTask.getVariable("aiAnalysisStartTime");
if (startTime != null) {
long duration = System.currentTimeMillis() - startTime;
delegateTask.setVariable("taskDuration", duration);
log.info("任务耗时: taskId={}, duration={}ms", taskId, duration);
}
// 4. 清理临时变量
cleanupTemporaryVariables(delegateTask);
log.info("AI Agent 任务完成处理完毕: taskId={}", taskId);
} catch (Exception e) {
log.error("AI Agent 任务完成处理失败: taskId={}, error={}", taskId, e.getMessage(), e);
}
}
/**
* 记录 AI 决策
*/
private void recordAiDecision(DelegateTask delegateTask, String operation,
Object aiSuggestion, Object aiConfidence) {
WflowAiDecisionRecordDo record = WflowAiDecisionRecordDo.builder()
.processInstanceId(delegateTask.getProcessInstanceId())
.taskId(delegateTask.getId())
.taskName(delegateTask.getName())
.operation(operation)
.aiSuggestion(aiSuggestion != null ? aiSuggestion.toString() : null)
.aiConfidence(aiConfidence != null ? Double.valueOf(aiConfidence.toString()) : null)
.decisionTime(new Date())
.build();
// 保存决策记录
AiDecisionRecordService recordService = SpringBeanUtil.getBean(AiDecisionRecordService.class);
recordService.save(record);
log.info("已记录 AI 决策: taskId={}, operation={}, confidence={}",
delegateTask.getId(), operation, aiConfidence);
}
/**
* 清理临时变量
*/
private void cleanupTemporaryVariables(DelegateTask delegateTask) {
// 清理不需要持久化的临时变量
delegateTask.removeVariable("aiAnalysisStartTime");
delegateTask.removeVariable("taskAssignTime");
}
}4.4 人工干预完成监听器
文件: core/listener/HumanInterventionCompleteListener.java
java
package com.pig4cloud.pigx.wflow.core.listener;
import com.pig4cloud.pigx.wflow.dal.ext.WflowHumanInterventionRecordDo;
import com.pig4cloud.pigx.wflow.service.HumanInterventionRecordService;
import com.pig4cloud.pigx.wflow.utils.SpringBeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.delegate.DelegateTask;
import org.flowable.engine.delegate.TaskListener;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
* 人工干预完成监听器
* 当人工干预任务完成时触发,负责:
* 1. 记录干预操作
* 2. 恢复 AI 处理状态
* 3. 更新流程变量
*
* @author willian fu
* @since 2026-01-09
*/
@Slf4j
@Component("humanInterventionCompleteListener")
public class HumanInterventionCompleteListener implements TaskListener {
@Override
public void notify(DelegateTask delegateTask) {
String taskId = delegateTask.getId();
String processInstanceId = delegateTask.getProcessInstanceId();
String intervener = delegateTask.getAssignee();
log.info("人工干预完成: taskId={}, processInstanceId={}, intervener={}",
taskId, processInstanceId, intervener);
try {
// 1. 获取干预信息
String operation = (String) delegateTask.getVariable("operation");
String interventionComment = (String) delegateTask.getVariable("interventionComment");
String interventionReason = (String) delegateTask.getVariable("interventionReason");
// 2. 记录干预操作
recordIntervention(delegateTask, intervener, operation, interventionComment, interventionReason);
// 3. 处理干预完成逻辑
if ("intervention_complete".equals(operation)) {
handleInterventionComplete(delegateTask, interventionComment);
} else if ("terminate_process".equals(operation)) {
handleProcessTermination(delegateTask);
}
log.info("人工干预处理完毕: taskId={}, operation={}", taskId, operation);
} catch (Exception e) {
log.error("人工干预处理失败: taskId={}, error={}", taskId, e.getMessage(), e);
}
}
/**
* 记录干预操作
*/
private void recordIntervention(DelegateTask delegateTask, String intervener,
String operation, String comment, String reason) {
WflowHumanInterventionRecordDo record = WflowHumanInterventionRecordDo.builder()
.processInstanceId(delegateTask.getProcessInstanceId())
.taskId(delegateTask.getId())
.intervener(intervener)
.interveneTime(new Date())
.operation(operation)
.comment(comment)
.reason(reason)
.build();
// 保存干预记录
HumanInterventionRecordService recordService =
SpringBeanUtil.getBean(HumanInterventionRecordService.class);
recordService.save(record);
log.info("已记录人工干预: taskId={}, intervener={}, operation={}",
delegateTask.getId(), intervener, operation);
}
/**
* 处理干预完成,返回 AI 任务
*/
private void handleInterventionComplete(DelegateTask delegateTask, String comment) {
// 重置干预标记
delegateTask.setVariable("humanInterruptRequested", false);
// 恢复 AI 处理
delegateTask.setVariable("aiProcessing", true);
// 记录干预结果
delegateTask.setVariable("lastInterventionResult", comment);
delegateTask.setVariable("lastInterventionTime", new Date());
log.info("干预完成,返回 AI 处理: taskId={}", delegateTask.getId());
}
/**
* 处理流程终止
*/
private void handleProcessTermination(DelegateTask delegateTask) {
// 设置终止标记
delegateTask.setVariable("processTerminated", true);
delegateTask.setVariable("terminationReason", "HUMAN_INTERVENTION");
log.info("流程被人工终止: taskId={}", delegateTask.getId());
}
}4.5 监听器注册
监听器通过 Spring 的 @Component 注解自动注册,Bean 名称与 BPMN 中的 delegateExpression 对应:
| 监听器类 | Bean 名称 | 触发事件 |
|---|---|---|
| AiAgentTaskCreateListener | aiAgentTaskCreateListener | 任务创建 |
| AiAgentTaskAssignListener | aiAgentTaskAssignListener | 任务分配 |
| AiAgentTaskCompleteListener | aiAgentTaskCompleteListener | 任务完成 |
| HumanInterventionCompleteListener | humanInterventionCompleteListener | 干预完成 |