Skip to main content

tiny_agent/core/
mod.rs

1mod builder;
2mod failure;
3mod prompt;
4mod reasoning;
5mod runtime;
6#[cfg(test)]
7mod tests;
8mod tool_execution;
9
10pub use builder::{AgentRunTimeBuilder, AgentRuntimeConfig};
11pub use failure::{AgentFailure, FailureKind};
12
13use crate::{
14    checkpoint::CheckpointStorage,
15    error::StorageError,
16    middleware::MiddlewareChain,
17    providers::LlmProvider,
18    sandbox::Sandbox,
19    shared::{ToolCall, UserInteraction},
20    skills::SkillManager,
21    state::AgentState,
22    tools::ToolRegistry,
23    trajectory::TrajectorySink,
24    transcript::TranscriptStorage,
25};
26use prompt::PromptComposer;
27use serde::{Deserialize, Serialize};
28use std::time::Duration;
29use std::{
30    collections::HashMap,
31    sync::{Arc, Weak},
32};
33use tokio::sync::Mutex;
34
35#[derive(Debug, Serialize, Deserialize)]
36pub enum Agent {
37    Ready(AgentState),
38    Reasoning(AgentState),
39    ToolExecuting(AgentState, ToolRunState),
40    WaitingForUser(AgentState, UserInteraction),
41    Success(AgentState),
42    Interrupted(AgentState),
43    Fail(AgentState, AgentFailure),
44}
45
46#[derive(Debug, Clone, Serialize, Deserialize)]
47pub struct ToolRunState {
48    pub calls: Vec<ToolCall>,
49    pub cursor: usize,
50}
51
52impl ToolRunState {
53    pub fn new(calls: Vec<ToolCall>) -> Self {
54        Self { calls, cursor: 0 }
55    }
56}
57
58pub struct AgentRunTime {
59    pub(crate) provider: Arc<dyn LlmProvider>,
60    pub(crate) max_iter: u32,
61    pub(crate) max_consecutive_fail_count: u32,
62    pub(crate) model: String,
63    pub(crate) system_prompt: Option<String>,
64    pub(crate) temperature: Option<f32>,
65    pub(crate) max_tokens: Option<u32>,
66    pub(crate) checkpoint_storage: Arc<dyn CheckpointStorage>,
67    pub(crate) transcript_storage: Arc<dyn TranscriptStorage>,
68    pub(crate) sandbox: Arc<dyn Sandbox>,
69    pub(crate) tools: ToolRegistry,
70    pub(crate) skills: Option<Arc<SkillManager>>,
71    pub(crate) prompt_composer: PromptComposer,
72    pub(crate) middleware: MiddlewareChain,
73    pub(crate) trajectory: Arc<dyn TrajectorySink>,
74    /// 可重试失败的退避基数(指数退避 + jitter 的 base)。设为 0 关闭退避。
75    pub(crate) retry_backoff: Duration,
76    /// 单个工具调用的超时时间。设为 0 时关闭工具超时。
77    pub(crate) tool_timeout: Duration,
78    pub(crate) session_locks: Mutex<HashMap<String, Weak<Mutex<()>>>>,
79}
80
81#[derive(Debug, Default)]
82pub(crate) struct PendingToolCall {
83    pub(crate) id: Option<String>,
84    pub(crate) name: Option<String>,
85    pub(crate) arguments: String,
86}
87
88pub(crate) fn storage_failure(ctx: AgentState, error: StorageError) -> Agent {
89    Agent::Fail(
90        ctx,
91        AgentFailure::new(FailureKind::Storage, error.to_string()),
92    )
93}