matrixcode-core 0.4.22

MatrixCode Agent Core - Pure logic, no UI
Documentation
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
//! Workflow Engine - State Machine Implementation
//!
//! 工作流引擎,实现状态机的基础结构和主运行循环。

use anyhow::{Context, Result};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use tokio::time::timeout;
use super::context::{WorkflowContext};
use super::def::{FailureStrategy, NodeDef, NodeType, WorkflowDef};
use super::rule_engine::evaluate_expression;
use super::template::TemplateRenderer;
use super::executors::{NodeExecutor, ExecutorFactory};
use crate::tools::toolproxy::{ProxyToolExecutor, ProxyToolDef};

/// 任务执行器 trait
#[async_trait::async_trait]
pub trait TaskExecutor: Send + Sync {
    /// 执行任务,返回输出数据
    async fn execute(
        &self,
        task_name: &str,
        params: &HashMap<String, serde_json::Value>,
        context: &WorkflowContext,
    ) -> Result<serde_json::Value>;
}

/// 工作流事件
#[derive(Debug, Clone)]
pub enum WorkflowEvent {
    /// 工作流开始
    Started,
    /// 节点开始执行
    NodeStarted { node_id: String },
    /// 节点执行完成
    NodeCompleted { node_id: String, output: Option<serde_json::Value> },
    /// 节点执行失败
    NodeFailed { node_id: String, error: String },
    /// 节点跳过
    NodeSkipped { node_id: String, reason: String },
    /// 工作流完成
    Completed,
    /// 工作流失败
    Failed { error: String },
    /// 工作流暂停
    Paused,
    /// 工作流恢复
    Resumed,
}

/// 事件监听器 trait
pub trait EventListener: Send + Sync {
    fn on_event(&self, event: WorkflowEvent);
}

/// 工作流引擎
pub struct WorkflowEngine {
    /// 工作流定义
    definition: WorkflowDef,
    /// 任务执行器(旧接口)
    executor: Option<Arc<dyn TaskExecutor>>,
    /// 节点执行器(新接口)
    node_executors: HashMap<String, Arc<dyn NodeExecutor>>,
    /// 执行器工厂
    executor_factory: Option<ExecutorFactory>,
    /// 代理工具执行器
    proxy_executor: Option<Arc<dyn ProxyToolExecutor>>,
    /// 代理工具定义列表
    proxy_tool_defs: Vec<ProxyToolDef>,
    /// 事件监听器
    listeners: Vec<Box<dyn EventListener>>,
    /// 模板渲染器
    template_renderer: TemplateRenderer,
}

impl WorkflowEngine {
    /// 创建新的工作流引擎
    pub fn new(definition: WorkflowDef) -> Result<Self> {
        definition.validate()
            .with_context(|| "Invalid workflow definition")?;

        Ok(Self {
            definition,
            executor: None,
            node_executors: HashMap::new(),
            executor_factory: None,
            proxy_executor: None,
            proxy_tool_defs: Vec::new(),
            listeners: Vec::new(),
            template_renderer: TemplateRenderer::new(),
        })
    }

    /// 设置任务执行器(旧接口)
    pub fn with_executor(mut self, executor: Arc<dyn TaskExecutor>) -> Self {
        self.executor = Some(executor);
        self
    }

    /// 设置执行器工厂
    pub fn with_executor_factory(mut self, factory: ExecutorFactory) -> Self {
        self.executor_factory = Some(factory);
        self
    }

    /// 设置代理工具执行器
    pub fn with_proxy_executor(mut self, executor: Arc<dyn ProxyToolExecutor>, tool_defs: Vec<ProxyToolDef>) -> Self {
        self.proxy_executor = Some(executor);
        self.proxy_tool_defs = tool_defs;
        self
    }

    /// 注册节点执行器
    pub fn register_node_executor(mut self, task_type: &str, executor: Arc<dyn NodeExecutor>) -> Self {
        self.node_executors.insert(task_type.to_string(), executor);
        self
    }

    /// 添加事件监听器
    pub fn add_listener(&mut self, listener: Box<dyn EventListener>) {
        self.listeners.push(listener);
    }

