Skip to main content

otherone/
lib.rs

1// 作用:otherone 主 crate — 统一导出所有公开 API
2// 关联:用户通过导入 otherone crate 来使用所有功能
3// 预期结果:提供统一的 Otherone struct,封装所有 Agent 框架功能
4
5use otherone_agent::types::{AiOptions, InputOptions};
6use otherone_agent::{AgentStreamHandle, StreamAgentEvent};
7use otherone_ai::types::ProviderType;
8use tokio::sync::mpsc;
9
10/// Otherone — 轻量级 AI Agent 框架的 Rust 实现
11pub struct Otherone;
12
13impl Otherone {
14    /// 创建新的 Multi-Agent Runtime builder。
15    pub fn multi_agent_runtime() -> otherone_agent::multi_agent::AgentRuntimeBuilder {
16        otherone_agent::multi_agent::AgentRuntime::builder()
17    }
18
19    /// Set the localfile storage root.
20    ///
21    /// By default localfile storage uses the current working directory. After
22    /// setting a root, storage is written under
23    /// `<root>/.otherone/storage/otherone-storage.json`.
24    pub fn set_localfile_root(root: impl Into<std::path::PathBuf>) {
25        otherone_storage::localfile::set_storage_root(root);
26    }
27
28    /// Clear the configured localfile storage root and restore current-dir behavior.
29    pub fn clear_localfile_root() {
30        otherone_storage::localfile::clear_storage_root();
31    }
32
33    /// Return the resolved localfile storage file path.
34    pub fn localfile_storage_path() -> std::path::PathBuf {
35        otherone_storage::localfile::get_storage_path()
36    }
37
38    /// 调用 Agent(非流式)
39    pub async fn invoke_agent(
40        input: &InputOptions,
41        ai: &mut AiOptions,
42        auxiliary_ai: Option<&mut AiOptions>,
43    ) -> Result<otherone_ai::types::ParsedResponse, otherone_agent::error::AgentError> {
44        otherone_agent::invoke_agent(input, ai, auxiliary_ai).await
45    }
46
47    /// 调用 Agent(流式)
48    /// 作用:启动流式 Agent 循环,返回 mpsc Receiver 用于异步接收事件
49    /// 关联:委托给 otherone_agent::invoke_agent_stream
50    /// 预期结果:调用者通过 receiver 接收 StreamAgentEvent
51    pub async fn invoke_agent_stream(
52        input: InputOptions,
53        ai: AiOptions,
54        auxiliary_ai: Option<AiOptions>,
55    ) -> Result<mpsc::Receiver<StreamAgentEvent>, otherone_agent::error::AgentError> {
56        otherone_agent::invoke_agent_stream(input, ai, auxiliary_ai).await
57    }
58
59    /// 调用 Agent(可交互流式)
60    /// 作用:返回事件接收器和运行中命令发送器,允许调用方在安全边界追加用户消息
61    pub async fn invoke_agent_stream_interactive(
62        input: InputOptions,
63        ai: AiOptions,
64        auxiliary_ai: Option<AiOptions>,
65    ) -> Result<AgentStreamHandle, otherone_agent::error::AgentError> {
66        otherone_agent::invoke_agent_stream_interactive(input, ai, auxiliary_ai).await
67    }
68
69    /// 调用 AI 模型(不经过 Agent 循环)
70    pub async fn invoke_model(
71        provider: ProviderType,
72        api_key: &str,
73        base_url: &str,
74        config: serde_json::Value,
75    ) -> Result<otherone_ai::types::ChatResponse, otherone_ai::error::AiError> {
76        otherone_ai::invoke_model(provider, api_key, base_url, config).await
77    }
78
79    /// 处理工具调用
80    pub fn process_tools(
81        tool_calls: &[otherone_ai::types::ToolCall],
82        tools_realize: &std::collections::HashMap<
83            String,
84            Box<dyn Fn(serde_json::Value) -> String + Send + Sync>,
85        >,
86    ) -> Result<Vec<otherone_tools::types::ToolResult>, String> {
87        otherone_tools::process_tools(tool_calls, tools_realize)
88    }
89
90    /// 检查 Token 阈值
91    pub fn check_threshold(
92        context_tokens: u32,
93        context_window: u32,
94        threshold_percentage: Option<f32>,
95    ) -> bool {
96        otherone_context::compact::check_threshold::check_threshold(
97            context_tokens,
98            context_window,
99            threshold_percentage,
100        )
101    }
102
103    /// 估算 Token 数量
104    pub fn estimate_tokens(messages: &[otherone_ai::types::Message]) -> u32 {
105        otherone_context::compact::estimate_tokens::estimate_tokens(messages)
106    }
107
108    /// 创建新会话(本地文件)
109    pub fn create_new_session() -> Result<String, otherone_storage::error::StorageError> {
110        otherone_storage::localfile::writer::create_new_session()
111    }
112
113    /// 创建新会话(数据库)
114    pub async fn create_new_session_in_database(
115        config: &otherone_storage::types::DatabaseConfig,
116    ) -> Result<String, otherone_storage::error::StorageError> {
117        otherone_storage::database::writer::create_new_session_in_database(config).await
118    }
119
120    pub async fn create_new_session_in_database_with_context(
121        config: &otherone_storage::types::DatabaseConfig,
122        runtime_context: &otherone_storage::types::RuntimeContext,
123    ) -> Result<String, otherone_storage::error::StorageError> {
124        otherone_storage::database::writer::create_new_session_in_database_with_context(
125            config,
126            runtime_context,
127        )
128        .await
129    }
130
131    /// 获取所有会话(本地文件)
132    pub fn get_all_sessions(
133    ) -> Result<Vec<otherone_storage::types::Session>, otherone_storage::error::StorageError> {
134        otherone_storage::localfile::reader::get_all_sessions()
135    }
136
137    /// 获取所有本地会话,包括 Multi-Agent 内部子会话。
138    pub fn get_all_sessions_including_internal(
139    ) -> Result<Vec<otherone_storage::types::Session>, otherone_storage::error::StorageError> {
140        otherone_storage::localfile::reader::get_all_sessions_with_internal(true)
141    }
142
143    /// 获取所有会话(数据库)
144    pub async fn get_all_sessions_from_database(
145        config: &otherone_storage::types::DatabaseConfig,
146    ) -> Result<Vec<otherone_storage::types::Session>, otherone_storage::error::StorageError> {
147        otherone_storage::database::reader::get_all_sessions_from_database(config).await
148    }
149
150    pub async fn get_all_sessions_from_database_with_context(
151        config: &otherone_storage::types::DatabaseConfig,
152        runtime_context: &otherone_storage::types::RuntimeContext,
153    ) -> Result<Vec<otherone_storage::types::Session>, otherone_storage::error::StorageError> {
154        otherone_storage::database::reader::get_all_sessions_from_database_with_context(
155            config,
156            runtime_context,
157        )
158        .await
159    }
160
161    /// 获取数据库中的所有会话,包括 Multi-Agent 内部子会话。
162    pub async fn get_all_sessions_from_database_with_context_including_internal(
163        config: &otherone_storage::types::DatabaseConfig,
164        runtime_context: &otherone_storage::types::RuntimeContext,
165    ) -> Result<Vec<otherone_storage::types::Session>, otherone_storage::error::StorageError> {
166        otherone_storage::database::reader::get_all_sessions_from_database_with_context_and_internal(
167            config,
168            runtime_context,
169            true,
170        )
171        .await
172    }
173
174    /// 读取会话数据(本地文件)
175    pub fn read_session_data(
176        session_id: &str,
177    ) -> Result<otherone_storage::types::SessionData, otherone_storage::error::StorageError> {
178        otherone_storage::localfile::reader::read_session_data(session_id)
179    }
180
181    /// 读取会话数据(数据库)
182    pub async fn read_session_data_from_database(
183        session_id: &str,
184        config: &otherone_storage::types::DatabaseConfig,
185    ) -> Result<otherone_storage::types::SessionData, otherone_storage::error::StorageError> {
186        otherone_storage::database::reader::read_session_data_from_database(session_id, config)
187            .await
188    }
189
190    pub async fn read_session_data_from_database_with_context(
191        session_id: &str,
192        config: &otherone_storage::types::DatabaseConfig,
193        runtime_context: &otherone_storage::types::RuntimeContext,
194    ) -> Result<otherone_storage::types::SessionData, otherone_storage::error::StorageError> {
195        otherone_storage::database::reader::read_session_data_from_database_with_context(
196            session_id,
197            config,
198            runtime_context,
199        )
200        .await
201    }
202
203    /// 初始化数据库
204    pub async fn init_database(
205        config: &otherone_storage::types::DatabaseConfig,
206    ) -> Result<(), otherone_storage::error::StorageError> {
207        otherone_storage::database::init::init_database(config).await
208    }
209
210    /// 读取原始存储文件
211    /// 作用:读取 .otherone/storage/otherone-storage.json 的完整内容
212    /// 关联:被用户调用,用于调试或直接访问存储数据
213    /// 预期结果:返回完整的 StorageFile 结构
214    pub fn read_storage_file(
215    ) -> Result<otherone_storage::types::StorageFile, otherone_storage::error::StorageError> {
216        otherone_storage::localfile::reader::read_storage_file()
217    }
218
219    /// 组合上下文
220    /// 作用:根据 session_id 加载历史消息,检查 token 阈值并触发压缩
221    /// 关联:被 invoke_agent 内部调用,也可由用户手动调用
222    /// 预期结果:返回 messages 数组(包含 system prompt)
223    pub async fn combine_context(
224        options: &otherone_context::types::CombineContextOptions,
225    ) -> Result<Vec<otherone_ai::types::Message>, otherone_context::error::ContextError> {
226        otherone_context::combine_context(options).await
227    }
228
229    /// 压缩上下文消息
230    /// 作用:保留最新消息,压缩旧消息为摘要
231    /// 关联:被 combine_context 内部调用,也可由用户手动调用
232    /// 预期结果:返回压缩后的 messages 数组
233    pub async fn compact_messages(
234        messages: &[otherone_ai::types::Message],
235        context_tokens: u32,
236        context_window: u32,
237        compact_ratio: Option<f32>,
238        ai_config: Option<&serde_json::Value>,
239        has_compacted_content: bool,
240        session_id: Option<&str>,
241        storage_type: Option<&otherone_storage::types::StorageType>,
242        database_config: Option<&otherone_storage::types::DatabaseConfig>,
243        original_entries: Option<&[otherone_storage::types::Entry]>,
244    ) -> Result<Vec<otherone_ai::types::Message>, otherone_context::error::ContextError> {
245        otherone_context::compact::compact_messages(
246            messages,
247            context_tokens,
248            context_window,
249            compact_ratio,
250            ai_config,
251            has_compacted_content,
252            session_id,
253            storage_type,
254            database_config,
255            original_entries,
256        )
257        .await
258    }
259}
260
261// 重新导出常用类型
262pub use otherone_agent::multi_agent::{
263    AccessPolicy, AgentAccessPolicy, AgentCallAuthorizer, AgentCallId, AgentCallRequest,
264    AgentCallResult, AgentDefinition, AgentEvent, AgentEventEnvelope, AgentId, AgentInput,
265    AgentLimits, AgentOutput, AgentRegistry, AgentRunCommand, AgentRunCommandSender,
266    AgentRunHandle as MultiAgentRunHandle, AgentRunRequest, AgentRunResult, AgentRuntime,
267    AgentRuntimeBuilder, AuthorizationDecision, ContextTransferPolicy, DefaultModelExecutor,
268    EventVisibility, InMemoryRunStore, MemoryPolicy, ModelExecutor, ModelProfile, ModelProfileId,
269    ModelRegistry, ModelSelector, ResultContract, RunId, RunLimitOverrides, RunOutcome, RunRecord,
270    RunStatus, RunUsage, RuntimeLimits, RuntimePolicy, SessionTarget, SkillAccessPolicy,
271    ToolAccessPolicy, AGENT_CALL_TOOL_NAME, MEMORY_RECALL_TOOL_NAME, MEMORY_STORE_TOOL_NAME,
272};
273pub use otherone_agent::types::{ContextLoadType as AgentContextLoadType, StorageType};
274pub use otherone_storage::database::mongodb;
275pub use otherone_storage::database::mysql;
276pub use otherone_storage::localfile::encrypt;
277pub use otherone_storage::redis;
278pub use otherone_storage::types::{AttributeBag, DatabaseConfig, RuntimeContext};
279
280// 重新导出子模块
281pub mod ai {
282    pub use otherone_ai::*;
283}
284pub mod agent {
285    pub use otherone_agent::*;
286}
287pub mod context {
288    pub use otherone_context::*;
289}
290pub mod memory {
291    pub use otherone_memory::*;
292}
293pub mod tools {
294    pub use otherone_tools::*;
295}
296pub mod storage {
297    pub use otherone_storage::*;
298}
299pub mod skills {
300    pub use otherone_skills::*;
301}
302pub mod mcp {
303    pub use otherone_mcp::*;
304}