Plan Mode
Explore and plan with read-only tools and bundled Planning until a person approves the plan, then continue implementing in the same run under normal permissions.
While Pydantic AI Harness is on 0.x releases, the API may change between minor releases; when it does, deprecation warnings and release-note migration guidance tell you (or your agent) exactly how to upgrade. See the version policy.
PlanMode is a combined capability pairing a planning tool filter (PlanModeGuard) with Planning. While active:
- Denies while active: checks and denies
FileSystemwrites (write_file,edit_file,create_directoryby tool kind),Shellcommands (tools declaringcode_arg_language='shell'andcode_arg_name),IPythonCodeModecells, andSubAgentsdelegations (plusmessage_taskandanswer_taskcalls) targeting delegates not markedread_only=True. Custom tools, MCP tools, and customCodeModeos_accessorexternal_moduleshandlers are not classified automatically (see below). - Code Mode mounts: downgrades
CodeMode'read-write'mounts to'read-only'on every feed while active ('overlay'mounts stay writable for ephemeral scratch), and keepsexit_plan_modenative outsiderun_code. - Planning: bundles
Planning()by default (or accepts a configuredPlanning(...), orplanning=False). - Cache-safe instructions: states
DEFAULT_PLAN_MODE_INSTRUCTIONSvia an append-only dynamicInstructionPart(on_change='append') and withdraws them cleanly when plan mode exits, leaving the earlier prompt-cache prefix intact. - In-run approval: registers
exit_plan_mode(summary='')(sequential=True), which raisesApprovalRequired. Approving it leaves plan mode, so the same run continues immediately under normal permissions. For staticPlanMode(), approval holds for the rest of the conversation and is recorded in history metadata for follow-up turns and durable replay (see Dynamic toggling andPermissionsfor dynamicactive=callbacks). Declining stays in plan mode and forwards optional feedback so the model can revise.
from pydantic_ai import Agent
from pydantic_ai.capabilities import HandleDeferredToolCalls, LocalWorkspace
from pydantic_ai_harness import FileSystem, PlanMode, Shell
from pydantic_ai_harness.plan_mode import (
PlanApprovalDecision,
PlanApprovalRequest,
plan_approval_ask,
)
async def approve(request: PlanApprovalRequest) -> PlanApprovalDecision:
answer = input(f'Approve plan?\n{request.summary}\n[y/N] ')
return PlanApprovalDecision(approved=answer.lower() == 'y')
agent = Agent(
'anthropic:claude-sonnet-5-5',
capabilities=[
LocalWorkspace('.'),
FileSystem(),
Shell(),
PlanMode(),
HandleDeferredToolCalls(plan_approval_ask(approve)),
],
)
Without a HandleDeferredToolCalls handler, the run pauses and returns the exit_plan_mode call as a DeferredToolRequests output, which requires DeferredToolRequests in output_type (extractable with plan_approval_requests(requests); see deferred tools). In durable engines without external event support (such as DBOS or Prefect; see Engines), use the two-parameter handler HandleDeferredToolCalls(lambda ctx, requests: ask_plan_approval(requests, approve)).
Pass a callable to active and an optional on_approve callback to drive plan mode from session state (as Pax does with /plan and Shift+Tab), allowing a conversation to re-enter plan mode on later turns:
from pydantic_ai import RunContext
from pydantic_ai_harness import PlanMode
state = {'planning': True}
def leave_plan_mode(ctx: RunContext[None]) -> None:
del ctx
state['planning'] = False
plan_mode = PlanMode(
active=lambda ctx: state['planning'],
on_approve=leave_plan_mode,
)
PlanMode orders itself outside Permissions so active plan-mode denials happen before permission prompts, and normal permissions take over automatically once approved.
How approval persists depends on active and on_approve:
- Static
PlanMode()(active=True): approval holds for the rest of the run (even across mid-run compaction), is remembered in-process perconversation_idfor the capability instance’s lifetime (long-lived multi-conversation servers should prefer dynamicactive=+on_approvebacked by session state), and is recorded underModelRequest.metadata'__pydantic_ai__'for trusted server-side follow-up runs and durable replay (sanitize_messagesstrips that namespace from untrusted client-supplied history). - Dynamic
active=with a flag-clearingon_approve: your state owns approval (including across durable replay), andPlanModewrites no marker so the same run can re-enter plan mode later. - Dynamic
active=withouton_approve(or with an observer-only callback that leavesactivetruthy):PlanModefalls back to run-scoped approval with arun_id-scopedplan_mode_approvedmarker for the rest of that run.
When combining static PlanMode() with compaction that drops or replaces the ModelRequest carrying plan_mode_approved across separate runs without conversation_id (or in durable workflows), use the dynamic active= + on_approve form above so dropping or replacing that request does not re-arm plan mode.
PlanMode guards FileSystem writes, shell-declared commands, CodeMode 'read-write' mounts, IPythonCodeMode, and non-read-only SubAgents delegations. Custom tools, MCP tools, and custom CodeMode os_access or external_modules handlers with their own side effects are not classified automatically; gate them with requires_approval=True, Permissions rules, a ToolGuardrail, or a read-only workspace when hard isolation is required.
On the open execute_tool span, PlanMode records:
| Attribute | Values |
|---|---|
plan_mode.decision | 'deny' or 'approve' |
plan_mode.action | 'write', 'command', 'delegate', or 'exit' |
PlanMode works with Pydantic AI’s agent spec:
# agent.yaml
model: anthropic:claude-sonnet-5-5
capabilities:
- PlanMode: {}
from pydantic_ai import Agent
from pydantic_ai_harness import PlanMode
agent = Agent.from_file('agent.yaml', custom_capability_types=[PlanMode])
Bases: CombinedCapability[AgentDepsT]
Planning mode that bundles Planning, filters mutating built-in tools while active, and exits in-run on approval.
While active, PlanMode denies FileSystem writes (write_file, edit_file, create_directory),
shell commands (tools with code_arg_language='shell' and code_arg_name), IPythonCodeMode cells,
and SubAgents delegations (plus message_task/answer_task calls) whose target delegate is not marked
read_only=True. CodeMode 'read-write' mounts are downgraded to 'read-only' while active. Other
custom tools, MCP tools, and custom CodeMode os_access or external_modules handlers are not
classified automatically. Read-only tools, planning tools, and read-only delegates remain available.
When the model finishes exploring and planning, it calls exit_plan_mode, which raises
ApprovalRequired so a
HandleDeferredToolCalls handler built with
plan_approval_ask(approver) (or a caller resuming with DeferredToolResults) can approve it in-run.
On approval, plan mode turns off for the rest of the conversation (or via on_approve for dynamic
active callbacks) and the same run continues immediately under normal permissions.
from pydantic_ai import Agent
from pydantic_ai.capabilities import HandleDeferredToolCalls, LocalWorkspace
from pydantic_ai_harness import FileSystem, PlanMode, Shell
from pydantic_ai_harness.plan_mode import PlanApprovalDecision, plan_approval_ask
async def approve(request):
return PlanApprovalDecision(approved=True)
agent = Agent(
'anthropic:claude-sonnet-4-6',
capabilities=[
LocalWorkspace('.'),
FileSystem(),
Shell(),
PlanMode(),
HandleDeferredToolCalls(plan_approval_ask(approve)),
],
)
def __init__(
active: bool | Callable[[RunContext[AgentDepsT]], bool] = True,
*,
planning: bool | Planning[AgentDepsT] = True,
instructions: str = DEFAULT_PLAN_MODE_INSTRUCTIONS,
on_approve: Callable[[RunContext[AgentDepsT]], None | Awaitable[None]] | None = None,
id: str | None = 'plan_mode',
) -> None
Build PlanMode, optionally bundling Planning alongside the read-only guard.
active : bool | Callable[[RunContext[AgentDepsT]], bool] Default: True
Whether plan mode starts active, or a callable queried on every request and tool call.
planning : bool | Planning[AgentDepsT] Default: True
Include Planning(). Pass a configured Planning(...) to share a store, or False
when planning is bound separately or omitted.
instructions : str Default: DEFAULT_PLAN_MODE_INSTRUCTIONS
Guidance stated while plan mode is active.
Optional sync or async callback invoked when the user approves exit_plan_mode.
Stable capability ID for the guard and its exit_plan_mode toolset.
@classmethod
def get_serialization_name(cls) -> str | None
Return the stable name used in agent specs.
@classmethod
def from_spec(
cls,
active: bool = True,
*,
planning: bool = True,
instructions: str = DEFAULT_PLAN_MODE_INSTRUCTIONS,
id: str | None = 'plan_mode',
) -> PlanMode[AgentDepsT]
Build the serializable configuration of PlanMode.
PlanMode[AgentDepsT]
Bases: AbstractCapability[AgentDepsT]
Filter write, shell, IPython, and non-read-only delegation tools, state plan-mode guidance, and expose exit_plan_mode.
Whether plan mode is active, or a function reading that state on each request and tool call.
Type: bool | Callable[[RunContext[AgentDepsT]], bool] Default: True
Instructions stated while plan mode is active, appended and withdrawn without rewriting earlier history.
Type: str Default: DEFAULT_PLAN_MODE_INSTRUCTIONS
Optional sync or async callback run when exit_plan_mode is approved.
Type: Callable[[RunContext[AgentDepsT]], None | Awaitable[None]] | None Default: None
Stable capability ID so the mode instruction block supports on_change='append' and merging.
Type: str | None Default: 'plan_mode'
def get_ordering() -> CapabilityOrdering
Run outside Permissions so plan-mode denials happen before permission prompts.
CapabilityOrdering
@async
def for_run(ctx: RunContext[AgentDepsT]) -> PlanModeGuard[AgentDepsT]
Return a per-run clone sharing this capability’s single toolset.
PlanModeGuard[AgentDepsT]
def is_active(ctx: RunContext[AgentDepsT]) -> bool
Whether plan mode is active for ctx right now.
def requires_read_only_mounts(ctx: RunContext[AgentDepsT]) -> bool
Downgrade writable CodeMode mounts while plan mode is active.
def get_instructions() -> Callable[[RunContext[AgentDepsT]], InstructionPart]
State instructions while active, and withdraw them with an append-only delta once off.
Callable[[RunContext[AgentDepsT]], InstructionPart]
def get_toolset() -> AgentToolset[AgentDepsT]
Provide the exit_plan_mode tool on a stable toolset matching self.id.
AgentToolset[AgentDepsT]
@async
def after_tool_validate(
ctx: RunContext[AgentDepsT],
*,
call: ToolCallPart,
tool_def: ToolDefinition,
args: dict[str, Any],
) -> dict[str, Any]
Hold exit_plan_mode for user approval before any execute hooks run.
@async
def after_node_run(
ctx: RunContext[AgentDepsT],
*,
node: AgentNode[AgentDepsT],
result: NodeResult[AgentDepsT],
) -> NodeResult[AgentDepsT]
Record the approval marker under ModelRequest.metadata['__pydantic_ai__'] for history and durable replay.
NodeResult[AgentDepsT]
@async
def before_tool_execute(
ctx: RunContext[AgentDepsT],
*,
call: ToolCallPart,
tool_def: ToolDefinition,
args: dict[str, Any],
) -> dict[str, Any]
Deny writes, commands, IPython cells, and writable delegations while active; exit on approval.
An exit_plan_mode call held until a person approves or asks to revise the plan.
The held exit_plan_mode call.
Type: ToolCallPart
The plan summary the model passed to exit_plan_mode, empty when omitted.
Type: str
The answer to one PlanApprovalRequest.
Leave plan mode and let the run proceed with normal permissions, or stay in plan mode to revise.
Type: bool
When not approved, optional feedback sent to the model so it can revise the plan.