@agent-corpus/policy-manager 0.7.0 → 0.9.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 +39 -3
- package/dist/adapters.d.ts +12 -0
- package/dist/adapters.js +74 -11
- package/dist/cli.js +107 -7
- package/dist/flow.js +38 -4
- package/dist/grants.d.ts +18 -0
- package/dist/grants.js +160 -0
- package/dist/permissive.d.ts +6 -0
- package/dist/permissive.js +69 -0
- package/dist/policy.js +10 -0
- package/dist/profile.d.ts +10 -0
- package/dist/profile.js +23 -0
- package/dist/review.d.ts +9 -0
- package/dist/review.js +16 -0
- package/dist/service.d.ts +19 -1
- package/dist/service.js +69 -6
- package/dist/session.d.ts +51 -0
- package/dist/session.js +188 -7
- package/dist/setup.d.ts +7 -0
- package/dist/setup.js +33 -5
- package/dist/shim.d.ts +24 -0
- package/dist/shim.js +114 -0
- package/dist/tools.d.ts +23 -0
- package/dist/tools.js +66 -0
- package/dist/types.d.ts +8 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -42,6 +42,8 @@ The canonical form is `policy-manager setup-hook <claude|codex|copilot>`. Each a
|
|
|
42
42
|
|
|
43
43
|
Setup merges only the managed hook definitions. Existing custom hooks, permissions, settings, allow rules, and deny rules remain. Repeated setup is idempotent. Package upgrades replace hooks carrying the managed marker; unmarked manual entries remain. Existing settings receive an owner-only backup, and updates use a temporary file with atomic replacement. Invalid JSON, unsupported schemas, symbolic links, concurrent setup, and detected concurrent edits fail without replacing the existing settings.
|
|
44
44
|
|
|
45
|
+
Setup also installs a small launcher named `pm` that runs this CLI, so a user can type `pm approve --last`: `~/.local/bin/pm` (a Node script, mode 0755) on macOS and Linux, `%LOCALAPPDATA%\agent-corpus\bin\pm.cmd` on Windows. It carries a marker with the version that wrote it. Setup replaces only a launcher it wrote for the same or an older version; a newer one, or a `pm` it did not write, is left alone and reported. Setup never edits `PATH`: the result's `shim.onPath` says whether the directory is on it, and the next steps say how to add it. `--shim-dir <directory>` puts the launcher elsewhere; with `--config-dir` and no `--shim-dir`, setup leaves the launcher alone.
|
|
46
|
+
|
|
45
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`.
|
|
46
48
|
|
|
47
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. Ambiguous requests retain the documented classification or human fallback; setup does not enable automatic AI fallback across unsupported native interfaces.
|
|
@@ -93,7 +95,7 @@ How a hook call flows (Claude Code, Codex and Copilot `PreToolUse`):
|
|
|
93
95
|
1. **First call.** The command is _not run_ and the person is not asked. The hook blocks it with a reason that tells the model to ask the session's policy-manager agent whether the exact command is recoverable and non-sensitive, to record the answer with `policy-manager classify`, and to retry the same command. The reason starts with `Needs classification (not an error)` and states the rule the classifier applies (`HUMAN_REVIEW_PRINCIPLE`). A person is needed only for unrecoverable loss, credential or secret retrieval, protected configuration or paths, and `humanPatterns`. A recoverable outward-facing write such as an issue comment is approvable, and so is a destructive-but-safe deletion inside a feature worktree. The request hash covers only effect-relevant input, so a retry with a different Bash `description` reuses the classification.
|
|
94
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 '…'`).
|
|
95
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.
|
|
96
|
-
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
|
|
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.
|
|
97
99
|
|
|
98
100
|
**What always stays with a person, in code, and is never AI-relaxable** (these are the owner's calls; they list exactly what this experiment does not change):
|
|
99
101
|
|
|
@@ -114,6 +116,32 @@ policy-manager review-classifications [--since 2026-11-12T00:00:00Z] [--json]
|
|
|
114
116
|
|
|
115
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.
|
|
116
118
|
|
|
119
|
+
## Approving from the terminal
|
|
120
|
+
|
|
121
|
+
Codex cannot ask in `PreToolUse`, so a request that needs a person is denied, and approving it in chat does not change the decision. The deny reason leads with what to do:
|
|
122
|
+
|
|
123
|
+
```text
|
|
124
|
+
⏸ Waiting for your approval. Not run: Protected path requires human approval.
|
|
125
|
+
Run in your own terminal, then say "retry":
|
|
126
|
+
pm approve --last
|
|
127
|
+
Add --session to also allow writes under /tmp/wt/.agent-config for the rest of this session.
|
|
128
|
+
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
|
+
Request <64-character request hash>.
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
`pm approve --last` approves the newest request that any running policy session of this user sent to a person in the last 15 minutes. It shows the harness and session, the tool, the redacted request, the rule, and (with `--session`) the scope, then asks y/N; it refuses to run without an interactive terminal. To approve one exact request instead:
|
|
133
|
+
|
|
134
|
+
```sh
|
|
135
|
+
policy-manager approve <claude|codex|copilot> <session-id> <request-hash> [--session]
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
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
|
+
|
|
140
|
+
- **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 scope: a protected-path write under the same protected root of the same checkout (`<worktree>/.agent-config`, not `.claude` or another worktree), the same `humanPatterns` entries in the same checkout, or, for other rules, 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. Credential and secret reads, possible unrecoverable loss (force pushes, deleting unmerged work) 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
|
+
|
|
143
|
+
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
|
+
|
|
117
145
|
## Policy
|
|
118
146
|
|
|
119
147
|
- Ordinary file reads must resolve inside a Git repository.
|
|
@@ -179,6 +207,14 @@ Every command that could run is judged, not only the first. Understood: `;`, new
|
|
|
179
207
|
- **Variables after an assignment chain.** `S=/abs && H=x; use $S $H` treats `H` as assigned: a bare assignment with no command substitution and no redirection cannot fail, so the `&&` chain always reaches `H=x`. This holds only for uppercase names the shell does not reserve. zsh's lowercase specials, read-only or numeric specials (`UID`, `SECONDS`, `BASH*`, `ZSH*`, ...), a value with `$(...)`, `export NAME=value` and a prefix assignment (`X=1 cmd`) can fail or do not persist, so the chain may stop there and a later name is still an environment variable. A value used as the program (`P=rm; $P -rf x`) is resolved and judged as that program. The remaining window is a `readonly` or `typeset -i` that the user's shell startup files set on a name outside that list (such as `HISTFILE`): bash 5 in default mode may then return 1 without exiting, so the chain could stop there. That is outside what the script controls and is accepted.
|
|
180
208
|
- **Still sent to a human:** brace expansion (`{a,b}`, `{1..3}`; `{}` and `@{u}` are literal), arithmetic (`$((`, `$[`, `(( ))`), arrays, other parameter forms (`${X:=y}`, `${!X}`, `${X/a/b}`), `function name` definitions, unquoted heredocs whose body expands, and scripts that expand to more than a few hundred commands. `cloudWrites: "allow"` also approves non-destructive cloud changes.
|
|
181
209
|
|
|
210
|
+
#### Harness tools approved by default
|
|
211
|
+
|
|
212
|
+
Under the permissive profile, a harness tool that is not a shell, file, patch or MCP tool is approved without a prompt or classification: task control (`TaskStop`, `TaskOutput`), scheduling the session's own wakeup, listing agents, loading tool schemas, asking the user, plan mode, and tools a harness adds later. Shell, file and patch tools (`Bash`, `exec_command`, `Read`, `Write`, `Edit`, `apply_patch`, `Grep`, `Glob`, `view_image`, and `Monitor`, which runs a command) always get the engine's checks. So does any tool that runs code, writes to a running command, or touches files, whether listed (Codex `shell_command`, `local_shell`, `write_stdin`; Copilot `write_bash`) or only named like one (a name containing `bash`, `shell`, `exec`, `stdin`, `command`, `repl`, `eval`, `python`, `run`, `file`, `delete`, `move`, `edit` and similar), so a new one fails closed. A false positive such as `BashOutput` only costs a classification. MCP tools follow `mcpReadOnly`. The strict profile approves none of them by default.
|
|
213
|
+
|
|
214
|
+
`toolsDeny` keeps chosen tools on today's path, an AI classification for each call: `{ "claude": ["SendMessage", "WebFetch"], "codex": [], "copilot": [] }`, exact names, at most 100 per harness. An unknown harness, a non-list, or a name that is not a tool name makes the profile invalid (strict). The built-in deny list is empty.
|
|
215
|
+
|
|
216
|
+
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
|
+
|
|
182
218
|
#### MCP read-only tools
|
|
183
219
|
|
|
184
220
|
`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.
|
|
@@ -195,7 +231,7 @@ A listed tool is approved. Any other MCP tool gets no decision from the policy m
|
|
|
195
231
|
|
|
196
232
|
Measure a profile against real usage with `policy-manager replay ~/.claude/projects --profile policy.json`: it replays the Bash commands recorded in Claude Code transcripts through the evaluator (nothing is executed) and prints the approval rate with and without the profile, plus the most common reasons that still need a human. Reports include short command excerpts, so keep them local.
|
|
197
233
|
|
|
198
|
-
Protected names (`.claude`, `.agent-config`, `AGENTS.md`, ...) are judged relative to the repository root, so a linked worktree under `<repo>/.claude/worktrees/<name>` is ordinary code while `<worktree>/.claude/settings.json` stays protected. `git config` is limited to a short allowlist of local, non-executable keys; hooks, aliases, credential helpers, URLs and `--global` always need a human. Read-only cloud verbs (`list`, `show`, `describe`, `get-*`) and `az boards query` (a WIQL read) are approved beyond the exact catalog unless the arguments name credentials or override the endpoint.
|
|
234
|
+
Protected names (`.claude`, `.agent-config`, `AGENTS.md`, ...) are judged relative to the repository root, so a linked worktree under `<repo>/.claude/worktrees/<name>` is ordinary code while `<worktree>/.claude/settings.json` stays protected. `git config` is limited to a short allowlist of local, non-executable keys; hooks, aliases, credential helpers, URLs and `--global` always need a human. For `--session`, a single shell command's scope comes from every word that could name a file it touches: non-option arguments, `--option=value` and `-oVALUE` values, and redirect targets (`>`, `>>`, `<`), so `printf x >> .agent-config/README.md` and `tee -a .agent-config/a` are covered like a patch, while a command that also names `AGENTS.md` or `.claude` is not. A variable assigned a single-quoted literal that is not one plain word (`Q='query($t: ID!)'`) is known only inside double quotes, so `gh api graphql -f query="$Q"` is judged on its value; an unquoted `$Q` stays unknown. Read-only cloud verbs (`list`, `show`, `describe`, `get-*`) and `az boards query` (a WIQL read) are approved beyond the exact catalog unless the arguments name credentials or override the endpoint.
|
|
199
235
|
|
|
200
236
|
`git worktree remove --force <path>` is approved when `<path>` is a linked worktree of the repository (listed by `git worktree list`, never the main worktree), resolves strictly inside a `scratchRoots` entry or the system temp directory, lies outside the main checkout, and holds no other worktree; exactly one `-f`/`--force` may be given (a second one also removes a locked worktree), and not after a command that can create symlinks. A worktree under the main checkout (`.worktrees/x`) still needs a human. `git worktree prune` with only `-n`/`-v` is approved: it drops records of worktrees whose directories are already gone.
|
|
201
237
|
|
|
@@ -222,7 +258,7 @@ The cache belongs to the service process and is scoped to harness plus session I
|
|
|
222
258
|
|
|
223
259
|
`SessionStart` reports the private temporary directory containing `audit.jsonl`. Each request and decision is recorded before an approval is returned. The log stores versioned event envelopes, readable action summaries, opaque session identifiers, request hashes, and hashed targets. It excludes paths, argument values, source text, credentials, and model explanations. Compare request hashes against the original request in the harness transcript during an investigation. Logs rotate at 10 MiB per segment and stop accepting writes at 100 MiB total. Earlier segments remain available through `audit-log query` and `audit-log export`; no records are automatically deleted. Logs remain after normal shutdown and can disappear during operating-system cleanup. Copy them before cleanup when needed.
|
|
224
260
|
|
|
225
|
-
Logging failure, malformed requests, service failure, and unknown semantics never produce an automatic approval. Permission hooks fall through to native human handling. Pre-tool failures exit 2. Host timeout behavior differs: Copilot command-hook timeouts fall through to its normal permission flow. Codex does not support `ask` in `PreToolUse`: it parses the value, marks the hook failed and runs the tool anyway. A decision that needs a human is therefore returned to Codex as a `deny` whose reason says the command was not run and that approving it in chat does not unblock it (the decision is deterministic, so a retry is denied again); there is no in-Codex button to approve it. The
|
|
261
|
+
Logging failure, malformed requests, service failure, and unknown semantics never produce an automatic approval. Permission hooks fall through to native human handling. Pre-tool failures exit 2. Host timeout behavior differs: Copilot command-hook timeouts fall through to its normal permission flow. Codex does not support `ask` in `PreToolUse`: it parses the value, marks the hook failed and runs the tool anyway. A decision that needs a human is therefore returned to Codex as a `deny` whose reason says the command was not run and that approving it in chat does not unblock it (the decision is deterministic, so a retry is denied again); there is no in-Codex button to approve it. The reason gives the `approve` command the user runs in their own terminal (see **Approving from the terminal**). An ambiguous request is the other way through: its reason points to the session policy-manager agent, and a classification of approved is accepted for the session, so a retry passes. Codex also rejects `PreToolUse` `permissionDecision: "allow"` without `updatedInput` ("PreToolUse hook returned unsupported permissionDecision:allow", checked against Codex CLI 0.167.2), so an approval there is no decision: empty output and exit 0. If Codex would still prompt, its `PermissionRequest` hook returns `{"hookSpecificOutput":{"hookEventName":"PermissionRequest","decision":{"behavior":"allow"}}}`, which suppresses the prompt; a request that needs a human gets no output there and Codex's own prompt.
|
|
226
262
|
|
|
227
263
|
## Audit API and reported outcomes
|
|
228
264
|
|
package/dist/adapters.d.ts
CHANGED
|
@@ -3,6 +3,8 @@ export declare function normalize(harness: Request["harness"], payload: Record<s
|
|
|
3
3
|
export interface HookContext {
|
|
4
4
|
cliPath: string;
|
|
5
5
|
sessionId: string;
|
|
6
|
+
/** A managed `pm` launcher for this CLI is installed and on PATH. */
|
|
7
|
+
pmOnPath?: boolean;
|
|
6
8
|
}
|
|
7
9
|
/**
|
|
8
10
|
* The exact command the model is told to run to record a classification. A here-string, not a
|
|
@@ -18,6 +20,16 @@ export declare function classifyCommand(harness: Request["harness"], context?: H
|
|
|
18
20
|
export declare function isClassifyRecord(command: string, harness: Request["harness"], context: HookContext): boolean;
|
|
19
21
|
/** A command that runs a policy-manager classification record, for any session or CLI. */
|
|
20
22
|
export declare function looksLikeClassifyRecord(command: string): boolean;
|
|
23
|
+
export declare function looksLikeApproveGrant(command: string): boolean;
|
|
24
|
+
/** The command the user runs in their own terminal to approve a human decision. */
|
|
25
|
+
export declare function approveCommand(harness: Request["harness"], requestHash: string, context?: HookContext): string;
|
|
26
|
+
/** The short command the user runs to approve the newest blocked request (`approve --last`). */
|
|
27
|
+
export declare function approveLastCommand(context?: HookContext): string;
|
|
28
|
+
/**
|
|
29
|
+
* What Codex shows for a decision that needs a person. Codex cannot ask, so the agent must stop
|
|
30
|
+
* and hand the user one command; the first line says so, and the command stands on its own line.
|
|
31
|
+
*/
|
|
32
|
+
export declare function approveInstruction(decision: Decision, context?: HookContext): string;
|
|
21
33
|
export declare function hookResponse(harness: Request["harness"], phase: string, decision: Decision, context?: HookContext): Record<string, unknown>;
|
|
22
34
|
/** The exact stdout of a PreToolUse or PermissionRequest hook. Codex gets no output for no decision. */
|
|
23
35
|
export declare function hookOutput(harness: Request["harness"], phase: string, decision: Decision, context?: HookContext): string;
|
package/dist/adapters.js
CHANGED
|
@@ -79,6 +79,53 @@ const CLASSIFY_INVOCATION = new RegExp(String.raw `(?:^|[;&|({` +
|
|
|
79
79
|
export function looksLikeClassifyRecord(command) {
|
|
80
80
|
return CLASSIFY_INVOCATION.test(command);
|
|
81
81
|
}
|
|
82
|
+
/**
|
|
83
|
+
* A command that runs, or names, a policy-manager `approve`, anywhere in the script and at any
|
|
84
|
+
* nesting (`sh -c '...'`, a here-document). Unlike a classification record, the agent never runs
|
|
85
|
+
* this: only the user approves, from their own terminal.
|
|
86
|
+
*/
|
|
87
|
+
const APPROVE_PROGRAM = /^(?:.*cli\.js|(?:@agent-corpus\/)?policy-manager(?:@.*)?)$/;
|
|
88
|
+
// A token scan rather than one regular expression over the command, so its cost stays linear.
|
|
89
|
+
export function looksLikeApproveGrant(command) {
|
|
90
|
+
const tokens = command.split(/[\s"'`;&|()]+/);
|
|
91
|
+
return tokens.some((token, i) => tokens[i + 1] === "approve" && APPROVE_PROGRAM.test(token));
|
|
92
|
+
}
|
|
93
|
+
/** The command the user runs in their own terminal to approve a human decision. */
|
|
94
|
+
export function approveCommand(harness, requestHash, context) {
|
|
95
|
+
const cliPath = context && /^[A-Za-z]:\\/.test(context.cliPath)
|
|
96
|
+
? context.cliPath.replace(/\\/g, "/")
|
|
97
|
+
: context?.cliPath;
|
|
98
|
+
return cliPath && context
|
|
99
|
+
? `node "${cliPath}" approve ${harness} ${context.sessionId} ${requestHash}`
|
|
100
|
+
: `policy-manager approve ${harness} <session-id> ${requestHash}`;
|
|
101
|
+
}
|
|
102
|
+
/** The short command the user runs to approve the newest blocked request (`approve --last`). */
|
|
103
|
+
export function approveLastCommand(context) {
|
|
104
|
+
if (context?.pmOnPath)
|
|
105
|
+
return "pm approve --last";
|
|
106
|
+
const cliPath = context && /^[A-Za-z]:\\/.test(context.cliPath)
|
|
107
|
+
? context.cliPath.replace(/\\/g, "/")
|
|
108
|
+
: context?.cliPath;
|
|
109
|
+
return cliPath ? `node "${cliPath}" approve --last` : "policy-manager approve --last";
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* What Codex shows for a decision that needs a person. Codex cannot ask, so the agent must stop
|
|
113
|
+
* and hand the user one command; the first line says so, and the command stands on its own line.
|
|
114
|
+
*/
|
|
115
|
+
export function approveInstruction(decision, context) {
|
|
116
|
+
return [
|
|
117
|
+
`⏸ Waiting for your approval. Not run: ${decision.reason}.`,
|
|
118
|
+
'Run in your own terminal, then say "retry":',
|
|
119
|
+
` ${approveLastCommand(context)}`,
|
|
120
|
+
...(decision.sessionGrantable
|
|
121
|
+
? [
|
|
122
|
+
`Add --session to also allow ${decision.sessionScopeLabel ?? "the same rule for the same scope"} for the rest of this session.`,
|
|
123
|
+
]
|
|
124
|
+
: []),
|
|
125
|
+
"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.",
|
|
126
|
+
`Request ${decision.requestHash}.`,
|
|
127
|
+
].join("\n");
|
|
128
|
+
}
|
|
82
129
|
/** What a blocked ambiguous request tells the model to do. Never ask for human approval here. */
|
|
83
130
|
function classifyInstruction(harness, decision, context) {
|
|
84
131
|
const command = classifyCommand(harness, context);
|
|
@@ -115,11 +162,19 @@ export function hookResponse(harness, phase, decision, context) {
|
|
|
115
162
|
return decision.decision === "approve" ? { behavior: "allow" } : {};
|
|
116
163
|
return decision.decision === "approve"
|
|
117
164
|
? { permissionDecision: "allow" }
|
|
118
|
-
: {
|
|
165
|
+
: {
|
|
166
|
+
permissionDecision: "ask",
|
|
167
|
+
permissionDecisionReason: decision.reason,
|
|
168
|
+
};
|
|
119
169
|
}
|
|
120
170
|
if (phase === "PermissionRequest")
|
|
121
171
|
return decision.decision === "approve"
|
|
122
|
-
? {
|
|
172
|
+
? {
|
|
173
|
+
hookSpecificOutput: {
|
|
174
|
+
hookEventName: phase,
|
|
175
|
+
decision: { behavior: "allow" },
|
|
176
|
+
},
|
|
177
|
+
}
|
|
123
178
|
: {};
|
|
124
179
|
// Codex rejects PreToolUse `permissionDecision: "allow"` without `updatedInput` ("unsupported
|
|
125
180
|
// permissionDecision:allow") and marks the hook failed. An approval there is no decision at all;
|
|
@@ -127,22 +182,30 @@ export function hookResponse(harness, phase, decision, context) {
|
|
|
127
182
|
if (decision.decision === "approve")
|
|
128
183
|
return harness === "codex"
|
|
129
184
|
? {}
|
|
130
|
-
: {
|
|
185
|
+
: {
|
|
186
|
+
hookSpecificOutput: {
|
|
187
|
+
hookEventName: phase,
|
|
188
|
+
permissionDecision: "allow",
|
|
189
|
+
},
|
|
190
|
+
};
|
|
131
191
|
// Codex parses permissionDecision "ask" but does not support it: it marks the hook failed and
|
|
132
192
|
// runs the tool anyway (https://developers.openai.com/codex/hooks). Only "deny" stops a command,
|
|
133
|
-
// so a decision that needs a human is a deny. Approving it in chat does not change the decision
|
|
134
|
-
//
|
|
135
|
-
// request (needsClassification),
|
|
136
|
-
// (PermissionRequest, above) still handles the requests it
|
|
193
|
+
// 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), or an
|
|
195
|
+
// ambiguous request (needsClassification) is classified, and a retry then sees the approval.
|
|
196
|
+
// Codex's own approval prompt (PermissionRequest, above) still handles the requests it asks about.
|
|
137
197
|
if (harness === "codex") {
|
|
138
|
-
const
|
|
139
|
-
|
|
140
|
-
|
|
198
|
+
const classify = decision.needsClassification === true && decision.classification !== "fallback";
|
|
199
|
+
const reason = !classify && !decision.userOnly
|
|
200
|
+
? approveInstruction(decision, context)
|
|
201
|
+
: `Policy manager: ${decision.reason}. This needs a human decision and was not run. ${classify
|
|
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}.`;
|
|
141
204
|
return {
|
|
142
205
|
hookSpecificOutput: {
|
|
143
206
|
hookEventName: phase,
|
|
144
207
|
permissionDecision: "deny",
|
|
145
|
-
permissionDecisionReason:
|
|
208
|
+
permissionDecisionReason: reason,
|
|
146
209
|
},
|
|
147
210
|
};
|
|
148
211
|
}
|
package/dist/cli.js
CHANGED
|
@@ -1,23 +1,28 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { dirname, join } from "node:path";
|
|
4
|
+
import { createInterface } from "node:readline/promises";
|
|
4
5
|
import { fileURLToPath } from "node:url";
|
|
5
6
|
import { parseArgs } from "node:util";
|
|
6
7
|
import { executionReport, hookOutput, normalize } from "./adapters.js";
|
|
8
|
+
import { sessionDirectoryPath } from "./audit.js";
|
|
7
9
|
import { hookConfig } from "./config.js";
|
|
8
10
|
import { HUMAN_REVIEW_PRINCIPLE } from "./principle.js";
|
|
9
11
|
import { defaultProfilePath, loadProfile, parseProfile } from "./profile.js";
|
|
10
12
|
import { replayTranscripts } from "./replay.js";
|
|
11
13
|
import { formatReview, reviewClassifications, sessionDirectories } from "./review.js";
|
|
12
|
-
import { send, serve, start, stop } from "./service.js";
|
|
14
|
+
import { latestHumanDecision, send, sendTo, serve, start, stop } from "./service.js";
|
|
13
15
|
import { SetupError, setupHook } from "./setup.js";
|
|
16
|
+
import { cliVersion, inspectShim, shimDirectory } from "./shim.js";
|
|
14
17
|
const usage = `policy-manager usage [--json]
|
|
15
18
|
policy-manager hook <claude|codex|copilot> <SessionStart|PreToolUse|PermissionRequest|PostToolUse|PostToolUseFailure|SessionEnd>
|
|
16
19
|
policy-manager review <claude|codex|copilot> <session-id> # normalized request JSON on stdin
|
|
17
20
|
policy-manager classify <claude|codex|copilot> <session-id> # {requestHash,category,confidence} on stdin
|
|
18
21
|
policy-manager record <claude|codex|copilot> <session-id> # host-reported human response or execution result JSON
|
|
19
|
-
policy-manager
|
|
20
|
-
policy-manager
|
|
22
|
+
policy-manager approve --last [--session] # the user, in their own terminal: allow the newest blocked request once, or its rule and scope for the session
|
|
23
|
+
policy-manager approve <claude|codex|copilot> <session-id> <request-hash> [--session] # the same for one exact request
|
|
24
|
+
policy-manager setup-hook <claude|codex|copilot> [--dry-run] [--config-dir <harness-config-directory>] [--shim-dir <directory>]
|
|
25
|
+
policy-manager setup-hook-claude|setup-hook-codex|setup-hook-copilot [--dry-run] [--config-dir <directory>] [--shim-dir <directory>]
|
|
21
26
|
policy-manager config <claude|codex|copilot> <absolute-installed-cli-path>
|
|
22
27
|
policy-manager profile validate <file> # check a policy profile without installing it
|
|
23
28
|
policy-manager profile install <file> # install it to the user config directory outside Git
|
|
@@ -28,6 +33,9 @@ A per-session background service checks policy and writes private temporary audi
|
|
|
28
33
|
AI classification comes from the session's policy-manager agent, never an external API.
|
|
29
34
|
Unknown effects require human approval. Exit 0: protocol response; exit 1: malformed input or service failure.
|
|
30
35
|
`;
|
|
36
|
+
/** An `approve` failure whose message is meant for the user. */
|
|
37
|
+
class ApproveError extends Error {
|
|
38
|
+
}
|
|
31
39
|
async function stdin() {
|
|
32
40
|
let text = "";
|
|
33
41
|
for await (const chunk of process.stdin) {
|
|
@@ -44,6 +52,16 @@ const args = process.argv.slice(2);
|
|
|
44
52
|
const [action, harnessArg, phase] = args;
|
|
45
53
|
const harness = harnessArg;
|
|
46
54
|
const cliPath = fileURLToPath(import.meta.url);
|
|
55
|
+
/** Whether a managed `pm` launcher for this CLI is installed and on PATH. */
|
|
56
|
+
function pmReady() {
|
|
57
|
+
try {
|
|
58
|
+
const status = inspectShim(shimDirectory(), cliPath, cliVersion(cliPath));
|
|
59
|
+
return status.state === "current" && status.onPath;
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
47
65
|
try {
|
|
48
66
|
if (action === "usage" || !action)
|
|
49
67
|
console.log(args.includes("--json") ? JSON.stringify({ usage }) : usage);
|
|
@@ -52,11 +70,16 @@ try {
|
|
|
52
70
|
const selected = (alias ?? harnessArg);
|
|
53
71
|
const { values } = parseArgs({
|
|
54
72
|
args: args.slice(alias ? 1 : 2),
|
|
55
|
-
options: {
|
|
73
|
+
options: {
|
|
74
|
+
"dry-run": { type: "boolean" },
|
|
75
|
+
"config-dir": { type: "string" },
|
|
76
|
+
"shim-dir": { type: "string" },
|
|
77
|
+
},
|
|
56
78
|
});
|
|
57
79
|
console.log(JSON.stringify(setupHook(selected, cliPath, {
|
|
58
80
|
dryRun: values["dry-run"],
|
|
59
81
|
configDirectory: values["config-dir"],
|
|
82
|
+
shimDirectory: values["shim-dir"],
|
|
60
83
|
}), null, 2));
|
|
61
84
|
}
|
|
62
85
|
else if (action === "config")
|
|
@@ -69,6 +92,7 @@ try {
|
|
|
69
92
|
mode: profile.mode,
|
|
70
93
|
cloudWrites: profile.cloudWrites,
|
|
71
94
|
mcpReadOnly: profile.mcpReadOnly.length,
|
|
95
|
+
toolsDeny: Object.values(profile.toolsDeny).reduce((n, list) => n + list.length, 0),
|
|
72
96
|
digest: profile.digest,
|
|
73
97
|
};
|
|
74
98
|
if (harnessArg === "install") {
|
|
@@ -114,6 +138,68 @@ try {
|
|
|
114
138
|
const review = await reviewClassifications(sessionDirectories(values.dir ?? []), values.since);
|
|
115
139
|
console.log(values.json ? JSON.stringify(review, null, 2) : formatReview(review));
|
|
116
140
|
}
|
|
141
|
+
else if (action === "approve") {
|
|
142
|
+
const { values, positionals } = parseArgs({
|
|
143
|
+
args: args.slice(1),
|
|
144
|
+
options: { session: { type: "boolean" }, last: { type: "boolean" } },
|
|
145
|
+
allowPositionals: true,
|
|
146
|
+
});
|
|
147
|
+
const usageText = "Usage: policy-manager approve --last [--session], or approve <claude|codex|copilot> <session-id> <request-hash> [--session]";
|
|
148
|
+
let directory;
|
|
149
|
+
let requestHash;
|
|
150
|
+
if (values.last) {
|
|
151
|
+
if (positionals.length)
|
|
152
|
+
throw new ApproveError(usageText);
|
|
153
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY)
|
|
154
|
+
throw new ApproveError("Run approve yourself in an interactive terminal; it asks you to confirm the request.");
|
|
155
|
+
const latest = await latestHumanDecision();
|
|
156
|
+
if (!latest)
|
|
157
|
+
throw new ApproveError("No running policy session has a request waiting for approval from the last 15 minutes. Have the agent retry so it is blocked again.");
|
|
158
|
+
({ directory, requestHash } = latest);
|
|
159
|
+
console.log(`Session: ${latest.harness} ${latest.sessionId}`);
|
|
160
|
+
}
|
|
161
|
+
else {
|
|
162
|
+
const [target, sessionId, hashArg] = positionals;
|
|
163
|
+
if (!["claude", "codex", "copilot"].includes(target) ||
|
|
164
|
+
!/^[A-Za-z0-9_.-]+$/.test(sessionId ?? "") ||
|
|
165
|
+
!/^[a-f0-9]{64}$/.test(hashArg ?? ""))
|
|
166
|
+
throw new ApproveError(usageText);
|
|
167
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY)
|
|
168
|
+
throw new ApproveError("Run approve yourself in an interactive terminal; it asks you to confirm the request.");
|
|
169
|
+
if (!existsSync(sessionDirectoryPath(target, sessionId)))
|
|
170
|
+
throw new ApproveError("No policy service is running for that session.");
|
|
171
|
+
directory = sessionDirectoryPath(target, sessionId);
|
|
172
|
+
requestHash = hashArg;
|
|
173
|
+
}
|
|
174
|
+
const ask = (confirm) => sendTo(directory, {
|
|
175
|
+
action: "grant",
|
|
176
|
+
grant: { requestHash, confirm, session: values.session === true },
|
|
177
|
+
});
|
|
178
|
+
const preview = await ask(false);
|
|
179
|
+
if (preview.refused)
|
|
180
|
+
throw new ApproveError(preview.refused);
|
|
181
|
+
console.log(`Tool: ${preview.tool}\nRequest: ${preview.detail}\nRule: ${preview.reason}`);
|
|
182
|
+
if (values.session && preview.scope !== "session")
|
|
183
|
+
console.log("This request can only be approved once: credential reads, possible unrecoverable loss and requests whose effect could not be determined are never approved for a session.");
|
|
184
|
+
if (preview.scope === "session" && preview.sessionScope)
|
|
185
|
+
console.log(`Scope: ${preview.sessionScope}`);
|
|
186
|
+
const prompt = createInterface({
|
|
187
|
+
input: process.stdin,
|
|
188
|
+
output: process.stdout,
|
|
189
|
+
});
|
|
190
|
+
const answer = await prompt.question(preview.scope === "session"
|
|
191
|
+
? "Allow this and later requests in this session that hit the same rule for the same scope? [y/N] "
|
|
192
|
+
: "Allow this request once? [y/N] ");
|
|
193
|
+
prompt.close();
|
|
194
|
+
if (!/^y(?:es)?$/i.test(answer.trim()))
|
|
195
|
+
throw new ApproveError("Not approved.");
|
|
196
|
+
const granted = await ask(true);
|
|
197
|
+
if (!granted.granted)
|
|
198
|
+
throw new ApproveError(granted.refused ?? "Not approved.");
|
|
199
|
+
console.log(granted.scope === "session"
|
|
200
|
+
? "Approved for this session. Tell the agent to retry the request unchanged."
|
|
201
|
+
: "Approved once. Tell the agent to retry the request unchanged.");
|
|
202
|
+
}
|
|
117
203
|
else if (action === "serve")
|
|
118
204
|
await serve(harness, phase ?? "", cliPath);
|
|
119
205
|
else if (action === "stop")
|
|
@@ -141,7 +227,12 @@ try {
|
|
|
141
227
|
const context = `Policy service started. Audit log: ${join(directory, "audit.jsonl")}. Native hooks route tool and permission requests directly to the deterministic service. An ambiguous request is blocked once with instructions to have the policy-manager agent classify it and then retry; the person is asked only if classification fails. ${HUMAN_REVIEW_PRINCIPLE} If .agent-config/agents/policy-manager.md exists, read it before creating a read-only policy-manager agent. Never ask an agent to approve its own tools.`;
|
|
142
228
|
console.log(JSON.stringify(harness === "copilot"
|
|
143
229
|
? { additionalContext: context }
|
|
144
|
-
: {
|
|
230
|
+
: {
|
|
231
|
+
hookSpecificOutput: {
|
|
232
|
+
hookEventName: phase,
|
|
233
|
+
additionalContext: context,
|
|
234
|
+
},
|
|
235
|
+
}));
|
|
145
236
|
}
|
|
146
237
|
else if (phase === "PostToolUse" || phase === "PostToolUseFailure") {
|
|
147
238
|
await send(harness, request.sessionId, {
|
|
@@ -159,6 +250,7 @@ try {
|
|
|
159
250
|
const output = hookOutput(harness, phase, decision, {
|
|
160
251
|
cliPath,
|
|
161
252
|
sessionId: request.sessionId,
|
|
253
|
+
pmOnPath: decision.decision === "human" && harness === "codex" && pmReady(),
|
|
162
254
|
});
|
|
163
255
|
if (output)
|
|
164
256
|
console.log(output);
|
|
@@ -171,7 +263,15 @@ try {
|
|
|
171
263
|
throw new Error(usage);
|
|
172
264
|
}
|
|
173
265
|
catch (error) {
|
|
174
|
-
if (
|
|
266
|
+
if (error instanceof ApproveError) {
|
|
267
|
+
console.error(error.message);
|
|
268
|
+
process.exitCode = 1;
|
|
269
|
+
}
|
|
270
|
+
else if (action === "approve") {
|
|
271
|
+
console.error("The approval could not be recorded. Nothing was approved.");
|
|
272
|
+
process.exitCode = 1;
|
|
273
|
+
}
|
|
274
|
+
else if (action?.startsWith("setup-hook")) {
|
|
175
275
|
console.error(error instanceof SetupError
|
|
176
276
|
? error.message
|
|
177
277
|
: "Hook setup failed. No automatic approval was granted.");
|
package/dist/flow.js
CHANGED
|
@@ -68,6 +68,16 @@ function replace(target, source) {
|
|
|
68
68
|
}
|
|
69
69
|
// --- words ------------------------------------------------------------------------------------
|
|
70
70
|
const isKnown = (values) => !!values?.length && values.every((v) => SIMPLE_VALUE.test(v));
|
|
71
|
+
/** The one literal value of a variable, usable only inside double quotes. */
|
|
72
|
+
function literalValue(values) {
|
|
73
|
+
const value = values?.length === 1 ? values[0] : undefined;
|
|
74
|
+
return value !== undefined &&
|
|
75
|
+
value.length <= 4096 &&
|
|
76
|
+
!value.includes("\0") &&
|
|
77
|
+
!value.includes(SUBSTITUTION)
|
|
78
|
+
? value
|
|
79
|
+
: undefined;
|
|
80
|
+
}
|
|
71
81
|
/**
|
|
72
82
|
* Environment variables whose value is harmless to print or pass on. Any other variable the script
|
|
73
83
|
* did not assign could hold a credential (`$GITHUB_TOKEN`, `$AWS_SECRET_ACCESS_KEY`), so using it
|
|
@@ -202,6 +212,9 @@ function instantiate(word, known, env, state) {
|
|
|
202
212
|
}
|
|
203
213
|
else if (known.has(part.name))
|
|
204
214
|
text += applyParamOp(env[part.name] ?? "", part.op);
|
|
215
|
+
else if (part.quoted && !part.op && literalValue(state?.vars.get(part.name)) !== undefined)
|
|
216
|
+
// Inside double quotes a literal value is one word with no further expansion.
|
|
217
|
+
text += literalValue(state?.vars.get(part.name));
|
|
205
218
|
else {
|
|
206
219
|
text += SUBSTITUTION;
|
|
207
220
|
// "$@" is one word per parameter even when quoted.
|
|
@@ -458,7 +471,11 @@ function splitAssignment(word) {
|
|
|
458
471
|
return undefined;
|
|
459
472
|
return {
|
|
460
473
|
name,
|
|
461
|
-
value: {
|
|
474
|
+
value: {
|
|
475
|
+
...word,
|
|
476
|
+
parts: [first.slice(eq + 1), ...word.parts.slice(1)],
|
|
477
|
+
subs: [],
|
|
478
|
+
},
|
|
462
479
|
};
|
|
463
480
|
}
|
|
464
481
|
/** grep and rg options whose value is a file-name glob. */
|
|
@@ -607,6 +624,13 @@ function runSimple(ctx, node, state, stage, piped) {
|
|
|
607
624
|
continue;
|
|
608
625
|
}
|
|
609
626
|
}
|
|
627
|
+
// A single literal value that is not one plain word (`Q='query($t: ID!)'`) is kept for
|
|
628
|
+
// double-quoted use only: isKnown rejects it, so an unquoted `$Q` stays unknown.
|
|
629
|
+
const set = [...new Set(texts)];
|
|
630
|
+
if (set.length === 1 && literalValue(set) !== undefined) {
|
|
631
|
+
state.vars.set(a.name, set);
|
|
632
|
+
continue;
|
|
633
|
+
}
|
|
610
634
|
state.vars.set(a.name, null);
|
|
611
635
|
}
|
|
612
636
|
ctx.box.last = result(request, "code-read", "Variable assignment", true);
|
|
@@ -672,7 +696,10 @@ function runSimple(ctx, node, state, stage, piped) {
|
|
|
672
696
|
}
|
|
673
697
|
/** In a loop, a pipeline or a background job, a later command can run first. */
|
|
674
698
|
function fillFor(ctx, piped) {
|
|
675
|
-
return {
|
|
699
|
+
return {
|
|
700
|
+
script: ctx.box.script,
|
|
701
|
+
reorder: ctx.loop > 0 || piped || !!ctx.reorder,
|
|
702
|
+
};
|
|
676
703
|
}
|
|
677
704
|
/**
|
|
678
705
|
* Programs that create no symlink: they read, print, or write regular files only. Shells are here
|
|
@@ -1500,13 +1527,20 @@ export function commandDecision(request, command, profile, depth = 0, start = [r
|
|
|
1500
1527
|
loop: 0,
|
|
1501
1528
|
calls: 0,
|
|
1502
1529
|
positional: !/argv/.test(command),
|
|
1503
|
-
box: {
|
|
1530
|
+
box: {
|
|
1531
|
+
calls: 0,
|
|
1532
|
+
script: fill?.script ?? { tainted: false, approved: false, jobs: 0 },
|
|
1533
|
+
},
|
|
1504
1534
|
...(fill?.reorder ? { reorder: true } : {}),
|
|
1505
1535
|
};
|
|
1506
1536
|
const opening = script.items[0];
|
|
1507
1537
|
if (depth === 0 && opening && !opening.background)
|
|
1508
1538
|
ctx.box.first = opening.node.first;
|
|
1509
|
-
const refusal = runList(ctx, script, {
|
|
1539
|
+
const refusal = runList(ctx, script, {
|
|
1540
|
+
cwds: [...start],
|
|
1541
|
+
vars: new Map(),
|
|
1542
|
+
funcs: new Map(),
|
|
1543
|
+
});
|
|
1510
1544
|
return refusal ?? ctx.box.last ?? human(request, "unknown", "Empty command");
|
|
1511
1545
|
}
|
|
1512
1546
|
//# sourceMappingURL=flow.js.map
|
package/dist/grants.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Profile } from "./profile.js";
|
|
2
|
+
import type { Decision, Request } from "./types.js";
|
|
3
|
+
export declare const PROTECTED_PATH = "Protected path requires human approval";
|
|
4
|
+
export declare const HUMAN_PATTERN = "Matches an organization human-approval pattern";
|
|
5
|
+
/**
|
|
6
|
+
* The scope a `--session` approval of this human decision covers, or undefined when it can only
|
|
7
|
+
* be approved once. Credential and secret reads, possible unrecoverable loss and anything whose
|
|
8
|
+
* targets cannot be read from the request stay one-time. Scopes:
|
|
9
|
+
* - a protected-path write: the protected roots it touches (`<worktree>/.agent-config`);
|
|
10
|
+
* - a humanPatterns match: the matching patterns, in the same checkout;
|
|
11
|
+
* - any other human rule for a simple command: that exact command, same checkout.
|
|
12
|
+
* Category unknown (the engine could not rule out loss) is approved once only.
|
|
13
|
+
* Shell scopes need a simple command, so nothing else in the script hides behind the rule.
|
|
14
|
+
*/
|
|
15
|
+
export declare function grantScope(request: Request, decision: Decision, profile: Profile): string | undefined;
|
|
16
|
+
/** What a session scope covers, in words the user can check before approving it. */
|
|
17
|
+
export declare function scopeLabel(scope: string, profile: Profile): string;
|
|
18
|
+
//# sourceMappingURL=grants.d.ts.map
|