    /// 触发事件
    fn emit_event(&self, event: WorkflowEvent) {
        for listener in &self.listeners {
            listener.on_event(event.clone());
        }
    }

    /// 获取节点执行器
    fn get_node_executor(&self, node: &NodeDef) -> Option<Arc<dyn NodeExecutor>> {
        // 优先从注册的执行器中查找
        if let Some(task) = &node.task
            && let Some(executor) = self.node_executors.get(task) {
                return Some(executor.clone());
            }

        // 检查是否是代理工具
        if let Some(task) = &node.task
            && self.proxy_tool_defs.iter().any(|t| t.definition.name == *task)
                && let Some(executor) = &self.proxy_executor {
                    return Some(Arc::new(super::executors::ProxyExecutor::new(
                        executor.clone(),
                        self.proxy_tool_defs.clone(),
                    )));
                }

        // 根据节点类型选择默认执行器
        match node.node_type {
            NodeType::Task => {
                // 尝试从工厂创建
                if let Some(factory) = &self.executor_factory
                    && let Some(task) = &node.task {
                        // 根据任务名称推断执行器类型
                        // ai / ai_* / claude* / gpt* 使用 AI 执行器
                        let task_lower = task.to_lowercase();
                        if task_lower == "ai" || task_lower.starts_with("ai_") || task_lower.starts_with("claude") || task_lower.starts_with("gpt") {
                            return factory.create_ai_executor().ok();
                        }
                        // 默认使用工具执行器
                        return Some(factory.create_tool_executor());
                    }
            }
            NodeType::Condition => {
                if let Some(factory) = &self.executor_factory {
                    return Some(factory.create_condition_executor());
                }
            }
            NodeType::Approval => {
                // 审批节点使用特殊的验证执行器
                if let Some(factory) = &self.executor_factory {
                    return Some(factory.create_validate_executor());
                }
            }
            _ => {}
        }

        None
    }

    /// 运行工作流
    pub async fn run(&self, inputs: HashMap<String, serde_json::Value>) -> Result<WorkflowContext> {
        // 创建上下文
        let mut context = WorkflowContext::new(self.definition.id.clone(), inputs.clone());

        // 验证必填输入
        self.validate_inputs(&context)?;

        // 初始化变量:先添加 inputs
        for (key, value) in inputs {
            context.set_variable(key.clone(), value.clone());
        }

        // 渲染并添加 workflow 定义的变量
        let renderer = crate::workflow::template::TemplateRenderer::new();
        for (key, value) in &self.definition.variables {
            // 如果是字符串,渲染模板
            let rendered_value = if let serde_json::Value::String(s) = value {
                match renderer.render(s, &context.variables) {
                    Ok(rendered) => serde_json::Value::String(rendered),
                    Err(_) => value.clone(), // 渲染失败保持原值
                }
            } else {
                value.clone()
            };
            context.set_variable(key.clone(), rendered_value);
        }

        // 开始工作流
        context.start();
        self.emit_event(WorkflowEvent::Started);

        // 获取开始节点
        let start_node = self.definition.get_start_node()
            .ok_or_else(|| anyhow::anyhow!("No start node found"))?;

        // 执行工作流
        match self.execute_from_node(start_node, &mut context).await {
            Ok(()) => {
                context.complete();
                self.emit_event(WorkflowEvent::Completed);
            }
            Err(e) => {
                context.fail(e.to_string());
                self.emit_event(WorkflowEvent::Failed { error: e.to_string() });
            }
        }

        Ok(context)
    }

