planify
LLM Agent framework: streaming agent loop, tool registry, dual provider backends (Anthropic / OpenAI-compatible), prompt caching friendly.
Downloads & Community Adoption
Health & Engineering Analysis (5 Pillars)
1. Governance & Community50 / 200 โพ
2. PEP Metadata & Packaging150 / 200 โพ
3. Security & Supply Chain100 / 200 โพ
4. Documentation, SEO & Ecosystem60 / 200 โพ
5. Engineering, CI & Quality0 / 200 โพ
Official Documentation & Usage Guide โ planify
Show full original documentation (English README) โพ
Planify
Planify is a single-process, multi-agent LLM agent framework. It provides a streaming agent loop, a statically composed tool registry, dual provider backends (Anthropic and OpenAI-compatible), and context compaction designed to preserve prompt prefix caching (reusing the unchanged head of a conversation so the provider charges less for repeated input). Planify ships as a Python library โ a host application embeds it and drives it, while providers, tools, and configuration can all be injected or extended from the outside.
Table of Contents
- Features
- Requirements
- Installation
- Quick Start (Library Usage)
- Configuration
- Architecture
- Built-in Tools
- Runtime Data Directories
- Embedding as a Host Application
- Development
- Documentation
- License
Features
Agent execution
- Streaming agent loop (primary path) โ fully asynchronous, consuming normalized stream events from the provider. Tool handlers run off the main loop, and a mid-run interrupt event lets the caller stop generation between rounds.
- Synchronous agent loop โ a legacy whole-response path that shares the same loop skeleton and compaction pipeline.
- One-shot subagents โ temporary agent loops capped at 30 rounds: they execute an isolated task, return a summary, and are destroyed. The
agent_typetrims the toolset (Exploreis read-only;general-purposeadds file writes). - Persistent teammates โ each teammate is a persistent agent running its own loop on a background daemon thread (a thread that does not block process exit), communicating through a file-based message bus. Idle teammates automatically claim unblocked tasks from the task board.
Context management
- Microcompact (truncation) keeps only the last 10 tool results and clears the rest. It is gated at 80% of the compaction threshold: below the gate, history is left completely untouched so the conversation head stays byte-stable and cache-friendly.
- Auto-compact (LLM summary) first writes the original transcript to disk, then asks the model to produce a continuity summary that replaces the history.
- Compaction triggers from four places: both agent loops internally, a
compresstool the model may call itself, and a manual command from the hosting front end.
LLM provider layer
- A single provider protocol with three methods (send / stream / count tokens) โ no caller touches SDK types directly.
- Two interchangeable backends: Anthropic (with prompt-caching breakpoints on the system prompt, tool table, and last user message) and OpenAI-compatible (via
/chat/completions, with a built-in translator between the two tool-call formats). - An error hierarchy carrying a
retryableflag, covering auth, rate limit, context length, and network failures.
Tool system
- The registry is statically composed and returns tool definitions plus their handlers in one pass; handlers may be synchronous or async.
- A host application can inject its own tools, filter the set with a whitelist environment variable, and enable a stricter path guard for sandboxed front ends (shell tools get wrapped; file tools are blocked from path escapes).
- About 29 built-in tools ship out of the box โ see Built-in Tools.
Skills
- Skill files (
SKILL.md) act as two-stage prompt injection rather than callable tools: a lightweight catalog is injected up front (cheap for caching), and the full body is fetched on demand via theload_skilltool. Skills hot-reload โ changed files are picked up at the start of the next conversation turn without a restart.
Task management
- TodoManager โ an in-memory, per-agent checklist: at most 20 items, exactly one in progress at a time, with a reminder nag if it goes stale for 3 rounds.
- TaskManager โ a file-persisted task board with dependency edges (blocked-by / blocks); completing a task automatically unblocks dependents, and any agent may claim an unowned task.
- BackgroundManager โ runs long shell commands on daemon threads (on Windows it falls back from Git Bash to PowerShell to cmd) and feeds results back into the agent loop as notifications.
Host integration
- Configuration and tools flow in through registration hooks; planify never imports the host application.
- Pluggable event emitters (SSE queue, console, callback routing) let one agent drive different front ends.
Requirements
- Python โฅ 3.10 (declared in
pyproject.toml) - An API key for an Anthropic-compatible or OpenAI-compatible endpoint
- Playwright's Chromium binary, needed only for fetching JavaScript-rendered pages:
# One-time download of the headless browser for the webfetch tool
python -m playwright install chromium --only-shell
Installation
Install from the repository root in editable mode (recommended for development):
# Editable install of the planify package
pip install -e ./planify
Core dependencies are pulled automatically: the two provider SDKs (anthropic, openai), httpx, python-dotenv, borax (lunar calendar data), and trafilatura + playwright (web fetching).
Quick Start (Library Usage)
Planify is embedded by a host application; it has no user-facing entry point of its own. The minimal path is: register configuration โ create a runtime โ drive the streaming loop.
import asyncio
from pathlib import Path
from planify.bootstrap import initialize, get_or_create_runtime
from planify.streaming import StreamingAgent
from planify.streaming.emitter import SSEEmitter # or your own emitter implementation
# 1. Boot the runtime manager singleton for this working directory
manager = initialize(base_workdir=Path.cwd())
# 2. Create the per-user runtime: wires the provider, managers, message bus, tools
runtime = get_or_create_runtime("alice", {
"api_key": "sk-...",
"model_id": "claude-sonnet-4-6",
})
# 3. Build a streaming agent on top of that runtime
agent = StreamingAgent(
client=runtime.client, # provider instance
model=runtime.model,
tools=runtime.tools,
tool_handlers=runtime.tool_handlers,
emitter=SSEEmitter(), # any emitter implementation
bus=runtime.bus,
skills_loader=runtime.skills,
runtime=runtime,
system_prompt_extra="Optional host policy appended to the system prompt.",
)
# 4. Run the loop. Note: `messages` is modified in place.
messages = []
asyncio.run(agent.run_stream(messages, "Summarize the repo layout.", session_id="demo-001"))
A one-shot subagent for isolated read-only exploration:
from planify.subagent.runner import run_subagent
from planify.tools.basic import run_bash, run_read, run_write, run_edit
summary = run_subagent(
prompt="List the top-level packages and their responsibilities.",
agent_type="Explore", # read-only toolset
workdir=Path.cwd(),
client=runtime.client,
model=runtime.model,
run_bash=run_bash, run_read=run_read, run_write=run_write, run_edit=run_edit,
)
Configuration
Config resolution order (highest first):
- Host-injected registration at startup
- The per-user config dict passed to
get_or_create_runtime() - Environment variables
.envfiles in the working directory (.planify/.envโ.env.localโ.env)- Built-in defaults
Environment variables
| Variable | Required | Description |
|---|---|---|
PLANIFY_API_KEY |
Yes | LLM provider API key |
PLANIFY_MODEL_ID |
Yes | Model ID, e.g. claude-sonnet-4-6, glm-4.7, deepseek-chat โ fully config-driven, no presets |
PLANIFY_PROTOCOL |
No | anthropic (default, /v1/messages) or openai_compat (/chat/completions) |
PLANIFY_BASE_URL |
No | Endpoint URL; empty = provider SDK default. Setting it removes ANTHROPIC_AUTH_TOKEN to avoid auth conflicts |
PLANIFY_ENABLED_TOOLS |
No | Comma-separated tool whitelist; empty/unset = register all tools |
PLANIFY_DISABLED_TOOLS |
No | Comma-separated tool blacklist; empty/unset = block nothing. Blacklist wins when both are set; an explicitly listed ask_user_question is honored in GUI mode (warning only) |
PLANIFY_ASK_MODE |
No | How the agent asks the user questions: interactive (default, blocking prompt) or chat (answered via the next user message); re-read per call |
ASSETS_DIR |
No | Assets directory, absolute or relative to the workdir |
BAIDU_WEATHER_API_URL / BAIDU_WEATHER_AK / BAIDU_WEATHER_DATA_TYPE |
No | Baidu Map weather API settings for the baidu_weather tool |
Switching LLM endpoints
The endpoint is chosen by protocol plus base URL โ there are no provider presets.
OpenAI-compatible endpoint:
export PLANIFY_PROTOCOL=openai_compat # use /chat/completions
export PLANIFY_BASE_URL=https://api.deepseek.com/v1
export PLANIFY_API_KEY=sk-...
export PLANIFY_MODEL_ID=deepseek-chat
Anthropic native (the default; no base URL needed):
export PLANIFY_API_KEY=sk-ant-...
export PLANIFY_MODEL_ID=claude-sonnet-4-6
Architecture
Four layers, with dependencies strictly one-directional (upper depends on lower, no cycles):
Entry host front ends (web SSE / console / callback routing)
โ
Assembly bootstrap.py โ core/runtime_manager.py โ core/runtime.py (component container)
โ tool registry assembly
Execution streaming/runner.py (async, primary) agent/runner.py (sync, legacy) subagent/runner.py (one-shot)
โโโโโโโโโโโโ all three share the provider protocol and the compaction pipeline โโโโโโโโโโโโ
Support core/llm/ (provider abstraction) ยท tools/ ยท skills/ ยท managers/ ยท messaging/ ยท context/compact.py
Source layout:
planify/
โโโ bootstrap.py # Assembly entry: runtime manager singleton + host dependency registration
โโโ prompts.py # System-prompt builder (per-agent-type branches; host extension point)
โโโ agent/
โ โโโ runner.py # Synchronous agent loop (legacy whole-response path)
โโโ streaming/
โ โโโ runner.py # StreamingAgent โ async main loop (primary path)
โ โโโ emitter.py # Emitter implementations (SSE queue / console / callback routing)
โ โโโ waiter.py # Cross-thread "agent asks, user answers" blocking wait
โ โโโ types.py # Event types, protocols, streaming config
โโโ subagent/
โ โโโ runner.py # One-shot subagent (โค 30 rounds, toolset trimmed by agent type)
โโโ context/
โ โโโ compact.py # Two-level compaction: truncation and LLM summary
โโโ core/
โ โโโ runtime.py # AgentRuntime: process-level component container
โ โโโ runtime_manager.py # Runtime lifecycle / component assembly (thread-safe singleton)
โ โโโ config.py # Config (.env multi-level loading + host-injection dual path)
โ โโโ encoding.py # Windows GBK/UTF-8 console handling
โ โโโ logging_config.py # Logging + first-run workspace init
โ โโโ llm/ # Provider protocol, factory, dual backends, translator, errors
โโโ managers/
โ โโโ todo_manager.py # In-memory per-agent todo list
โ โโโ task_manager.py # File-persisted task board with dependency edges
โ โโโ background_manager.py # Background shell commands (thread + notification queue)
โ โโโ teammate_manager.py # Persistent teammates (one daemon thread + agent loop each)
โโโ messaging/
โ โโโ message_bus.py # File-level per-recipient inbox
โโโ skills/
โ โโโ skill_loader.py # SKILL.md scan/parse, lazy hot-reload
โ โโโ access_state.py # Per-session loaded-skill state
โโโ tools/
โโโ registry.py # Tool registry assembly + external tool injection + whitelist
โโโ basic.py # bash / powershell / read_file / write_file / edit_file (+ path guard)
โโโ grep.py / glob_tool.py # ripgrep-based content search / glob file matching
โโโ webfetch.py # Web fetching: trafilatura โ Playwright fallback, SSRF checks
โโโ user_interaction.py # User-question tools (host binds emitter + waiter at runtime)
โโโ team_tools.py # Team collaboration tools
โโโ file_tasks.py # Task-board tools
โโโ protocols.py # shutdown / plan_approval / idle protocol tools
โโโ weather_tool.py / baidu_weather.py / lunar.py # Weather + lunar calendar
โโโ guard.py # Path guard for sandboxed front ends
Key concepts
- Subagent vs teammate โ a subagent is temporary: it runs one task, returns a summary, and is destroyed. A teammate is persistent: it runs its own agent loop in a background thread and communicates through the message bus.
- TodoManager vs TaskManager โ the former is an in-memory checklist private to one agent; the latter is a file-persisted task board shared across agents, with dependency edges.
- Two-level compaction โ truncation clears old tool results automatically each round; the LLM summary kicks in once the token threshold is exceeded. Both protect prompt prefix caching through the 0.8 gate described above.
A deeper analysis (layering, call chains, known technical debt) lives in docs/ARCHITECTURE.md.
Built-in Tools
About 29 tools, statically assembled by the tool registry in tools/registry.py. Tool definitions are plain dicts in Anthropic format; handlers may be sync or async. The host can inject more via the registration hook and filter the set with the whitelist variable.
| Category | Tools | Notes |
|---|---|---|
| Files & commands | bash, powershell, read_file, write_file, edit_file |
Path-escape guard, dangerous-command filtering, timeouts, output truncation; reads are line-numbered with offset/limit paging; edits enforce unique match or explicit replace-all |
| Search | grep, glob |
ripgrep-based content search and file-name matching |
| Web | webfetch |
trafilatura extraction with Playwright fallback; SSRF (server-side request forgery) protection |
| User interaction | ask_user, user_confirm, ask_user_question |
Registered unbound; the host binds an emitter and response waiter at runtime, so the same tools drive any front end |
| Team collaboration | spawn_teammate, list_teammates, send_message, read_inbox, broadcast |
Delegate to the teammate manager and message bus |
| Protocol | shutdown_request, plan_approval, idle |
Team lifecycle coordination |
| Task board | task_create, task_get, task_update, task_list, claim_task |
Forward to the persistent task board |
| Agent-internal | TodoWrite, task (one-shot subagent), load_skill, background_run, check_background, compress |
Loop-adjacent conveniences |
| Weather & calendar | baidu_weather |
Baidu Map API plus borax lunar calendar |
Runtime Data Directories
All runtime state lives under the working directory (.planify/ namespace plus convention dirs):
your-project/
โโโ .planify/
โ โโโ team/ # Team config and per-recipient inboxes (inbox/)
โ โโโ tasks/ # Task board JSON files
โ โโโ transcript.json # Compaction transcript sink
โ โโโ .env # Highest-priority .env location
โโโ skills/ # SKILL.md skill files (scanned recursively)
โโโ .transcripts/ # Conversation transcripts saved by auto-compact
โโโ logs/ # Log files
Embedding as a Host Application
Planify never imports the host โ everything flows in through registration hooks:
from planify import bootstrap
# 1. Inject configuration (highest priority, beats environment variables)
bootstrap.register_planify_config(
api_key="sk-...",
model_id="claude-sonnet-4-6",
base_url="", # empty = SDK default
protocol="anthropic", # or "openai_compat"
)
# 2. Inject host tools (e.g. domain-specific retrieval tools)
bootstrap.register_app_dependencies(
external_tools=[{"name": "read_document", "description": "...", "input_schema": {...}}],
external_handlers={"read_document": my_handler},
)
# 3. Inject host-owned runtime paths (optional)
from planify.core.logging_config import register_data_dirname, register_env_loader
register_data_dirname(".yourdata") # where the host keeps its data dir
register_env_loader(load_your_dotenv) # callback: load your .env into os.environ
Steps 3 let the host tell the framework where its data directory and .env live
without the framework importing the host (framework code stays host-neutral and
depends on nothing above it). Leave them unset when running standalone โ the
framework then uses its own .planify namespace and loads .planify/.env
(see planify.core.config.get_config).
User-question tools are wired at runtime: the host binds its event emitter and response waiter with bind_user_interaction_handlers() (in tools/user_interaction.py), so agent questions reach whatever front end the host provides and answers flow back asynchronously.
The host-application integration surface (SSE streaming, custom tool development, config injection) is documented in docs/ARCHITECTURE.md.
Development
# Install with dev extras (pytest / pytest-asyncio)
pip install -e "./planify[dev]"
# Run the test suite
pytest
Documentation
- docs/ARCHITECTURE.md โ deep architecture analysis (layering, call chains, technical debt)
- docs/DESIGN-async-refactor.md โ the async refactor that moved the streaming loop onto the ASGI event loop
License
Apache-2.0 โ see the repository root LICENSE.