agent-base 0.1.1

A lightweight Agent Runtime Kernel for building AI agents in Rust
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
use std::sync::Arc;

use async_trait::async_trait;
use serde_json::{json, Value};

use crate::engine::{PlanGenerator, PlanStore, StepExecutor};
use crate::tool::{Tool, ToolContext, ToolControlFlow, ToolOutput};
use crate::types::{AgentError, AgentEvent, AgentResult, PlanStatus, StepStatus};

/// PlanOrchestrator is a domain-agnostic tool for creating execution plans.
/// It delegates plan generation to a `PlanGenerator` implementation and
/// stores the plan via a `PlanStore`.
#[derive(Clone)]
pub struct PlanOrchestrator {
    plan_generator: Arc<dyn PlanGenerator>,
    step_executor: Arc<dyn StepExecutor>,
    plan_store: Arc<dyn PlanStore>,
}

impl PlanOrchestrator {
    pub fn new(
        plan_generator: Arc<dyn PlanGenerator>,
        step_executor: Arc<dyn StepExecutor>,
        plan_store: Arc<dyn PlanStore>,
    ) -> Self {
        Self {
            plan_generator,
            step_executor,
            plan_store,
        }
    }

    pub fn with_step_executor(&mut self, step_executor: Arc<dyn StepExecutor>) {
        self.step_executor = step_executor;
    }
}

#[async_trait]
impl Tool for PlanOrchestrator {
    fn name(&self) -> &'static str {
        "create_plan"
    }

    fn definition(&self) -> Value {
        json!({
            "type": "function",
            "function": {
                "name": "create_plan",
                "description": "Analyze a task and generate an execution plan (without executing commands). Used for complex tasks that require multiple steps. The system will analyze the objective and generate a plan; after user review and confirmation, use execute_plan to execute it.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "objective": {
                            "type": "string",
                            "description": "The overall goal of the task, e.g. 'check disk space', 'troubleshoot network issues'"
                        },
                        "context": {
                            "type": "string",
                            "description": "Additional context information, such as target host, environment variables, etc."
                        }
                    },
                    "required": ["objective"]
                }
            }
        })
    }

    async fn call(&self, args: &Value, ctx: &ToolContext) -> AgentResult<ToolOutput> {
        let objective = args
            .get("objective")
            .and_then(Value::as_str)
            .unwrap_or("unnamed task")
            .to_string();
        let context = args
            .get("context")
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string();

        let plan_id = {
            let timestamp = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis();
            static COUNTER: std::sync::atomic::AtomicU64 =
                std::sync::atomic::AtomicU64::new(0);
            let count = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            format!("plan-{timestamp}-{count}")
        };

        let event_bus_g = ctx.event_bus.clone();
        let session_id_g = ctx.session_id.clone();
        let plan_id_g = plan_id.clone();
        let on_generating = Box::new(move || {
            let _ = event_bus_g.send(AgentEvent::PlanGenerating {
                session_id: session_id_g.clone(),
                plan_id: plan_id_g.clone(),
            });
        });

        let event_bus_s = ctx.event_bus.clone();
        let session_id_s = ctx.session_id.clone();
        let plan_id_s = plan_id.clone();
        let on_step_parsed = Box::new(move |index: usize, step_id: String, description: String| {
            let _ = event_bus_s.send(AgentEvent::PlanStepParsed {
                session_id: session_id_s.clone(),
                plan_id: plan_id_s.clone(),
                step_index: index,
                step_id,
                step_description: description,
            });
        });

        let event_bus_t = ctx.event_bus.clone();
        let session_id_t = ctx.session_id.clone();
        let on_raw_chunk = Box::new(move |text: String| {
            let _ = event_bus_t.send(AgentEvent::ThoughtDelta {
                session_id: session_id_t.clone(),
                text,
            });
        });

        let tools = vec![];

        match self
            .plan_generator
            .generate_plan_streaming(
                &objective,
                &context,
                &tools,
                on_generating,
                on_step_parsed,
                on_raw_chunk,
            )
            .await
        {
            Ok(mut plan) => {
                plan.id = plan_id.clone();
                plan.objective = objective.clone();

                self.plan_store
                    .save_plan(&plan, json!({"session_id": ctx.session_id.to_string()}))
                    .await?;

                let _ = ctx.event_bus.send(AgentEvent::PlanGenerated {
                    session_id: ctx.session_id.clone(),
                    plan: plan.clone(),
                });

                let step_details: Vec<Value> = plan
                    .steps
                    .iter()
                    .map(|s| {
                        json!({
                            "id": s.id,
                            "description": s.description,
                        })
                    })
                    .collect();

                let summary = if ctx.language == crate::types::Language::Zh {
                    format!(
                        "计划已生成,包含 {} 个步骤,等待用户确认。计划ID: {}",
                        plan.steps.len(),
                        plan_id
                    )
                } else {
                    format!(
                        "Plan generated with {} steps, awaiting user confirmation. plan_id: {}",
                        plan.steps.len(),
                        plan_id
                    )
                };

                Ok(ToolOutput {
                    summary,
                    raw: Some(json!({
                        "objective": objective,
                        "plan_id": plan_id,
                        "steps_count": plan.steps.len(),
                        "steps": step_details,
                        "success": true,
                        "status": "awaiting_confirmation",
                    })),
                    control_flow: ToolControlFlow::Continue,
                    truncation: None,
                })
            }
            Err(e) => {
                let _ = ctx.event_bus.send(AgentEvent::PlanFailed {
                    session_id: ctx.session_id.clone(),
                    plan_id: plan_id.clone(),
                    error: e.to_string(),
                });

                let summary = if ctx.language == crate::types::Language::Zh {
                    format!("计划生成失败: {e}")
                } else {
                    format!("Plan generation failed: {e}")
                };

                Ok(ToolOutput {
                    summary,
                    raw: Some(json!({
                        "objective": objective,
                        "plan_id": plan_id,
                        "success": false,
                        "error": e.to_string(),
                    })),
                    control_flow: ToolControlFlow::Continue,
                    truncation: None,
                })
            }
        }
    }
}