    /// 从指定节点开始执行
    async fn execute_from_node(
        &self,
        node: &NodeDef,
        context: &mut WorkflowContext,
    ) -> Result<()> {
        let mut current_node = Some(node);

        while let Some(node) = current_node {
            // 检查工作流状态
            if !context.can_continue() {
                break;
            }

            // 执行节点
            match self.execute_node(node, context).await {
                Ok(next_node_id) => {
                    current_node = next_node_id
                        .as_ref()
                        .and_then(|id| self.definition.get_node(id));
                }
                Err(e) => {
                    // 处理失败
                    match &node.on_failure {
                        FailureStrategy::Retry { max_attempts, interval_ms } => {
                            let exec = context.get_or_create_node_execution(&node.id);
                            if exec.retry_count < *max_attempts {
                                exec.increment_retry();
                                if let Some(interval) = interval_ms {
                                    tokio::time::sleep(Duration::from_millis(*interval)).await;
                                }
                                continue; // 重试当前节点
                            } else {
                                return Err(e);
                            }
                        }
                        FailureStrategy::Ignore => {
                            // 忽略错误,标记节点为 Skipped 并继续执行下一个节点
                            let exec = context.get_or_create_node_execution(&node.id);
                            exec.skip();
                            self.emit_event(WorkflowEvent::NodeSkipped {
                                node_id: node.id.clone(),
                                reason: e.to_string(),
                            });
                            let next = self.get_next_node(node, context)?;
                            current_node = next
                                .as_ref()
                                .and_then(|id| self.definition.get_node(id));
                        }
                        FailureStrategy::Abort => {
                            return Err(e);
                        }
                        FailureStrategy::Goto { target } => {
                            current_node = self.definition.get_node(target);
                        }
                    }
                }
            }
        }

        Ok(())
    }

    /// 执行单个节点
    async fn execute_node(
        &self,
        node: &NodeDef,
        context: &mut WorkflowContext,
    ) -> Result<Option<String>> {
        // 创建执行记录
        let execution = context.get_or_create_node_execution(&node.id);
        execution.start();
        self.emit_event(WorkflowEvent::NodeStarted { node_id: node.id.clone() });

        // 设置当前节点
        context.set_current_node(node.id.clone());

        // 处理超时
        let result = if let Some(timeout_ms) = node.timeout_ms {
            timeout(
                Duration::from_millis(timeout_ms),
                self.execute_node_inner(node, context),
            )
            .await
            .with_context(|| format!("Node '{}' timed out after {}ms", node.id, timeout_ms))?
        } else {
            self.execute_node_inner(node, context).await
        };

        match result {
            Ok(output) => {
                let exec = context.get_or_create_node_execution(&node.id);
                exec.complete(output.clone());
                self.emit_event(WorkflowEvent::NodeCompleted {
                    node_id: node.id.clone(),
                    output,
                });

                // 获取下一个节点
                self.get_next_node(node, context)
            }
            Err(e) => {
                let exec = context.get_or_create_node_execution(&node.id);
                exec.fail(e.to_string());
                self.emit_event(WorkflowEvent::NodeFailed {
                    node_id: node.id.clone(),
                    error: e.to_string(),
                });
                Err(e)
            }
        }
    }

    /// 节点内部执行逻辑
    async fn execute_node_inner(
        &self,
        node: &NodeDef,
        context: &mut WorkflowContext,
    ) -> Result<Option<serde_json::Value>> {
        match &node.node_type {
            NodeType::Start => {
                Ok(None)
            }
            NodeType::End => {
                Ok(None)
            }
            NodeType::Task => {
                self.execute_task(node, context).await
            }
            NodeType::Condition => {
                self.execute_condition(node, context).await
            }
            NodeType::Parallel => {
                self.execute_parallel(node, context).await
            }
            NodeType::SubWorkflow => {
                self.execute_subworkflow(node, context).await
            }
            NodeType::Wait => {
                self.execute_wait(node, context).await
            }
            NodeType::Approval => {
                self.execute_approval(node, context).await
            }
        }
    }

    /// 执行任务节点
    async fn execute_task(
        &self,
        node: &NodeDef,
        context: &mut WorkflowContext,
    ) -> Result<Option<serde_json::Value>> {
        let task_name = node.task.as_ref()
            .ok_or_else(|| anyhow::anyhow!("Task node '{}' has no task name", node.id))?;

        // 渲染参数
        let mut rendered_params = HashMap::new();
        for (key, value) in &node.params {
            if let serde_json::Value::String(s) = value {
                let rendered = self.template_renderer.render(s, &context.variables)?;
                rendered_params.insert(key.clone(), serde_json::Value::String(rendered));
            } else {
                rendered_params.insert(key.clone(), value.clone());
            }
        }

        // 尝试使用新的 NodeExecutor 接口
        if let Some(node_executor) = self.get_node_executor(node) {
            let output = node_executor.execute(node, context).await?;
            return Ok(Some(output));
        }

        // 回退到旧的 TaskExecutor 接口
        if let Some(executor) = &self.executor {
            let output = executor.execute(task_name, &rendered_params, context).await?;
            Ok(Some(output))
        } else {
            // 无执行器,返回模拟输出
            Ok(Some(serde_json::json!({ "task": task_name, "status": "completed" })))
        }
    }

