@agent-corpus/policy-manager 0.7.0 → 0.8.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 +17 -2
- package/dist/adapters.d.ts +3 -0
- package/dist/adapters.js +35 -6
- package/dist/cli.js +57 -2
- package/dist/grants.d.ts +18 -0
- package/dist/grants.js +131 -0
- package/dist/service.d.ts +6 -1
- package/dist/service.js +15 -3
- package/dist/session.d.ts +44 -0
- package/dist/session.js +156 -3
- package/dist/types.d.ts +4 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -93,7 +93,7 @@ How a hook call flows (Claude Code, Codex and Copilot `PreToolUse`):
|
|
|
93
93
|
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
94
|
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
95
|
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
|
|
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 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
97
|
|
|
98
98
|
**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
99
|
|
|
@@ -114,6 +114,21 @@ policy-manager review-classifications [--since 2026-11-12T00:00:00Z] [--json]
|
|
|
114
114
|
|
|
115
115
|
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
116
|
|
|
117
|
+
## Approving from the terminal
|
|
118
|
+
|
|
119
|
+
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 gives the command the user runs in their own terminal:
|
|
120
|
+
|
|
121
|
+
```sh
|
|
122
|
+
policy-manager approve <claude|codex|copilot> <session-id> <request-hash> [--session]
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
It shows the tool, the redacted request and the rule, and asks for confirmation; it refuses to run without an interactive terminal. The request must be one this session sent to a person in the last 15 minutes. Then the agent retries the same request unchanged.
|
|
126
|
+
|
|
127
|
+
- **Once (default).** The next review of that exact request is approved, once per hook phase (`PreToolUse`, then `PermissionRequest`), and the grant is spent.
|
|
128
|
+
- **`--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.
|
|
129
|
+
|
|
130
|
+
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.
|
|
131
|
+
|
|
117
132
|
## Policy
|
|
118
133
|
|
|
119
134
|
- Ordinary file reads must resolve inside a Git repository.
|
|
@@ -222,7 +237,7 @@ The cache belongs to the service process and is scoped to harness plus session I
|
|
|
222
237
|
|
|
223
238
|
`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
239
|
|
|
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
|
|
240
|
+
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
241
|
|
|
227
242
|
## Audit API and reported outcomes
|
|
228
243
|
|
package/dist/adapters.d.ts
CHANGED
|
@@ -18,6 +18,9 @@ export declare function classifyCommand(harness: Request["harness"], context?: H
|
|
|
18
18
|
export declare function isClassifyRecord(command: string, harness: Request["harness"], context: HookContext): boolean;
|
|
19
19
|
/** A command that runs a policy-manager classification record, for any session or CLI. */
|
|
20
20
|
export declare function looksLikeClassifyRecord(command: string): boolean;
|
|
21
|
+
export declare function looksLikeApproveGrant(command: string): boolean;
|
|
22
|
+
/** The command the user runs in their own terminal to approve a human decision. */
|
|
23
|
+
export declare function approveCommand(harness: Request["harness"], requestHash: string, context?: HookContext): string;
|
|
21
24
|
export declare function hookResponse(harness: Request["harness"], phase: string, decision: Decision, context?: HookContext): Record<string, unknown>;
|
|
22
25
|
/** The exact stdout of a PreToolUse or PermissionRequest hook. Codex gets no output for no decision. */
|
|
23
26
|
export declare function hookOutput(harness: Request["harness"], phase: string, decision: Decision, context?: HookContext): string;
|
package/dist/adapters.js
CHANGED
|
@@ -79,6 +79,33 @@ 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
|
+
function approveInstruction(harness, decision, context) {
|
|
103
|
+
const command = approveCommand(harness, decision.requestHash, context);
|
|
104
|
+
const session = decision.sessionGrantable
|
|
105
|
+
? " Adding --session also allows later requests in this session that hit the same rule for the same scope."
|
|
106
|
+
: "";
|
|
107
|
+
return `Approving it in chat does not unblock it. To allow it once, the user runs in their own terminal: ${command} — then retry the same request unchanged.${session} Do not run that command yourself.`;
|
|
108
|
+
}
|
|
82
109
|
/** What a blocked ambiguous request tells the model to do. Never ask for human approval here. */
|
|
83
110
|
function classifyInstruction(harness, decision, context) {
|
|
84
111
|
const command = classifyCommand(harness, context);
|
|
@@ -130,14 +157,16 @@ export function hookResponse(harness, phase, decision, context) {
|
|
|
130
157
|
: { hookSpecificOutput: { hookEventName: phase, permissionDecision: "allow" } };
|
|
131
158
|
// Codex parses permissionDecision "ask" but does not support it: it marks the hook failed and
|
|
132
159
|
// 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
|
|
160
|
+
// so a decision that needs a human is a deny. Approving it in chat does not change the decision;
|
|
161
|
+
// the user approves it from their own terminal (`approve`, once or for the session), or an
|
|
162
|
+
// ambiguous request (needsClassification) is classified, and a retry then sees the approval.
|
|
163
|
+
// Codex's own approval prompt (PermissionRequest, above) still handles the requests it asks about.
|
|
137
164
|
if (harness === "codex") {
|
|
138
165
|
const next = decision.needsClassification === true && decision.classification !== "fallback"
|
|
139
|
-
? "Classify it with the session policy-manager agent and retry. If it is not classified as approved,
|
|
140
|
-
:
|
|
166
|
+
? "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."
|
|
167
|
+
: decision.userOnly
|
|
168
|
+
? "Do not run approve yourself: ask the user to approve the original request from their own terminal."
|
|
169
|
+
: approveInstruction(harness, decision, context);
|
|
141
170
|
return {
|
|
142
171
|
hookSpecificOutput: {
|
|
143
172
|
hookEventName: phase,
|
package/dist/cli.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
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";
|
|
@@ -16,6 +18,7 @@ policy-manager hook <claude|codex|copilot> <SessionStart|PreToolUse|PermissionRe
|
|
|
16
18
|
policy-manager review <claude|codex|copilot> <session-id> # normalized request JSON on stdin
|
|
17
19
|
policy-manager classify <claude|codex|copilot> <session-id> # {requestHash,category,confidence} on stdin
|
|
18
20
|
policy-manager record <claude|codex|copilot> <session-id> # host-reported human response or execution result JSON
|
|
21
|
+
policy-manager approve <claude|codex|copilot> <session-id> <request-hash> [--session] # the user, in their own terminal: allow a blocked request once, or its rule and scope for the session
|
|
19
22
|
policy-manager setup-hook <claude|codex|copilot> [--dry-run] [--config-dir <harness-config-directory>]
|
|
20
23
|
policy-manager setup-hook-claude|setup-hook-codex|setup-hook-copilot [--dry-run] [--config-dir <directory>]
|
|
21
24
|
policy-manager config <claude|codex|copilot> <absolute-installed-cli-path>
|
|
@@ -28,6 +31,9 @@ A per-session background service checks policy and writes private temporary audi
|
|
|
28
31
|
AI classification comes from the session's policy-manager agent, never an external API.
|
|
29
32
|
Unknown effects require human approval. Exit 0: protocol response; exit 1: malformed input or service failure.
|
|
30
33
|
`;
|
|
34
|
+
/** An `approve` failure whose message is meant for the user. */
|
|
35
|
+
class ApproveError extends Error {
|
|
36
|
+
}
|
|
31
37
|
async function stdin() {
|
|
32
38
|
let text = "";
|
|
33
39
|
for await (const chunk of process.stdin) {
|
|
@@ -114,6 +120,47 @@ try {
|
|
|
114
120
|
const review = await reviewClassifications(sessionDirectories(values.dir ?? []), values.since);
|
|
115
121
|
console.log(values.json ? JSON.stringify(review, null, 2) : formatReview(review));
|
|
116
122
|
}
|
|
123
|
+
else if (action === "approve") {
|
|
124
|
+
const { values, positionals } = parseArgs({
|
|
125
|
+
args: args.slice(1),
|
|
126
|
+
options: { session: { type: "boolean" } },
|
|
127
|
+
allowPositionals: true,
|
|
128
|
+
});
|
|
129
|
+
const [target, sessionId, requestHash] = positionals;
|
|
130
|
+
if (!["claude", "codex", "copilot"].includes(target) ||
|
|
131
|
+
!/^[A-Za-z0-9_.-]+$/.test(sessionId ?? "") ||
|
|
132
|
+
!/^[a-f0-9]{64}$/.test(requestHash ?? ""))
|
|
133
|
+
throw new ApproveError("Usage: policy-manager approve <claude|codex|copilot> <session-id> <request-hash> [--session]");
|
|
134
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY)
|
|
135
|
+
throw new ApproveError("Run approve yourself in an interactive terminal; it asks you to confirm the request.");
|
|
136
|
+
if (!existsSync(sessionDirectoryPath(target, sessionId)))
|
|
137
|
+
throw new ApproveError("No policy service is running for that session.");
|
|
138
|
+
const ask = (confirm) => send(target, sessionId, {
|
|
139
|
+
action: "grant",
|
|
140
|
+
grant: { requestHash, confirm, session: values.session === true },
|
|
141
|
+
});
|
|
142
|
+
const preview = await ask(false);
|
|
143
|
+
if (preview.refused)
|
|
144
|
+
throw new ApproveError(preview.refused);
|
|
145
|
+
console.log(`Tool: ${preview.tool}\nRequest: ${preview.detail}\nRule: ${preview.reason}`);
|
|
146
|
+
if (values.session && preview.scope !== "session")
|
|
147
|
+
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.");
|
|
148
|
+
if (preview.scope === "session" && preview.sessionScope)
|
|
149
|
+
console.log(`Scope: ${preview.sessionScope}`);
|
|
150
|
+
const prompt = createInterface({ input: process.stdin, output: process.stdout });
|
|
151
|
+
const answer = await prompt.question(preview.scope === "session"
|
|
152
|
+
? "Allow this and later requests in this session that hit the same rule for the same scope? [y/N] "
|
|
153
|
+
: "Allow this request once? [y/N] ");
|
|
154
|
+
prompt.close();
|
|
155
|
+
if (!/^y(?:es)?$/i.test(answer.trim()))
|
|
156
|
+
throw new ApproveError("Not approved.");
|
|
157
|
+
const granted = await ask(true);
|
|
158
|
+
if (!granted.granted)
|
|
159
|
+
throw new ApproveError(granted.refused ?? "Not approved.");
|
|
160
|
+
console.log(granted.scope === "session"
|
|
161
|
+
? "Approved for this session. Tell the agent to retry the request unchanged."
|
|
162
|
+
: "Approved once. Tell the agent to retry the request unchanged.");
|
|
163
|
+
}
|
|
117
164
|
else if (action === "serve")
|
|
118
165
|
await serve(harness, phase ?? "", cliPath);
|
|
119
166
|
else if (action === "stop")
|
|
@@ -171,7 +218,15 @@ try {
|
|
|
171
218
|
throw new Error(usage);
|
|
172
219
|
}
|
|
173
220
|
catch (error) {
|
|
174
|
-
if (
|
|
221
|
+
if (error instanceof ApproveError) {
|
|
222
|
+
console.error(error.message);
|
|
223
|
+
process.exitCode = 1;
|
|
224
|
+
}
|
|
225
|
+
else if (action === "approve") {
|
|
226
|
+
console.error("The approval could not be recorded. Nothing was approved.");
|
|
227
|
+
process.exitCode = 1;
|
|
228
|
+
}
|
|
229
|
+
else if (action?.startsWith("setup-hook")) {
|
|
175
230
|
console.error(error instanceof SetupError
|
|
176
231
|
? error.message
|
|
177
232
|
: "Hook setup failed. No automatic approval was granted.");
|
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
|
package/dist/grants.js
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { existsSync, statSync } from "node:fs";
|
|
2
|
+
import { dirname, join, relative } from "node:path";
|
|
3
|
+
import { canonical, git, inside, policyState, protectedPath, resolveWord, sensitive, } from "./evidence.js";
|
|
4
|
+
import { SHELL_TOOLS, words } from "./policy.js";
|
|
5
|
+
export const PROTECTED_PATH = "Protected path requires human approval";
|
|
6
|
+
export const HUMAN_PATTERN = "Matches an organization human-approval pattern";
|
|
7
|
+
const FILE_TOOLS = new Set(["Write", "create", "write_file", "Edit", "edit", "MultiEdit"]);
|
|
8
|
+
function topLevel(path) {
|
|
9
|
+
let parent = existsSync(path) && statSync(path).isDirectory() ? path : dirname(path);
|
|
10
|
+
while (!existsSync(parent))
|
|
11
|
+
parent = dirname(parent);
|
|
12
|
+
return canonical(git(parent, ["rev-parse", "--show-toplevel"]));
|
|
13
|
+
}
|
|
14
|
+
/** `<checkout>/<first protected name>` for a path inside a protected directory of a checkout. */
|
|
15
|
+
function protectedRoot(path) {
|
|
16
|
+
const top = topLevel(path);
|
|
17
|
+
const target = canonical(path);
|
|
18
|
+
if (!inside(top, target))
|
|
19
|
+
return undefined;
|
|
20
|
+
const parts = relative(top, target).split(/[\\/]/);
|
|
21
|
+
const index = parts.findIndex((part) => protectedPath(part));
|
|
22
|
+
return index < 0 ? undefined : join(top, ...parts.slice(0, index + 1));
|
|
23
|
+
}
|
|
24
|
+
/** The paths a request names: file tool targets, patch headers, or a simple command's path words. */
|
|
25
|
+
function targets(request) {
|
|
26
|
+
const input = request.input;
|
|
27
|
+
if (FILE_TOOLS.has(request.tool)) {
|
|
28
|
+
const file = input.file_path ?? input.path;
|
|
29
|
+
return typeof file === "string" ? [file] : undefined;
|
|
30
|
+
}
|
|
31
|
+
if (request.tool === "apply_patch") {
|
|
32
|
+
const patch = input.command ?? input.patch ?? input.input;
|
|
33
|
+
if (typeof patch !== "string")
|
|
34
|
+
return undefined;
|
|
35
|
+
const found = patch
|
|
36
|
+
.split("\n")
|
|
37
|
+
.flatMap((line) => /^\*\*\* (?:Add File|Update File|Delete File|Move to): /.test(line)
|
|
38
|
+
? [line.slice(line.indexOf(": ") + 2).trim()]
|
|
39
|
+
: []);
|
|
40
|
+
return found.length ? found : undefined;
|
|
41
|
+
}
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
/** A simple command (one program, no operators, expansions or redirects) as words. */
|
|
45
|
+
function simple(request) {
|
|
46
|
+
const command = request.input.command ?? request.input.cmd;
|
|
47
|
+
if (!SHELL_TOOLS.has(request.tool) || typeof command !== "string")
|
|
48
|
+
return undefined;
|
|
49
|
+
const argv = words(command);
|
|
50
|
+
return argv?.length ? argv : undefined;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* The scope a `--session` approval of this human decision covers, or undefined when it can only
|
|
54
|
+
* be approved once. Credential and secret reads, possible unrecoverable loss and anything whose
|
|
55
|
+
* targets cannot be read from the request stay one-time. Scopes:
|
|
56
|
+
* - a protected-path write: the protected roots it touches (`<worktree>/.agent-config`);
|
|
57
|
+
* - a humanPatterns match: the matching patterns, in the same checkout;
|
|
58
|
+
* - any other human rule for a simple command: that exact command, same checkout.
|
|
59
|
+
* Category unknown (the engine could not rule out loss) is approved once only.
|
|
60
|
+
* Shell scopes need a simple command, so nothing else in the script hides behind the rule.
|
|
61
|
+
*/
|
|
62
|
+
export function grantScope(request, decision, profile) {
|
|
63
|
+
try {
|
|
64
|
+
if (decision.reason === PROTECTED_PATH) {
|
|
65
|
+
let paths = targets(request);
|
|
66
|
+
if (!paths) {
|
|
67
|
+
const argv = simple(request);
|
|
68
|
+
paths = argv
|
|
69
|
+
?.slice(1)
|
|
70
|
+
.filter((word) => !word.startsWith("-") && (word.includes("/") || word.startsWith(".")));
|
|
71
|
+
}
|
|
72
|
+
if (!paths?.length)
|
|
73
|
+
return undefined;
|
|
74
|
+
const roots = new Set();
|
|
75
|
+
let top;
|
|
76
|
+
for (const path of paths) {
|
|
77
|
+
const lexical = resolveWord(request.cwd, path);
|
|
78
|
+
if (sensitive(lexical) || policyState(lexical))
|
|
79
|
+
return undefined;
|
|
80
|
+
const resolved = canonical(lexical);
|
|
81
|
+
if (sensitive(resolved) || policyState(resolved))
|
|
82
|
+
return undefined;
|
|
83
|
+
const root = protectedRoot(resolved);
|
|
84
|
+
const checkout = topLevel(resolved);
|
|
85
|
+
if (top !== undefined && checkout !== top)
|
|
86
|
+
return undefined;
|
|
87
|
+
top = checkout;
|
|
88
|
+
if (root)
|
|
89
|
+
roots.add(root);
|
|
90
|
+
}
|
|
91
|
+
return roots.size ? `protected:${[...roots].sort().join("\u0000")}` : undefined;
|
|
92
|
+
}
|
|
93
|
+
const argv = simple(request);
|
|
94
|
+
if (!argv)
|
|
95
|
+
return undefined;
|
|
96
|
+
const checkout = topLevel(request.cwd);
|
|
97
|
+
if (decision.reason === HUMAN_PATTERN) {
|
|
98
|
+
const joined = argv.join(" ");
|
|
99
|
+
const matched = profile.humanPatterns.flatMap((pattern, index) => pattern.test(joined) ? [index] : []);
|
|
100
|
+
return matched.length ? `pattern:${matched.join(",")}:${checkout}` : undefined;
|
|
101
|
+
}
|
|
102
|
+
if (decision.category === "sensitive" ||
|
|
103
|
+
decision.category === "destructive" ||
|
|
104
|
+
decision.category === "unknown")
|
|
105
|
+
return undefined;
|
|
106
|
+
if (argv.slice(1).some((word) => sensitive(word)))
|
|
107
|
+
return undefined;
|
|
108
|
+
return `command:${decision.reason}:${JSON.stringify(argv)}:${checkout}`;
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
return undefined;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/** What a session scope covers, in words the user can check before approving it. */
|
|
115
|
+
export function scopeLabel(scope, profile) {
|
|
116
|
+
if (scope.startsWith("protected:"))
|
|
117
|
+
return `writes under ${scope.slice("protected:".length).split("\u0000").join(", ")}`;
|
|
118
|
+
if (scope.startsWith("pattern:")) {
|
|
119
|
+
const [, indexes = "", ...checkout] = scope.split(":");
|
|
120
|
+
const patterns = indexes
|
|
121
|
+
.split(",")
|
|
122
|
+
.map((index) => profile.humanPatterns[Number(index)]?.source ?? index)
|
|
123
|
+
.join(", ");
|
|
124
|
+
return `commands matching ${patterns} in ${checkout.join(":")}`;
|
|
125
|
+
}
|
|
126
|
+
const rest = scope.slice(scope.indexOf(":[") + 1);
|
|
127
|
+
const end = rest.lastIndexOf("]:");
|
|
128
|
+
const argv = JSON.parse(rest.slice(0, end + 1));
|
|
129
|
+
return `the exact command \`${argv.join(" ")}\` in ${rest.slice(end + 2)}`;
|
|
130
|
+
}
|
|
131
|
+
//# sourceMappingURL=grants.js.map
|
package/dist/service.d.ts
CHANGED
|
@@ -1,11 +1,16 @@
|
|
|
1
1
|
import type { Classification, OutcomeReport, Request } from "./types.js";
|
|
2
2
|
interface Message {
|
|
3
3
|
token: string;
|
|
4
|
-
action: "ping" | "review" | "classify" | "record" | "stop";
|
|
4
|
+
action: "ping" | "review" | "classify" | "record" | "grant" | "stop";
|
|
5
5
|
request?: Request;
|
|
6
6
|
classification?: Classification;
|
|
7
7
|
report?: OutcomeReport;
|
|
8
8
|
phase?: string;
|
|
9
|
+
grant?: {
|
|
10
|
+
requestHash: string;
|
|
11
|
+
confirm: boolean;
|
|
12
|
+
session?: boolean;
|
|
13
|
+
};
|
|
9
14
|
}
|
|
10
15
|
export declare function serve(harness: string, sessionId: string, cliPath?: string): Promise<void>;
|
|
11
16
|
export declare function send(harness: string, sessionId: string, message: Omit<Message, "token">): Promise<unknown>;
|
package/dist/service.js
CHANGED
|
@@ -5,7 +5,7 @@ import { join } from "node:path";
|
|
|
5
5
|
import { audit, sessionDirectory, sessionDirectoryPath, sessionToken } from "./audit.js";
|
|
6
6
|
import { hash, requestHash } from "./policy.js";
|
|
7
7
|
import { loadProfile, strictProfile } from "./profile.js";
|
|
8
|
-
import { PolicySession } from "./session.js";
|
|
8
|
+
import { GrantError, PolicySession } from "./session.js";
|
|
9
9
|
function endpoint(directory) {
|
|
10
10
|
return process.platform === "win32"
|
|
11
11
|
? `\\\\.\\pipe\\acp-${hash(directory).slice(0, 32)}`
|
|
@@ -49,8 +49,10 @@ export async function serve(harness, sessionId, cliPath) {
|
|
|
49
49
|
? { requestHash: message.classification.requestHash }
|
|
50
50
|
: message.report
|
|
51
51
|
? { requestHash: message.report.requestHash }
|
|
52
|
-
:
|
|
53
|
-
|
|
52
|
+
: message.grant
|
|
53
|
+
? { requestHash: String(message.grant.requestHash) }
|
|
54
|
+
: {}),
|
|
55
|
+
action: ["ping", "review", "classify", "record", "grant", "stop"].includes(message.action)
|
|
54
56
|
? message.action
|
|
55
57
|
: "invalid",
|
|
56
58
|
});
|
|
@@ -71,6 +73,16 @@ export async function serve(harness, sessionId, cliPath) {
|
|
|
71
73
|
session.record(message.report);
|
|
72
74
|
result = { recorded: true };
|
|
73
75
|
}
|
|
76
|
+
else if (message.action === "grant" && message.grant) {
|
|
77
|
+
try {
|
|
78
|
+
result = session.grant(String(message.grant.requestHash), message.grant.confirm === true, message.grant.session === true);
|
|
79
|
+
}
|
|
80
|
+
catch (error) {
|
|
81
|
+
if (!(error instanceof GrantError))
|
|
82
|
+
throw error;
|
|
83
|
+
result = { granted: false, refused: error.message };
|
|
84
|
+
}
|
|
85
|
+
}
|
|
74
86
|
else
|
|
75
87
|
throw new Error("Invalid service request");
|
|
76
88
|
socket.end(`${JSON.stringify({ result })}\n`);
|
package/dist/session.d.ts
CHANGED
|
@@ -2,6 +2,23 @@ import { type Profile } from "./profile.js";
|
|
|
2
2
|
import { type Classification, type Decision, type OutcomeReport, type Request } from "./types.js";
|
|
3
3
|
/** AI approvals per session; beyond this, ambiguous requests go to a human. */
|
|
4
4
|
export declare const MAX_AI_APPROVALS = 50;
|
|
5
|
+
export declare const APPROVE_GUARD = "Only the user may approve a request, by running approve in their own terminal";
|
|
6
|
+
/** How long after a human decision the user may still approve that exact request once. */
|
|
7
|
+
export declare const GRANT_WINDOW_MS: number;
|
|
8
|
+
/** What `approve` shows the user before a one-time grant: the request a person must decide. */
|
|
9
|
+
export interface GrantPreview {
|
|
10
|
+
requestHash: string;
|
|
11
|
+
tool: string;
|
|
12
|
+
category: Decision["category"];
|
|
13
|
+
reason: string;
|
|
14
|
+
/** Redacted command or target, for the user to recognize the request. */
|
|
15
|
+
detail: string;
|
|
16
|
+
/** What a session approval would cover, when this request can be approved for the session. */
|
|
17
|
+
sessionScope?: string;
|
|
18
|
+
}
|
|
19
|
+
/** A grant the service refuses; its message is safe to show the user. */
|
|
20
|
+
export declare class GrantError extends Error {
|
|
21
|
+
}
|
|
5
22
|
export declare class PolicySession {
|
|
6
23
|
readonly directory: string;
|
|
7
24
|
readonly harness: string;
|
|
@@ -17,6 +34,12 @@ export declare class PolicySession {
|
|
|
17
34
|
/** Files this session created, and the paths each approved request may create. */
|
|
18
35
|
private created;
|
|
19
36
|
private creating;
|
|
37
|
+
/** Requests this session sent to a person, which the user may approve once. */
|
|
38
|
+
private humanDecisions;
|
|
39
|
+
/** One-time user approvals, each usable once per hook phase. */
|
|
40
|
+
private grants;
|
|
41
|
+
/** Session grants: hashes of a human rule and the scope the user approved it for. */
|
|
42
|
+
private sessionGrants;
|
|
20
43
|
constructor(directory: string, harness: string, sessionId: string, profile?: Profile,
|
|
21
44
|
/** This package's `cli.js`: the path in the record command the hook gives the model. */
|
|
22
45
|
cliPath?: string | undefined);
|
|
@@ -27,6 +50,27 @@ export declare class PolicySession {
|
|
|
27
50
|
* another session or CLI or with anything added, goes to a person.
|
|
28
51
|
*/
|
|
29
52
|
private classifyRecord;
|
|
53
|
+
/**
|
|
54
|
+
* Only the user approves a request once, from their own terminal. A shell command that runs a
|
|
55
|
+
* policy-manager `approve`, in any form or nesting, is never approved for the agent.
|
|
56
|
+
*/
|
|
57
|
+
private approveGrant;
|
|
58
|
+
/**
|
|
59
|
+
* A user approval that covers this human decision: a one-time grant for this exact request
|
|
60
|
+
* (used once per hook phase), or a session grant for its rule and scope. Each use is audited.
|
|
61
|
+
*/
|
|
62
|
+
private granted;
|
|
63
|
+
/**
|
|
64
|
+
* Looks up, and with `confirm` grants, a user approval of a request this session sent to a
|
|
65
|
+
* person within the last GRANT_WINDOW_MS. Without `session` the next review of that exact
|
|
66
|
+
* request is approved once per hook phase; with it, every later request in this session that
|
|
67
|
+
* hits the same rule for the same scope is approved. A request with no session scope (credential
|
|
68
|
+
* reads, possible unrecoverable loss) is approved once only, and the result says so.
|
|
69
|
+
*/
|
|
70
|
+
grant(requestHash: string, confirm: boolean, session?: boolean): GrantPreview & {
|
|
71
|
+
granted: boolean;
|
|
72
|
+
scope: "once" | "session";
|
|
73
|
+
};
|
|
30
74
|
private state;
|
|
31
75
|
private remember;
|
|
32
76
|
/**
|
package/dist/session.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { isClassifyRecord, looksLikeClassifyRecord } from "./adapters.js";
|
|
1
|
+
import { isClassifyRecord, looksLikeApproveGrant, looksLikeClassifyRecord } from "./adapters.js";
|
|
2
2
|
import { audit, requestSummary } from "./audit.js";
|
|
3
3
|
import { creationTargets, pathKey, settle, withCreated, } from "./created.js";
|
|
4
|
+
import { grantScope, scopeLabel } from "./grants.js";
|
|
4
5
|
import { evaluate, hash, requestHash as requestHashOf, result, SHELL_TOOLS } from "./policy.js";
|
|
5
6
|
import { strictProfile } from "./profile.js";
|
|
6
7
|
import { redactText } from "./redact.js";
|
|
@@ -11,6 +12,26 @@ const CLASSIFICATION_TTL_MS = 5 * 60_000;
|
|
|
11
12
|
export const MAX_AI_APPROVALS = 50;
|
|
12
13
|
/** How long after its approval an execution report may still record the files a tool created. */
|
|
13
14
|
const CREATION_REPORT_MS = 15 * 60_000;
|
|
15
|
+
export const APPROVE_GUARD = "Only the user may approve a request, by running approve in their own terminal";
|
|
16
|
+
/** How long after a human decision the user may still approve that exact request once. */
|
|
17
|
+
export const GRANT_WINDOW_MS = 15 * 60_000;
|
|
18
|
+
/** A grant the service refuses; its message is safe to show the user. */
|
|
19
|
+
export class GrantError extends Error {
|
|
20
|
+
}
|
|
21
|
+
function grantDetail(request) {
|
|
22
|
+
const command = request.input.command ?? request.input.cmd;
|
|
23
|
+
if (typeof command === "string")
|
|
24
|
+
return redactText(command, 300);
|
|
25
|
+
const file = request.input.file_path ?? request.input.path;
|
|
26
|
+
if (typeof file === "string")
|
|
27
|
+
return redactText(file, 300);
|
|
28
|
+
if (typeof request.input.patch === "string" || typeof request.input.input === "string")
|
|
29
|
+
return redactText(String(request.input.patch ?? request.input.input)
|
|
30
|
+
.split("\n")
|
|
31
|
+
.filter((line) => /^\*\*\* (?:Add|Update|Delete) File:/.test(line))
|
|
32
|
+
.join("; "), 300);
|
|
33
|
+
return request.tool;
|
|
34
|
+
}
|
|
14
35
|
export class PolicySession {
|
|
15
36
|
directory;
|
|
16
37
|
harness;
|
|
@@ -25,6 +46,12 @@ export class PolicySession {
|
|
|
25
46
|
/** Files this session created, and the paths each approved request may create. */
|
|
26
47
|
created = new Map();
|
|
27
48
|
creating = new Map();
|
|
49
|
+
/** Requests this session sent to a person, which the user may approve once. */
|
|
50
|
+
humanDecisions = new Map();
|
|
51
|
+
/** One-time user approvals, each usable once per hook phase. */
|
|
52
|
+
grants = new Map();
|
|
53
|
+
/** Session grants: hashes of a human rule and the scope the user approved it for. */
|
|
54
|
+
sessionGrants = new Set();
|
|
28
55
|
constructor(directory, harness, sessionId, profile = strictProfile,
|
|
29
56
|
/** This package's `cli.js`: the path in the record command the hook gives the model. */
|
|
30
57
|
cliPath) {
|
|
@@ -60,6 +87,107 @@ export class PolicySession {
|
|
|
60
87
|
return result(request, "temp-write", "Records a classification for this session", true);
|
|
61
88
|
return result(request, "unknown", "A classification record for another session or CLI, or with anything added, requires human review");
|
|
62
89
|
}
|
|
90
|
+
/**
|
|
91
|
+
* Only the user approves a request once, from their own terminal. A shell command that runs a
|
|
92
|
+
* policy-manager `approve`, in any form or nesting, is never approved for the agent.
|
|
93
|
+
*/
|
|
94
|
+
approveGrant(request) {
|
|
95
|
+
const command = request.input.command ?? request.input.cmd;
|
|
96
|
+
if (!SHELL_TOOLS.has(request.tool) || typeof command !== "string")
|
|
97
|
+
return undefined;
|
|
98
|
+
if (!looksLikeApproveGrant(command))
|
|
99
|
+
return undefined;
|
|
100
|
+
return result(request, "sensitive", APPROVE_GUARD);
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* A user approval that covers this human decision: a one-time grant for this exact request
|
|
104
|
+
* (used once per hook phase), or a session grant for its rule and scope. Each use is audited.
|
|
105
|
+
*/
|
|
106
|
+
granted(request, decision, phase) {
|
|
107
|
+
const once = this.grants.get(decision.requestHash);
|
|
108
|
+
const slot = phase ?? "review";
|
|
109
|
+
if (once && !once.phases.has(slot)) {
|
|
110
|
+
once.phases.add(slot);
|
|
111
|
+
// PreToolUse runs before PermissionRequest; once both have allowed the tool, it is spent.
|
|
112
|
+
if (once.phases.has("PreToolUse") && once.phases.has("PermissionRequest"))
|
|
113
|
+
this.grants.delete(decision.requestHash);
|
|
114
|
+
audit(this.directory, {
|
|
115
|
+
event: "human-grant-use",
|
|
116
|
+
requestHash: decision.requestHash,
|
|
117
|
+
scope: "once",
|
|
118
|
+
phase: slot,
|
|
119
|
+
});
|
|
120
|
+
return { ...result(request, decision.category, "Approved once by the user", true) };
|
|
121
|
+
}
|
|
122
|
+
const scope = grantScope(request, decision, this.profile);
|
|
123
|
+
if (scope === undefined)
|
|
124
|
+
return undefined;
|
|
125
|
+
const key = hash([decision.reason, scope]);
|
|
126
|
+
if (!this.sessionGrants.has(key))
|
|
127
|
+
return undefined;
|
|
128
|
+
audit(this.directory, {
|
|
129
|
+
event: "human-grant-use",
|
|
130
|
+
requestHash: decision.requestHash,
|
|
131
|
+
scope: "session",
|
|
132
|
+
scopeHash: key,
|
|
133
|
+
phase: slot,
|
|
134
|
+
});
|
|
135
|
+
return {
|
|
136
|
+
...result(request, decision.category, "Approved for this session by the user", true),
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Looks up, and with `confirm` grants, a user approval of a request this session sent to a
|
|
141
|
+
* person within the last GRANT_WINDOW_MS. Without `session` the next review of that exact
|
|
142
|
+
* request is approved once per hook phase; with it, every later request in this session that
|
|
143
|
+
* hits the same rule for the same scope is approved. A request with no session scope (credential
|
|
144
|
+
* reads, possible unrecoverable loss) is approved once only, and the result says so.
|
|
145
|
+
*/
|
|
146
|
+
grant(requestHash, confirm, session = false) {
|
|
147
|
+
if (!/^[a-f0-9]{64}$/.test(requestHash))
|
|
148
|
+
throw new GrantError("Not a request hash");
|
|
149
|
+
const pending = this.humanDecisions.get(requestHash);
|
|
150
|
+
if (!pending || Date.now() - pending.at > GRANT_WINDOW_MS) {
|
|
151
|
+
this.humanDecisions.delete(requestHash);
|
|
152
|
+
throw new GrantError("No request in this session needed a person with that hash in the last 15 minutes. Retry the request so it is blocked again, then approve the new hash.");
|
|
153
|
+
}
|
|
154
|
+
const { at: _at, sessionScope, ...rest } = pending;
|
|
155
|
+
const scope = session && sessionScope !== undefined ? "session" : "once";
|
|
156
|
+
const preview = {
|
|
157
|
+
...rest,
|
|
158
|
+
...(scope === "session" && sessionScope !== undefined
|
|
159
|
+
? { sessionScope: scopeLabel(sessionScope, this.profile) }
|
|
160
|
+
: {}),
|
|
161
|
+
};
|
|
162
|
+
if (!confirm)
|
|
163
|
+
return { ...preview, granted: false, scope };
|
|
164
|
+
this.humanDecisions.delete(requestHash);
|
|
165
|
+
if (scope === "session" && sessionScope !== undefined) {
|
|
166
|
+
if (this.sessionGrants.size >= 64)
|
|
167
|
+
this.sessionGrants.clear();
|
|
168
|
+
this.sessionGrants.add(hash([preview.reason, sessionScope]));
|
|
169
|
+
}
|
|
170
|
+
if (this.grants.size >= 64)
|
|
171
|
+
this.grants.delete(this.grants.keys().next().value ?? "");
|
|
172
|
+
this.grants.set(requestHash, { phases: new Set() });
|
|
173
|
+
audit(this.directory, {
|
|
174
|
+
event: "human-grant",
|
|
175
|
+
requestHash,
|
|
176
|
+
category: preview.category,
|
|
177
|
+
scope,
|
|
178
|
+
...(scope === "session" ? { scopeHash: hash([preview.reason, sessionScope]) } : {}),
|
|
179
|
+
summary: scope === "session"
|
|
180
|
+
? "User approved the rule for this session"
|
|
181
|
+
: "User approved the request once",
|
|
182
|
+
});
|
|
183
|
+
audit(this.directory, {
|
|
184
|
+
event: "human-response",
|
|
185
|
+
requestHash,
|
|
186
|
+
response: "approved",
|
|
187
|
+
summary: "User approved the request from the terminal",
|
|
188
|
+
});
|
|
189
|
+
return { ...preview, granted: true, scope };
|
|
190
|
+
}
|
|
63
191
|
state(requestHash) {
|
|
64
192
|
const state = this.states.get(requestHash);
|
|
65
193
|
if (state && state.expires <= Date.now()) {
|
|
@@ -124,7 +252,8 @@ export class PolicySession {
|
|
|
124
252
|
...(ai.recoverable === undefined ? {} : { recoverable: ai.recoverable }),
|
|
125
253
|
...(ai.rationale ? { rationale: redactText(ai.rationale, 200) } : {}),
|
|
126
254
|
});
|
|
127
|
-
let decision = this.
|
|
255
|
+
let decision = this.approveGrant(request) ??
|
|
256
|
+
this.classifyRecord(request) ??
|
|
128
257
|
withCreated(this.created, () => evaluate(request, ai ?? cachedAi ?? known?.ai, this.profile));
|
|
129
258
|
if (decision.tier === "ambiguous") {
|
|
130
259
|
if (ai && !decision.classification)
|
|
@@ -180,8 +309,32 @@ export class PolicySession {
|
|
|
180
309
|
}
|
|
181
310
|
}
|
|
182
311
|
}
|
|
183
|
-
if (decision.decision === "human")
|
|
312
|
+
if (decision.decision === "human") {
|
|
313
|
+
const allowed = this.granted(request, decision, phase);
|
|
314
|
+
if (allowed)
|
|
315
|
+
decision = allowed;
|
|
316
|
+
}
|
|
317
|
+
if (decision.decision === "human" && decision.reason === APPROVE_GUARD) {
|
|
318
|
+
this.cache.delete(key);
|
|
319
|
+
decision = { ...decision, userOnly: true, sessionGrantable: false };
|
|
320
|
+
}
|
|
321
|
+
else if (decision.decision === "human") {
|
|
184
322
|
this.cache.delete(key);
|
|
323
|
+
const sessionScope = grantScope(request, decision, this.profile);
|
|
324
|
+
decision = { ...decision, sessionGrantable: sessionScope !== undefined };
|
|
325
|
+
if (this.humanDecisions.size >= 256)
|
|
326
|
+
this.humanDecisions.delete(this.humanDecisions.keys().next().value ?? "");
|
|
327
|
+
this.humanDecisions.delete(requestHash);
|
|
328
|
+
this.humanDecisions.set(requestHash, {
|
|
329
|
+
requestHash,
|
|
330
|
+
tool: request.tool,
|
|
331
|
+
category: decision.category,
|
|
332
|
+
reason: decision.reason,
|
|
333
|
+
detail: grantDetail(request),
|
|
334
|
+
at: Date.now(),
|
|
335
|
+
...(sessionScope === undefined ? {} : { sessionScope }),
|
|
336
|
+
});
|
|
337
|
+
}
|
|
185
338
|
// Evaluation always precedes lookup. Filesystem evidence is never cached.
|
|
186
339
|
if (decision.decision === "approve" && decision.cache === "session") {
|
|
187
340
|
decision.cached = entry !== undefined && entry.expires > Date.now() && ai === undefined;
|
package/dist/types.d.ts
CHANGED
|
@@ -38,6 +38,10 @@ export interface Decision {
|
|
|
38
38
|
/** Why a human was asked after classification could not decide. */
|
|
39
39
|
fallbackReason?: "unavailable" | "invalid-result" | "limit";
|
|
40
40
|
ai?: Classification;
|
|
41
|
+
/** A human decision the user may approve for the rest of the session (`approve --session`). */
|
|
42
|
+
sessionGrantable?: boolean;
|
|
43
|
+
/** The agent tried to approve a request itself: no approval instruction is offered for it. */
|
|
44
|
+
userOnly?: boolean;
|
|
41
45
|
}
|
|
42
46
|
export interface OutcomeReport {
|
|
43
47
|
requestHash: string;
|
package/package.json
CHANGED