/// PlanExecTool is a domain-agnostic tool for executing previously created plans.
#[derive(Clone)]
pub struct PlanExecTool {
    step_executor: Arc<dyn StepExecutor>,
    plan_store: Arc<dyn PlanStore>,
    recovery: Arc<dyn crate::engine::RecoveryStrategy>,
}

impl PlanExecTool {
    pub fn new(
        step_executor: Arc<dyn StepExecutor>,
        plan_store: Arc<dyn PlanStore>,
        recovery: Arc<dyn crate::engine::RecoveryStrategy>,
    ) -> Self {
        Self {
            step_executor,
            plan_store,
            recovery,
        }
    }
}

#[async_trait]
impl Tool for PlanExecTool {
    fn name(&self) -> &'static str {
        "execute_plan"
    }

    fn definition(&self) -> Value {
        json!({
            "type": "function",
            "function": {
                "name": "execute_plan",
                "description": "Execute a previously generated plan. First use create_plan to generate a plan, then after user review and confirmation, use this tool to execute it.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "plan_id": {
                            "type": "string",
                            "description": "The plan ID to execute (obtained from the create_plan result)"
                        }
                    },
                    "required": ["plan_id"]
                }
            }
        })
    }

    async fn call(&self, args: &Value, ctx: &ToolContext) -> AgentResult<ToolOutput> {
        let plan_id = args
            .get("plan_id")
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string();

        let is_zh = ctx.language == crate::types::Language::Zh;

        if plan_id.is_empty() {
            let summary = if is_zh {
                "缺少 plan_id 参数".to_string()
            } else {
                "Missing plan_id parameter".to_string()
            };
            return Ok(ToolOutput {
                summary,
                raw: Some(json!({
                    "success": false,
                    "error": "plan_id is required",
                })),
                control_flow: ToolControlFlow::Continue,
                truncation: None,
            });
        }

        let plan_data = self
            .plan_store
            .load_plan(&plan_id)
            .await?
            .ok_or_else(|| AgentError::plan_storage(
                if is_zh {
                    format!("计划 {plan_id} 不存在,可能已过期或从未创建")
                } else {
                    format!("Plan {plan_id} does not exist, it may have expired or never been created")
                }
            ))?;

        let mut plan = plan_data.plan;
        let objective = plan.objective.clone();
        let mut execution_summary = if is_zh {
            format!("计划 '{}' 的执行结果:\n", objective)
        } else {
            format!("Execution results for plan '{}':\n", objective)
        };
        let mut step_results = Vec::new();
        let mut overall_success = true;
        let mut failed_step_name: Option<String> = None;
        let mut _completed_count = 0usize;

        for (index, step) in plan.steps.iter_mut().enumerate() {
            if step.status != StepStatus::Pending {
                continue;
            }

            step.status = StepStatus::Running;

            let _ = ctx.event_bus.send(AgentEvent::PlanStepStarted {
                session_id: ctx.session_id.clone(),
                step_id: step.id.clone(),
                step_description: step.description.clone(),
            });

            execution_summary.push_str(&if is_zh {
                format!("步骤 {}: {}\n", index + 1, step.description)
            } else {
                format!("Step {}: {}\n", index + 1, step.description)
            });

            match self
                .step_executor
                .execute_step(step, &plan_data.metadata)
                .await
            {
                Ok(result) => {
                    let step_success = result.success;
                    step.status = if step_success {
                        StepStatus::Completed
                    } else {
                        StepStatus::Failed
                    };
                    step.result = Some(result.clone());

                    execution_summary.push_str(&if is_zh {
                        format!(
                            "  结果: {}\n",
                            if step_success { "成功" } else { "失败" }
                        )
                    } else {
                        format!(
                            "  Result: {}\n",
                            if step_success { "OK" } else { "FAILED" }
                        )
                    });

                    let _ = ctx.event_bus.send(AgentEvent::PlanStepCompleted {
                        session_id: ctx.session_id.clone(),
                        step_id: step.id.clone(),
                        success: step_success,
                        result: result.output.clone(),
                    });

                    if step_success {
                        _completed_count += 1;
                    } else {
                        if let Some(ref output) = result.output {
                            execution_summary.push_str(&if is_zh {
                                format!("  错误: {output}\n")
                            } else {
                                format!("  Error: {output}\n")
                            });
                        }

                        match self
                            .recovery
                            .handle_step_failure(
                                step,
                                result.output.as_deref().unwrap_or(""),
                                0,
                            )
                            .await
                        {
                            Ok(action) => match action {
                                crate::types::RecoveryAction::Retry => {
                                    execution_summary.push_str(
                                        if is_zh {
                                            "  [重试] 系统建议重试该步骤(计划标记为未完全成功)\n"
                                        } else {
                                            "  [Retry] System suggests retrying this step (plan marked as not fully successful)\n"
                                        },
                                    );
                                    overall_success = false;
                                }
                                crate::types::RecoveryAction::Skip => {
                                    execution_summary.push_str(
                                        if is_zh {
                                            "  [跳过] 系统建议跳过该步骤(计划标记为未完全成功)\n"
                                        } else {
                                            "  [Skip] System suggests skipping this step (plan marked as not fully successful)\n"
                                        },
                                    );
                                    step.status = StepStatus::Skipped;
                                    overall_success = false;
                                }
                                crate::types::RecoveryAction::Abort => {
                                    execution_summary.push_str(
                                        if is_zh {
                                            "  [中止] 系统建议中止计划\n"
                                        } else {
                                            "  [Abort] System suggests aborting the plan\n"
                                        },
                                    );
                                    overall_success = false;
                                    failed_step_name = Some(step.description.clone());
                                    break;
                                }
                            },
                            Err(_e) => {
                                overall_success = false;
                                failed_step_name = Some(step.description.clone());
                                break;
                            }
                        }
                    }

                    step_results.push(json!({
                        "step": step.description,
                        "success": step_success,
                        "output": result.output,
                    }));
                }
                Err(e) => {
                    step.status = StepStatus::Failed;
                    execution_summary.push_str(&if is_zh {
                        format!("  执行错误: {e}\n")
                    } else {
                        format!("  Execution error: {e}\n")
                    });

                    let _ = ctx.event_bus.send(AgentEvent::PlanStepCompleted {
                        session_id: ctx.session_id.clone(),
                        step_id: step.id.clone(),
                        success: false,
                        result: Some(e.to_string()),
                    });

                    overall_success = false;
                    failed_step_name = Some(step.description.clone());
                    break;
                }
            }
        }

        plan.status = if overall_success && plan.is_completed() {
            PlanStatus::Completed
        } else if plan.has_failed() {
            PlanStatus::Failed
        } else {
            PlanStatus::Executing
        };

        self.plan_store
            .save_plan(&plan, plan_data.metadata)
            .await?;

        if overall_success {
            execution_summary.push_str(
                if is_zh { "所有步骤执行完毕。" } else { "All steps completed." }
            );
        }

        let _ = ctx.event_bus.send(AgentEvent::PlanCompleted {
            session_id: ctx.session_id.clone(),
            plan_id: plan_id.clone(),
            success: overall_success,
        });

        Ok(ToolOutput {
            summary: execution_summary,
            raw: Some(json!({
                "objective": objective,
                "plan_id": plan_id,
                "steps": step_results,
                "success": overall_success,
                "failed_step": failed_step_name,
            })),
            control_flow: ToolControlFlow::Continue,
            truncation: None,
        })
    }
}