    /// 执行条件节点
    async fn execute_condition(
        &self,
        node: &NodeDef,
        context: &mut WorkflowContext,
    ) -> Result<Option<serde_json::Value>> {
        let branches = node.branches.as_ref()
            .ok_or_else(|| anyhow::anyhow!("Condition node '{}' has no branches", node.id))?;

        for branch in branches {
            if evaluate_expression(&branch.condition, &context.variables)? {
                // 找到匹配的分支,设置目标节点
                return Ok(Some(serde_json::Value::String(branch.target.clone())));
            }
        }

        // 没有匹配的分支
        Ok(None)
    }

    /// 执行并行节点
    async fn execute_parallel(
        &self,
        node: &NodeDef,
        _context: &mut WorkflowContext,
    ) -> Result<Option<serde_json::Value>> {
        let branches = node.parallel_branches.as_ref()
            .ok_or_else(|| anyhow::anyhow!("Parallel node '{}' has no branches", node.id))?;

        // 并行执行所有分支
        let mut outputs = Vec::new();
        for branch in branches {
            // 这里简化处理,实际应该并行执行
            outputs.push(serde_json::json!({
                "branch": branch.name,
                "status": "completed"
            }));
        }

        Ok(Some(serde_json::Value::Array(outputs)))
    }

    /// 执行子工作流
    async fn execute_subworkflow(
        &self,
        node: &NodeDef,
        _context: &mut WorkflowContext,
    ) -> Result<Option<serde_json::Value>> {
        let workflow_name = node.workflow.as_ref()
            .ok_or_else(|| anyhow::anyhow!("SubWorkflow node '{}' has no workflow name", node.id))?;

        // 这里简化处理,实际应该加载并执行子工作流
        Ok(Some(serde_json::json!({
            "workflow": workflow_name,
            "status": "completed"
        })))
    }

    /// 执行等待节点
    async fn execute_wait(
        &self,
        node: &NodeDef,
        _context: &mut WorkflowContext,
    ) -> Result<Option<serde_json::Value>> {
        let wait_ms = node.wait_ms.unwrap_or(0);
        if wait_ms > 0 {
            tokio::time::sleep(Duration::from_millis(wait_ms)).await;
        }
        Ok(None)
    }

    /// 执行审批节点
    async fn execute_approval(
        &self,
        node: &NodeDef,
        _context: &mut WorkflowContext,
    ) -> Result<Option<serde_json::Value>> {
        let approvers = node.approvers.as_ref()
            .ok_or_else(|| anyhow::anyhow!("Approval node '{}' has no approvers", node.id))?;

        // 这里简化处理,实际应该等待审批
        Ok(Some(serde_json::json!({
            "approvers": approvers,
            "status": "pending_approval"
        })))
    }

    /// 获取下一个节点
    fn get_next_node(
        &self,
        node: &NodeDef,
        context: &WorkflowContext,
    ) -> Result<Option<String>> {
        // 结束节点没有下一个节点
        if node.node_type == NodeType::End {
            return Ok(None);
        }

        // 获取输出边
        let edges = self.definition.get_outgoing_edges(&node.id);

        if edges.is_empty() {
            return Ok(None);
        }

        // 条件节点从分支获取下一个节点
        if node.node_type == NodeType::Condition {
            let exec = context.get_node_execution(&node.id);
            if let Some(exec) = exec
                && let Some(serde_json::Value::String(target)) = &exec.output {
                    return Ok(Some(target.clone()));
                }
        }

        // 根据边条件选择下一个节点
        for edge in edges {
            if let Some(condition) = &edge.condition {
                if evaluate_expression(condition, &context.variables)? {
                    return Ok(Some(edge.to.clone()));
                }
            } else {
                // 无条件的边,直接返回
                return Ok(Some(edge.to.clone()));
            }
        }

        // 没有匹配的边
        Ok(None)
    }

