Expand description
phi-agent: Rust AI Agent runtime framework — orchestration, sessions, streaming all built-in. You only define tools, prompts, and domain knowledge.
Built on agent-base and agent-works, providing builder factory, renderer,
config resolution, session management, and other infrastructure.
Ships with zero application tools. Kernel tools (file I/O, shell,
multi-agent) are available via phi-kernel-tools behind feature flags —
all off by default. Application tools are injected by consumers.
Re-exports§
pub use agent::PhiAgent;pub use agent::PhiAgentConfig;pub use agent::base_agent_builder;pub use agent::base_agent_builder_no_compression;pub use agent::base_agent_builder_with_excludes;pub use agent::base_agent_builder_with_options;pub use agent::clear_compression_cache;pub use agent::run_compact_session;pub use cli::ApprovalItem;pub use cli::ApprovalMode;pub use cli::AutoApprovalHandler;pub use cli::QueuedApprovalHandler;pub use config::LlmConfig;pub use config::resolve_llm_config;pub use event_log::event_to_jsonl;pub use event_log::event_to_value;pub use event_log::save_turn_log;pub use prompt::build_system_prompt;pub use prompt::build_system_prompt_cn;pub use prompt::build_system_prompt_with_fragments;pub use render::EventRenderer;pub use render::JsonStreamRenderer;pub use render::NullRenderer;pub use render::OutputFormat;pub use render::create_renderer;pub use render::create_stdout_renderer;pub use session::SessionContext;pub use session::SessionInfo;pub use session::SnapshotInfo;pub use session::cleanup_expired_sessions;pub use session::clear_messages_jsonl;pub use session::create_snapshot;pub use session::delete_snapshot;pub use session::list_sessions;pub use session::list_snapshots;pub use session::load_session_messages;pub use session::persist_window_messages;pub use session::read_session_title;pub use session::resolve_session;pub use session::restore_snapshot;pub use session::validate_session_id;pub use session::validate_snapshot_name;pub use session::write_session_title;pub use agent_base::llm_trait;
Modules§
- agent
- Agent construction and lifecycle management.
- bridge
- Bridge protocol — adapts phi-agent for SDK consumption.
- cli
- CLI helpers — approval strategies and utilities shared across consumers.
- config
- Configuration resolution helpers.
- event_
log - Event log: serialize turn events to JSONL files.
- prompt
- System prompt generation (EN/CN). System prompt construction using composable fragments.
- render
- Event renderers — transform
RuntimeEventstreams into display output. - session
- Session management — ID resolution, locking, snapshots, cleanup.
Structs§
- Agent
Builder - Agent
Runtime - Allow
AllApproval Handler - Approval
Request - Checkpoint
Data - Compaction
Outcome - Successful compaction outcome: what happened plus the messages to install.
- Compression
Middleware - Middleware that compresses conversation history before each LLM call.
- Consecutive
Failure Recovery - Recovery strategy that tracks consecutive failures per tool and stops after a limit.
- Context
Window Manager - Default
Guard - Guard policies from agent-works (tool gating, reasoning-only enforcement). Default guard implementation
- Default
Guard Config - Guard policies from agent-works (tool gating, reasoning-only enforcement). Default guard configuration
- Deny
AllApproval Handler - Dynamic
Tools Fragment - Dynamically generate tool descriptions from registered tools.
- Environment
Fragment - Injects runtime environment information: OS, working directory, git branch.
- Focus
- A focused LLM call.
- Focus
Context - Structured context for multi-field input scenarios.
- Focus
Output - Output wrapper for a Focus call.
- Fragment
Context - Context passed to each fragment during rendering.
- MaxTurns
Nudge Config - Middleware that nudges the model when it nears the turn limit. Configuration for the max-turns nudge middleware.
- MaxTurns
Nudge Middleware - Middleware that nudges the model when it nears the turn limit. Middleware that injects a nudge message when approaching the max turns limit.
- McpServe
Config - Configuration for running as an MCP server.
- McpServer
- An MCP Server that wraps an
AgentRuntimeand exposes it as an MCP tool. - McpServer
Config - Plan
Item - A single step in a lightweight plan checklist.
- Post
LlmCtx - PreLlm
Ctx - Reasoning
Config - Reasoning/thinking configuration, unifying reasoning/thinking parameters across vendors.
- Repeat
Tool Limit Config - Middleware that breaks repeated identical tool-call loops (e.g. polling).
Configuration for
RepeatToolLimitMiddleware. - Repeat
Tool Limit Middleware - Middleware that breaks repeated identical tool-call loops (e.g. polling). Break poll loops — repeated identical tool calls — hard.
- Retry
OnError - Continue on tool failure, feeding the error back to the model
- Safety
Config - Safety configuration for agent runtime guardrails.
- Session
Id - Unique identifier for an agent session.
- Session
Metrics - Accumulated session metrics. Written incrementally to
session_metrics.jsonat the end of each turn. - Session
Summary - Lightweight summary returned by
list_all(). - Token
Budget Config - Configuration for the token-budget window strategy.
- Token
Budget Core - Pure decision core for the token-budget window strategy.
- Token
Budget State - State tracker for the token budget across compaction calls within a single window.
- Tool
Context - Tool
Metadata - Machine-readable metadata for a registered tool — origin, version, and runtime requirements in a stable shape consumers can inspect without parsing the LLM-facing definition JSON.
- Tool
Registry - Turn
Fact Middleware - Turn fact summary middleware — injects structured facts from the previous turn’s tool results into the next user message.
- Turn
Metrics - Per-turn metrics — one per LLM interaction.
- Turn
Tool Limit Middleware - Middleware that enforces a hard limit on tool calls per turn.
- Update
Plan Tool - A lightweight tool that records and displays a plan checklist to the user.
- User
Message Ctx
Enums§
- Agent
Error - Approval
Decision - Chat
Message - A chat message in a conversation.
- Checkpoint
Step - Compaction
Kind - What a successful
ContextCompaction::compactactually did to the history. agent-base stays strategy-free: it only relays the kind into the log line, so a nudge append never reads as a compaction and a real replacement always does (issue #33). - Content
- Structured content returned by a tool, aligned with the MCP
contentarray shape (no envelope, no orchestration/failure/truncation semantics). - Finish
Reason - Semantic finish reason, replacing scattered
Option<String>matching. - Focus
Error - Error type for Focus calls.
- Language
- McpServer
Transport - Transport mode for the MCP server.
- McpTransport
- Notice
Kind - Notice kinds for
UserEvent::Notice— consumers match on these to decide rendering (e.g. Warning → persistent red line). Notice category — decides how consumers render the notification. - Plan
Step Status - Lightweight plan step status — display-only, no execution semantics.
- Reasoning
Effort - Reasoning intensity/depth enumeration.
- Reasoning
Only Action - Guard policies from agent-works (tool gating, reasoning-only enforcement). Reasoning-only handling strategy
- Risk
Level - RunOutcome
- The outcome of an Agent turn or run.
- Runtime
Event - Unified runtime event — the single event type for both internal and external consumers (frontends, CLIs, tests).
- Session
Outcome - Outcome of a session (the entire conversation).
- Token
Budget Action - What the shell should do for this compaction check.
- Tool
Decision - Decision returned by
ToolPolicy::before_callto control tool execution. - Turn
Outcome - Outcome of a single turn (one LLM interaction).
- User
Event - Plan / user lifecycle event types surfaced to consumers. User-space events produced by tools during execution.
Constants§
- DEFAULT_
SEED_ MESSAGE - Default user seed message for new windows (see
TokenBudgetConfig::seed_message).
Traits§
- Approval
Handler - Trait for handling tool approval requests.
- Context
Compaction - Trait for inline context compaction within the react loop.
- Focus
Input - Input for a Focus call — either a simple string or a structured context.
- Middleware
- Prompt
Fragment - Composable prompt fragment — each fragment owns one concern.
- Tool
- Tool
Policy - Policy-based control over tool execution.
Functions§
- build_
context_ window_ info - The window-info system message injected at the start of each window.
- compose_
fragments - Sort fragments by priority (ascending) and concatenate with double newlines.
- create_
provider - LLM provider factory (resolves protocol/client from an
llm_traitconfig). Create a provider from configuration. - estimate_
messages_ tokens - Estimate total tokens across a message list using
ContextWindowManager::message_tokens. - first_
system_ prompt - Find the first non-ephemeral System message (the system prompt).
- format_
number - Format a number with K/M suffixes for display.
- list_
all_ metrics - List all session summaries by scanning the sessions directory.
Reads each
session_metrics.jsonand extracts summary fields. - load_
metrics - Load session metrics from
session_metrics.jsonin a session directory. - save_
metrics - Incrementally write session metrics to
session_metrics.json. - token_
budget_ base_ overhead - Token estimate of the fixed content every window starts with: system prompt + window info + guidance + seed (no thread hint — the best case; app-provided hints add on top).
- try_
load_ metrics - Try to load session metrics, returning
Noneif the file doesn’t exist.