Skip to content

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.

Source

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 FileSystem writes (write_file, edit_file, create_directory by tool kind), Shell commands (tools declaring code_arg_language='shell' and code_arg_name), IPythonCodeMode cells, and SubAgents delegations (plus message_task and answer_task calls) targeting delegates not marked read_only=True. Custom tools, MCP tools, and custom CodeMode os_access or external_modules handlers 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 keeps exit_plan_mode native outside run_code.
  • Planning: bundles Planning() by default (or accepts a configured Planning(...), or planning=False).
  • Cache-safe instructions: states DEFAULT_PLAN_MODE_INSTRUCTIONS via an append-only dynamic InstructionPart (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 raises ApprovalRequired. Approving it leaves plan mode, so the same run continues immediately under normal permissions. For static PlanMode(), approval holds for the rest of the conversation and is recorded in history metadata for follow-up turns and durable replay (see Dynamic toggling and Permissions for dynamic active= callbacks). Declining stays in plan mode and forwards optional feedback so the model can revise.

Quick start

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)).

Dynamic toggling and Permissions

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 per conversation_id for the capability instance’s lifetime (long-lived multi-conversation servers should prefer dynamic active= + on_approve backed by session state), and is recorded under ModelRequest.metadata'__pydantic_ai__' for trusted server-side follow-up runs and durable replay (sanitize_messages strips that namespace from untrusted client-supplied history).
  • Dynamic active= with a flag-clearing on_approve: your state owns approval (including across durable replay), and PlanMode writes no marker so the same run can re-enter plan mode later.
  • Dynamic active= without on_approve (or with an observer-only callback that leaves active truthy): PlanMode falls back to run-scoped approval with a run_id-scoped plan_mode_approved marker 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.

Telemetry

On the open execute_tool span, PlanMode records:

AttributeValues
plan_mode.decision'deny' or 'approve'
plan_mode.action'write', 'command', 'delegate', or 'exit'

Agent spec (YAML/JSON)

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])

API reference

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)),
    ],
)

Methods

__init__
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.

Returns

None

Parameters

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.

on_approve : Callable[[RunContext[AgentDepsT]], None | Awaitable[None]] | None Default: None

Optional sync or async callback invoked when the user approves exit_plan_mode.

id : str | None Default: 'plan_mode'

Stable capability ID for the guard and its exit_plan_mode toolset.

get_serialization_name

@classmethod

def get_serialization_name(cls) -> str | None

Return the stable name used in agent specs.

Returns

str | None

from_spec

@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.

Returns

PlanMode[AgentDepsT]

PlanModeGuard

Bases: AbstractCapability[AgentDepsT]

Filter write, shell, IPython, and non-read-only delegation tools, state plan-mode guidance, and expose exit_plan_mode.

Attributes

active

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

Instructions stated while plan mode is active, appended and withdrawn without rewriting earlier history.

Type: str Default: DEFAULT_PLAN_MODE_INSTRUCTIONS

on_approve

Optional sync or async callback run when exit_plan_mode is approved.

Type: Callable[[RunContext[AgentDepsT]], None | Awaitable[None]] | None Default: None

id

Stable capability ID so the mode instruction block supports on_change='append' and merging.

Type: str | None Default: 'plan_mode'

Methods

get_ordering
def get_ordering() -> CapabilityOrdering

Run outside Permissions so plan-mode denials happen before permission prompts.

Returns

CapabilityOrdering

for_run

@async

def for_run(ctx: RunContext[AgentDepsT]) -> PlanModeGuard[AgentDepsT]

Return a per-run clone sharing this capability’s single toolset.

Returns

PlanModeGuard[AgentDepsT]

is_active
def is_active(ctx: RunContext[AgentDepsT]) -> bool

Whether plan mode is active for ctx right now.

Returns

bool

requires_read_only_mounts
def requires_read_only_mounts(ctx: RunContext[AgentDepsT]) -> bool

Downgrade writable CodeMode mounts while plan mode is active.

Returns

bool

get_instructions
def get_instructions() -> Callable[[RunContext[AgentDepsT]], InstructionPart]

State instructions while active, and withdraw them with an append-only delta once off.

Returns

Callable[[RunContext[AgentDepsT]], InstructionPart]

get_toolset
def get_toolset() -> AgentToolset[AgentDepsT]

Provide the exit_plan_mode tool on a stable toolset matching self.id.

Returns

AgentToolset[AgentDepsT]

after_tool_validate

@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.

Returns

dict[str, Any]

after_node_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.

Returns

NodeResult[AgentDepsT]

before_tool_execute

@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.

Returns

dict[str, Any]

PlanApprovalRequest

An exit_plan_mode call held until a person approves or asks to revise the plan.

Attributes

call

The held exit_plan_mode call.

Type: ToolCallPart

summary

The plan summary the model passed to exit_plan_mode, empty when omitted.

Type: str

PlanApprovalDecision

The answer to one PlanApprovalRequest.

Attributes

approved

Leave plan mode and let the run proceed with normal permissions, or stay in plan mode to revise.

Type: bool

feedback

When not approved, optional feedback sent to the model so it can revise the plan.

Type: str | None Default: None