telos_agent/lib.rs
1#![warn(rustdoc::broken_intra_doc_links)]
2#![doc(html_root_url = "https://docs.rs/telos_agent/0.1.0")]
3
4//! Core Rust runtime for **telos**.
5//!
6//! `telos_agent` is a provider-agnostic agent runtime for applications that
7//! need the loop:
8//!
9//! ```text
10//! user intent -> model sampling -> tool execution -> result injection -> final answer
11//! ```
12//!
13//! The crate is intended to be embedded by CLIs, desktop apps, servers, and
14//! workflow tools. The terminal client (`telos-cli`) and desktop prototype are
15//! hosts built on top of this library.
16//!
17//! # Primary API
18//!
19//! Most consumers only need these types:
20//!
21//! - [`AgentRuntime`] — owns the provider, tools, and runtime configuration.
22//! - [`AgentSession`] — concurrency-safe conversation state created by the runtime.
23//! - [`AgentConfig`] — configures cwd, env, storage, approvals, compaction,
24//! token budgets, policies, and cancellation.
25//! - [`ModelProvider`] — trait implemented by LLM backends.
26//! - [`DeepSeekProvider`], [`RoutedProvider`], and [`MockProvider`] — built-in
27//! provider implementations.
28//! - [`Tool`] and [`ToolRegistry`] — define and register callable tools.
29//! - [`TurnEvent`] — streaming UI/API event surface for assistant deltas,
30//! thinking deltas, tool lifecycle, retries, usage, approvals, and turn
31//! completion.
32//! - [`Storage`], [`JsonlStorage`], and [`NoopStorage`] — session persistence.
33//!
34//! # Quick Start
35//!
36//! Build an [`AgentConfig`], create a [`ToolRegistry`], pick a
37//! [`ModelProvider`], then drive turns through [`AgentRuntime::run_turn`] or
38//! [`AgentRuntime::start_turn`] for a UI-friendly event stream.
39//!
40//! ```rust
41//! use telos_agent::{
42//! AgentConfig, AgentError, AgentRuntime, CompletionResponse, Message,
43//! MockProvider, StopReason, ToolRegistry,
44//! };
45//! use std::sync::Arc;
46//!
47//! #[tokio::main]
48//! async fn main() -> Result<(), AgentError> {
49//! let provider = Arc::new(MockProvider::new(vec![CompletionResponse {
50//! message: Message::assistant("done"),
51//! stop_reason: StopReason::EndTurn,
52//! usage: None,
53//! model: None,
54//! }]));
55//!
56//! let tools = ToolRegistry::new();
57//! let runtime = AgentRuntime::new(AgentConfig {
58//! base_system_prompt: Some("You are concise.".into()),
59//! ..Default::default()
60//! }, provider, tools)?;
61//! let session = runtime.create_session().await?;
62//!
63//! let result = runtime.run_turn(&session, "hello").await?;
64//! assert_eq!(result.final_message.text_content(), "done");
65//! Ok(())
66//! }
67//! ```
68//!
69//! # Streaming Turns
70//!
71//! Hosts that render live UI should use [`AgentRuntime::start_turn`]. Its
72//! [`TurnHandle`] yields [`TurnEvent`] values in order, so the host can update assistant text,
73//! thinking text, tool activity, approval prompts, token usage, and completion
74//! state without parsing model messages directly.
75//!
76//! # Extension Points
77//!
78//! - Implement [`ModelProvider`] to add a new model backend.
79//! - Implement [`Tool`] to expose a new capability.
80//! - Implement [`ApprovalHandler`] for host-specific approval UI.
81//! - Implement [`Policy`] to enforce semantic session, model, turn, or tool rules.
82//! - Implement [`Storage`] for a custom persistence backend.
83//! - Use [`McpManager`] and [`McpToolBridge`] to bridge MCP servers into the
84//! tool registry.
85//!
86//! # Public Module Map
87//!
88//! The crate root re-exports the supported high-level API. Public modules are
89//! also available for advanced callers that need lower-level types.
90//!
91//! | Module | Purpose |
92//! |---|---|
93//! | [`agent`] | Runtime, sessions, turns, context, prompts, policies, and compaction. |
94//! | [`model`] | Provider APIs, model messages, token counting, and test doubles. |
95//! | [`tools`] | Tool APIs, execution, built-ins, approvals, permissions, and command safety. |
96//! | [`knowledge`] | Memory, skills, tasks, and repository indexing. |
97//! | [`integrations`] | MCP, plugins, and external event channels. |
98//! | [`orchestration`] | Subagents and multi-agent teams. |
99//! | [`diagnostics`] / [`metrics`] | Sanitized tool failure records and session counters. |
100
101/// Agent lifecycle, context, prompting, policies, and turn execution.
102pub mod agent;
103/// Runtime configuration and cancellation state.
104pub mod config;
105/// Sanitized tool failure diagnostics.
106pub mod diagnostics;
107/// Error types shared across runtime, tools, and providers.
108pub mod error;
109/// External event, protocol, and plugin integrations.
110pub mod integrations;
111/// Persistent knowledge, skills, tasks, and repository indexing.
112pub mod knowledge;
113/// Runtime metrics accumulated by sessions.
114pub mod metrics;
115/// Model messages, providers, token accounting, and test doubles.
116pub mod model;
117/// Nested-agent and multi-agent orchestration.
118pub mod orchestration;
119/// Session persistence backends.
120pub mod storage;
121
122/// Tool APIs, execution, built-ins, approvals, permissions, and command safety.
123pub mod tools;
124
125// Approval — asynchronous human-in-the-loop gating for tool calls.
126pub use tools::approval::{
127 ApprovalDecision, ApprovalHandler, ApprovalRequest, AutoDenyHandler, FixedDecisionHandler,
128};
129// Compaction — history- and message-level shrinking strategies.
130pub use agent::compaction::{HistoryCompactionStrategy, SummaryHistoryCompaction};
131// Configuration — the session config aggregate, task path, and token-budget knob.
132pub use config::{AgentConfig, TaskPath, TokenBudget, platform_base_env};
133// Diagnostics — sanitized local recording of tool execution failures.
134pub use diagnostics::{
135 JsonlToolDiagnosticsSink, NoopToolDiagnosticsSink, SanitizedToolFailure, ToolDiagnosticsSink,
136 ToolFailureEvent, ToolFailureKind, ToolFailureSanitizer,
137};
138// Errors — the single failure type used across the crate.
139pub use error::{AgentError, ProviderError};
140// Event channel — bidirectional HTTP event channel for external pub/sub.
141pub use integrations::event_channel::{
142 EventChannel, EventChannelConfig, ExternalEvent, Subscription,
143};
144// Tool executor — direct entry points for callers that bypass the turn loop.
145pub use tools::executor::{
146 ToolExecutionEvent, ToolExecutionOutput, ToolExecutionStreamItem, execute_tool_calls_stream,
147};
148// Semantic session, model, turn, and tool policies.
149pub use agent::policies::{
150 Policy, PolicyContext, PolicyDecision, PolicyEntry, PolicyOutcome, PolicyPoint, PolicyRegistry,
151 SessionMode,
152};
153// Message model — the lingua franca between session, provider, and tools.
154pub use model::message::{
155 ContentBlock, Message, Role, TextBlock, ThinkingBlock, ToolCall, ToolResult,
156};
157// Memory — persistent cross-session agent memory.
158pub use knowledge::memory::ProfileManager;
159pub use knowledge::memory::{
160 MemoryCategory, MemoryEntry, MemoryFormat, MemoryMaintenanceAction,
161 MemoryMaintenanceActionKind, MemoryMaintenancePolicy, MemoryMaintenanceReport, MemoryQuery,
162 MemorySort, MemoryStatus, MemoryStore, UpsertOutcome, unix_timestamp,
163};
164pub use tools::builtin::{
165 MemoryEditTool, MemoryGrepTool, MemoryReadTool, MemoryStatusTool, MemoryWriteTool,
166};
167// Code index — lightweight repository search and path/line lookup.
168pub use knowledge::code_index::{CodeContextLine, CodeIndex, CodeSearchMatch, IndexedFile};
169// Metrics — session-level counters accumulated by the runtime.
170pub use config::CancellationState;
171pub use metrics::SessionMetrics;
172// Test helper — pre-canned [`ModelProvider`] for unit tests.
173pub use model::mock::MockProvider;
174// Permissions — rule-based gating of tool calls.
175pub use tools::permissions::{PermissionEngine, PermissionRule, RuleDecision};
176// Provider — the trait downstream LLM backends implement, plus built-in impls.
177pub use model::provider::{
178 CompletionRequest, CompletionResponse, DeepSeekBalance, DeepSeekBalanceInfo,
179 DeepSeekChatOptions, DeepSeekConfig, DeepSeekFimChoice, DeepSeekFimRequest,
180 DeepSeekFimResponse, DeepSeekModel, DeepSeekModelList, DeepSeekProvider,
181 DeepSeekResponseFormat, ErasedProvider, ModelHint, ModelProvider, ProviderEvent,
182 RoutedModelConfig, RoutedProvider, StopReason, TokenUsage,
183};
184
185pub use agent::runtime::{AgentRuntime, AgentSession, TurnHandle};
186// Context injection services.
187pub use agent::context::{MemoryInjector, SkillInjector};
188// Turn — streaming event types and input channel.
189pub use agent::turn::{
190 TurnEvent, TurnInputReceiver, TurnInputSender, TurnResult, turn_input_channel,
191};
192// Skills — user-defined slash-commands loaded from markdown files.
193pub use knowledge::skills::{Skill, SkillArg, SkillLoader, SkillRegistry, SkillSource};
194// Storage — persistence backends for saving and resuming sessions.
195pub use storage::{JsonlStorage, NoopStorage, Storage};
196// Subagent — nested agent run exposed as a tool and Fork concurrent-execution engine.
197pub use orchestration::subagent::{
198 AgentDefinition, AgentIsolation, AgentSource, ForkExecution, ForkLens, ForkResult, ForkShared,
199 SubagentRegistry, SubagentTool, Synapse, register_subagent_tool,
200};
201// Tasks — task management system with tracking, persistence, and tool integration.
202pub use knowledge::tasks::{Task, TaskManager, TaskStatus};
203pub use orchestration::team::{
204 TeamConfig, TeamMember, cleanup_team, has_active_members, lead_agent_id, load_team_config,
205 save_team_config, team_config_path, team_tasks_dir, teams_root,
206};
207
208// MCP — stdio-based Model Context Protocol client + manager + bridge.
209pub use integrations::mcp::{McpClient, McpManager, McpTool, McpToolBridge};
210// Plugin — marketplace-based plugin system for extensibility.
211pub use integrations::plugin::{
212 BUILTIN_MARKETPLACE, PluginError, PluginId, PluginPromptSection, PluginRegistry,
213};
214// Prompt system — modular, cache-aware construction of the system prompt.
215pub use agent::prompt::{
216 CwdSection, DateSection, GitStatusSection, IdentitySection, McpSection, MemorySection,
217 ProfileSection, PromptAssembly, PromptProfile, PromptSection, PromptSectionStat,
218 PromptStability, PromptStats, SafetySection, ShellAwareToolUsageSection, SkillsSection,
219 TaskGuidanceSection, ToneStyleSection, ToolUsageSection, ToolsSection,
220};
221
222// Tool abstraction — the trait every callable capability implements, plus its registry.
223pub use tools::api::validate::{ValidationError, ValidationResult, validate_arguments};
224pub use tools::api::{
225 InterruptBehavior, PermissionDecision, Tool, ToolContext, ToolDefinition, ToolOutput,
226 ToolProgress, ToolRegistry,
227};
228// Built-in tools — filesystem, shell, search, web, user interaction.
229pub use tools::builtin::{
230 AskUserQuestionTool, BrowserBackTool, BrowserClickTool, BrowserCloseTool, BrowserFindUrlTool,
231 BrowserManager, BrowserNavigateTool, BrowserScreenshotTool, BrowserScrollTool,
232 BrowserSelectTool, BrowserStartTool, BrowserStateTool, BrowserTypeTool, CodeContextTool,
233 CodeIndexRefreshTool, CodeSearchTool, DefaultShell, EnterPlanModeTool, ExitPlanModeTool,
234 FileEditTool, FileReadTool, FileWriteTool, GlobTool, GrepTool, PowerShellTool,
235 SendUserMessageTool, ShellTool, SkillTool, TaskCreateTool, TaskGetTool, TaskListTool,
236 TaskOutputTool, TaskStopTool, TaskUpdateTool, TeamCreateTool, TeamDeleteTool, TodoWriteTool,
237 WebFetchTool, WebSearchTool, register_core_tools, register_core_tools_with_shell,
238 register_memory_tools, register_task_tools,
239};