@yuru7/pi-ai-approval0.9.0
A fail-closed approval gate for Pi that classifies every covered tool call into six risk levels with an isolated AI reviewer and enforces per-level allow/ask/deny from local configuration.
Untested on omp
This is a pi package. No one has reported whether it works on omp yet. If you try it, add your result below.
Reports 0
No reports yet.
Readme
pi-ai-approval
English | 日本語
A fail-closed approval gate for Pi, the coding agent. An isolated AI reviewer classifies covered operations into six risk levels, and a local riskActions policy decides whether a tool call runs: allow, ask, or deny. Explicit Command Bypass rules can skip the intrinsic review of matching Bash commands.
The AI never decides the final outcome. It only assesses risk and explains what the operation does; the decision always comes from your local configuration, and anything the reviewer cannot classify is blocked.
How it works
Tool call
↓
AI review (isolated reviewer session)
↓
Risk level + instruction alignment + operation summary + rationale
↓
riskActions configuration
↓
allow ─────────→ execute
ask → Deny / Approve once / Approve & Bypass
Approve: execute this call
Approve & Bypass: configure scope and rules before approval
Deny: block
deny ─────────→ block
allowruns the tool call without confirmation.askoffers Deny (preselected), Approve once, and Approve & Bypass when there are validated candidates.askTimeoutSecondsdefaults tonull(no timeout); a deadline applies through final confirmation.denyblocks the tool call and returns the AI's rationale to the agent, together with instructions not to retry the same action through a workaround.
When available, the reviewer also uses the agent reasoning directly associated with the current tool call as supporting evidence. That reasoning is untrusted and does not prove the user authorized or requested the action. If the model or provider does not expose reasoning, the review uses only the conversation and the planned action.
Approve once affects exactly one call. Concurrent approval prompts are serialized.
Risk levels
Risk is the practical risk of running the action in the context of the user's current task: how much damage its failure, misuse, or unintended side effects could cause, how costly it would be to reverse, and how directly it implements what the user asked for. Alongside the risk level, the reviewer reports an instruction_alignment of direct, implied, weak, or unrelated.
Key principles:
- Ordinary development actions that directly implement the user's request, are narrowly scoped, and are easily reversible are
lowrisk — even when they modify project files. - Explicit user instruction reduces uncertainty, but it does not eliminate blast radius, irreversibility, production impact, or security consequences.
very_highandcriticalactions stay at that level even when explicitly requested.
| Level | Meaning |
|---|---|
very_low |
No state change: reading files, grep/find/ls, git status, checking test results or config values |
low |
Normal, limited, easily recoverable work implementing the request: editing requested sources, creating files, refactoring, formatters, local build/test, deleting build artifacts |
medium |
Aligned with the goal but with larger side effects or recovery: bulk changes, dependency updates, local DB migrations, dev service restarts, mild git history operations, out-of-project config, external service writes |
high |
Important data/environments/services affected, or a large leap from instruction to side effect: production/shared changes, force pushes, critical settings, DB data updates, firewall/IAM/network changes. Explicitly requested production work keeps a medium-to-high floor |
very_high |
Even when explicitly requested, blast radius, recovery cost, or irreversibility requires human re-verification: bulk production data operations, mass deletions, major IAM changes, protected-branch force updates |
critical |
Beyond normal agent auto-execution regardless of instruction: secret exfiltration, unrecoverable mass destruction, permanent security-mechanism disablement, broad privilege grants |
Worked examples: editing a file to fix the reported bug → low; installing a needed dependency → medium; a requested operation under /tmp → very_low/low (rm -rf /tmp/* at most medium; deleting /tmp itself → high); an explicitly requested plain local git commit → low (--amend and history rewrites stay medium or above); an unrequested git reset --hard → high (explicitly requested → medium); a production DB migration, even explicitly requested → high; bulk-deleting production data → very_high; sending secrets to an external URL, even if requested → critical.
Command Bypass
Bash calls normally receive a structured review of individual operations plus their interactions. A Command Bypass pattern skips only the intrinsic review of a matching command. A plain sequence made up only of matching commands and ordinary fixed shell assignments skips the reviewer entirely. For example, aws-safety * covers AWSI=aws-safety; $AWSI run; $AWSI write-path. The rule author takes responsibility for implicit interactions in that sequence, such as commands sharing a file. Redirects, substitutions, pipelines, and unmatched commands still require review, including any additional interaction risks. PowerShell and other tools do not support Command Bypass.
Patterns match argument by argument, not by string prefix. git status matches exactly two arguments (including the command name). git status * accepts zero or more additional arguments. Only a standalone final * acts as a wildcard. Quote a literal argument containing whitespace or a literal asterisk. Shell expansions and operators are not valid patterns. Use a narrow pattern: git * trusts the intrinsic side effects of any future Git subcommand and arguments.
When a reviewed command has a validated suggestion, choose Approve & Bypass to open the draft. In the TUI, Tab cycles scopes, Enter adds a line, Ctrl+S approves and registers all lines, and Esc returns to the approval prompt with Deny selected. In other interactive modes, use the scope and editor menu. Nothing is approved or registered until final confirmation succeeds. Invalid, empty or unrelated patterns and save failures leave the draft unregistered. Use Approve once to authorize this call without adding a rule.
| Scope | Storage |
|---|---|
| Session | In memory, until the Pi session resets |
| Project | .pi/pi-ai-approval.json in the Pi session's working directory |
| Global | ~/.pi/agent/pi-ai-approval.json (or the configured Pi agent directory) |
The three scopes are combined. Project rules are not inherited from parent directories. Use /pi-ai-approval bypass-rules to list rules, add or edit lines, remove individual rules, or clear a scope after confirmation. This replaces the former /ai-approval session-rules; natural-language rules are no longer supported and are not migrated.
{
"bypassCommands": ["git status *", "pnpm test *"],
"bypassCandidatesAskOnly": true
}
Set bypassCandidatesAskOnly to false to include eligible commands that were classified as allow in a call that already requires approval. The setting defaults to true, and the project value overrides the global value. Invalid rules disable Bypass for that scope and trigger a warning; the review continues. Other project approval settings still use the existing trusted-project file, .pi/ai-approval.json.
Analysis limits and trust
The analyzer uses unbash 6.0.5 and supports simple commands, scalar assignments and expansions, logical lists, pipelines, groups, subshells, substitutions, redirects, heredocs, functions and common branch/loop structures. For nested execution it parses simple literal bash -c/sh -c bodies and uncomplicated env/command wrappers; it does not inspect arbitrary external scripts. Arithmetic, arrays, advanced parameter expansions, brace expansions, bracket or extended globs, possible tilde expansion, and other unsupported or oversized syntax fall back to whole-command review without Bypass. Replacement Bash tools, custom shell paths, command prefixes, Windows, and identifiable shell startup overrides also use whole-command review.
Command Bypass is not a sandbox. Project Bypass settings are trusted without a prompt; anyone able to edit the file can change what is trusted. Executable resolution (including PATH and functions), executable or wrapper contents, and filesystem or runtime state between analysis and execution remain trust assumptions. The reviewer can misclassify risk. Treat rules as explicit trust in the command's behavior, use narrow patterns, and use an external sandbox such as ai-jail when you need enforced isolation.
Configuration
The standard global configuration file is ~/.pi/agent/pi-ai-approval.json. If it is absent, the extension reads ~/.pi/agent/ai-approval.json instead. If both exist, the extension warns and reads only pi-ai-approval.json. It does not rename either file. The first Global Bypass save copies active legacy settings into the new standard file if needed, so existing policy settings remain effective.
For trusted projects, the project configuration is still .pi/ai-approval.json. Project settings can only make the policy stricter; they cannot weaken it. If neither a global nor a project configuration exists, the extension warns on startup and suggests running /pi-ai-approval init to create one; built-in defaults stay active until then.
{
"primaryModel": "CURRENT",
"primaryThinkingLevel": "low",
"secondaryModel": "CURRENT",
"secondaryThinkingLevel": "low",
"timeoutMs": 90000,
"askTimeoutSeconds": null,
"reviewOriginalCommand": false,
"riskActions": {
"very_low": "allow",
"low": "allow",
"medium": "ask",
"high": "deny",
"very_high": "deny",
"critical": "deny"
}
}
Review before command-rewriting hooks
Set "reviewOriginalCommand": true in the global configuration to review the assistant's original Bash or PowerShell command instead of the input rewritten by an earlier tool_call hook. The default is false, which reviews the command received by AI Approval. Project configuration cannot change this setting.
Load rewriting extensions (such as pi-rtk-optimizer) before AI Approval. This option does not change hook order or undo rewrites. It trusts earlier hooks to preserve the command's intent; enable it only with rewriters you trust. The actual execution input is locked after approval, so later hooks cannot rewrite it. Commands typed directly by the user are not affected.
Without a unique matching call in the current assistant message, AI Approval reviews the received input. If the rewritten command contains a detectable private-data reference, AI Approval reviews the execution command with private-data restrictions instead. Access to Pi's auth.json remains blocked. When the reviewed command differs from the execution command, confirmation shows both; rewrites detected in this mode cannot match or register Command Bypass rules.
riskActions
| Key | Allowed values | Default |
|---|---|---|
very_low, low, medium, high |
allow, ask, deny |
allow, allow, ask, deny |
very_high, critical |
ask, deny |
deny, deny |
very_high and critical cannot be set to allow. If you try, the config parser warns and uses deny.
To confirm every non-trivial action with a human, use:
{
"riskActions": {
"very_low": "allow",
"low": "allow",
"medium": "ask",
"high": "ask",
"very_high": "ask",
"critical": "ask"
}
}
Reviewer models
primaryModel and secondaryModel configure the two-step reviewer chain; the current session model always remains the last-resort third channel. Both settings accept either an explicit provider/model-id or the special value CURRENT — which is also the default, meaning "use the current session model".
A model that appears more than once in the chain is tried only once: the first channel that resolves to it owns the attempt and later duplicates are skipped, so a temporarily unavailable model is never requested repeatedly. Duplicate detection uses the model only; thinking levels never create a separate channel. For example, with primaryModel: "openai/gpt-5.6-luna" failing and secondaryModel: "openai/gpt-5.6-luna", the secondary is skipped even when their thinking levels differ. If every distinct channel fails, the action is blocked — the risk is never guessed.
Reviewer thinking levels
primaryThinkingLevel and secondaryThinkingLevel set the thinking effort for each reviewer channel. Allowed values are off, minimal, low, medium, high, xhigh, max, and the special value CURRENT — which inherits the current session's thinking level at review time. The default is low. When CURRENT is set but the session thinking level is unavailable, low is used. The last-resort current-model channel always uses the session's thinking level (or low when unavailable).
{
"primaryThinkingLevel": "low",
"secondaryThinkingLevel": "CURRENT"
}
Environment overrides (PI_AI_APPROVAL_PRIMARY_MODEL, PI_AI_APPROVAL_SECONDARY_MODEL, PI_AI_APPROVAL_PRIMARY_THINKING_LEVEL, PI_AI_APPROVAL_SECONDARY_THINKING_LEVEL, PI_AI_APPROVAL_TIMEOUT_MS, PI_AI_APPROVAL_POLICY) are also supported.
Ask timeout
askTimeoutSeconds is how long an approval prompt waits, in seconds. The default null does not time out. 0 and negative numbers are the same as null. A positive number counts down on the prompt, in whole seconds, and declines the action when it reaches zero. That decline blocks the tool call.
{
"askTimeoutSeconds": 30
}
A trusted project file overrides the global file, including an explicit null. timeoutMs is a different setting: it limits the reviewer, not the approval prompt.
Assessment language
assessmentLanguage controls the language of the reviewer's action_summary and rationale (shown in the approval prompt and rejection reasons). The default auto follows the user's primary conversation language. Set a fixed language name to pin it:
{
"assessmentLanguage": "Japanese"
}
Project settings override the global setting.
Fail-closed guarantees
The following all block the tool call, without ever showing an approval prompt:
- reviewer timeout, failure, cancellation, or unparseable output
- an unknown risk level in the reviewer response
- all reviewer channels failing
- the approval prompt being dismissed or unavailable
Invalid structured results, including missing operation IDs, never trigger automatic approval. A failed Bypass save never approves the call.
A denial circuit breaker stops runaway retry loops: repeated adverse outcomes (denials, declined approvals, review failures, timeouts) within one turn abort the agent turn.
Review scope
Which tool calls get reviewed is controlled by review rules (tool parameter → scope), independent of the risk policy:
{
"review": {
"bash.command": "always",
"powershell.command": "always",
"read.path": "outside-or-private",
"grep.path": "outside-or-private",
"write.path": "outside-or-private",
"edit.path": "outside-or-private"
}
}
Built-in defaults are bash.command: always and powershell.command: always; read.path, grep.path, write.path, edit.path: outside-or-private; find.path, ls.path: private-only.
Rule keys are <tool>.<parameter>: bash.command/powershell.command route the command string of every bash/PowerShell call, read.path/grep.path/find.path/ls.path route the read or search scope, and write.path/edit.path route the file being modified. Tools without a built-in rule but with a top-level string path parameter (for example custom_reader.path) are supported too and default to private-only.
Scope values
| Scope | A call is reviewed when… |
|---|---|
off |
Never — the tool/parameter is not reviewed at all. |
private-only |
The target path is classified as private data. |
outside-or-private |
The target path resolves outside the project root or is private. For write/edit, security-relevant in-project files also count. |
always |
Always, regardless of the target. |
"Private" is decided by a deterministic rule catalog: credential and secret files (.env*, key files, auth.json, token stores, browser login data, …), private directories outside the project (.ssh, .gnupg, .aws/.kube/cloud-CLI configs, browser profiles, Pi agent data, …) and, for the search tools, directory scopes or globs that may contain such files. For write/edit, "sensitive" additionally covers security-relevant in-project targets such as CI workflows, container/deploy manifests, dependency lockfiles, shell profiles, key material (.pem, .key, …) and sensitive directory segments (.git, secrets, terraform, k8s, …).
Pi's global configuration directory (getAgentDir()) and the OS temporary directory (tmpdir()) are exempt from private classification. Outside-project and sensitive-mutation rules still apply. The global configuration directory's auth.json is protected: detected reads and writes are blocked before AI review, even if review is off or bypassed. Shell checks are best-effort path detection, not a sandbox for arbitrary shell code.
bash.command and powershell.command are special: they route a command string rather than a path, so only off skips them — every other scope reviews each of those shell commands (commands that reference private data are reviewed in a restricted no-tool mode).
Being reviewed does not mean being blocked: a reviewed call goes to the AI reviewer, which classifies its risk level, and your riskActions config then decides allow/ask/deny.
Commands
/pi-ai-approval— status: reviewer channels, timeout, config paths, warnings/pi-ai-approval init— write the default configuration file (chooses global/project; asks before overwriting an existing file)/pi-ai-approval rules— the review matrix and the effective risk actions/pi-ai-approval bypass-rules— manage Command Bypass rules for all three scopes/pi-ai-approval bypass//pi-ai-approval enable— temporarily disable/restore review (interactive TUI only, with a persistent warning)
Install
pi install npm:@yuru7/pi-ai-approval
Development
pnpm install
pnpm typecheck
pnpm test
Acknowledgments
This project was created with inspiration from pi-approval-guardian.