@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/dist/grants.js
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
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
|
+
import { parseShell, SUBSTITUTION } from "./shell.js";
|
|
6
|
+
export const PROTECTED_PATH = "Protected path requires human approval";
|
|
7
|
+
export const HUMAN_PATTERN = "Matches an organization human-approval pattern";
|
|
8
|
+
const FILE_TOOLS = new Set(["Write", "create", "write_file", "Edit", "edit", "MultiEdit"]);
|
|
9
|
+
function topLevel(path) {
|
|
10
|
+
let parent = existsSync(path) && statSync(path).isDirectory() ? path : dirname(path);
|
|
11
|
+
while (!existsSync(parent))
|
|
12
|
+
parent = dirname(parent);
|
|
13
|
+
return canonical(git(parent, ["rev-parse", "--show-toplevel"]));
|
|
14
|
+
}
|
|
15
|
+
/** `<checkout>/<first protected name>` for a path inside a protected directory of a checkout. */
|
|
16
|
+
function protectedRoot(path) {
|
|
17
|
+
const top = topLevel(path);
|
|
18
|
+
const target = canonical(path);
|
|
19
|
+
if (!inside(top, target))
|
|
20
|
+
return undefined;
|
|
21
|
+
const parts = relative(top, target).split(/[\\/]/);
|
|
22
|
+
const index = parts.findIndex((part) => protectedPath(part));
|
|
23
|
+
return index < 0 ? undefined : join(top, ...parts.slice(0, index + 1));
|
|
24
|
+
}
|
|
25
|
+
/** The paths a request names: file tool targets, patch headers, or a simple command's path words. */
|
|
26
|
+
function targets(request) {
|
|
27
|
+
const input = request.input;
|
|
28
|
+
if (FILE_TOOLS.has(request.tool)) {
|
|
29
|
+
const file = input.file_path ?? input.path;
|
|
30
|
+
return typeof file === "string" ? [file] : undefined;
|
|
31
|
+
}
|
|
32
|
+
if (request.tool === "apply_patch") {
|
|
33
|
+
const patch = input.command ?? input.patch ?? input.input;
|
|
34
|
+
if (typeof patch !== "string")
|
|
35
|
+
return undefined;
|
|
36
|
+
const found = patch
|
|
37
|
+
.split("\n")
|
|
38
|
+
.flatMap((line) => /^\*\*\* (?:Add File|Update File|Delete File|Move to): /.test(line)
|
|
39
|
+
? [line.slice(line.indexOf(": ") + 2).trim()]
|
|
40
|
+
: []);
|
|
41
|
+
return found.length ? found : undefined;
|
|
42
|
+
}
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Every word of a single shell command that could name a file it touches: non-option arguments,
|
|
47
|
+
* the value of `--option=value` or `-oVALUE`, and redirect targets (`> f`, `>> f`, `< f`). One program, no
|
|
48
|
+
* operators, pipes, substitutions or variables. A word that is not a path only adds a scope, so
|
|
49
|
+
* treating it as one fails closed.
|
|
50
|
+
*/
|
|
51
|
+
function shellPaths(request) {
|
|
52
|
+
const command = request.input.command ?? request.input.cmd;
|
|
53
|
+
if (!SHELL_TOOLS.has(request.tool) || typeof command !== "string")
|
|
54
|
+
return undefined;
|
|
55
|
+
const pipelines = parseShell(command);
|
|
56
|
+
const only = pipelines?.length === 1 && pipelines[0]?.length === 1 ? pipelines[0][0] : undefined;
|
|
57
|
+
if (!only || only.env.length || only.subs.length || only.stdin !== undefined)
|
|
58
|
+
return undefined;
|
|
59
|
+
const texts = [...only.argv, ...only.redirects.map((r) => r.target)];
|
|
60
|
+
if (texts.some((text) => text.includes(SUBSTITUTION)))
|
|
61
|
+
return undefined;
|
|
62
|
+
const paths = [];
|
|
63
|
+
for (const word of only.argv.slice(1)) {
|
|
64
|
+
if (!word.startsWith("-"))
|
|
65
|
+
paths.push(word);
|
|
66
|
+
else if (word.startsWith("--")) {
|
|
67
|
+
if (word.includes("="))
|
|
68
|
+
paths.push(word.slice(word.indexOf("=") + 1));
|
|
69
|
+
}
|
|
70
|
+
// `-oFILE` attaches a value to a short option; flags like `-rf` only add a harmless path.
|
|
71
|
+
else if (word.length > 2)
|
|
72
|
+
paths.push(word.slice(2).replace(/^=/, ""));
|
|
73
|
+
}
|
|
74
|
+
for (const redirect of only.redirects)
|
|
75
|
+
if (redirect.op !== ">&" && redirect.target !== "/dev/null")
|
|
76
|
+
paths.push(redirect.target);
|
|
77
|
+
return paths.filter((path) => path.length > 0);
|
|
78
|
+
}
|
|
79
|
+
/** A simple command (one program, no operators, expansions or redirects) as words. */
|
|
80
|
+
function simple(request) {
|
|
81
|
+
const command = request.input.command ?? request.input.cmd;
|
|
82
|
+
if (!SHELL_TOOLS.has(request.tool) || typeof command !== "string")
|
|
83
|
+
return undefined;
|
|
84
|
+
const argv = words(command);
|
|
85
|
+
return argv?.length ? argv : undefined;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* The scope a `--session` approval of this human decision covers, or undefined when it can only
|
|
89
|
+
* be approved once. Credential and secret reads, possible unrecoverable loss and anything whose
|
|
90
|
+
* targets cannot be read from the request stay one-time. Scopes:
|
|
91
|
+
* - a protected-path write: the protected roots it touches (`<worktree>/.agent-config`);
|
|
92
|
+
* - a humanPatterns match: the matching patterns, in the same checkout;
|
|
93
|
+
* - any other human rule for a simple command: that exact command, same checkout.
|
|
94
|
+
* Category unknown (the engine could not rule out loss) is approved once only.
|
|
95
|
+
* Shell scopes need a simple command, so nothing else in the script hides behind the rule.
|
|
96
|
+
*/
|
|
97
|
+
export function grantScope(request, decision, profile) {
|
|
98
|
+
try {
|
|
99
|
+
if (decision.reason === PROTECTED_PATH) {
|
|
100
|
+
const paths = targets(request) ?? shellPaths(request);
|
|
101
|
+
if (!paths?.length)
|
|
102
|
+
return undefined;
|
|
103
|
+
const roots = new Set();
|
|
104
|
+
let top;
|
|
105
|
+
for (const path of paths) {
|
|
106
|
+
const lexical = resolveWord(request.cwd, path);
|
|
107
|
+
if (sensitive(lexical) || policyState(lexical))
|
|
108
|
+
return undefined;
|
|
109
|
+
const resolved = canonical(lexical);
|
|
110
|
+
if (sensitive(resolved) || policyState(resolved))
|
|
111
|
+
return undefined;
|
|
112
|
+
const root = protectedRoot(resolved);
|
|
113
|
+
const checkout = topLevel(resolved);
|
|
114
|
+
if (top !== undefined && checkout !== top)
|
|
115
|
+
return undefined;
|
|
116
|
+
top = checkout;
|
|
117
|
+
if (root)
|
|
118
|
+
roots.add(root);
|
|
119
|
+
}
|
|
120
|
+
return roots.size ? `protected:${[...roots].sort().join("\u0000")}` : undefined;
|
|
121
|
+
}
|
|
122
|
+
const argv = simple(request);
|
|
123
|
+
if (!argv)
|
|
124
|
+
return undefined;
|
|
125
|
+
const checkout = topLevel(request.cwd);
|
|
126
|
+
if (decision.reason === HUMAN_PATTERN) {
|
|
127
|
+
const joined = argv.join(" ");
|
|
128
|
+
const matched = profile.humanPatterns.flatMap((pattern, index) => pattern.test(joined) ? [index] : []);
|
|
129
|
+
return matched.length ? `pattern:${matched.join(",")}:${checkout}` : undefined;
|
|
130
|
+
}
|
|
131
|
+
if (decision.category === "sensitive" ||
|
|
132
|
+
decision.category === "destructive" ||
|
|
133
|
+
decision.category === "unknown")
|
|
134
|
+
return undefined;
|
|
135
|
+
if (argv.slice(1).some((word) => sensitive(word)))
|
|
136
|
+
return undefined;
|
|
137
|
+
return `command:${decision.reason}:${JSON.stringify(argv)}:${checkout}`;
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
return undefined;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
/** What a session scope covers, in words the user can check before approving it. */
|
|
144
|
+
export function scopeLabel(scope, profile) {
|
|
145
|
+
if (scope.startsWith("protected:"))
|
|
146
|
+
return `writes under ${scope.slice("protected:".length).split("\u0000").join(", ")}`;
|
|
147
|
+
if (scope.startsWith("pattern:")) {
|
|
148
|
+
const [, indexes = "", ...checkout] = scope.split(":");
|
|
149
|
+
const patterns = indexes
|
|
150
|
+
.split(",")
|
|
151
|
+
.map((index) => profile.humanPatterns[Number(index)]?.source ?? index)
|
|
152
|
+
.join(", ");
|
|
153
|
+
return `commands matching ${patterns} in ${checkout.join(":")}`;
|
|
154
|
+
}
|
|
155
|
+
const rest = scope.slice(scope.indexOf(":[") + 1);
|
|
156
|
+
const end = rest.lastIndexOf("]:");
|
|
157
|
+
const argv = JSON.parse(rest.slice(0, end + 1));
|
|
158
|
+
return `the exact command \`${argv.join(" ")}\` in ${rest.slice(end + 2)}`;
|
|
159
|
+
}
|
|
160
|
+
//# sourceMappingURL=grants.js.map
|
package/dist/permissive.d.ts
CHANGED
|
@@ -3,6 +3,12 @@ import { commandDecision } from "./flow.js";
|
|
|
3
3
|
import type { Profile } from "./profile.js";
|
|
4
4
|
import { type Redirect, type SimpleCommand } from "./shell.js";
|
|
5
5
|
import type { Decision, Request } from "./types.js";
|
|
6
|
+
/**
|
|
7
|
+
* The files `sort` writes: its `-o`/`--output` file and its `-T`/`--temporary-directory`. Options
|
|
8
|
+
* are parsed as GNU getopt does (clustered short options, exact or unique long prefixes).
|
|
9
|
+
* Undefined when it may run another program (`--compress-program`) or an option is unknown.
|
|
10
|
+
*/
|
|
11
|
+
export declare function sortWrites(args: string[]): string[] | undefined;
|
|
6
12
|
export declare const BANNED_ENV: RegExp;
|
|
7
13
|
export declare function human(request: Request, category: Decision["category"], reason: string): Decision;
|
|
8
14
|
export declare function permissiveRead(cwd: string, input: string): {
|
package/dist/permissive.js
CHANGED
|
@@ -51,6 +51,65 @@ const WRITERS = new Set([
|
|
|
51
51
|
"chown",
|
|
52
52
|
]);
|
|
53
53
|
const WRAPPERS = new Set(["env", "nohup", "time", "command", "nice", "timeout", "xargs"]);
|
|
54
|
+
const SORT_LONG = [
|
|
55
|
+
...["ignore-leading-blanks", "dictionary-order", "ignore-case", "general-numeric-sort"],
|
|
56
|
+
...["ignore-nonprinting", "month-sort", "human-numeric-sort", "numeric-sort", "random-sort"],
|
|
57
|
+
...["random-source", "reverse", "sort", "version-sort", "batch-size", "check", "debug"],
|
|
58
|
+
...["compress-program", "files0-from", "key", "merge", "output", "stable", "buffer-size"],
|
|
59
|
+
...["field-separator", "temporary-directory", "parallel", "unique", "zero-terminated"],
|
|
60
|
+
...["help", "version"],
|
|
61
|
+
];
|
|
62
|
+
const SORT_LONG_VALUE = new Set([
|
|
63
|
+
...["random-source", "sort", "batch-size", "compress-program", "files0-from", "key"],
|
|
64
|
+
...["output", "buffer-size", "field-separator", "temporary-directory", "parallel"],
|
|
65
|
+
]);
|
|
66
|
+
/**
|
|
67
|
+
* The files `sort` writes: its `-o`/`--output` file and its `-T`/`--temporary-directory`. Options
|
|
68
|
+
* are parsed as GNU getopt does (clustered short options, exact or unique long prefixes).
|
|
69
|
+
* Undefined when it may run another program (`--compress-program`) or an option is unknown.
|
|
70
|
+
*/
|
|
71
|
+
export function sortWrites(args) {
|
|
72
|
+
const writes = [];
|
|
73
|
+
for (let i = 0; i < args.length; i++) {
|
|
74
|
+
const arg = args[i] ?? "";
|
|
75
|
+
if (arg === "--")
|
|
76
|
+
break;
|
|
77
|
+
if (arg.startsWith("--")) {
|
|
78
|
+
const [given = "", inline] = arg.slice(2).split(/=(.*)/s, 2);
|
|
79
|
+
const exact = SORT_LONG.includes(given)
|
|
80
|
+
? [given]
|
|
81
|
+
: SORT_LONG.filter((n) => n.startsWith(given));
|
|
82
|
+
if (exact.length !== 1)
|
|
83
|
+
return undefined;
|
|
84
|
+
const name = exact[0] ?? "";
|
|
85
|
+
if (!SORT_LONG_VALUE.has(name))
|
|
86
|
+
continue;
|
|
87
|
+
const value = inline ?? args[++i];
|
|
88
|
+
if (value === undefined)
|
|
89
|
+
return undefined;
|
|
90
|
+
if (name === "compress-program")
|
|
91
|
+
return undefined;
|
|
92
|
+
if (name === "output" || name === "temporary-directory")
|
|
93
|
+
writes.push(value);
|
|
94
|
+
}
|
|
95
|
+
else if (arg.startsWith("-") && arg.length > 1) {
|
|
96
|
+
for (let j = 1; j < arg.length; j++) {
|
|
97
|
+
const flag = arg[j] ?? "";
|
|
98
|
+
if ("ktSTo".includes(flag)) {
|
|
99
|
+
const value = arg.slice(j + 1) || args[++i];
|
|
100
|
+
if (value === undefined)
|
|
101
|
+
return undefined;
|
|
102
|
+
if (flag === "o" || flag === "T")
|
|
103
|
+
writes.push(value);
|
|
104
|
+
break;
|
|
105
|
+
}
|
|
106
|
+
if (!"bdfgiMhnRrVcCmsuz".includes(flag))
|
|
107
|
+
return undefined;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return writes;
|
|
112
|
+
}
|
|
54
113
|
/**
|
|
55
114
|
* Programs whose behaviour cannot be changed by an unknown argument: they only print or compare
|
|
56
115
|
* strings. The output of a command substitution may be an argument of these and of nothing else,
|
|
@@ -1611,6 +1670,16 @@ export function simpleDecision(request, command, profile, depth, stageIndex, cwd
|
|
|
1611
1670
|
if (program === "find" &&
|
|
1612
1671
|
args.some((arg) => ["-delete", "-exec", "-execdir", "-ok", "-okdir", "-fprint", "-fprintf", "-fls"].includes(arg)))
|
|
1613
1672
|
return human(request, "destructive", "find with actions requires human review");
|
|
1673
|
+
if (program === "sort") {
|
|
1674
|
+
const outputs = sortWrites(args);
|
|
1675
|
+
if (outputs === undefined)
|
|
1676
|
+
return human(request, "unknown", "sort with an option that runs a program requires review");
|
|
1677
|
+
for (const file of outputs) {
|
|
1678
|
+
const check = permissiveWrite(cwd, file, profile, fill);
|
|
1679
|
+
if (!check.allowed)
|
|
1680
|
+
return human(request, check.category, check.reason);
|
|
1681
|
+
}
|
|
1682
|
+
}
|
|
1614
1683
|
if (["chmod", "chown"].includes(program) && args.some((arg) => /^-[a-zA-Z]*R/.test(arg)))
|
|
1615
1684
|
return human(request, "destructive", "Recursive permission changes require human approval");
|
|
1616
1685
|
if ((program === "sed" &&
|
package/dist/policy.js
CHANGED
|
@@ -5,6 +5,7 @@ import { branchEvidence, canonical, git, inside, pathEvidence } from "./evidence
|
|
|
5
5
|
import { commandDecision, permissiveRead, permissiveWrite, WORKTREE_DELETION, } from "./permissive.js";
|
|
6
6
|
import { mcpReadOnly, strictProfile } from "./profile.js";
|
|
7
7
|
import { redactText } from "./redact.js";
|
|
8
|
+
import { defaultAllowed } from "./tools.js";
|
|
8
9
|
import { CATEGORIES, } from "./types.js";
|
|
9
10
|
export function hash(value) {
|
|
10
11
|
return createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
@@ -315,6 +316,15 @@ function evaluateCore(request, profile) {
|
|
|
315
316
|
...result(request, "unknown", "MCP tool not listed as read-only; left to the harness"),
|
|
316
317
|
decision: "native",
|
|
317
318
|
};
|
|
319
|
+
// Harness tools that are not shell, file, patch or MCP tools (task control, plan mode, asking
|
|
320
|
+
// the user, loading tool schemas) are approved by default under the permissive profile; the
|
|
321
|
+
// profile's toolsDeny keeps chosen ones on the classification path. Each approval names the tool.
|
|
322
|
+
if (profile.mode === "permissive" &&
|
|
323
|
+
defaultAllowed(request.harness, request.tool, profile.toolsDeny[request.harness] ?? []))
|
|
324
|
+
return {
|
|
325
|
+
...result(request, "code-read", "Harness tool approved by default", true),
|
|
326
|
+
defaultTool: request.tool,
|
|
327
|
+
};
|
|
318
328
|
const cwd = input.workdir ?? input.cwd ?? request.cwd;
|
|
319
329
|
if (typeof cwd !== "string" || cwd !== request.cwd)
|
|
320
330
|
return result(request, "unknown", "Execution directory differs from the reviewed directory");
|
package/dist/profile.d.ts
CHANGED
|
@@ -16,6 +16,15 @@ export interface Profile {
|
|
|
16
16
|
* last segment ends in `*` (`mcp__github__get_*`). Unlisted MCP tools are left to the harness.
|
|
17
17
|
*/
|
|
18
18
|
mcpReadOnly: string[];
|
|
19
|
+
/**
|
|
20
|
+
* Harness tools, per harness, that are not approved by default and keep the classification
|
|
21
|
+
* path. Every other harness tool that is not a shell, file, patch or MCP tool is approved.
|
|
22
|
+
*/
|
|
23
|
+
toolsDeny: {
|
|
24
|
+
claude: string[];
|
|
25
|
+
codex: string[];
|
|
26
|
+
copilot: string[];
|
|
27
|
+
};
|
|
19
28
|
/** SHA-256 of the file the profile came from, for the audit log. */
|
|
20
29
|
digest?: string;
|
|
21
30
|
}
|
|
@@ -23,6 +32,7 @@ export declare const strictProfile: Profile;
|
|
|
23
32
|
export declare const MAX_MCP_READ_ONLY = 200;
|
|
24
33
|
/** Whether `tool` is listed in the profile's `mcpReadOnly`. */
|
|
25
34
|
export declare function mcpReadOnly(profile: Profile, tool: string): boolean;
|
|
35
|
+
export declare const MAX_TOOLS_DENY = 100;
|
|
26
36
|
export declare function defaultProfilePath(): string;
|
|
27
37
|
export declare class ProfileError extends Error {
|
|
28
38
|
}
|
package/dist/profile.js
CHANGED
|
@@ -3,12 +3,14 @@ import { lstatSync, readFileSync } from "node:fs";
|
|
|
3
3
|
import { homedir } from "node:os";
|
|
4
4
|
import { dirname, isAbsolute, join } from "node:path";
|
|
5
5
|
import { canonical, git } from "./evidence.js";
|
|
6
|
+
import { TOOL_NAME } from "./tools.js";
|
|
6
7
|
export const strictProfile = {
|
|
7
8
|
mode: "strict",
|
|
8
9
|
cloudWrites: "human",
|
|
9
10
|
humanPatterns: [],
|
|
10
11
|
scratchRoots: [],
|
|
11
12
|
mcpReadOnly: [],
|
|
13
|
+
toolsDeny: { claude: [], codex: [], copilot: [] },
|
|
12
14
|
};
|
|
13
15
|
export const MAX_MCP_READ_ONLY = 200;
|
|
14
16
|
/**
|
|
@@ -28,6 +30,24 @@ export function mcpReadOnly(profile, tool) {
|
|
|
28
30
|
return tool.startsWith(entry.slice(0, -1)) && !tool.slice(server.length).includes("__");
|
|
29
31
|
});
|
|
30
32
|
}
|
|
33
|
+
export const MAX_TOOLS_DENY = 100;
|
|
34
|
+
function parseToolsDeny(raw) {
|
|
35
|
+
const result = { claude: [], codex: [], copilot: [] };
|
|
36
|
+
if (raw === undefined)
|
|
37
|
+
return result;
|
|
38
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
39
|
+
throw new ProfileError("toolsDeny must be an object of per-harness tool name lists");
|
|
40
|
+
for (const [harness, names] of Object.entries(raw)) {
|
|
41
|
+
if (!(harness in result))
|
|
42
|
+
throw new ProfileError(`toolsDeny has an unknown harness: ${harness}`);
|
|
43
|
+
if (!Array.isArray(names) ||
|
|
44
|
+
names.length > MAX_TOOLS_DENY ||
|
|
45
|
+
names.some((name) => typeof name !== "string" || !TOOL_NAME.test(name)))
|
|
46
|
+
throw new ProfileError(`toolsDeny.${harness} must list at most ${MAX_TOOLS_DENY} tool names`);
|
|
47
|
+
result[harness] = [...new Set(names)];
|
|
48
|
+
}
|
|
49
|
+
return result;
|
|
50
|
+
}
|
|
31
51
|
export function defaultProfilePath() {
|
|
32
52
|
const base = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
|
|
33
53
|
return join(base, "agent-corpus", "policy-manager", "policy.json");
|
|
@@ -75,6 +95,7 @@ export function parseProfile(text) {
|
|
|
75
95
|
"humanPatterns",
|
|
76
96
|
"scratchRoots",
|
|
77
97
|
"mcpReadOnly",
|
|
98
|
+
"toolsDeny",
|
|
78
99
|
"description",
|
|
79
100
|
]);
|
|
80
101
|
for (const key of Object.keys(value))
|
|
@@ -98,6 +119,7 @@ export function parseProfile(text) {
|
|
|
98
119
|
mcp.length > MAX_MCP_READ_ONLY ||
|
|
99
120
|
mcp.some((entry) => typeof entry !== "string" || entry.length > 128 || !MCP_ENTRY.test(entry)))
|
|
100
121
|
throw new ProfileError(`mcpReadOnly must list at most ${MAX_MCP_READ_ONLY} names like mcp__server__tool, optionally ending in *`);
|
|
122
|
+
const toolsDeny = parseToolsDeny(value.toolsDeny);
|
|
101
123
|
let humanPatterns;
|
|
102
124
|
try {
|
|
103
125
|
humanPatterns = patterns.map((p) => new RegExp(p));
|
|
@@ -120,6 +142,7 @@ export function parseProfile(text) {
|
|
|
120
142
|
humanPatterns,
|
|
121
143
|
scratchRoots: value.mode === "permissive" ? [...scratchRoots] : [],
|
|
122
144
|
mcpReadOnly: [...new Set(mcp)],
|
|
145
|
+
toolsDeny,
|
|
123
146
|
digest: createHash("sha256").update(text).digest("hex"),
|
|
124
147
|
};
|
|
125
148
|
}
|
package/dist/review.d.ts
CHANGED
|
@@ -48,6 +48,15 @@ export interface ClassificationReview {
|
|
|
48
48
|
reclassified: ClassifiedRequest[];
|
|
49
49
|
/** Requests the AI denied and later approved. */
|
|
50
50
|
deniedThenApproved: ClassifiedRequest[];
|
|
51
|
+
/**
|
|
52
|
+
* Harness tools approved by default (not shell, file, patch or MCP tools), newest first by when
|
|
53
|
+
* each was first seen, so a tool a harness newly added is noticed and can go into toolsDeny.
|
|
54
|
+
*/
|
|
55
|
+
defaultTools: Array<{
|
|
56
|
+
tool: string;
|
|
57
|
+
firstSeen: string;
|
|
58
|
+
count: number;
|
|
59
|
+
}>;
|
|
51
60
|
}
|
|
52
61
|
export declare function sessionDirectories(extra?: string[]): string[];
|
|
53
62
|
export declare function reviewClassifications(directories: string[], since?: string): Promise<ClassificationReview>;
|
package/dist/review.js
CHANGED
|
@@ -30,6 +30,7 @@ const text = (value) => typeof value === "string" ? value : undefined;
|
|
|
30
30
|
const num = (value) => typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
31
31
|
export async function reviewClassifications(directories, since) {
|
|
32
32
|
const requests = [];
|
|
33
|
+
const defaultTools = new Map();
|
|
33
34
|
let sessions = 0;
|
|
34
35
|
for (const directory of directories) {
|
|
35
36
|
const records = [];
|
|
@@ -72,6 +73,17 @@ export async function reviewClassifications(directories, since) {
|
|
|
72
73
|
};
|
|
73
74
|
for (const record of records) {
|
|
74
75
|
const a = record.attributes;
|
|
76
|
+
const tool = text(a.defaultTool);
|
|
77
|
+
if (record.eventName === "decision" && tool) {
|
|
78
|
+
const seen = defaultTools.get(tool);
|
|
79
|
+
if (!seen)
|
|
80
|
+
defaultTools.set(tool, { tool, firstSeen: record.timestamp, count: 1 });
|
|
81
|
+
else {
|
|
82
|
+
seen.count++;
|
|
83
|
+
if (record.timestamp < seen.firstSeen)
|
|
84
|
+
seen.firstSeen = record.timestamp;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
75
87
|
// Only requests that entered the classification flow are reviewed.
|
|
76
88
|
if (record.eventName !== "classification-requested" && !byRequest.has(record.requestId ?? ""))
|
|
77
89
|
continue;
|
|
@@ -156,6 +168,7 @@ export async function reviewClassifications(directories, since) {
|
|
|
156
168
|
fallbackReasons[key] = (fallbackReasons[key] ?? 0) + 1;
|
|
157
169
|
}
|
|
158
170
|
return {
|
|
171
|
+
defaultTools: [...defaultTools.values()].sort((x, y) => y.firstSeen.localeCompare(x.firstSeen)),
|
|
159
172
|
sessions,
|
|
160
173
|
requested: requests.length,
|
|
161
174
|
approved: approved.length,
|
|
@@ -220,6 +233,9 @@ export function formatReview(review) {
|
|
|
220
233
|
`Commands a person later denied (${review.humanDenied.length}):`,
|
|
221
234
|
...review.humanDenied.map(row),
|
|
222
235
|
"",
|
|
236
|
+
`Harness tools approved by default, newest first (${review.defaultTools.length}):`,
|
|
237
|
+
...review.defaultTools.map((t) => ` ${t.tool} first seen ${t.firstSeen} ${t.count}x`),
|
|
238
|
+
"",
|
|
223
239
|
`All AI-approved commands (${review.aiApproved.length}):`,
|
|
224
240
|
...review.aiApproved.map(row),
|
|
225
241
|
"",
|
package/dist/service.d.ts
CHANGED
|
@@ -1,14 +1,32 @@
|
|
|
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" | "pending" | "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>;
|
|
17
|
+
/**
|
|
18
|
+
* The newest request waiting for a person across this user's running policy services, for
|
|
19
|
+
* `approve --last`. Only private session directories owned by this user are asked.
|
|
20
|
+
*/
|
|
21
|
+
export declare function latestHumanDecision(): Promise<{
|
|
22
|
+
directory: string;
|
|
23
|
+
requestHash: string;
|
|
24
|
+
at: number;
|
|
25
|
+
harness: string;
|
|
26
|
+
sessionId: string;
|
|
27
|
+
} | undefined>;
|
|
28
|
+
/** Sends to the service of an existing session directory (see `approve --last`). */
|
|
29
|
+
export declare function sendTo(directory: string, message: Omit<Message, "token">): Promise<unknown>;
|
|
12
30
|
/**
|
|
13
31
|
* Stops a session's service. A session with no service (it never started, already ended, or the
|
|
14
32
|
* harness fired SessionEnd outside a real session such as `claude update`) is not an error:
|
package/dist/service.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
|
-
import { chmodSync, existsSync } from "node:fs";
|
|
2
|
+
import { chmodSync, existsSync, lstatSync, readdirSync } from "node:fs";
|
|
3
3
|
import { createConnection, createServer } from "node:net";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
4
5
|
import { join } from "node:path";
|
|
5
6
|
import { audit, sessionDirectory, sessionDirectoryPath, sessionToken } from "./audit.js";
|
|
6
7
|
import { hash, requestHash } from "./policy.js";
|
|
7
8
|
import { loadProfile, strictProfile } from "./profile.js";
|
|
8
|
-
import { PolicySession } from "./session.js";
|
|
9
|
+
import { GrantError, PolicySession } from "./session.js";
|
|
9
10
|
function endpoint(directory) {
|
|
10
11
|
return process.platform === "win32"
|
|
11
12
|
? `\\\\.\\pipe\\acp-${hash(directory).slice(0, 32)}`
|
|
@@ -49,8 +50,10 @@ export async function serve(harness, sessionId, cliPath) {
|
|
|
49
50
|
? { requestHash: message.classification.requestHash }
|
|
50
51
|
: message.report
|
|
51
52
|
? { requestHash: message.report.requestHash }
|
|
52
|
-
:
|
|
53
|
-
|
|
53
|
+
: message.grant
|
|
54
|
+
? { requestHash: String(message.grant.requestHash) }
|
|
55
|
+
: {}),
|
|
56
|
+
action: ["ping", "review", "classify", "record", "grant", "pending", "stop"].includes(message.action)
|
|
54
57
|
? message.action
|
|
55
58
|
: "invalid",
|
|
56
59
|
});
|
|
@@ -58,6 +61,8 @@ export async function serve(harness, sessionId, cliPath) {
|
|
|
58
61
|
let result;
|
|
59
62
|
if (message.action === "ping")
|
|
60
63
|
result = { ready: true };
|
|
64
|
+
else if (message.action === "pending")
|
|
65
|
+
result = session.latestHumanDecision() ?? null;
|
|
61
66
|
else if (message.action === "stop") {
|
|
62
67
|
audit(directory, { event: "session-end" });
|
|
63
68
|
result = { stopped: true };
|
|
@@ -71,6 +76,16 @@ export async function serve(harness, sessionId, cliPath) {
|
|
|
71
76
|
session.record(message.report);
|
|
72
77
|
result = { recorded: true };
|
|
73
78
|
}
|
|
79
|
+
else if (message.action === "grant" && message.grant) {
|
|
80
|
+
try {
|
|
81
|
+
result = session.grant(String(message.grant.requestHash), message.grant.confirm === true, message.grant.session === true);
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
if (!(error instanceof GrantError))
|
|
85
|
+
throw error;
|
|
86
|
+
result = { granted: false, refused: error.message };
|
|
87
|
+
}
|
|
88
|
+
}
|
|
74
89
|
else
|
|
75
90
|
throw new Error("Invalid service request");
|
|
76
91
|
socket.end(`${JSON.stringify({ result })}\n`);
|
|
@@ -100,7 +115,11 @@ export async function serve(harness, sessionId, cliPath) {
|
|
|
100
115
|
resolve();
|
|
101
116
|
});
|
|
102
117
|
});
|
|
103
|
-
audit(directory, {
|
|
118
|
+
audit(directory, {
|
|
119
|
+
event: "session-start",
|
|
120
|
+
harness,
|
|
121
|
+
sessionHash: hash(sessionId),
|
|
122
|
+
});
|
|
104
123
|
audit(directory, {
|
|
105
124
|
event: "profile",
|
|
106
125
|
mode: profile.mode,
|
|
@@ -113,7 +132,51 @@ export async function serve(harness, sessionId, cliPath) {
|
|
|
113
132
|
});
|
|
114
133
|
}
|
|
115
134
|
export function send(harness, sessionId, message) {
|
|
116
|
-
|
|
135
|
+
return sendTo(sessionDirectory(harness, sessionId), message);
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* The newest request waiting for a person across this user's running policy services, for
|
|
139
|
+
* `approve --last`. Only private session directories owned by this user are asked.
|
|
140
|
+
*/
|
|
141
|
+
export async function latestHumanDecision() {
|
|
142
|
+
const root = tmpdir();
|
|
143
|
+
const prefix = `acp-${process.getuid?.() ?? "user"}-`;
|
|
144
|
+
let best;
|
|
145
|
+
for (const name of readdirSync(root)) {
|
|
146
|
+
if (!name.startsWith(prefix) || !/^[a-f0-9]{24}$/.test(name.slice(prefix.length)))
|
|
147
|
+
continue;
|
|
148
|
+
const directory = join(root, name);
|
|
149
|
+
try {
|
|
150
|
+
const stat = lstatSync(directory);
|
|
151
|
+
if (!stat.isDirectory() ||
|
|
152
|
+
stat.isSymbolicLink() ||
|
|
153
|
+
(process.getuid && (stat.uid !== process.getuid() || (stat.mode & 0o077) !== 0)) ||
|
|
154
|
+
!existsSync(join(directory, "token")))
|
|
155
|
+
continue;
|
|
156
|
+
const found = (await sendTo(directory, { action: "pending" }));
|
|
157
|
+
if (found &&
|
|
158
|
+
typeof found.requestHash === "string" &&
|
|
159
|
+
/^[a-f0-9]{64}$/.test(found.requestHash) &&
|
|
160
|
+
typeof found.at === "number" &&
|
|
161
|
+
typeof found.harness === "string" &&
|
|
162
|
+
typeof found.sessionId === "string" &&
|
|
163
|
+
(!best || found.at > best.at))
|
|
164
|
+
best = {
|
|
165
|
+
directory,
|
|
166
|
+
requestHash: found.requestHash,
|
|
167
|
+
at: found.at,
|
|
168
|
+
harness: found.harness,
|
|
169
|
+
sessionId: found.sessionId,
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
catch {
|
|
173
|
+
/* A stopped or unreachable service has nothing to approve. */
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return best;
|
|
177
|
+
}
|
|
178
|
+
/** Sends to the service of an existing session directory (see `approve --last`). */
|
|
179
|
+
export function sendTo(directory, message) {
|
|
117
180
|
return new Promise((resolve, reject) => {
|
|
118
181
|
const socket = createConnection(endpoint(directory));
|
|
119
182
|
let data = "";
|
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,34 @@ 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
|
+
/** The newest request this session sent to a person that the user may still approve. */
|
|
64
|
+
latestHumanDecision(): {
|
|
65
|
+
requestHash: string;
|
|
66
|
+
at: number;
|
|
67
|
+
harness: string;
|
|
68
|
+
sessionId: string;
|
|
69
|
+
} | undefined;
|
|
70
|
+
/**
|
|
71
|
+
* Looks up, and with `confirm` grants, a user approval of a request this session sent to a
|
|
72
|
+
* person within the last GRANT_WINDOW_MS. Without `session` the next review of that exact
|
|
73
|
+
* request is approved once per hook phase; with it, every later request in this session that
|
|
74
|
+
* hits the same rule for the same scope is approved. A request with no session scope (credential
|
|
75
|
+
* reads, possible unrecoverable loss) is approved once only, and the result says so.
|
|
76
|
+
*/
|
|
77
|
+
grant(requestHash: string, confirm: boolean, session?: boolean): GrantPreview & {
|
|
78
|
+
granted: boolean;
|
|
79
|
+
scope: "once" | "session";
|
|
80
|
+
};
|
|
30
81
|
private state;
|
|
31
82
|
private remember;
|
|
32
83
|
/**
|