Permissions
Ask a person before the agent writes files or runs commands, by permission mode, and allow, ask about, or deny tool calls and shell commands by rule.
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.
A coding agent’s FileSystem and Shell tools run with your permissions as soon as the model calls them. Sometimes that is what you want; sometimes you want to watch what the agent does and stop a rm -rf or a git push before it happens. Marking each tool requires_approval=True asks about every call, including the harmless ls, so the person stops reading the requests.
Permissions holds the calls a permission mode asks about and lets the rest run:
| Mode | File writes | Commands |
|---|---|---|
'full' (default) | run | run |
'auto' | run | run, unless they match ask_commands |
'read-only' | ask | ask |
A call that asks raises ApprovalRequired, so it uses the same deferred approval flow as requires_approval=True. Without a handler the run ends with the call in its DeferredToolRequests output. To ask a person inline instead, add a HandleDeferredToolCalls handler that calls ask_permissions with an approver:
from pydantic_ai import Agent
from pydantic_ai.capabilities import HandleDeferredToolCalls, LocalWorkspace
from pydantic_ai_harness.file_system import FileSystem
from pydantic_ai_harness.permissions import (
PermissionDecision,
PermissionRequest,
Permissions,
ask_permissions,
)
from pydantic_ai_harness.shell import Shell
async def approve(request: PermissionRequest) -> PermissionDecision:
answer = input(f'{request.reason}\n {request.subject}\nRun it? [y/N/always] ')
return PermissionDecision(approved=answer in ('y', 'always'), remember=answer == 'always')
agent = Agent(
'anthropic:claude-opus-5-5',
capabilities=[
LocalWorkspace('.'),
FileSystem(),
Shell(),
Permissions('auto'),
HandleDeferredToolCalls(handler=lambda ctx, requests: ask_permissions(requests, approve)),
],
)
ask_permissions asks about each held call in turn. A denied call does not run, and the model gets a tool result saying the user denied it, with the person’s reason when they gave one. A PermissionDecision with remember=True also lets later calls of the same tool on the same command or path run without asking, for the rest of the conversation (by the run’s conversation_id). That memory is the remembered set, which you can pass in to own: share it, clear it, or drop it with the conversation. It lives in this process, so inside a durable execution workflow the approval is kept in the message history instead, in the metadata of the approved call’s ToolReturnPart: it holds when the workflow replays, and in a later run given that history. Since a marker in the history skips asking, only pass in history you trust; compaction that drops the part makes the call ask again.
Approvals that other capabilities ask for, such as a tool registered with requires_approval=True, are left for the next handler.
- File writes are the
FileSystemtoolswrite_file,edit_file, andcreate_directory, recognized by their tool kind, so a renamed or prefixed tool is still recognized. They only reach files inside the file system’s root, so'auto'lets them run. - Commands are the tools whose metadata declares
code_arg_language='shell'and acode_arg_name, the argument holding the command, as theShelltools that take a command (run_command,start_command, andshell) do. - Sub-agents run only the capabilities that reach them. A delegate does not see a
Permissionspassed to the parent’s run, so pass it inSubAgents(shared_capabilities=[permissions, handler])to check delegates too. - Every other tool runs in every mode, unless a rule matches it. Gate a tool of your own with
requires_approval=True, aToolGuardrail, or aToolCallJudge.
ask_commands is a list of regular expressions, each searched for anywhere in the command. DEFAULT_ASK_COMMANDS asks about forced or recursive deletes (rm -rf), git push, git reset --hard and git clean, sudo, network clients (curl, wget, ssh, and others), package installs, dd, and mkfs. It is a convenience, not a sandbox: a command can do the same thing in a form no pattern matches, such as a script it writes first. Use a sandbox when the agent must not reach something.
rules allow, ask about, or deny calls by tool, arguments, and shell command, before the mode decides. A call no rule matches follows the mode:
from pydantic_ai_harness.permissions import PermissionRule, Permissions
permissions = Permissions(
'read-only',
rules=[
PermissionRule('allow', command='git status'),
PermissionRule('allow', command='rg'),
PermissionRule('ask', command='git push'),
PermissionRule('deny', command='rm -rf', reason='Delete files one at a time.'),
PermissionRule('allow', tools=['write_file'], args={'path': 'docs/*'}),
PermissionRule('ask', tools=['deploy'], args={'env': 'prod*'}),
],
)
A PermissionRule matches a call when every field it sets matches:
toolsis aToolSelector, as for other tool-scoped capabilities:'all'(the default), a list of names, a metadata match, or a predicate.argsmaps argument names to globs for their string values. Each value is matched as given and as a normalized path, sonotes/../secrets/keyis also matched assecrets/key. On a'windows'workspace both forms are compared case-insensitively, with/for separators. Symlinks are not resolved. An allow rule needs both forms to match. An ask or deny rule needs either, and also matches the end of a longer path, sosecrets/*covers/project/secrets/keyand../secrets/key. Values over 4096 characters aren’t globbed: ask and deny rules match them, and allow rules don’t.commandis the words of a shell command, described below. An allow rule that globs a shell tool’s command argument throughargsnever matches, since a glob would letgit status; python evil.pythroughgit *: usecommandto allow commands.
When several rules match, 'deny' beats 'ask', which beats 'allow', whatever their order, so a broad allow rule cannot override a deny rule.
'allow'runs the call without the'read-only'mode asking. A command that matchesask_commandsstill asks in'auto'and'read-only': remove a pattern fromask_commandsto let it run.'ask'holds the call like the mode does. A file write or command goes toask_permissionswith the rule’sreason. A call to any other tool is held with a plainApprovalRequired, likerequires_approval=True, with the rule’sreasonin its metadata.ask_permissionsdoes not ask about it and leaves it for the next handler, so add one, as shown below.'deny'refuses the call without running it, even when it was approved, for example by another capability’s approval. The model gets a tool result withoutcome='denied'saying a permission rule refused it, with the rule’sreason. A call that needs approval for another reason, such asrequires_approval=True, is put to the person before the rule refuses it.
A second handler answers the asks ask_permissions leaves, after it in the capabilities list:
from pydantic_ai import DeferredToolRequests, DeferredToolResults, RunContext
from pydantic_ai.capabilities import HandleDeferredToolCalls
async def approve_other_calls(ctx: RunContext, requests: DeferredToolRequests) -> DeferredToolResults:
return DeferredToolResults(
approvals={
call.tool_call_id: input(f'Run {call.tool_name}({call.args_as_dict()})? [y/N] ') == 'y'
for call in requests.approvals
}
)
other_calls = HandleDeferredToolCalls(handler=approve_other_calls)
A command rule only matches tools that declare a shell command argument (see Which calls are checked), and judges a compound command by each of its simple commands, split at ;, &&, ||, |, and &:
- A command runs by rule only when an
'allow'rule matches every simple command in it. An allow rule matches a simple command that starts with its words and has no redirection other than to/dev/nullor a file descriptor. SoPermissionRule('allow', command='git status')letsls && git status --shortrun whenlsis allowed too, but notgit status > ~/.bashrcorFOO=1 git status. - An
'ask'or'deny'rule matches a simple command that contains its first word followed by its other words in order, other words allowed in between. A short-option cluster such as-rfmatches the same options in any grouping or case (-fr,-Rf,-r -f). Sosudo rm -rf /andls; rm -fr /match'rm -rf',git -C repo pushmatches'git push', its first word also matches a path ending in it, such as/bin/rm, and a pattern with a literal character matches the words it could expand to, sosudo /bin/r[m] -rf xmatches too, while a bare*matches no rule word. - A rule also matches the text inside one quoted word, as in
sh -c "rm -rf /". That text may be data, such as a commit message or a search pattern, so a deny rule matched only there asks instead, andgit commit -m "push the fix"doesn’t match'git push', whose words come from two places. - Some commands are too complex to split: those with
$(expansions, substitutions, and$'...'quoting), backticks, quoted or escaped operators (echo '|'), brace expansion ({rm,-rf,x}), a pattern in a command name (/bin/r[m]), process substitution, subshells, here-documents, line breaks or carriage returns, or unbalanced quotes. Any command on a'windows'workspace is one too, since PowerShell quotes differently, and its words are compared ignoring case. Nocommandrule allows such a command. Its text is checked against the ask and deny rules with quotes removed, sopython -c 'a(); rm -rf x'still matches'rm -rf', as an ask since the match is in quoted text. When part of it is expanded by the shell ($or a backtick outside single quotes, brace expansion, a line continuation, or a pattern in a command name), a rule’s words could be hidden, so it asks whenever ask or deny command rules apply to the tool. Otherwise, with no rule matching, the mode decides, sogrep -E 'a|b' x.pyor a multi-line script runs in'full'with only a deny rule.
An allow rule trusts everything after its words, so allowing find also allows find . -delete: allow the narrowest commands you can. Deny rules match words, not behavior, so rm --recursive --force does not match 'rm -rf'. Rules are checked when a call is about to run, so calls to external tools, which your application runs, are not checked. Like ask_commands, rules are a convenience, not a sandbox.
In an agent spec, rules is a list of mappings of these fields (PermissionRuleSpec), with tools limited to the serializable forms.
mode can be a function of the run context. It is read on every call, so an application can switch modes while a run is going, and the run’s next call follows the new mode:
from pydantic_ai_harness.permissions import PermissionMode, Permissions
current: PermissionMode = 'read-only'
permissions = Permissions(lambda ctx: current)
Permissions emits no spans of its own. A held call shows up in core’s tool spans and in the run’s deferred tool requests and results, which carry the request’s subject and reason as metadata. A call a rule denies shows up in core’s tool span with the denial as its result, and in the history as a ToolReturnPart with outcome='denied'.
- Approval Reviewer: let a second model approve the low-risk calls that need approval.
- Tool Call Judge: let a second model block calls.
- Ask User: let the model ask a person multiple-choice questions.