@agent-corpus/policy-manager 0.9.0 → 0.11.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 +126 -29
- package/dist/adapters.d.ts +3 -1
- package/dist/adapters.js +37 -18
- package/dist/classifier.d.ts +98 -0
- package/dist/classifier.js +343 -0
- package/dist/cli.js +66 -7
- package/dist/config.d.ts +2 -0
- package/dist/config.js +6 -2
- package/dist/evidence.d.ts +1 -0
- package/dist/evidence.js +60 -0
- package/dist/flow.d.ts +4 -0
- package/dist/flow.js +91 -18
- package/dist/gitalias.d.ts +13 -0
- package/dist/gitalias.js +33 -0
- package/dist/grants.d.ts +9 -9
- package/dist/grants.js +46 -30
- package/dist/hard.d.ts +63 -0
- package/dist/hard.js +1637 -0
- package/dist/helpers.d.ts +59 -0
- package/dist/helpers.js +304 -0
- package/dist/merged.d.ts +6 -0
- package/dist/merged.js +23 -0
- package/dist/nativerules.d.ts +44 -0
- package/dist/nativerules.js +653 -0
- package/dist/permissive.js +179 -7
- package/dist/policy.d.ts +12 -0
- package/dist/policy.js +228 -45
- package/dist/profile.d.ts +7 -0
- package/dist/profile.js +32 -1
- package/dist/prompt.d.ts +32 -0
- package/dist/prompt.js +334 -0
- package/dist/reads.d.ts +46 -0
- package/dist/reads.js +812 -0
- package/dist/replay.d.ts +42 -0
- package/dist/replay.js +174 -1
- package/dist/service.d.ts +12 -1
- package/dist/service.js +23 -6
- package/dist/session.d.ts +76 -13
- package/dist/session.js +373 -116
- package/dist/shell.d.ts +2 -0
- package/dist/shell.js +1 -1
- package/dist/shellscan.d.ts +58 -0
- package/dist/shellscan.js +395 -0
- package/dist/statepaths.d.ts +41 -0
- package/dist/statepaths.js +706 -0
- package/dist/types.d.ts +11 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
# @agent-corpus/policy-manager
|
|
2
2
|
|
|
3
|
-
A coding-agent-independent permission evaluator. It starts a private background service for each session, verifies ordinary code operations and cloud inspection commands, and records requests and decisions in a temporary audit log. Uses the shared `@agent-corpus/audit-log` package and
|
|
3
|
+
A coding-agent-independent permission evaluator. It starts a private background service for each session, verifies ordinary code operations and cloud inspection commands, and records requests and decisions in a temporary audit log. Uses the shared `@agent-corpus/audit-log` package and calls no model API itself.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
Every request goes through three steps (see **How a request is decided**): a deterministic engine approves what it can prove safe; otherwise the hook asks an AI classifier, run through the user's own logged-in harness CLI, and approves what it judges recoverable; otherwise it asks the person and waits, and remembers a "yes" for the session.
|
|
6
6
|
|
|
7
7
|
## Usage
|
|
8
8
|
|
|
@@ -25,7 +25,7 @@ policy-manager config copilot /absolute/reviewed/install/dist/cli.js
|
|
|
25
25
|
|
|
26
26
|
Use the generated absolute installed path. Do not point approval hooks at a mutable worktree or an unpinned `npx` download. Keep native sandboxes and interactive approval modes enabled. Existing host grants and other hooks can authorize actions independently; this service does not revoke them.
|
|
27
27
|
|
|
28
|
-
The `SessionStart` hook starts one
|
|
28
|
+
The `SessionStart` hook starts one service per session and tells the agent, in one line, how requests are decided. It does not ask the agent to classify anything: classification happens inside the hook.
|
|
29
29
|
|
|
30
30
|
## Install native hooks
|
|
31
31
|
|
|
@@ -46,7 +46,9 @@ Setup also installs a small launcher named `pm` that runs this CLI, so a user ca
|
|
|
46
46
|
|
|
47
47
|
`--dry-run` prints the target path, proposed managed hooks, and next steps without writing files or printing existing settings. `--config-dir <directory>` selects a harness configuration root for portable profiles or testing. Defaults respect `CLAUDE_CONFIG_DIR`, `CODEX_HOME`, and `COPILOT_HOME`, then use the standard user directories listed above. Setup refuses to activate an entrypoint inside a Git checkout, including an npm link into a checkout. Source builds can preview with `--dry-run`.
|
|
48
48
|
|
|
49
|
-
Start a new session after setup. Codex still requires explicit review and trust through `/hooks`; setup does not grant that trust. Existing sandbox controls and host permission rules continue to apply.
|
|
49
|
+
Start a new session after setup. Codex still requires explicit review and trust through `/hooks`; setup does not grant that trust. Existing sandbox controls and host permission rules continue to apply.
|
|
50
|
+
|
|
51
|
+
Every managed hook gets an explicit timeout of 45 seconds (Codex `SessionEnd`: 3, its limit), above the classifier's own timeout (15 s for Claude and Codex, 20 s for Copilot) plus the service's wait. This matters most for Copilot, whose default hook timeout is 30 seconds and whose command hooks fail open on a timeout. Setup also adds `PostToolUse` and, for Claude Code and Copilot, `PostToolUseFailure`, which remember a person's answer (step 3).
|
|
50
52
|
|
|
51
53
|
### Codex hook trust
|
|
52
54
|
|
|
@@ -74,47 +76,108 @@ Pass one JSON object on standard input:
|
|
|
74
76
|
}
|
|
75
77
|
```
|
|
76
78
|
|
|
77
|
-
Run `policy-manager review codex session-example`. The response includes `decision` (`approve`, `human`, `deny`, or `native` for
|
|
79
|
+
Run `policy-manager review codex session-example`. The response includes `decision` (`approve`, `human`, `deny`, or `native` for no decision, which leaves the request to the harness), `category`, `reason`, `requestHash`, `cache`, and `cached`. It runs the same three steps as the hooks. The library exports the evaluator.
|
|
80
|
+
|
|
81
|
+
Categories are `code-read`, `worktree-write`, `temp-write` (a recoverable write outside any repository), `cloud-read`, `git-read`, `impactful-write`, `destructive`, `sensitive`, and `unknown`.
|
|
82
|
+
|
|
83
|
+
`policy-manager classify <harness> <session-id>` still accepts a recorded classification (`{requestHash, category, confidence, recoverable, rationale}` on standard input) for a request a person was asked about, for compatibility. Nothing asks an agent to run it any more.
|
|
84
|
+
|
|
85
|
+
## How a request is decided
|
|
86
|
+
|
|
87
|
+
1. **The deterministic engine** approves what it can prove safe (see **Policy** and **Policy profiles**), and plain reads (below). The deterministic floor (below) runs after it: no engine rule approves a floor item, which asks instead. A file tool (Write, Edit, MultiEdit, NotebookEdit, a patch) is judged by its target path only; the text it writes is data. As the script's first command, `cd` into an absolute directory that exists and can be entered does not fail, so what follows it runs there however it is joined (`cd /x && a; b`); a `cd` later in a script may still fail.
|
|
88
|
+
2. **The user's own rules.** The harness permission rules the user wrote (below) are checked next, so an allowed command never waits on a classifier run. A deny or ask rule, from any level, leaves the request to the harness (no decision). An allow rule counts as the person's answer and approves, except for the items no allow rule approves (below).
|
|
89
|
+
3. **The AI classifier, in the hook.** Anything else the engine escalates is classified synchronously, inside the hook, by the harness's own CLI (below). The request is approved when the answer is `recoverable` with `confidence >= 0.95` and a category other than `sensitive` or `unknown`. Hard human items skip this step.
|
|
90
|
+
4. **The person.** Otherwise the person is asked and the harness waits. Claude Code and Copilot ask in their own prompt. Codex cannot ask: it gets a deny with `pm approve --last` and stops (see **Approving from the terminal**). Under Claude Code, a "yes" can be remembered for that exact request (see **Remembering an answer**).
|
|
91
|
+
|
|
92
|
+
**No allow rule, at any level, approves** credential or secret reads; writes to harness settings, hooks or permission files (`.claude/settings*.json`, `.claude/hooks`, `.codex/config.toml`, `.codex/rules`, Copilot configuration, the policy profile); or a force push (`-f`, `--force`, `--force-with-lease`, `--force-if-includes`, `--mirror`, a `+` refspec, combined short flags such as `-uf`), however the rule is written, even `Bash(git push --force *)`. These are the places the policy manager is stricter than the user's allow rule: the person is asked (under Codex, a deny with `pm approve --last`). A Write, Edit or patch to harness settings or the policy profile is never approved by any step, the engine's included.
|
|
93
|
+
|
|
94
|
+
### Hard human items
|
|
95
|
+
|
|
96
|
+
These go straight to the person. They are never sent to the classifier, and no classification approves them:
|
|
97
|
+
|
|
98
|
+
- credential or secret retrieval, and reads of credential paths;
|
|
99
|
+
- protected configuration: the policy profile, harness settings and hooks (`.claude/settings*.json`, `.claude/hooks/`, `~/.claude.json`, `.codex/config.toml`, `.codex/hooks.json`, `.codex/hooks/`, `.codex/rules/`, `.copilot/config.json`, `.copilot/settings.json`, `.copilot/hooks/`, `.github/hooks/`, including under `CLAUDE_CONFIG_DIR`, `CODEX_HOME` and `COPILOT_HOME`), and protected repository paths;
|
|
100
|
+
- unrecoverable loss: force and mirror pushes and `+` refspecs, deleting a branch whose tip exists only locally, forced worktree removal and `git worktree prune`, and `git clean`. Deleting a branch whose tip is on a remote-tracking ref loses nothing and is approved by the engine;
|
|
101
|
+
- **the deterministic floor under the classifier**: cloud and infrastructure writes and deletes (`az`, `aws` and `gcloud` without a read verb such as `list`, `show` or `get`, where `az rest` and `az devops invoke` read unless a method other than GET is given; `kubectl`, `oc`, `helm`, `terraform`, `tofu`, `terragrunt`, `pulumi`, `eksctl` write verbs); HTTP writes (`curl`, `wget`, httpie, `Invoke-RestMethod`/`Invoke-WebRequest` with a method other than GET or HEAD, or a body, form or upload that implies one) to any target but an explicit loopback host (`localhost`, `127.x.x.x`, `::1`), a bare host, a variable or a missing URL included; GitHub writes that cannot be taken back, and changes to what `gh` runs or which credentials it uses: `gh repo create|fork|delete|archive|unarchive|rename|edit`, `gh release create|edit|upload|delete`, `gh gist create|edit|delete`, `gh secret set|delete`, `gh variable set|delete`, `gh extension install|upgrade`, `gh alias set|import`, `gh config set`, `gh auth refresh|login|logout|setup-git|token`, `gh pr merge`, `gh workflow run|enable|disable`, `gh run rerun`, and every `gh api` write (a method other than GET or HEAD, or fields, which make it a POST) except a short allow-list of recoverable PR and issue conversation that goes to the classifier: issue and PR comments (create, edit), review comments and replies, reviews (create, update, submit), labels and assignees, and PR create and edit without a `state`. Any GraphQL mutation outside `addComment`, `updateIssueComment`, `addPullRequestReview`, `addPullRequestReviewComment`, `addPullRequestReviewThreadReply`, `updatePullRequestReviewComment`, `submitPullRequestReview`, `resolveReviewThread`, `unresolveReviewThread`, `createPullRequest`, `updatePullRequest` (without `state`), `addLabelsToLabelable`, `removeLabelsFromLabelable`, `addAssigneesToAssignable` and `removeAssigneesFromAssignable` is a floor item too, and so is an endpoint or query it cannot read (a variable, `query=@file`, `--input` to GraphQL). The one exception is a comment or reply POST with fields whose only variable parts are numeric-id segments (`repos/o/r/pulls/7/comments/$id/replies -f body=...`), which goes to the classifier. Known limit: the variable's own value is not checked (`ID='1/../../x'` changes the path once the API normalizes it); the endpoint still has to end in `/comments` or `/replies` and be a POST with fields. Options are read anywhere after the endpoint: `-X`/`--method`, a header that overrides the method (`X-HTTP-Method-Override`) or is not literal, and an unquoted expansion such as `$EXTRA` (which can split into `-X DELETE`) are floor items. That includes an unquoted variable in a field value (`-f body=$BODY`): word splitting can inject options, so agents should quote it (`-f body="$BODY"`). `gh repo deploy-key add|delete`, `gh ssh-key add|delete`, `gh gpg-key add|delete`, `gh issue delete|transfer` and `gh codespace` writes (`create`, `delete`, `edit`, `stop`, `rebuild`, `cp`, `ssh`, `ports`) are floor items too. Merging, workflow dispatch, deployments, rulesets, transfers, memberships, secrets, variables and repository settings all ask; GraphQL queries are reads; package publishing (`npm`, `pnpm`, `yarn`, `cargo`, `twine`, `gem`, `poetry`, `dotnet nuget push`, `docker`/`podman push`); and a recursive `rm`, `find -delete` or `find -exec rm` outside a linked feature worktree, the temp directory and the profile's `scratchRoots`, including any glob or brace expansion in the home directory. These are found through `eval`, `sh -c`, `xargs`, `env`, `nohup`, `timeout`, `watch` and the bodies of unquoted here-documents. None of them is provably recoverable, so one model call is not enough. The floor is a list of known verbs and programs, so it is best-effort, not complete: a program named through a variable (`X=az; $X group delete`), a `make` target, an `ssh` command, `git -C <other repo> reset --hard`, or interpreter code that deletes files (`python3 -c 'shutil.rmtree(...)'`, `node -e`) is not recognized and is left to the classifier.
|
|
102
|
+
- the policy service's own state: any write, move, delete, truncation, permission change or redirection into an `acp-<uid>-*` session directory in the temp directory (audit logs, token, socket, grants, cache), by a shell command or a file tool. Targets are matched as the shell would expand them, against the real state directories and a sample `acp-<uid>-...` name: a glob (`acp-*`, `a*p-501*`, `[a]cp-?01-*`), a variable (`$TMPDIR` filled in, anything else read as `*`), and for a delete or move any directory above the state (`rm -rf "$TMPDIR"`). `find` with `-delete` or `-exec` counts when it starts in or above a state directory and its `-name`/`-path` filters can match on the way down (a `-regex`, or no filter, fails closed). `xargs` into a writer counts when it runs where the state lies or the script names `acp` or a path that could reach it, and inline interpreter code (`python3 -c`, `perl -e`, `node -e`, a here-document) counts when it names `acp`, or when it deletes, moves or writes files and either computes the temp directory at run time (`os.environ['TMPDIR']`, `tempfile.gettempdir()`, `os.tmpdir()`) or names a path that could reach the state the way a shell target does: a state directory, a directory above one, a glob matching one, or a path built at run time (`f'/tmp/{x}'`, `'/tmp/' + x`). A literal path into another directory in temp (`/tmp/pm-x/notes.md`) does not count. Every file call that deletes, moves, copies, writes, changes permissions or enters a directory (Python `os`/`shutil`/`pathlib`, Node `fs`, Ruby `File`/`FileUtils`/`Dir`, Perl and PHP builtins) must name its path as one plain string literal, or a variable assigned one exactly once: a path built with concatenation, `chr()`, `os.sep`, `join`, an f-string or template, or taken from `listdir`/`walk`/`readdir`/`glob` counts as reaching the state, since the state lies in temp. State paths are listed under both the temp directory as the system gives it (`/var/folders/...` on macOS) and its real path (`/private/var/folders/...`), so a glob written against either form matches. File calls are recognized by method name whatever the receiver (`require('fs').rmSync(x)`, `require('fs/promises').rm(x)`, `__import__('os').remove(x)`, an `import os as o` alias); dynamic import or attribute indirection (`__import__`, `importlib`, `getattr`, `require(x)`, `eval`, `exec`, `Function`, `send`) together with a temp lookup or a path built at run time fails closed. awk's `system("...")`, `print | "..."` and `"..." | getline` run literal commands, which are judged like `sh -c`; a command that is not a literal string, or output piped into a shell or interpreter, is `opaque-script`. Interpreter detection is best-effort: an agent can always hide intent in code, so the classifier, which reads the whole command, is the second line for anything this does not catch. `chmod`/`chown`/`chgrp -R` count like a delete, and an archive extracted into a directory above the state (`tar -x -C`, `unzip -d`, `cpio -i`) counts too. Only reading the audit logs is allowed (see **Plain reads**). No engine rule, user allow rule or session grant approves it, and the classifier prompt also calls any change to `acp-*` sensitive. Matching is linear: brace expansions are found in one pass, and a word or pattern over 4,096 characters, or inline code over 100,000, fails closed. A shell command over 100,000 characters is asked at once, before any parsing, and one with more than 1,000 words (here-document bodies aside) before the engine judges it; an evaluation that runs past 5 seconds stops between commands and asks;
|
|
103
|
+
- commands matching the profile's `humanPatterns`;
|
|
104
|
+
- `opaque-script`: a script fed to a shell or interpreter that the policy cannot read. The stage a pipe feeds is the piped command and, when it opens a group (`( ... )`, `{ ...; }`, `if`, `while`, `for`, `case`), every command inside the group; a here-string or redirected standard input feeds its own command. If any command there reads its script from standard input, the input decides: a literal `echo`, `printf`, quoted here-document or here-string is unwrapped (a shell's script gets the floor and every hard rule, as with `sh -c`; an interpreter's code gets the interpreter rule above), and anything else is `opaque-script`. A command reads its script from standard input when it is a shell (`sh`, `bash`, `zsh`, `dash`, `ksh`, `mksh`, `yash`, `ash`, `rbash`, `fish`, `csh`, `tcsh`, `nu`, `elvish`, `xonsh`, `busybox sh`) with no script operand or with `-s`, a shell whose `-c` script contains such a command (`bash -c 'sh'`), `source /dev/stdin`, or an interpreter with no code flag or script. PowerShell, a shell run by `xargs`, a `-c` script that is not literal (`sh -c "$l"`), and `. <(...)` are always `opaque-script`. Examples: `cat x.sh | sh`, `curl ... | bash`, `sh < x.sh`, `cat x | (cd /tmp && sh)`, `cat x | while read l; do sh -c "$l"; done`, `bash -s <<< "$X"`, `echo $CMD | sh`. awk output redirections (`print > "f"`, `>>`), sed `w`/`W`/`s///w`, ex and vim `-c 'w file'`, ed's `w` and sqlite3 `.output`/`.once`/`.save`/`.backup` get the checks a shell redirection does (the policy state, protected configuration); a target that is not a literal is `opaque-script`;
|
|
105
|
+
- an agent running `approve` itself, or any `classify` record command.
|
|
106
|
+
|
|
107
|
+
The floor finds a CLI's command words past its global options: `gh pr -R o/r merge 1`, `gh -R o/r pr merge 1`, `kubectl -n prod delete pod x`, `helm -n x uninstall app`, `aws --profile p s3 rm ...`, `gcloud --project p ... delete` and `npm --registry r publish` are floor items like the plain forms. Known global options (`-R`/`--repo`, `--hostname`, `-n`/`--namespace`, `--context`, `--kubeconfig`, `--profile`, `--region`, `--project`, `--subscription` and the like, with `--name=value` forms) and their values are skipped. An option the CLI is not known to take before its command fails closed: for `gh`, `kubectl`, `helm` and the publishers every later word is then a possible verb, and for `az`, `aws` and `gcloud` the command is a cloud write.
|
|
108
|
+
|
|
109
|
+
The check reads the command the way the shell runs it: quotes and backslashes removed, `eval`, `sh -c` and `$(…)` bodies read as commands, wrappers (`env`, `sudo`, `timeout`, `xargs`, …) skipped, `cd` targets followed for relative paths, and Git aliases resolved with a read-only `git config --get alias.<name>`. Data is not code: the body of a here-document with a quoted delimiter written to a file (`cat > f <<'EOF'`), a commit message or a PR body is not scanned as commands (with an unquoted delimiter, its `$(…)`, backtick and `${…}` expansions run, so they are scanned as commands), unless the script runs text somewhere (a shell, an interpreter, `eval`, `xargs`, `find`, `sed` with GNU `e`, `awk` with `system(` or a command pipe...), as in `cat <<EOF | sh`, `bash <<EOF` or `python - <<EOF`; then a plain-text reading of the whole command is unioned in, so a script piped into a shell or inline interpreter code still counts. A false match asks rather than approves. Requests the classifier cannot judge from what it is shown (an incomplete request, another working directory, an unreadable patch, a custom environment) also go to a person.
|
|
110
|
+
|
|
111
|
+
### Plain reads and read-only chains
|
|
112
|
+
|
|
113
|
+
Plain reads are approved by the engine, protected configuration included. `cat`, `ls`, `grep`, `rg`, `head`, `tail`, `find`, `git grep` and the read-only git commands (`git show`, `git log`, `git diff`, `git status`...), alone, joined by `&&`, `||`, `;` or piped into one another and into read-only filters (`sed` without `-i` and without a command that writes or runs, `awk` without `system`, `getline`, pipes or `>`, `sort` without `-o`, `uniq`, `wc`, `cut`, `tr`, `jq`, `nl`, `column`), with an optional `cd <dir>`, and the Read tool, are approved under a checkout's own `.claude`, `.codex`, `.agent-config`, `.github`, `AGENTS.md` and `CLAUDE.md` as anywhere else in it. The read must be tight:
|
|
114
|
+
|
|
115
|
+
- options are allow-listed per program; any other option (`rg --pre`, `rg --hostname-bin`, `rg -u`/`--hidden`/`--no-ignore`, `git grep -O`/`--open-files-in-pager` or an abbreviation of it, `git grep --untracked`/`--no-index`, `find -exec`/`-delete`) is not a plain read;
|
|
116
|
+
- no command substitution, variables, assignments, globs (except `git grep` pathspecs), here-documents, or redirections other than `2>/dev/null`, `2>&1` and `<` from a file;
|
|
117
|
+
- every named path is inside a Git checkout, the system temp directory, a profile `scratchRoots` entry, or Claude Code's auto-memory (`<CLAUDE_CONFIG_DIR or ~/.claude>/projects/*/memory/`). Nothing else under the home directory is a plain read: agent transcripts and history (`~/.claude/history.jsonl`, `~/.claude/projects/*/*.jsonl`, `~/.codex/sessions`, `~/.copilot/session-state`), `~/.config`, `~/.local` and shell history go the normal way. The policy service's own audit logs (`audit.jsonl`, `audit.N.jsonl`) in this user's session directories (`<temp>/acp-<uid>-*`, an absolute path directly under the real temp directory) are plain reads, with a glob allowed only in the `acp-<uid>-` part; a glob naming the directories themselves is allowed only for `ls` and `find`. A relative path, another user's directory, the token and the socket are not plain reads, and writing, moving or deleting any of them is a hard item. None is a secret: credential files (`.env`, keys, `.git`, `credentials`, `auth.json`), harness settings that can hold tokens (`settings*.json`, `.claude.json`, `config.toml`, `config.json`, `hooks.json`, `permissions-config.json`) or the policy profile;
|
|
118
|
+
- a recursive search may not reach a secret: `grep -r` walks the directory (unless `--exclude`/`--exclude-dir` leave the secrets out), `rg` walks it skipping hidden entries, and `git grep` refuses a checkout that tracks a credential file (a `.env`, a key, a state file; a committed `.npmrc` or `.env.example` is configuration). Quoted `git grep` pathspecs (`'src/**'`) are Git's and are read-only.
|
|
119
|
+
|
|
120
|
+
A chain whose commands before the last only read (`git status`, `git fetch`, `git log`, `git show`, `git grep`, the readers above, `sed -n <range>p`, `sort`, `uniq`, `wc`, `cut`, `jq`..., a `cd` into an existing directory) is approved when its last command is approved on its own. The prefix may not read a secret either: every stage, filters (`jq`, `cut`, `wc`, `diff`, `sort`) included, gets the full plain-read check through the same path rule, so a file elsewhere under the home directory (`~/.zsh_history`, `~/.config/github-copilot/apps.json`) is not approved. Every prefix program and git subcommand takes only allow-listed options, so an option that writes a file (`git show|diff|log --output`, `sort -o`, a `uniq` output operand) or runs a program (`--ext-diff`, `--compress-program`) is not read-only, and `git fetch` with a refspec destination (which can overwrite a local branch) is not either. Pipes count only when every stage reads. Claude Code's Glob and Grep tools are not routed to the hooks.
|
|
121
|
+
|
|
122
|
+
### The classifier
|
|
123
|
+
|
|
124
|
+
| Harness | Command (no shell, from a private empty directory) | Timeout |
|
|
125
|
+
| ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- |
|
|
126
|
+
| Claude Code | `claude -p --model <model> --tools "" --setting-sources "" --settings '{"disableAllHooks":true,"autoMemoryEnabled":false}' --no-session-persistence --strict-mcp-config --disable-slash-commands --permission-mode dontAsk --max-turns 5 --output-format json --json-schema <schema> <prompt>`; the answer is `.structured_output` | 15 s |
|
|
127
|
+
| Codex | `codex exec --ephemeral --ignore-user-config --ignore-rules --disable hooks --skip-git-repo-check -s read-only -c approval_policy="never" -c model_reasoning_effort="low" -m <model> -C <empty dir> --output-schema <schema.json> -o <out.json> <prompt>`, standard input closed | 15 s |
|
|
128
|
+
| Copilot | `copilot -p <prompt> --model <model> --available-tools "" --no-custom-instructions --disable-builtin-mcps --no-ask-user --no-auto-update --disable-client-telemetry --output-format json`, with `COPILOT_HOME` set to a private scratch directory whose `settings.json` is `{"disableAllHooks":true}` | 20 s |
|
|
129
|
+
|
|
130
|
+
Claude Code and Copilot run with no tools. Codex documents no switch that removes its shell tool: it runs in a read-only sandbox with approvals off and an empty working directory, so its child can still run read-only commands while it reads the command text. Its only output is the verdict.
|
|
131
|
+
|
|
132
|
+
Copilot still authenticates in that scratch home: its stored login lives in the system credential store (the Keychain on macOS), not in `COPILOT_HOME`, and `COPILOT_GITHUB_TOKEN`, `GH_TOKEN` or `GITHUB_TOKEN` are passed through when set. A login stored in plain text (`storeTokenPlaintext`) lives in `COPILOT_HOME` and does not reach the scratch home, so the classifier fails and the person is asked. On Windows only an executable (`.exe`) CLI is run, since `.cmd` launchers need a shell; otherwise the person is asked.
|
|
78
133
|
|
|
79
|
-
The
|
|
134
|
+
The prompt gives the command (at most 20,000 characters; a longer one is never sent and goes to the person), the working directory, Git facts (repository root, branch, default branch, main checkout or linked worktree), each path the command names with whether it is in the linked feature worktree, the main checkout, the temp directory or one of the profile's `scratchRoots`, and whether this session created it, and the engine's reason. The command is untrusted: it is JSON-encoded and fenced by a boundary chosen at random for each call, and the prompt says everything inside is data. Deleting scratch files, screenshots, temp directories or files the session created is approvable.
|
|
135
|
+
|
|
136
|
+
Verdicts are cached for five minutes by request (tool, input and working directory) within the session, and concurrent hooks for one request share one run. Any failure (the CLI is not installed or not logged in, a nonzero exit, a timeout, output that is not JSON or not the schema, a command over the length cap) asks the person; it never approves, and a `classify` record cannot settle it afterwards. A missing CLI is not tried again in that session. There is no limit on AI approvals per session. `--max-turns` is 5 because the schema answer is itself a tool call: at 2, a model that first reached for a tool it does not have sometimes stopped at the turn limit.
|
|
137
|
+
|
|
138
|
+
Configure it in the profile:
|
|
80
139
|
|
|
81
140
|
```json
|
|
82
|
-
{
|
|
141
|
+
{
|
|
142
|
+
"version": 1,
|
|
143
|
+
"mode": "permissive",
|
|
144
|
+
"classifier": {
|
|
145
|
+
"claude": { "model": "haiku" },
|
|
146
|
+
"codex": { "model": "gpt-6-luna" },
|
|
147
|
+
"copilot": { "model": "auto" }
|
|
148
|
+
}
|
|
149
|
+
}
|
|
83
150
|
```
|
|
84
151
|
|
|
85
|
-
|
|
152
|
+
Each harness uses its own CLI; the models above are the defaults. `"enabled": false` turns the classifier off, so everything the engine escalates goes to the person. An unknown key or an invalid model name makes the profile invalid, and an invalid profile is replaced by the strict default.
|
|
153
|
+
|
|
154
|
+
**Privacy.** Commands, paths and the facts above are sent to the user's own model provider through their own logged-in CLI, under that account's terms. Nothing is sent anywhere else. The audit log records each classification's CLI, model, latency and verdict, never the prompt.
|
|
86
155
|
|
|
87
|
-
|
|
156
|
+
### The user's own permission rules
|
|
88
157
|
|
|
89
|
-
|
|
158
|
+
Read, never written, right after the engine. Allow rules count only from the user's own settings; deny and ask rules count from every level, the checkout's included (a checkout can be anyone's branch, and its rules can only make a request stricter).
|
|
90
159
|
|
|
91
|
-
|
|
160
|
+
- **Claude Code** ([permissions](https://code.claude.com/docs/en/permissions)): `permissions.allow`, `ask` and `deny`. Allow from `settings.json` under `CLAUDE_CONFIG_DIR` (default `~/.claude`) and the managed settings file; deny and ask also from the project's `.claude/settings.json` and `.claude/settings.local.json`. Deny, then ask, then allow; the first match decides. `Bash(cmd)` is exact, `Bash(cmd *)` and `Bash(cmd:*)` are prefixes, and `*` matches any text. A compound command (`&&`, `||`, `;`, `|`, `|&`, `&`, newlines) is allowed only when every subcommand is; deny and ask rules match any subcommand, including `$(…)` bodies, through any wrapper. For an allow rule only Claude Code's own wrappers are stripped (`timeout`, `time`, `nice`, `nohup`, `stdbuf`, `command`, `builtin`, `noglob`, bare `xargs`): `sudo`, `doas`, `env` and `exec` stay the program, so `Bash(git status:*)` does not allow `sudo git status`. `watch`, `setsid`, `ionice`, `flock` and `find -exec`/`-delete` are never allowed by a rule. `Read(...)` and `Edit(...)` path rules use the documented `//`, `~/`, `/` and relative forms, matched on Windows with either separator, any case, 8.3 short names expanded, and `//` rules without the drive letter; `Edit` rules cover `Write`.
|
|
161
|
+
- **Codex** ([rules](https://developers.openai.com/codex/rules), [configuration](https://developers.openai.com/codex/config-reference)): `prefix_rule(pattern=[...], decision="allow"|"prompt"|"forbidden")` in `*.rules`. Allow from `CODEX_HOME/rules` (default `~/.codex/rules`); prompt and forbidden also from the checkout's `.codex/rules`. The pattern is matched against the command's words as written, with no wrapper stripped. A linear chain of plain commands is checked per command and the strictest decision wins; anything else is one `bash -lc` invocation. Codex documents no other command allowlist in `config.toml`.
|
|
162
|
+
- **Copilot** ([allowing tools](https://docs.github.com/en/copilot/how-tos/copilot-cli/use-copilot-cli/allowing-tools)): none. Its allow and deny lists are the `--allow-tool` and `--deny-tool` flags, which apply to one session and are not saved; the format of saved per-location approvals is not documented, and trusted folders gate file access, not commands.
|
|
92
163
|
|
|
93
|
-
|
|
164
|
+
An allow rule approves, audited with `userAllowRule`.
|
|
94
165
|
|
|
95
|
-
|
|
96
|
-
2. **Recorded.** The session approves the record command in that reason deterministically, in every profile: exactly `node "<this package's dist/cli.js>" classify <harness> <session-id> <<< '<json>'` for the current harness and session, with one single-quoted JSON object and nothing else in the command. Any other direct invocation of a classification record goes to a person: `node … cli.js classify` or `policy-manager classify`, at the start of a command or after an operator, including behind assignments, wrappers such as `env`, `exec` or `xargs`, or keywords such as `then`. That covers another session, harness or CLI path, and anything added before or after. A command that only mentions one, such as a `grep` pattern, gets the normal decision, and so does a record nested in a quoted script (`sh -c '…'`).
|
|
97
|
-
3. **Classified.** `classify` takes `{requestHash, category, confidence, recoverable, rationale}`. The request is approved only when `recoverable` is `true`, `confidence` is at least 0.95, and the category is not `sensitive` or `unknown`. A `destructive` label approves only a deletion the engine itself identified inside a linked feature worktree, on the same terms. Any other request the AI labels `destructive` (an unparsable `rm -rf ~/{a,b}`, for example), and any such deletion not judged recoverable, goes to a **person** (under Codex, a deny), since it may lose data for good. No other deterministic `destructive` escalation is classified. Anything else is a **deny with a reason** the model sees and works around. The outcome is remembered for five minutes for that exact request, and a verdict is final in that time: a deny cannot be reclassified into an approve.
|
|
98
|
-
4. **Fallback.** If the classifier is unavailable or its answer is invalid, the retry reaches a person through the normal prompt (under Codex, which cannot ask, it is a deny that gives the `approve` command the user runs; see **Approving from the terminal**). This happens at most once per request, so there is never a loop and never a lost prompt. After 50 AI approvals in a session, further ambiguous requests go to a person.
|
|
166
|
+
### Remembering an answer
|
|
99
167
|
|
|
100
|
-
|
|
168
|
+
Claude Code's `PreToolUse` carries a `tool_use_id` and the session's `permission_mode`. When the hook asks in a mode that shows the ask to a person (`default`, `acceptEdits`, `plan`), the session records the id; the `PostToolUse` (or `PostToolUseFailure`) for that id means the person said yes, and a rejection is not counted. Under `bypassPermissions`, `dontAsk`, an auto mode or no reported mode, nothing is remembered. Copilot is not remembered at all, by design: its hooks report no permission mode and its `postToolUse` carries no tool-call id, so a run under `--allow-all` or `--yolo` (where an ask is never shown) cannot be told apart from a person saying yes; recording it would turn an automatic run into a session grant nobody gave. The ask text says what a yes covers.
|
|
101
169
|
|
|
102
|
-
|
|
103
|
-
- Destructive operations: unmerged-work loss, history and remote rewrites, cloud deletion, publishing, and deletion outside a linked feature worktree. Recoverable deletion is approved deterministically (see **Recoverable deletions and resets**). The only destructive escalation the classifier decides is an `rm` inside a linked feature worktree that the evidence cannot prove recoverable.
|
|
104
|
-
- Commands matching the profile's `humanPatterns`.
|
|
105
|
-
- Writes outside a linked feature worktree (main clones and protected branches).
|
|
106
|
-
- Cloud operations outside the read catalog. The profile's `cloudWrites: "allow"` is the way to automate these.
|
|
107
|
-
- Requests the engine cannot trust: incomplete or invalid requests, a different execution directory, unrecognized patches, and environment or loader overrides such as `LD_PRELOAD`.
|
|
170
|
+
A remembered yes is narrow: the same rule and the same exact target, in the same checkout. For a protected-path write that is the exact files written; for any other rule (a `humanPatterns` match included) the exact command. Harness settings, hooks, permission files, the policy profile, credential reads, possible unrecoverable loss and the deterministic floor are asked every time, and unknown, sensitive and destructive requests are approved once only. `approve --session` uses the same scope.
|
|
108
171
|
|
|
109
|
-
|
|
172
|
+
## Recording and review
|
|
110
173
|
|
|
111
|
-
|
|
174
|
+
The audit log gets `classification-requested` the first time a request reaches the classifier (with the command redacted under a permissive profile: secret-looking values, URL credentials and long tokens are replaced and the text is capped; the strict default keeps only a vocabulary summary), `ai-classification` (CLI, model, latency, and the verdict or the failure reason), `classification` (category, confidence, recoverable, redacted rationale), `decision` (with the stage `approved`, `denied` or `fallback`, and `userAllowRule` or `userRule` when the user's own rule decided), `classification-fallback` (with the failure reason), and `human-response` and `human-grant` for a remembered answer. Review them across sessions:
|
|
112
175
|
|
|
113
176
|
```sh
|
|
114
177
|
policy-manager review-classifications [--since 2026-11-12T00:00:00Z] [--json]
|
|
115
178
|
```
|
|
116
179
|
|
|
117
|
-
The report shows how many ambiguous requests were approved, denied, fell back to a person (and why), and never resolved; a confidence histogram; every AI-approved command with its outcome; approved commands that then failed; and commands a person later denied. It reads the session logs under the temporary directory, which the operating system clears after a few days, so run it within two days of starting. `replay` prints how many escalations in recorded transcripts would go to the classifier instead of a person.
|
|
180
|
+
The report shows how many ambiguous requests were approved, denied, fell back to a person (and why), and never resolved; a confidence histogram; every AI-approved command with its outcome; approved commands that then failed; and commands a person later denied. It reads the session logs under the temporary directory, which the operating system clears after a few days, so run it within two days of starting. `replay` prints how many escalations in recorded transcripts would go to the classifier instead of a person; `replay --classify` runs the real classifier on the newest escalations (`--limit`, default 300, four at a time) and reports engine, AI and user-rule approvals, what still asks and why, classifier errors and latency. It sends those commands to your model provider and executes nothing.
|
|
118
181
|
|
|
119
182
|
## Approving from the terminal
|
|
120
183
|
|
|
@@ -124,7 +187,7 @@ Codex cannot ask in `PreToolUse`, so a request that needs a person is denied, an
|
|
|
124
187
|
⏸ Waiting for your approval. Not run: Protected path requires human approval.
|
|
125
188
|
Run in your own terminal, then say "retry":
|
|
126
189
|
pm approve --last
|
|
127
|
-
Add --session to also allow writes
|
|
190
|
+
Add --session to also allow writes to /tmp/wt/.agent-config/README.md for the rest of this session.
|
|
128
191
|
Agent: stop now and end your turn; approving it in chat does not unblock it. Show the user the command above exactly, in a code block. Never run it yourself.
|
|
129
192
|
Request <64-character request hash>.
|
|
130
193
|
```
|
|
@@ -138,12 +201,14 @@ policy-manager approve <claude|codex|copilot> <session-id> <request-hash> [--ses
|
|
|
138
201
|
The deny reason uses `pm` when the managed launcher (see **Install native hooks**) for this version is installed and its directory is on `PATH`, and `node "<cli>" approve --last` otherwise. Then the agent retries the same request unchanged.
|
|
139
202
|
|
|
140
203
|
- **Once (default).** The next review of that exact request is approved, once per hook phase (`PreToolUse`, then `PermissionRequest`), and the grant is spent.
|
|
141
|
-
- **`--session`.** Also approves later requests in this session that hit the same rule for the same
|
|
204
|
+
- **`--session`.** Also approves later requests in this session that hit the same rule for the same exact target: a write to the same protected files of the same checkout, or, for other rules (a `humanPatterns` match included), the exact same command in the same checkout. `approve --session` prints the scope before asking. Shell commands are covered only when they are a single simple command, so nothing else in a script hides behind the rule. Harness settings, hooks, permission files, the policy profile, credential and secret reads, possible unrecoverable loss, the deterministic floor, and requests whose effect the engine could not determine (category `unknown`, such as an interpreter script) are approved once only, even with `--session`; the deny reason offers `--session` only when it applies.
|
|
142
205
|
|
|
143
206
|
Each grant is audited as `human-grant` (and `human-response` `approved`), and each use as `human-grant-use` with its scope. A shell command that runs or names a policy-manager `approve`, at any nesting (`sh -c`, `npx`, wrappers), always goes to a person, so an agent that follows the deny reason cannot approve its own request. The guard is lexical and the service trusts any holder of the session token, so it is not a boundary against an agent that deliberately works around it. Grants live in the session's policy service; if it restarts (it exits after 30 idle minutes), retry the request and approve the new hash. Claude Code and Copilot ask natively and do not need this, though it works for them too.
|
|
144
207
|
|
|
145
208
|
## Policy
|
|
146
209
|
|
|
210
|
+
What the list below says "requires human approval" is what the deterministic engine does not approve. It then goes to the AI classifier, unless it is a hard human item (see **How a request is decided**).
|
|
211
|
+
|
|
147
212
|
- Ordinary file reads must resolve inside a Git repository.
|
|
148
213
|
- Ordinary file writes must resolve inside a linked worktree on a feature branch.
|
|
149
214
|
- Main clones, protected branches, credentials, Git metadata, policy files, and hook settings require human approval.
|
|
@@ -215,6 +280,38 @@ Under the permissive profile, a harness tool that is not a shell, file, patch or
|
|
|
215
280
|
|
|
216
281
|
Each default approval's audit `decision` record carries `defaultTool` with the tool name. `review-classifications` lists these tools newest first by when each was first seen, so a tool a harness newly added is noticed and can be put in `toolsDeny`.
|
|
217
282
|
|
|
283
|
+
#### Credential helpers
|
|
284
|
+
|
|
285
|
+
Reading a credential always goes to a person, except through a script listed in `credentialHelpers` (permissive profile only). A helper reads a secret for one narrow job, such as posting a review as a GitHub App:
|
|
286
|
+
|
|
287
|
+
```json
|
|
288
|
+
"credentialHelpers": [
|
|
289
|
+
{
|
|
290
|
+
"path": "tools/review-bot.mjs",
|
|
291
|
+
"remotes": ["github.com/example-org/"],
|
|
292
|
+
"args": [
|
|
293
|
+
["--repo", "<repo>", "check"],
|
|
294
|
+
["--repo", "<repo>", "gh", "api", "repos/<repo>/pulls/<int>/reviews", "--input", "<file>"],
|
|
295
|
+
["--repo", "<repo>", "gh", "pr", "review", "<int>", "-R", "<repo>", ["--approve", "--comment"], "--body-file", "<file>"]
|
|
296
|
+
]
|
|
297
|
+
}
|
|
298
|
+
]
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
`node <script> <args>` is approved, and named in the audit `decision` record as `credentialHelpers: ["<path>#<shape index>"]`, only when all of these hold:
|
|
302
|
+
|
|
303
|
+
- The checkout comes from a listed remote. `remotes` (required) lists normalized prefixes such as `github.com/example-org/`: a lowercase host, then at least an owner, where a trailing `/` makes it a prefix. The checkout's `remote.origin.url` (https, ssh or `git@host:` form, normalized to lowercase `host/owner/repo` without `.git`) must match one. It must equal what `git remote get-url origin` resolves, so no `url.*.insteadOf` rewrite applies, and there must be no `remote.origin.pushurl`. A clone of a local or other repository, or a `git init`, has an origin that does not match.
|
|
304
|
+
- The script, however it is named (relative, absolute, from another directory), is the regular file at `<checkout>/<path>` with no symlink on the way, tracked, and identical to the committed file on the default branch of `origin`. The branch is found by full ref name only (`refs/remotes/origin/HEAD` when it points into `refs/remotes/origin/`, else `refs/remotes/origin/main`), so a tag or branch named `origin/HEAD` cannot stand in for it, and every lookup ignores replace refs. The committed blob's bytes are compared in Node with the working file: an exact match, or, when the blob has no CR, a match once the file's CRLF line ends become LF (a `core.autocrlf` checkout). No clean filter or `.gitattributes` setting applies. A local edit makes it a different script.
|
|
305
|
+
- The arguments match one listed shape exactly, word for word. A token is a literal, a list of literal alternatives, or a word with placeholders: `<repo>` (`owner/name`, each part starting with a letter or digit), `<int>`, `<sha>` (7 to 40 hex digits), `<word>` (a letter or digit, then letters, digits, `_.-`), `<url>` (a `https://github.com/` URL), `<file>` (a path with no pattern or `~` characters and not under `/dev/`, inside the working checkout or a temp or scratch root, that passes the usual read check), or `<text>` (any one argument, only as a whole word). Profiles hold no regular expressions.
|
|
306
|
+
- No argument the shell would expand: an unquoted `*`, `?` or `[`, or a leading `~`. Quote a literal pattern (`--reason '*'`).
|
|
307
|
+
- No environment prefix, wrapper (`env`, `command`), input redirect, standard input or pipe into it.
|
|
308
|
+
|
|
309
|
+
The default-branch check trusts the local remote-tracking refs, so the engine refuses local writes that could move them or what they show: `git update-ref` on anything but a plain `refs/heads/*` or `refs/tags/*` name that is not a symbolic ref (so not `refs/remotes/*`, `refs/replace/*` or `HEAD`), `update-ref --stdin` or `--no-deref`, `symbolic-ref` with a name or target under `refs/remotes/`, a fetch from `.`, a path or a `file:` URL, a fetch whose refspec writes `refs/remotes/<remote>/<branch>` from anything but that branch of that configured remote, `--refmap`, and a push to `.` or a local path. (`remotes/<r>/<b>` counts as `refs/remotes/<r>/<b>`.) To keep the origin honest it also refuses `git remote add`, `set-url`, `rename`, `set-branches`, `remove` and `set-head`; `git config` writes outside a short list of safe keys, which covers `remote.*`, `url.*` and `include*`; `git clone` with `-c`/`--config`, `-o`/`--origin`, `--template`, `--separate-git-dir` or `--upload-pack`; and `git init --template` or `--separate-git-dir`. Direct writes into `.git/config`, `.git/worktrees/*/config` and `config.worktree` are refused as protected paths. A normal `git fetch origin [main | +pull/N/head:prN]`, and a plain clone from the listed remote, stay approved.
|
|
310
|
+
|
|
311
|
+
**This is an audit label, not yet a security boundary.** In a worktree the engine approves `node <script>` for a script it does not list without reading it ([#48](https://github.com/agent-corpus/tools/issues/48)), so an agent could run an unlisted script that reads the same secret. Until #48 lands, a helper approval records which listed helper ran; it does not stop an unlisted one.
|
|
312
|
+
|
|
313
|
+
Every other command in the same script is judged as usual. A script with a listed file name that fails any check (changed, untracked, outside a checkout, a symlink, other arguments) goes to a person as a credential read. A listed helper counts as creating no symlink, so a later temp write in the same script stays approvable. An entry's path must be repository-relative with `/` separators and no `.` or `..` segments; the list holds at most 20 helpers of 50 shapes each, and an invalid entry makes the profile invalid (strict).
|
|
314
|
+
|
|
218
315
|
#### MCP read-only tools
|
|
219
316
|
|
|
220
317
|
`mcpReadOnly` lists MCP tools that run without a prompt, in any `mode`. Each entry is an exact `mcp__<server>__<tool>` name, or a name whose tool segment ends in `*` (`mcp__docs__search_*`). Neither segment may contain `__`, and a wildcard approves only a tool whose whole tool segment (after `mcp__<server>__`) is free of `__`, so it cannot reach another server such as `github__get`. Whole-server wildcards (`mcp__github__*`), regular expressions and other tool names are rejected, and the list holds at most 200 entries of 128 characters. List only tools that cannot change anything and cannot return credentials: the tool name is all the engine checks, not the arguments. Prefer exact names. A prefix also covers tools that a server adds later, and read-looking prefixes can include secret readers: the GitHub server's `get_*` and `list_*` cover its secret-scanning alert tools, which return the detected secret.
|
|
@@ -246,7 +343,7 @@ Deletion that Git can undo is approved; anything Git cannot restore still goes t
|
|
|
246
343
|
- **`git reset --hard [<commit>]`** (with at most `-q`) when no tracked change is uncommitted, every commit it drops from the branch is on a remote-tracking ref, no untracked or ignored file sits where the target writes, and the target changes no protected path.
|
|
247
344
|
- **`git checkout -- <paths>`, `git checkout .` and `git restore [-W] <paths>`** when the working tree already matches the index for those paths, or the files are only missing. `git restore -SW` needs the working tree and index to match `HEAD`. A tree-ish, `--source`, `-p` or `-f` stays human.
|
|
248
345
|
|
|
249
|
-
An `rm` whose operands are all plain paths inside a linked feature worktree, but which the evidence above cannot prove recoverable (another untracked file, a directory),
|
|
346
|
+
An `rm` whose operands are all plain paths inside a linked feature worktree, but which the evidence above cannot prove recoverable (another untracked file, a directory), is not approved by the engine and goes to the AI classifier (step 2 of **How a request is decided**) like any other escalation, which approves it on `recoverable: true` at 0.95. `git clean`, forced pushes and refspecs, unmerged branch deletion and forced worktree removal are hard human items and are never classified.
|
|
250
347
|
|
|
251
348
|
Deleting a branch is automatic only when it is already merged into `origin/main` (or `master`): reachable from it, or patch-equivalent to a squash or rebase merge. Remote deletion also needs `origin` and a `git ls-remote` tip that matches the fetched tracking ref, so unfetched commits block it. Evidence uses the locally fetched default branch; fetch first for very recent merges.
|
|
252
349
|
|
package/dist/adapters.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { Decision, OutcomeReport, Request } from "./types.js";
|
|
2
2
|
export declare function normalize(harness: Request["harness"], payload: Record<string, unknown>): Request;
|
|
3
3
|
export interface HookContext {
|
|
4
4
|
cliPath: string;
|
|
@@ -30,6 +30,8 @@ export declare function approveLastCommand(context?: HookContext): string;
|
|
|
30
30
|
* and hand the user one command; the first line says so, and the command stands on its own line.
|
|
31
31
|
*/
|
|
32
32
|
export declare function approveInstruction(decision: Decision, context?: HookContext): string;
|
|
33
|
+
/** Why a person is asked, as the harness's prompt shows it. */
|
|
34
|
+
export declare function askReason(decision: Decision, remembers?: boolean): string;
|
|
33
35
|
export declare function hookResponse(harness: Request["harness"], phase: string, decision: Decision, context?: HookContext): Record<string, unknown>;
|
|
34
36
|
/** The exact stdout of a PreToolUse or PermissionRequest hook. Codex gets no output for no decision. */
|
|
35
37
|
export declare function hookOutput(harness: Request["harness"], phase: string, decision: Decision, context?: HookContext): string;
|
package/dist/adapters.js
CHANGED
|
@@ -1,6 +1,4 @@
|
|
|
1
1
|
import { requestHash } from "./policy.js";
|
|
2
|
-
import { HUMAN_REVIEW_PRINCIPLE } from "./principle.js";
|
|
3
|
-
import { CATEGORIES } from "./types.js";
|
|
4
2
|
export function normalize(harness, payload) {
|
|
5
3
|
let input = payload.tool_input ?? payload.toolInput ?? payload.toolArgs ?? {};
|
|
6
4
|
if (typeof input === "string")
|
|
@@ -115,6 +113,7 @@ export function approveLastCommand(context) {
|
|
|
115
113
|
export function approveInstruction(decision, context) {
|
|
116
114
|
return [
|
|
117
115
|
`⏸ Waiting for your approval. Not run: ${decision.reason}.`,
|
|
116
|
+
...(askWhy(decision) ? [`${askWhy(decision)}.`] : []),
|
|
118
117
|
'Run in your own terminal, then say "retry":',
|
|
119
118
|
` ${approveLastCommand(context)}`,
|
|
120
119
|
...(decision.sessionGrantable
|
|
@@ -126,18 +125,40 @@ export function approveInstruction(decision, context) {
|
|
|
126
125
|
`Request ${decision.requestHash}.`,
|
|
127
126
|
].join("\n");
|
|
128
127
|
}
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
128
|
+
const FALLBACK_TEXT = {
|
|
129
|
+
disabled: "the AI classifier is turned off in the profile",
|
|
130
|
+
"too-long": "the command is too long to classify",
|
|
131
|
+
missing: "the classifier CLI is not installed",
|
|
132
|
+
"not-logged-in": "the classifier CLI is not logged in",
|
|
133
|
+
exit: "the classifier CLI failed",
|
|
134
|
+
timeout: "the classifier timed out",
|
|
135
|
+
"bad-json": "the classifier's answer was not JSON",
|
|
136
|
+
schema: "the classifier's answer did not match the schema",
|
|
137
|
+
};
|
|
138
|
+
/** Why the classifier did not settle a request, or undefined. */
|
|
139
|
+
function askWhy(decision) {
|
|
140
|
+
const why = decision.hard
|
|
141
|
+
? "it needs a person by rule (credentials, protected configuration, unrecoverable loss or a profile pattern), so it was not sent to the AI classifier"
|
|
142
|
+
: decision.classifierNote
|
|
143
|
+
? decision.classifierNote
|
|
144
|
+
: decision.fallbackReason && FALLBACK_TEXT[decision.fallbackReason]
|
|
145
|
+
? `no AI classification: ${FALLBACK_TEXT[decision.fallbackReason]}`
|
|
146
|
+
: undefined;
|
|
147
|
+
return why && `${why[0]?.toUpperCase()}${why.slice(1)}`;
|
|
148
|
+
}
|
|
149
|
+
/** Why a person is asked, as the harness's prompt shows it. */
|
|
150
|
+
export function askReason(decision, remembers = false) {
|
|
151
|
+
const why = askWhy(decision);
|
|
152
|
+
const remembered = remembers && decision.sessionGrantable && decision.sessionScopeLabel
|
|
153
|
+
? ` If you allow it, ${decision.sessionScopeLabel} is allowed for the rest of this session.`
|
|
154
|
+
: "";
|
|
155
|
+
return `Policy manager: ${decision.reason}${why ? `. ${why}` : ""}.${remembered}`;
|
|
133
156
|
}
|
|
134
157
|
export function hookResponse(harness, phase, decision, context) {
|
|
135
158
|
if (decision.decision === "native")
|
|
136
159
|
return {};
|
|
137
160
|
if (decision.decision === "deny") {
|
|
138
|
-
const reason = decision.
|
|
139
|
-
? classifyInstruction(harness, decision, context)
|
|
140
|
-
: decision.reason;
|
|
161
|
+
const reason = decision.reason;
|
|
141
162
|
if (phase === "PermissionRequest")
|
|
142
163
|
return harness === "copilot"
|
|
143
164
|
? {}
|
|
@@ -164,7 +185,7 @@ export function hookResponse(harness, phase, decision, context) {
|
|
|
164
185
|
? { permissionDecision: "allow" }
|
|
165
186
|
: {
|
|
166
187
|
permissionDecision: "ask",
|
|
167
|
-
permissionDecisionReason: decision
|
|
188
|
+
permissionDecisionReason: askReason(decision),
|
|
168
189
|
};
|
|
169
190
|
}
|
|
170
191
|
if (phase === "PermissionRequest")
|
|
@@ -191,16 +212,14 @@ export function hookResponse(harness, phase, decision, context) {
|
|
|
191
212
|
// Codex parses permissionDecision "ask" but does not support it: it marks the hook failed and
|
|
192
213
|
// runs the tool anyway (https://developers.openai.com/codex/hooks). Only "deny" stops a command,
|
|
193
214
|
// so a decision that needs a human is a deny. Approving it in chat does not change the decision;
|
|
194
|
-
// the user approves it from their own terminal (`approve`, once or for the session),
|
|
195
|
-
//
|
|
215
|
+
// the user approves it from their own terminal (`approve`, once or for the session), and a
|
|
216
|
+
// retry then sees the approval. This comes only after the AI classifier or a hard rule said a
|
|
217
|
+
// person is needed.
|
|
196
218
|
// Codex's own approval prompt (PermissionRequest, above) still handles the requests it asks about.
|
|
197
219
|
if (harness === "codex") {
|
|
198
|
-
const
|
|
199
|
-
const reason = !classify && !decision.userOnly
|
|
220
|
+
const reason = !decision.userOnly
|
|
200
221
|
? approveInstruction(decision, context)
|
|
201
|
-
: `Policy manager: ${decision.reason}. This needs a human decision and was not run. ${
|
|
202
|
-
? "Classify it with the session policy-manager agent and retry. If it is not classified as approved, the retry is blocked with the command the user runs to approve it."
|
|
203
|
-
: "Do not run approve yourself: ask the user to approve the original request from their own terminal."} Request ${decision.requestHash}.`;
|
|
222
|
+
: `Policy manager: ${decision.reason}. This needs a human decision and was not run. Do not run approve yourself: ask the user to approve the original request from their own terminal. Request ${decision.requestHash}.`;
|
|
204
223
|
return {
|
|
205
224
|
hookSpecificOutput: {
|
|
206
225
|
hookEventName: phase,
|
|
@@ -213,7 +232,7 @@ export function hookResponse(harness, phase, decision, context) {
|
|
|
213
232
|
hookSpecificOutput: {
|
|
214
233
|
hookEventName: phase,
|
|
215
234
|
permissionDecision: "ask",
|
|
216
|
-
permissionDecisionReason: decision
|
|
235
|
+
permissionDecisionReason: askReason(decision, harness === "claude"),
|
|
217
236
|
},
|
|
218
237
|
};
|
|
219
238
|
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { type Category, type Request } from "./types.js";
|
|
2
|
+
/** The JSON schema every classifier CLI is given for its answer. */
|
|
3
|
+
export declare const VERDICT_SCHEMA: {
|
|
4
|
+
readonly type: "object";
|
|
5
|
+
readonly properties: {
|
|
6
|
+
readonly category: {
|
|
7
|
+
readonly type: "string";
|
|
8
|
+
readonly enum: readonly ["code-read", "worktree-write", "temp-write", "cloud-read", "git-read", "impactful-write", "destructive", "sensitive", "unknown"];
|
|
9
|
+
};
|
|
10
|
+
readonly confidence: {
|
|
11
|
+
readonly type: "number";
|
|
12
|
+
};
|
|
13
|
+
readonly recoverable: {
|
|
14
|
+
readonly type: "boolean";
|
|
15
|
+
};
|
|
16
|
+
readonly rationale: {
|
|
17
|
+
readonly type: "string";
|
|
18
|
+
};
|
|
19
|
+
};
|
|
20
|
+
readonly required: readonly ["category", "confidence", "recoverable", "rationale"];
|
|
21
|
+
readonly additionalProperties: false;
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* The AI classifier: the harness's own CLI, run as a child process with the user's own login, no
|
|
25
|
+
* tools, no hooks, no session persistence and no project context. Nothing here approves: it
|
|
26
|
+
* returns a verdict, or a failure that sends the request to a person.
|
|
27
|
+
*/
|
|
28
|
+
/** Per-harness classifier settings from the profile's `classifier` key. */
|
|
29
|
+
export interface ClassifierConfig {
|
|
30
|
+
/** `false` turns the classifier off: everything the engine escalates goes to a person. */
|
|
31
|
+
enabled: boolean;
|
|
32
|
+
claude: {
|
|
33
|
+
model: string;
|
|
34
|
+
};
|
|
35
|
+
codex: {
|
|
36
|
+
model: string;
|
|
37
|
+
};
|
|
38
|
+
copilot: {
|
|
39
|
+
model: string;
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
export declare const DEFAULT_CLASSIFIER: ClassifierConfig;
|
|
43
|
+
/** How long each CLI may take, in milliseconds. */
|
|
44
|
+
export declare const CLASSIFIER_TIMEOUT_MS: Record<Request["harness"], number>;
|
|
45
|
+
/** Set in the classifier's environment, so a policy hook that still runs there refuses tools. */
|
|
46
|
+
export declare const CLASSIFIER_ENV = "AGENT_CORPUS_POLICY_CLASSIFIER";
|
|
47
|
+
export interface Verdict {
|
|
48
|
+
category: Category;
|
|
49
|
+
confidence: number;
|
|
50
|
+
recoverable: boolean;
|
|
51
|
+
rationale: string;
|
|
52
|
+
}
|
|
53
|
+
export type FailureReason = "disabled" | "too-long" | "missing" | "not-logged-in" | "exit" | "timeout" | "bad-json" | "schema";
|
|
54
|
+
export type ClassifierResult = {
|
|
55
|
+
ok: true;
|
|
56
|
+
verdict: Verdict;
|
|
57
|
+
cli: Request["harness"];
|
|
58
|
+
model: string;
|
|
59
|
+
latencyMs: number;
|
|
60
|
+
} | {
|
|
61
|
+
ok: false;
|
|
62
|
+
reason: FailureReason;
|
|
63
|
+
cli: Request["harness"];
|
|
64
|
+
model: string;
|
|
65
|
+
latencyMs: number;
|
|
66
|
+
};
|
|
67
|
+
export interface RunResult {
|
|
68
|
+
/** Exit code; null when killed. */
|
|
69
|
+
code: number | null;
|
|
70
|
+
stdout: string;
|
|
71
|
+
stderr: string;
|
|
72
|
+
/** `ENOENT` when the program is not installed; `timeout` when it was killed for time. */
|
|
73
|
+
error?: "ENOENT" | "timeout" | "other";
|
|
74
|
+
}
|
|
75
|
+
export interface RunOptions {
|
|
76
|
+
cwd: string;
|
|
77
|
+
env: NodeJS.ProcessEnv;
|
|
78
|
+
timeoutMs: number;
|
|
79
|
+
}
|
|
80
|
+
/** Runs a program without a shell. Replaceable in tests. */
|
|
81
|
+
export type Runner = (file: string, args: string[], options: RunOptions) => Promise<RunResult>;
|
|
82
|
+
/** `execFile`, no shell, standard input closed, output capped, killed at the timeout. */
|
|
83
|
+
export declare const execRunner: Runner;
|
|
84
|
+
/** A verdict with exactly the schema's shape, or undefined. */
|
|
85
|
+
export declare function parseVerdict(value: unknown): Verdict | undefined;
|
|
86
|
+
export interface ClassifyOptions {
|
|
87
|
+
runner?: Runner;
|
|
88
|
+
timeoutMs?: number;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Classifies one prompt with `cli`'s own CLI. Every failure (not installed, not logged in, a
|
|
92
|
+
* nonzero exit, a timeout, output that is not JSON or not the schema) is a result with `ok: false`,
|
|
93
|
+
* never an exception and never an approval.
|
|
94
|
+
*/
|
|
95
|
+
export declare function classifyWithCli(cli: Request["harness"], prompt: string | undefined, config?: ClassifierConfig, options?: ClassifyOptions): Promise<ClassifierResult>;
|
|
96
|
+
/** Parses the profile's `classifier` key. Throws a message for anything invalid. */
|
|
97
|
+
export declare function parseClassifierConfig(raw: unknown): ClassifierConfig;
|
|
98
|
+
//# sourceMappingURL=classifier.d.ts.map
|