    /// 验证输入参数
    fn validate_inputs(&self, context: &WorkflowContext) -> Result<()> {
        for input_def in &self.definition.inputs {
            if input_def.required
                && context.get_input(&input_def.name).is_none()
                    && input_def.default.is_none() {
                        anyhow::bail!("Required input '{}' is missing", input_def.name);
                    }
        }
        Ok(())
    }

    /// 获取工作流定义
    pub fn definition(&self) -> &WorkflowDef {
        &self.definition
    }
}

/// 默认任务执行器(用于测试)
pub struct DefaultTaskExecutor;

#[async_trait::async_trait]
impl TaskExecutor for DefaultTaskExecutor {
    async fn execute(
        &self,
        task_name: &str,
        _params: &HashMap<String, serde_json::Value>,
        _context: &WorkflowContext,
    ) -> Result<serde_json::Value> {
        Ok(serde_json::json!({
            "task": task_name,
            "status": "completed",
            "output": null
        }))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use super::super::def::EdgeDef;
    use super::super::context::WorkflowStatus;

    fn create_simple_workflow() -> WorkflowDef {
        WorkflowDef {
            id: "test-workflow".to_string(),
            name: "Test Workflow".to_string(),
            version: "1.0.0".to_string(),
            description: None,
            inputs: vec![],
            outputs: vec![],
            nodes: vec![
                NodeDef {
                    id: "start".to_string(),
                    node_type: NodeType::Start,
                    name: "Start".to_string(),
                    description: None,
                    task: None,
                    params: HashMap::new(),
                    on_failure: FailureStrategy::Abort,
                    timeout_ms: None,
                    branches: None,
                    parallel_branches: None,
                    workflow: None,
                    wait_ms: None,
                    approvers: None,
                },
                NodeDef {
                    id: "task1".to_string(),
                    node_type: NodeType::Task,
                    name: "Task 1".to_string(),
                    description: None,
                    task: Some("do_something".to_string()),
                    params: HashMap::new(),
                    on_failure: FailureStrategy::Abort,
                    timeout_ms: None,
                    branches: None,
                    parallel_branches: None,
                    workflow: None,
                    wait_ms: None,
                    approvers: None,
                },
                NodeDef {
                    id: "end".to_string(),
                    node_type: NodeType::End,
                    name: "End".to_string(),
                    description: None,
                    task: None,
                    params: HashMap::new(),
                    on_failure: FailureStrategy::Abort,
                    timeout_ms: None,
                    branches: None,
                    parallel_branches: None,
                    workflow: None,
                    wait_ms: None,
                    approvers: None,
                },
            ],
            edges: vec![
                EdgeDef {
                    id: "e1".to_string(),
                    from: "start".to_string(),
                    to: "task1".to_string(),
                    condition: None,
                    label: None,
                },
                EdgeDef {
                    id: "e2".to_string(),
                    from: "task1".to_string(),
                    to: "end".to_string(),
                    condition: None,
                    label: None,
                },
            ],
            variables: HashMap::new(),
            default_failure_strategy: FailureStrategy::Abort,
            timeout_ms: None,
        }
    }

    #[tokio::test]
    async fn test_engine_run() {
        let workflow = create_simple_workflow();
        let engine = WorkflowEngine::new(workflow).unwrap();

        let inputs = HashMap::new();
        let context = engine.run(inputs).await.unwrap();

        assert_eq!(context.status, WorkflowStatus::Completed);
        assert_eq!(context.execution_path.len(), 3);
    }

    #[tokio::test]
    async fn test_engine_with_executor() {
        let workflow = create_simple_workflow();
        let executor = Arc::new(DefaultTaskExecutor);
        let engine = WorkflowEngine::new(workflow)
            .unwrap()
            .with_executor(executor);

        let inputs = HashMap::new();
        let context = engine.run(inputs).await.unwrap();

        assert_eq!(context.status, WorkflowStatus::Completed);
    }
}