pydantic-ai / pydantic_clai2
AGENTS.md20k starsChanged 2 months agoMITView on GitHub
Read this before touching pydantic-clai2/. The repository-level AGENTS.md still applies (no em-dashes, no Any, pyright strict, keyword-only arguments, 100% branch coverage). This file adds what is specific to the terminal shell. A thin terminal around any Pydantic AI agent. It reads a prompt, runs the agent, streams the answer, and repeats. Everything beyond that is a plugin, including the default coding tools. The three layers, and who owns what: If a change needs the agent loop to behave differently, propose…
Trending
Less talk lately.about the whole repository
Who's talking about pydantic/pydantic-ai
- A Hacker News story“MCP Run Python”Hacker News · Apr 15, 2025 · 173 points
- @pythonhub.dev“PydanticAI PydanticAI is a Python Agent Framework designed to make it less painful to build production …”Bluesky · Dec 11, 2024 · 8 likes
- langfuse/langfuse“Add support for `gen_ai.system_instructions` gen-ai field”GitHub · Sep 19, 2025 · 7 reactions
- A Hacker News story“Agent Framework / shim to use Pydantic with LLMs”Hacker News · Dec 2, 2024 · 7 points
- pydantic/mcp-run-python“Dockerise the MCP Run Python server”GitHub · May 27, 2025 · 5 reactions
The biggest 5 of 64 mentions linking to the repository that our crawl found. Each line is their own headline.
See all 64
Talked about on GitHub, Bluesky, Hacker News and the web (64 times).
On GitHub · 50
- Sep 19, 2025Add support for `gen_ai.system_instructions` gen-ai field — langfuse/langfuse7 reactions · 4 comments
- May 27, 2025Dockerise the MCP Run Python server — pydantic/mcp-run-python5 reactions · 6 comments
- Oct 16, 2025Inngest Durable execution with Pydantic-AI — inngest/inngest-py4 reactions · 9 comments
- May 23, 2025Handle `type[T]` for type variables — astral-sh/ty4 reactions · 3 comments
- Mar 12, 2026Impossible to run the app due to Mistral import error — Denario-AI/Denario3 reactions · 3 comments
45 more on GitHub
- Feb 27, 2026Anthropic cache tokens double-counted: usage.input already includes cache via OTel/genai-prices — langfuse/langfuse3 reactions · 6 comments
- May 25, 2025Misc. bug: Streaming with tools causes pydantic-ai to mess up tool name — ggml-org/llama.cpp3 reactions · 5 comments
- Jun 30, 2026chore(deps): bump pydantic-ai-slim from 1.63.0 to 1.102.0 in /python/examples/pydantic-ai-cdp-chatbot — Dustin4444/agentkit2 reactions · 5 comments
- Jun 30, 2026chore(deps): bump pydantic-ai from 1.63.0 to 1.102.0 in /python/examples/pydantic-ai-cdp-chatbot — Dustin4444/agentkit2 reactions · 6 comments
- May 21, 2026chore(deps): bump pydantic-ai from 1.66.0 to 1.99.0 in /python/framework-extensions/pydantic-ai — Dustin4444/agentkit2 reactions · 4 comments
- May 21, 2026chore(deps): bump pydantic-ai-slim from 1.66.0 to 1.99.0 in /python/framework-extensions/pydantic-ai — Dustin4444/agentkit2 reactions · 4 comments
- Apr 1, 2026chore(deps): bump pydantic-ai from 0.2.15 to 1.56.0 in /backend — cicero-im/meeting-minutes2 reactions · 1 comment
- Apr 1, 2026Bump pydantic-ai-slim from 1.0.1 to 1.56.0 — cicero-im/codantic-aidisplayagent2 reactions · 2 comments
- Apr 1, 2026Bump pydantic-ai from 1.0.1 to 1.56.0 — cicero-im/codantic-aidisplayagent2 reactions · 2 comments
- Apr 1, 2026Bump pydantic-ai-slim from 0.0.46 to 1.56.0 in /pydantic-ai-langfuse — cicero-im/ottomator-agents2 reactions · 1 comment
- Apr 1, 2026Bump pydantic-ai-slim from 0.6.2 to 1.56.0 — cicero-im/paigeant2 reactions · 2 comments
- Apr 1, 2026chore(deps): bump pydantic-ai from 0.2.6 to 1.56.0 — cicero-im/tunacode2 reactions · 2 comments
- Apr 1, 2026Bump pydantic-ai-slim from 0.7.4 to 1.56.0 in /agent-backend — cicero-im/pydantic-ai-fastapi-react-vite-agent2 reactions · 2 comments
- Apr 1, 2026Bump pydantic-ai from 1.0.10 to 1.56.0 in /examples/integrations/pydanticAI_researcher_example — cicero-im/memori2 reactions · 2 comments
- Apr 1, 2026Bump pydantic-ai from 1.0.17 to 1.56.0 — cicero-im/github-issue-analysis2 reactions · 2 comments
- Apr 1, 2026Bump pydantic-ai from 0.6.2 to 1.56.0 — cicero-im/paigeant2 reactions · 2 comments
- Apr 1, 2026Bump pydantic-ai from 0.0.46 to 1.56.0 in /pydantic-ai-langfuse — cicero-im/ottomator-agents2 reactions · 1 comment
- Apr 1, 2026chore(deps): bump pydantic-ai-slim from 1.0.15 to 1.56.0 — cicero-im/pydantic_ai_claude_code2 reactions · 2 comments
- Apr 1, 2026Bump pydantic-ai from 0.7.4 to 1.56.0 in /agent-backend — cicero-im/pydantic-ai-fastapi-react-vite-agent2 reactions · 1 comment
- Apr 1, 2026Bump pydantic-ai-slim from 0.0.30 to 1.56.0 — cicero-im/pydanticai_mcp_demo2 reactions · 1 comment
- Apr 1, 2026build(deps): bump pydantic-ai from 0.2.0 to 1.56.0 — cicero-im/lightblue-ai2 reactions · 1 comment
- Apr 1, 2026Bump pydantic-ai from 0.3.1 to 1.56.0 — cicero-im/pydantic_ai_editor2 reactions · 2 comments
- Apr 1, 2026chore(deps): bump pydantic-ai from 0.3.4 to 1.56.0 — cicero-im/mcp2 reactions · 2 comments
- Apr 1, 2026chore(deps): bump pydantic-ai-slim from 0.3.4 to 1.56.0 — cicero-im/mcp2 reactions · 3 comments
- Apr 1, 2026chore(deps): bump pydantic-ai-slim from 0.2.12 to 1.56.0 — cicero-im/pydantic-ai-mcp-experiment2 reactions · 1 comment
- Apr 1, 2026build(deps): bump pydantic-ai-slim from 0.2.18 to 1.56.0 — cicero-im/me-pydanticai-2 reactions · 1 comment
- Apr 1, 2026Bump pydantic-ai from 0.0.30 to 1.56.0 — cicero-im/pydanticai_mcp_demo2 reactions · 2 comments
- Apr 1, 2026Bump pydantic-ai-slim from 0.3.1 to 1.56.0 — cicero-im/pydantic_ai_editor2 reactions · 2 comments
- Apr 1, 2026build(deps): bump pydantic-ai from 0.2.18 to 1.56.0 — cicero-im/me-pydanticai-2 reactions · 2 comments
- Apr 1, 2026build(deps): bump pydantic-ai-slim from 0.0.52 to 1.56.0 — cicero-im/wa_llm2 reactions · 1 comment
- Apr 1, 2026build(deps): bump pydantic-ai-slim from 0.2.0 to 1.56.0 — cicero-im/lightblue-ai2 reactions · 1 comment
- Apr 1, 2026Bump pydantic-ai-slim from 0.0.43 to 1.56.0 — cicero-im/Ai_Tutor2 reactions · 1 comment
- Apr 1, 2026chore(deps): bump pydantic-ai from 0.0.42 to 1.56.0 — cicero-im/automagik-agents2 reactions · 2 comments
- Apr 1, 2026Bump pydantic-ai from 0.0.43 to 1.56.0 — cicero-im/Ai_Tutor2 reactions · 2 comments
- Apr 1, 2026build(deps): bump pydantic-ai from 0.0.52 to 1.56.0 — cicero-im/wa_llm2 reactions · 1 comment
- Mar 26, 2026build(deps): bump the pip group across 5 directories with 4 updates — GoldenEagle-23/oss-fuzz2 reactions · 1 comment
- Feb 28, 2026Error because `thoughtSignature` missing from Gemini 3 function call — Arjun-Vashistha/Test-Repo-22 reactions
- Nov 21, 2025Run generator.__anext__ in the same task to avoid anyio RuntimeError — langfuse/langfuse-python2 reactions · 1 comment
- Nov 14, 2025Dockerise MCP-run-python server + add git workflows to publish images — pydantic/mcp-run-python2 reactions · 5 comments
- Aug 4, 2025Tracking: Contribute FastMCP Toolset to Pydantic AI — PrefectHQ/fastmcp2 reactions · 1 comment
- Jul 12, 2025Tool context kwarg detection not compatible with string-valued/__future__ annotations — modelcontextprotocol/python-sdk2 reactions · 3 comments
- May 23, 2025Sequence of types — python/mypy2 reactions · 2 comments
- Aug 7, 2026Pydantic AI as an agentic engine — github/gh-aw1 reaction · 12 comments
- Jul 8, 2026chore: port pydantic-ai v2.6.0 changes — a7ul/vibes1 reaction
- Jul 7, 2026chore: port pydantic-ai v2.5.1 changes — a7ul/vibes1 reaction
On Bluesky · 7
- Dec 11, 2024PydanticAI PydanticAI is a Python Agent Framework designed to make it less painful to build production grade applications with Generative… — @pythonhub.dev8 likes and reposts
- Aug 9, 2025I use 'llm' now for my cli explorations with genai. Will i move to `clai` for that "FastAPI feeling" they promise? i do love pydantic! see:… — @paulkarayan.bsky.social2 likes and reposts
- Dec 4, 2024🚀 Skyrocketing! 🚀 (200+ new stars) 📦 pydantic / pydantic-ai ⭐ 1,319 (+429) 🗒 Python Agent Framework / shim to use Pydantic with LLMs — @github-trending.bsky.social2 likes and reposts · 1 reply
- Sep 3, 2025https://github.com/pydantic/pydantic-ai — @tom-doerr.bsky.social1 likes and repost
- Jul 18, 2025📦 pydantic / pydantic-ai ⭐ 10,912 (+49) 🗒 Python Agent Framework / shim to use Pydantic with LLMs — @github-trending.bsky.social1 likes and repost
2 more on Bluesky
- Dec 6, 2024PydanticAI: Build production-grade Agentic AI apps in pure Python! PydanticAI offers the same elegance and ease of use as FastAPI, now… — @akshay-pachaar.bsky.social1 likes and repost · 1 reply
- Dec 4, 2024github.com/pydantic/pyd... — @presidentlin.bsky.social0 likes and reposts · 1 reply
On Hacker News · 5
- Apr 15, 2025MCP Run Python173 points · 66 comments
- Dec 2, 2024Agent Framework / shim to use Pydantic with LLMs7 points · 3 comments
- Dec 3, 2024Pydantic AI3 points
- Dec 6, 2024PydanticAI using Ollama (llama3.2) running locally2 points · 3 comments
- Dec 5, 2024PydanticAI1 point
On the web · 2
- Oct 7, 2026Test Pydantic AI Agents – Scenario — langwatch.ai
- Jul 9, 2026Pydantic AI AI Agent Security Evaluation — trustvector.guard0.ai
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.
Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository56 other files it gives its agents.
- AGENTS.mdAGENTS.md
- docs/AGENTS.mdAGENTS.md
- docs/harness/AGENTS.mdAGENTS.md
- docs/realtime/AGENTS.mdAGENTS.md
- .github/workflows/AGENTS.mdAGENTS.md
- pydantic_ai_slim/pydantic_ai/AGENTS.mdAGENTS.md
- pydantic_ai_slim/pydantic_ai/capabilities/AGENTS.mdAGENTS.md
- pydantic_ai_slim/pydantic_ai/durable_exec/AGENTS.mdAGENTS.md
- pydantic_ai_slim/pydantic_ai/models/AGENTS.mdAGENTS.md
- pydantic_ai_slim/pydantic_ai/native_tools/AGENTS.mdAGENTS.md
- pydantic_ai_slim/pydantic_ai/profiles/AGENTS.mdAGENTS.md
- pydantic_ai_slim/pydantic_ai/providers/AGENTS.mdAGENTS.md
- pydantic_ai_slim/pydantic_ai/realtime/AGENTS.mdAGENTS.md
- pydantic_ai_slim/pydantic_ai/toolsets/AGENTS.mdAGENTS.md
- pydantic_ai_slim/pydantic_ai/ui/AGENTS.mdAGENTS.md
- src/pydantic_ai_harness/AGENTS.mdAGENTS.md
- tests/AGENTS.mdAGENTS.md
- tests/benchmarks/AGENTS.mdAGENTS.md
- tests/harness/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- docs/CLAUDE.mdCLAUDE.md
- docs/harness/CLAUDE.mdCLAUDE.md
- docs/realtime/CLAUDE.mdCLAUDE.md
- .github/workflows/CLAUDE.mdCLAUDE.md
- pydantic_ai_slim/pydantic_ai/CLAUDE.mdCLAUDE.md
- pydantic_ai_slim/pydantic_ai/models/CLAUDE.mdCLAUDE.md
- pydantic_ai_slim/pydantic_ai/native_tools/CLAUDE.mdCLAUDE.md
- pydantic_ai_slim/pydantic_ai/realtime/CLAUDE.mdCLAUDE.md
- pydantic_ai_slim/pydantic_ai/ui/CLAUDE.mdCLAUDE.md
- src/pydantic_ai_harness/CLAUDE.mdCLAUDE.md
- src/pydantic_clai2/CLAUDE.mdCLAUDE.md
- tests/benchmarks/CLAUDE.mdCLAUDE.md
- tests/CLAUDE.mdCLAUDE.md
- tests/harness/CLAUDE.mdCLAUDE.md
- adding-a-provider-api-featureSkill
- add-new-modelSkill
- complete-partial-prSkill
- docs-parity-reviewerSkill
- i-have-adhdSkill
- poweruser-feature-auditSkill
- pushing-commits-to-the-repoSkill
- address-feedbackSkill
- pre-push-reviewSkill
- testing-skillSkill
- building-pydantic-ai-agentsSkill
- migrating-agno-to-pydantic-aiSkill
- migrating-claude-agent-sdk-to-pydantic-aiSkill
- migrating-google-adk-to-pydantic-aiSkill
- migrating-langchain-to-pydantic-aiSkill
- migrating-mastra-to-pydantic-aiSkill
- migrating-openai-agents-sdk-to-pydantic-aiSkill
- migrating-pi-to-pydantic-aiSkill
- migrating-vercel-ai-sdk-and-eve-to-pydantic-aiSkill
- migrating-deep-agents-to-pydantic-ai-harnessSkill
- pydantic-ai-harnessSkill
- reviewerSkill
The file
Show its rules and text
We split this AGENTS.md into the rules it gives an agent
20 rules. About 0 are common, 7 are distinctive, and 13 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈7
Distinctive · estimate
This author's own choices. Worth a look.
13
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 3
Read this before touching pydantic-clai2/.
- Distinctive: line 21
If a change needs the agent loop to behave differently, propose it in core.
- Very specific: line 117
A load failure leaves the session as it was: Import, construction, or get_* errors are reported and the plugin stays unloaded.
- Very specific: line 134
Add the event dataclass and an on_* method (or a get_* method with a no-op default) to Plugin, and route it in _HANDLERS or collect.
- Very specific: line 137
Document it in PLUGINS.md in the table it belongs to, and in docs/declarative-plugins.md if it changes the design.
- Very specific: line 150
Every key mutates immediately and replace_items redraws.
- Very specific: line 196
Do not define new palettes.
- Very specific: line 224
Do not add broad backwards-compatibility shim modules for internal file moves.
- Very specific: line 225
Keep documented plugin-author paths (pydantic_clai2.plugins and pydantic_clai2.commands) intact.
- Distinctive: line 297
Keep files concise - we don't need any 10,000 line files.
- Very specific: line 301
When adding or modifying a CLAI2 CLI UX feature, test every affected UX feature with your changes in a fresh tmux window before opening a …
- Very specific: line 307
Test a moment by loading the plugin with load_plugin and firing the event from the shell path that owns it (or LoadedPlugin.dispatch).
- Distinctive: line 315
Before adding, removing, or renaming a setting, changing its type, meaning, or default, or changing the SQL schema, consider upgrades, …
- Very specific: line 319
Add regression cases to tests/test_settings_compatibility.py and affected CLI tests using the previous stored format.
- Distinctive: line 322
Verify older databases load with documented defaults for missing settings and preserve existing preferences, plugin declarations, and model …
- Distinctive: line 327
Keep validation strict for known values, new writes, and plugin declarations.
- Distinctive: line 331
Verify rejected values and unsupported schema versions leave stored data intact.
- Distinctive: line 332
If a change introduces a migration, test failure rollback as well as success.
- Very specific: line 333
When a plugin setting's valid values or meaning depend on code other builds may lack, add a feature name to SUPPORTED_FEATURES in …
- Very specific: line 346
Run from the repository root.
≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
CLAI 2 guide for AI code assistants
Read this before touching pydantic-clai2/. The repository-level AGENTS.md
still applies (no em-dashes, no Any, pyright strict, keyword-only arguments,
100% branch coverage). This file adds what is specific to the terminal shell.
What CLAI is
A thin terminal around any Pydantic AI agent. It reads a prompt, runs the agent, streams the answer, and repeats. Everything beyond that is a plugin, including the default coding tools.
The three layers, and who owns what:
| Layer | Owns | Never does |
| Pydantic AI core | the agent loop, hooks, events, toolsets | know CLAI exists |
pydantic_ai_harness | reusable capabilities (Coder, Shell, ...) | print to a terminal |
pydantic_clai2 | the prompt loop, rendering, /commands, plugin loading | reimplement a core hook |
If a change needs the agent loop to behave differently, propose it in core. If it is a reusable behavior with no terminal in it, it belongs in harness. Only the shell itself lives here.
The plugin model
A plugin is a Plugin subclass, or a bare capability class. It is declarative
in the same way core's AbstractCapability is: every contribution is a method
with a default that contributes nothing, and a plugin overrides only what it
needs. get_capabilities for tools, instructions, and agent-run hooks (a Hooks
capability, or @on_event on your own capability); get_commands for
/commands; render for custom output; get_status_segments, get_spinners,
and get_model_providers; configure for a settings menu; on_session_start,
on_session_end, on_turn_start, on_turn_end, and on_plugin_load_failed for CLAI's own moments. The
settings model is the class's type parameter (Plugin[Settings]), validated into
self.settings. self.host is a PluginHost, the plugin's runtime context
(console, conversation, status, full screen, saved settings); it registers
nothing. docs/declarative-plugins.md records the design. PLUGINS.md is the
user contract. If code and PLUGINS.md disagree, fix one so they agree in the
same PR.
Rules for the plugin API
- Declare, do not register. A plugin returns what it offers from
get_*methods, which the loader calls once per load (collect). No registration calls, no module-level dicts, no import-time side effects. Tests callload_plugin(PluginClass, host). - One method per moment, one typed event per method. A handler never receives
*args,**kwargs,dict, orcontext: object = None. - No string sub-dispatch. A handler does not receive
event_type: strand switch on it. Use the event class as the key. - One async spelling. No
_syncor_asyncpairs. - Observers return
None. Deciders mutate the event (event.text = ...,event.cancel()). Nothing collects a list of return values. - Fail closed, one way. A raising handler on a decidable moment cancels the action and reports the error. No per-registration "fail open" flag.
- CLAI moments are
on_<subject>_<moment>(on_turn_start). Core hooks stay core's, reached through aHookscapability. Do not wrap a core hook in a plugin method. - Payloads are kw-only dataclasses. Not
BaseModel. Pydantic is for the settings JSON boundary only. - No
getattr/hasattron a plugin to discover what it supports. It returned the thing from aget_*method or it did not;has_configureandhas_rendercompare against the base-class default. - Only shell-owned moments.
on_session_start,on_session_end,on_turn_start,on_turn_end,on_plugin_load_failed. Startup load failures happen before an agent run, so core'sbefore_runcannot observe them. The loader reports them after trying every enabled plugin so observability can receive failures that preceded its own load. Additional moments need the same justification: say which core hook you checked and why it does not fit.
Loading and unloading
Plugins load and unload while CLAI runs. The rules that make that safe:
- One
LoadedPluginper plugin. It holds the instance and what itsget_*methods returned, so unloading is "discard thisLoadedPlugin". Nocallback -> ownermap, no scanning registries for a plugin's name. - Load and unload only between turns.
/commandsalready run between turns, so this falls out for free; do not add a mid-run path. - Load runs
on_session_startfor that plugin; unload runson_session_end. A plugin cannot tell whether it was loaded at startup or later, and must not need to. reloadis unload, re-import, load. Drop-in entry modules use fresh source. Installed modules useimportlib.reload, which retains globals absent from the new source. Plugins keep their state on the instance, set up in__init__.- Instruction order is capability order. Placement is a core
CapabilityOrdering(position,wraps,wrapped_by), not a CLAI list. - Registration is idempotent per name. "Active for the next prompt" is the
natural unit. Stock agents are rebuilt when the capability snapshot changes,
with plugins bound at construction so self-delegation carries their tools,
instructions, and guardrails. Supplied agents still receive plugins per run
(
agent.run(capabilities=...)) and are never rebuilt. - Shipped plugins register first, in declared order. The menu's alphabetical
order is for scanning only. Registration order is the order instructions,
renderers, and status segments are consulted in, so
coder's guidance leads the prompt.customization_guide()orders itself after the guidance plugins contribute and before harnessRepoContext, so the CLAI hint never leads. - Built-ins are declarations, not code paths.
DEFAULT_PLUGINSin_app.pylists the library's built-ins;STOCK_PLUGINSopts the CLI-owned agent into delegation without changing supplied-agent defaults. CLAI ships enabled (coder,ask_user,repo_context,compaction,persistence,observability). The loader treats them like drop-ins with the lowest precedence: a store declaration with the same id replaces one,disablepersists an override,removeresets it. Do not special-caseCoderanywhere else; the agent fromcreate_agent()has no coding tools of its own.coderis declared withrepo_context: falsebecauserepo_contextbinds harnessRepoContextitself; keep it that way orAGENTS.mdreaches the model twice. When a built-in takes the id of a row the former harness catalog offered, add that old row to_RETIRED_BUILTINSinplugins/loader.py, so a user's saved toggle of it maps to the built-in instead of outranking it. - Project declarations rank just above built-ins and start off.
.clai/settings.json(project_settings.py) may declare plugins; the loader takes them asproject=, every oneenabled=False, because a repository must not run code as the user on launch./plugins enableis the approval and persists the approved declaration in the store. Precedence is store, drop-in folder, project, built-in. CLAI never writes the project file. - A load failure leaves the session as it was. Import, construction, or
get_*errors are reported and the plugin stays unloaded; nothing it declared is kept. When construction succeeded,on_session_endruns withreason='error'under a shield with a five-second cooperative timeout before a failed/cancelled load drops the plugin. Cleanup must tolerate an incompleteon_session_start.
Compaction registers harness FallbackCompaction directly with max_fraction
and context_window for both strategies. Harness owns the trigger; do not add
threshold math or an orchestrator in CLAI. Register the usage gauge after the
chain so yellow means the compacted request still exceeds the threshold.
/compact drives the same chain regardless of threshold. Only ModelAPIError,
FallbackExceptionGroup, and UsageLimitExceeded select truncation after a
summary failure; other exceptions propagate.
Adding or changing a CLAI moment or contribution
- Add the event dataclass and an
on_*method (or aget_*method with a no-op default) toPlugin, and route it in_HANDLERSorcollect. - Fire it, or read the collected value, from exactly one place in the shell.
- Document it in
PLUGINS.mdin the table it belongs to, and indocs/declarative-plugins.mdif it changes the design.
The /plugins, /set, /theme, /model, and /add_model menus
Built on termflow's MenuBuilder (and TextInputBuilder for typed values),
exactly like Code Puppy's /agent, /mcp, /set, and /model menus:
alternate screen, a .preview panel on the right, .on_key for single-key
actions, .footer_hint for the key legend, markdown_style() for colours.
- Split it in two: a pure
build_plugins_menu(...)that returns the menu (so tests drive it headless, no terminal), and a thin async runner that owns the screen and callsmenu.runin a thread. - Every key mutates immediately and
replace_itemsredraws. No pending-changes state, no save/cancel pair. Settings menus still end with a Save & close row (save_and_close_item(), recognized bypicked(result)) that only leaves;FieldMenu,/keys, and/pluginsadd it for you. - Turning a plugin on opens its
configuremenu. A widget cannot open from inside another menu's key handler, soPluginMenucloses with aConfigureresult andopen_plugins_menuruns the settings menu, then reopens the list. - Nothing prints to the console while the menu is open; the alternate screen would hide it. Show empty states and errors inside the menu as disabled rows.
- Esc and Ctrl-C close cleanly. They are not errors.
- A widget opened mid-run (including the inline
ask_userpicker) goes insideasync with host.full_screen(), which flushes streamed text and suspends the editor's input reader first, preserving its draft. Slash-command handlers already run with the editor suspended. Do not start a second input reader alongside the live editor. - Adding a plugin is not in the menu. It needs free text, so it stays
/plugins add. - Anything that is "edit named, validated fields" uses
field_menu.py: aFieldSourcesupplies rows, current values, validation, apply, and reset;FieldMenubuilds the widgets;run_flowis the loop./setand per-model settings are two sources, not two editors. Do not write a third editor. /setedits go throughCommandContext.set_setting/reset_setting, the same path as the typed command, so validation lives in one place.- Widget runners are a
Runnersvalue passed into the loops; tests pass scripted ones (tests/menu_script.py). Only the realwidget.run()one-liners areno cover. - Model sources live in
model_catalog.py. To add one (models.dev, a provider API), write a function returningCatalogModels and merge it incatalog(). The menu never talks to a source directly. - Per-model settings are the editable subset of core's
ModelSettings, declared once asModelSettingsFormwith descriptions and bounds. Extend the form, not the menu, to expose another setting.
Rendering
StreamRenderer owns text and thinking. It knows nothing about any specific
tool. Tool-specific output (shell previews, diffs, grep) comes from render on
the plugin that owns the event. Match on event classes, never on tool_name
strings. Always flush the stream before printing anything else; the shell does
this for renderers, so do not call console.print from an event hook when a
renderer would do.
Colours
/theme offers the unchanged default appearance and termflow.themes.PALETTES.
Do not define new palettes. Resolve brand roles with theme.color(...) for Rich;
theme.sgr(...) resolves raw ANSI itself. theme.current() returns a Termflow
palette or None for the original appearance. Termflow owns palette application
and reset; theme.use(...) leaves the terminal untouched in the default session.
Markdown keeps its original style by default and uses to_render_style() for a
selected palette. The preview renders a sample without OSC changes or persistence.
Heavy imports in theme.py stay lazy for the splash. Code uses the terminal
foreground and ANSI syntax colours through theme.syntax_theme(), shared by
streamed fences and theme previews. Default diff colours stay unchanged; bundled
palettes get diff lines from theme.diff_renderer(), tinted from the palette.
Source layout
The package root composes the shell (_app.py, __main__.py) and keeps the
plugin-author imports pydantic_clai2.plugins and pydantic_clai2.commands
stable. Other code is grouped by responsibility:
cli/owns argument handling, command context, headless output, and shell passthrough.config/owns settings, credential storage, and project declarations.config/__init__.pyprovides the existingpydantic_clai2.configsettings API.runtime/owns sessions, forks, worktrees, reload, and speculative turns.models/owns model discovery, settings validation, and optional provider adapters. Pure model parameter expansion belongs here, not in a menu.ui/prompt/owns editing, terminal input, surface painting, and resize.ui/menus/owns widgets and command-specific pickers;ui/rendering/owns themes, streaming, status, and output formatting.plugins/owns the host API, loading, and credential picker helpers.builtin_plugins/andmcp/retain their plugin and server boundaries.
Move a capability to core or harness if it does not need a terminal. Keep UI
imports out of reusable validation code. The CLI and app may compose these
packages; new package initializers should not eagerly import the app or heavy UI.
Do not add broad backwards-compatibility shim modules for internal file moves.
Keep documented plugin-author paths (pydantic_clai2.plugins and
pydantic_clai2.commands) intact; update example imports when moving UI helpers.
File map
| File | Holds |
cli/_cli.py | argument parsing, startup, --agent |
cli/agent_import.py | resolves --agent MODULE:ATTR to an agent instance |
cli/self_update.py | /update and the status-row notice: PyPI (stable) or the newest CLAI commit on main (bleeding, an HTTPS source archive with --overrides, no git), reinstalled with uv tool install --force |
_app.py | the prompt loop and built-in /commands |
runtime/_session.py | conversation state, revision-checked saves, restore-only resume, plugin snapshots and stock-agent rebuilding |
runtime/sessions.py | resume command and background namer ownership; built-in step capture |
runtime/session_naming.py | resume-browser naming prompt, SessionName card schema, and the bounded SessionNamer worker |
runtime/forks.py | /fork and /forks: history snapshot, background child sessions, deferred fork output |
ui/menus/session_browser.py | project/session browser using Termflow layout and terminal primitives |
ui/menus/rewind.py | double-Esc rewind picker: run boundaries, compaction guard, and durable history replacement before draft restoration |
ui/rendering/_rendering.py | streaming Markdown and thinking |
plugins/__init__.py | Plugin, PluginHost, LoadedPlugin/collect, event dataclasses |
plugins/_factories.py | resolving a declaration's factory to a Plugin (module, module:Class, capability class) |
plugins/loader.py | discovery, load, unload, reload; the /plugins subcommands |
ui/menus/plugin_menu.py | the /plugins full-screen menu (PluginMenu plus its runner) |
plugins/describe.py | a plugin's description from its docstring, parsed with ast, never imported |
builtin_plugins/ask_user_menu.py | the built-in ask_user plugin: QuestionMenu, TerminalAnswerer, the transcript renderer |
ui/prompt/screen.py | Screen, what host.full_screen() binds to during a prompt |
ui/menus/field_menu.py | the shared field editor (FieldSource, FieldMenu, Runners, run_flow) |
ui/menus/set_menu.py | /set: SettingsSource over CommandContext |
ui/menus/model_menu.py | /add_model: provider discovery, ModelSettingsSource, run_model_flow |
ui/menus/model_picker.py | /model: selection, completion, and confirmed deletion of saved models; protects the current model and saved default |
models/model_catalog.py | model sources (genai-prices today) merged by catalog() |
models/model_settings.py | ModelSettingsForm, the editable subset of ModelSettings |
models/custom_params.py | dotted custom-parameter validation and expansion, independent of menus |
ui/menus/custom_params.py | the editor for custom model parameters |
builtin_plugins/logfire.py | the default-enabled observability plugin, configuring Logfire locally over core Instrumentation; token picks a /keys write token, ui_events subscribes it to UI telemetry; configure is a FieldMenu whose project row runs logfire_setup |
builtin_plugins/logfire_setup.py | the observability plugin's setup menu: region or self-hosted URL, Logfire's device sign-in (not the MCP OAuth in logfire_oauth.py), project pick, write token saved in /keys |
ui/telemetry.py | UI telemetry sinks, record/span, and the menu naming; instrument shared chokepoints (run_worker, Commands.execute_async, FieldMenu, the loader, /keys, the prompt), never one menu at a time, and record names, not content |
builtin_plugins/compaction.py | the built-in compaction plugin: harness FallbackCompaction([SummarizingCompaction, SlidingWindowCompaction]), /compact, the context alert |
commands.py | Command, the registry, completion |
ui/rendering/usage_report.py | /usage, /cost, and the footer cost, derived from Session.messages |
ui/rendering/status.py | the footer Status fields, StatusSegment, and the StatusLine row painter |
ui/prompt/live_prompt.py | pinned editor lifecycle, completion worker, submission queue, timed double-Esc gesture, and menu handoff |
ui/prompt/prompt_surface.py | scroll-region ownership, serialized transcript writes and changed-row painting |
ui/prompt/prompt_transcript.py | bounded styled transcript tail for viewport replay |
ui/prompt/prompt_resize.py | scoped resize notifications, without terminal IO in signal handlers |
ui/prompt/prompt_buffer.py | pure draft editing, history navigation, search and cell-width wrapping |
ui/prompt/prompt_completion.py | bounded daemon completion worker; no terminal ownership |
ui/prompt/prompt_keys.py | keyboard decoder attachment only; no prompt-toolkit Application or renderer |
config/__init__.py | Settings, PluginSettings |
config/theme_names.py | theme choices shared by settings validation and the picker |
config/settings_store.py | the SQLite store under $XDG_CONFIG_HOME/pydantic-clai2/, including saved models and removal of their overrides |
config/features.py | SUPPORTED_FEATURES, the feature names this build implements, and CAPABILITY_REQUIREMENTS for capability classes |
config/plugin_requirements.py | pure rules for requirement tags: parse stored rows, drop unsupported settings, merge tags on save, the notice |
runtime/capability_guard.py | PluginGuard: a plugin capability's run setup UserError becomes CapabilitySetupError; that turn fails, later turns leave the capability out |
config/project_settings.py | .clai/settings.json: the walk-up to the git root, validation, ProjectSettings |
builtin_plugins/repo_context.py | the built-in repo_context plugin over harness RepoContext |
builtin_plugins/coder.py | the built-in coder plugin over harness Coder: validated settings, named agent folders (.agents/.claude/.codex, project then home), and its settings menu (file access, sub-agents, agent folders) |
builtin_plugins/slack.py | the opt-in built-in slack plugin over harness Slack; its settings menu picks a /keys user token or a browser sign-in, resolved each turn |
slack_app.py | Slack browser sign-in: the CLAI Slack app manifest (PKCE, MCP access, token rotation), scopes, and PKCESignIn for a Client ID |
plugins/keys.py | choose_key, browser_sign_in, and on_loop: a plugin settings menu's credential rows, Esc-cancellable |
pkce.py | PKCESignIn: browser sign-in for a registered public OAuth client (PKCE, no secret), with tokens in the credential store and locked refresh; built on core's OAuthFlow |
runtime/speculation.py | the run.speculative_code_mode switch, Ctrl+X Ctrl+S toggle, session counters and pinned row |
runtime/speculative_mode.py | harness CodeMode wiring (native writes, read-only speculation allowlist, guidance), imported only while on |
runtime/eager_timing.py | eager run_code latency measurement and the nested-call id pattern |
runtime/sandbox_calls.py | events and ordering that render calls from inside run_code like direct calls; no harness imports |
ui/rendering/theme.py | Existing brand roles, opt-in Termflow palette scope, color(), sgr() |
ui/menus/theme_picker.py | /theme picker over Termflow's bundled palettes |
ui/rendering/spinners.py | the working-animation catalogue: builtins, plugin get_spinners, the user's spinners.json, Spinners |
ui/rendering/spinner_frames.py | frame data for the Code Puppy cli-spinners pack |
ui/menus/spinner_picker.py | /spinner: animated picker, by-name selection with speed, init |
The other built-in plugin implementations (notifications, github, pylon, google_workspace, day_ai, ordinal, notion, logfire_mcp, posthog, grain, and linear) also live in builtin_plugins/. The loader redirects old factory paths in saved declarations to this package.
Keep files concise - we don't need any 10,000 line files. Single responsibility.
Testing
- When adding or modifying a CLAI2 CLI UX feature, test every affected UX feature
with your changes in a fresh tmux window before opening a PR. Run CLAI2 with
uv run clai2. Verify the actual terminal behavior against the intention of the user's request, not just the implementation or automated tests. pytest-anyio; real model calls are blocked globally.- Drive the shell with
TestModeland aConsole(file=StringIO()). - Test a moment by loading the plugin with
load_pluginand firing the event from the shell path that owns it (orLoadedPlugin.dispatch). Assert the handler's effect (the cancelled turn, the rewritten text), not a mock call count. - Renderers get synthetic events. They must not need
Coderinstalled. - Cancellation: use a real
anyiocancel scope, order withEvents, no sleeps.
Settings and database compatibility
Before adding, removing, or renaming a setting, changing its type, meaning, or default, or changing the SQL schema, consider upgrades, downgrades, and branch switches. Different versions can share the same settings database.
- Add regression cases to
tests/test_settings_compatibility.pyand affected CLI tests using the previous stored format. Keep historical fixtures unchanged; do not regenerate them with current models or rewrite them to make a change pass. - Verify older databases load with documented defaults for missing settings and preserve existing preferences, plugin declarations, and model settings. Test migrations and repeated initialization for data preservation and idempotence.
- Preserve unknown saved setting names and their values when reading, editing other settings, resetting, and reopening. Unknown does not mean obsolete. Keep validation strict for known values, new writes, and plugin declarations.
- For renamed fields or changed types, meanings, or defaults, define the migration
or intentional behavior change and test it explicitly. Comparing only against
the current
Settings()defaults will not catch an unintended default change. - Verify rejected values and unsupported schema versions leave stored data intact. If a change introduces a migration, test failure rollback as well as success.
- When a plugin setting's valid values or meaning depend on code other builds may
lack, add a feature name to
SUPPORTED_FEATURESinconfig/features.pyand tag the setting (host.settings(Model, requires=...), orCAPABILITY_REQUIREMENTSfor amodule:Classcapability). Tags live in theplugin_requirementstable; never add a field toPluginSettings, a key to itssettings, or bumpuser_version, since older builds reject all three. A build lacking a feature drops only that setting and uses the default. Run setupUserErrors are caught only byPluginGuard, and only around a capability CLAI built from amodule:Classdeclaration's settings with noHooksinside, so policy hooks and plugin-contributed capabilities always fail closed. See "Settings that need a feature" incustomization.md.
Local verification
Run from the repository root. CLAI shares the root uv.lock, .venv, and
Pyright configuration with Harness.
uv sync --locked --all-packages --group lint
uv run --no-sync ruff format --check .
uv run --no-sync ruff check .
PYRIGHT_PYTHON_IGNORE_WARNINGS=1 uv run --no-sync pyright pydantic-clai2/src pydantic-clai2/tests
uv run --no-sync pytest -p no:cacheprovider -c pydantic-clai2/pyproject.toml pydantic-clai2/testsDocs parity
README.md is the tour, PLUGINS.md is the plugin contract, this file is for
agents. A user-facing change updates the first two in the same PR. Plain
language, short sentences, no jargon a first-time plugin author would not know.
The resume browser is a focused exception to the single MenuBuilder convention:
it needs independently focused projects/sessions and two-line cards. Keep its
frame pure, inject keys/size/IO, use Termflow terminal ownership and layout, and
run through menu_worker. Metadata refreshes must preserve selection by ID.
History-changing plugins use await conversation.commit_messages, not the legacy
in-memory replace_messages, so exiting immediately after /compact is durable.
The interactive editor owns its layout explicitly. Do not reintroduce a
PromptSession renderer or mutate generated layout children. Transcript writes
go directly to the scroll region, never through an erase/redraw of the editor.
The hardware cursor stays hidden until release; the input cursor is a painted
reverse-video cell. Keep terminal mutations in PromptSurface, and detach the
key reader before a menu owns the screen. The remaining prompt-toolkit decoder
preserves paste and modified keys not yet exposed by Termflow's read_key.
Physical resize blanks the viewport and defers output until size notifications
have been quiet for 250 ms. Rebuild from TranscriptBuffer, not guessed old row
coordinates or cursor reports. Never send erase-scrollback (CSI 3 J). Keep editor
height changes separate from physical resize, preserve the draft, and close the
resize output spool on both normal handoff and failure. SIGWINCH only marks the
resize and schedules a paint; the signal handler must not perform terminal IO.
The ask_user picker is an inline exception to the full-screen menu convention.
It borrows the released PromptSurface while the editor is suspended, retaining
the shared transcript for resize replay. Keep its numbered choices and Enter
toggles; do not reintroduce alternate-screen switching or Space-to-toggle.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

