Skip to main content

phi_agent/
lib.rs

1//! phi-agent: Rust AI Agent runtime framework — orchestration, sessions, streaming all built-in.
2//! You only define tools, prompts, and domain knowledge.
3//!
4//! Built on agent-base and agent-works, providing builder factory, renderer,
5//! config resolution, session management, and other infrastructure.
6//! **Ships with zero application tools.** Kernel tools (file I/O, shell,
7//! multi-agent) are available via `phi-kernel-tools` behind feature flags —
8//! all off by default. Application tools are injected by consumers.
9
10#![warn(missing_docs)]
11
12pub mod agent;
13pub mod bridge;
14pub mod cli;
15pub mod config;
16pub mod event_log;
17/// System prompt generation (EN/CN).
18pub mod prompt;
19pub mod render;
20/// Session management — ID resolution, locking, snapshots, cleanup.
21pub mod session;
22
23// ── Common agent-base types ──
24// Only re-export the types consumers use most often.
25// For the full type set, import directly from agent-base.
26//
27// Note: AgentBuilder re-exports agent_works::AgentBuilder (not agent_base::AgentBuilder)
28// because phi-agent is a full-stack framework that includes multi-agent, skills, MCP, etc.
29// For the bare runtime builder, use agent_base::AgentBuilder directly.
30pub use agent_base::{
31    AgentError, AgentResult, AgentRuntime, AllowAllApprovalHandler, ApprovalDecision, ApprovalHandler, ApprovalRequest,
32    ChatMessage, CheckpointData, CheckpointStep, ConsecutiveFailureRecovery, Content, ContextCompaction,
33    ContextWindowManager, DenyAllApprovalHandler, FinishReason, Language, Middleware, PlanItem, PlanStepStatus,
34    PostLlmCtx, PreLlmCtx, ReasoningConfig, ReasoningEffort, RetryOnError, RiskLevel, RunOutcome, RuntimeEvent,
35    SafetyConfig, SessionId, Tool, ToolContext, ToolDecision, ToolMetadata, ToolPolicy, ToolRegistry,
36    TurnFactMiddleware, TurnToolLimitMiddleware, UpdatePlanTool, UserMessageCtx, estimate_messages_tokens,
37    first_system_prompt,
38};
39// Token-budget window strategy — a pure strategy in agent-works (agent-base
40// stays strategy-free: contract + primitives only).
41pub use agent_works::AgentBuilder;
42pub use agent_works::rotation_policy::{
43    DEFAULT_SEED_MESSAGE, TokenBudgetAction, TokenBudgetConfig, TokenBudgetCore, TokenBudgetState,
44    build_context_window_info, token_budget_base_overhead,
45};
46
47// ── phi-telemetry (metrics types and storage) ──
48#[cfg(feature = "telemetry")]
49pub use phi_telemetry::{
50    SessionMetrics, SessionOutcome, SessionSummary, TurnMetrics, TurnOutcome, list_all_metrics, load_metrics,
51    save_metrics, try_load_metrics,
52};
53
54// ── agent-works ──
55#[cfg(feature = "focus")]
56pub use agent_works::focus::{Context as FocusContext, Focus, FocusError, FocusInput, FocusOutput};
57#[cfg(feature = "multi-agent")]
58pub use agent_works::multi_agent::{
59    ChildPermissionMode, ChildReport, ChildResultEvent, ControlConfig, MultiAgentConfig,
60};
61// Child-result fan-in delivery policy — data-only routes; the consumer renders
62// the words. Sunk down from phimint's UI so any multi-agent UI reuses it.
63#[cfg(feature = "multi-agent")]
64pub use agent_works::multi_agent::fan_in::{ChildResultRoute, ChildResultRouter};
65#[cfg(feature = "multi-agent")]
66pub use agent_works::multi_agent::registry::{AgentSnapshot, RegistrySnapshot};
67
68// ── Persistent auto-memory (Phase 9b, feature-gated) ──
69/// Memory configuration for persistent auto-memory: consumer-injected policy
70/// (storage root, index filename, prompt template). Hand it to
71/// `AgentBuilder::memory_config` to register the four `memory_*` tools and
72/// append the MEMORY.md index snapshot + tool guidance to the system prompt.
73#[cfg(feature = "memory")]
74pub use agent_works::memory::MemoryConfig;
75
76// ── Framework pass-through (facade completion) ──
77// These are the remaining types a product needs to name directly, so its
78// Cargo.toml can depend on `phi-agent` alone. Only actually-consumed items
79// are re-exported — no catch-all facade.
80/// Plan / user lifecycle event types surfaced to consumers.
81pub use agent_base::UserEvent;
82/// Middleware that nudges the model when it nears the turn limit.
83pub use agent_base::engine::max_turns_nudge::{MaxTurnsNudgeConfig, MaxTurnsNudgeMiddleware};
84/// Middleware that breaks repeated identical tool-call loops (e.g. polling).
85pub use agent_base::engine::repeat_tool_limit::{RepeatToolLimitConfig, RepeatToolLimitMiddleware};
86/// LLM provider trait family (`LlmProvider`, `Protocol`, `config::LlmConfig`):
87/// build a provider with [`create_provider`] and hand it to the runtime.
88pub use agent_base::llm_trait;
89/// Guard policies from agent-works (tool gating, reasoning-only enforcement).
90pub use agent_works::guard::{DefaultGuard, DefaultGuardConfig, ReasoningOnlyAction};
91/// LLM provider factory (resolves protocol/client from an [`llm_trait`] config).
92pub use llm_unified::create_provider;
93
94// ── Kernel tools (feature-gated) ──
95#[cfg(feature = "shell")]
96pub use phi_kernel_tools::local_shell::LocalShellTool;
97
98// ── Skills (feature-gated) ──
99#[cfg(feature = "skill")]
100pub use agent_works::skill::{
101    MAX_CATALOG_SKILLS, Skill, SkillCatalogRefreshMiddleware, SkillResolver, SkillTelemetry, SkillTool,
102    catalog::demote_h2_headings, prompt_skill::PromptSkill, prompt_skill::SkillScope, refresh_catalog, render_catalog,
103    strip_catalog,
104};
105
106// ── MCP (feature-gated) ──
107#[cfg(feature = "mcp")]
108pub use agent_works::mcp::{McpServeConfig, McpServer, McpServerConfig, McpServerTransport, McpTransport};
109
110// ── phi-agent types ──
111#[cfg(feature = "compression")]
112pub use agent::CompressionMiddleware;
113pub use agent::{
114    PhiAgent, PhiAgentConfig, base_agent_builder, base_agent_builder_no_compression, base_agent_builder_with_excludes,
115    base_agent_builder_with_options, clear_compression_cache, run_compact_session,
116};
117pub use agent_works::prompt::{
118    DynamicToolsFragment, EnvironmentFragment, FragmentContext, PromptFragment, compose_fragments,
119};
120pub use cli::{ApprovalItem, ApprovalMode, AutoApprovalHandler, QueuedApprovalHandler};
121pub use config::{LlmConfig, resolve_llm_config};
122pub use event_log::{event_to_jsonl, event_to_value, save_turn_log};
123pub use prompt::{build_system_prompt, build_system_prompt_cn, build_system_prompt_with_fragments};
124pub use render::{
125    EventRenderer, JsonStreamRenderer, NullRenderer, OutputFormat, create_renderer, create_stdout_renderer,
126};
127pub use session::{
128    SessionContext, SessionInfo, SnapshotInfo, cleanup_expired_sessions, clear_messages_jsonl, create_snapshot,
129    delete_snapshot, list_sessions, list_snapshots, load_session_messages, persist_window_messages, read_session_title,
130    resolve_session, restore_snapshot, validate_session_id, validate_snapshot_name, write_session_title,
131};
132
133/// Format a number with K/M suffixes for display.
134///
135/// - `n < 1_000` → plain number
136/// - `1_000 <= n < 1_000_000` → `{:.1}K`
137/// - `n >= 1_000_000` → `{:.1}M`
138pub fn format_number(n: u64) -> String {
139    if n >= 1_000_000 {
140        format!("{:.1}M", n as f64 / 1_000_000.0)
141    } else if n >= 1_000 {
142        format!("{:.1}K", n as f64 / 1_000.0)
143    } else {
144        n.to_string()
145    }
146}
147
148#[cfg(test)]
149mod proptests {
150    use super::*;
151
152    proptest::proptest! {
153        #[test]
154        fn format_number_never_panics(n: u64) {
155            let _ = format_number(n);
156        }
157
158        #[test]
159        fn format_number_correct_suffix(n: u64) {
160            let s = format_number(n);
161            if n < 1_000 {
162                proptest::prop_assert_eq!(s, n.to_string());
163            } else if n < 1_000_000 {
164                proptest::prop_assert!(s.ends_with('K'), "expected K suffix for {}, got '{}'", n, s);
165            } else {
166                proptest::prop_assert!(s.ends_with('M'), "expected M suffix for {}, got '{}'", n, s);
167            }
168        }
169
170        #[test]
171        fn format_number_boundary_correct(n in 0u64..1_001) {
172            // At the exact boundary (1000), must switch to K
173            let s = format_number(n);
174            if n < 1_000 {
175                proptest::prop_assert!(!s.contains('K'));
176                proptest::prop_assert!(!s.contains('M'));
177            } else {
178                proptest::prop_assert!(s.ends_with('K'));
179            }
180        }
181    }
182}