@phren/agent 0.3.20 → 0.3.22
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/dist/agent-loop/index.js +113 -19
- package/dist/agent-loop/stream.js +3 -1
- package/dist/attach-images.js +57 -0
- package/dist/commands/info.js +6 -2
- package/dist/commands/model.js +55 -13
- package/dist/commands/session.js +79 -18
- package/dist/commands.js +9 -2
- package/dist/config.js +45 -0
- package/dist/context/clear-tool-results.js +43 -0
- package/dist/context/compactor.js +8 -2
- package/dist/context/usage.js +26 -0
- package/dist/cost.js +10 -3
- package/dist/headless.js +41 -0
- package/dist/index.js +180 -56
- package/dist/mcp-client.js +38 -1
- package/dist/mcp-prompts.js +94 -0
- package/dist/multi/child-entry.js +3 -1
- package/dist/multi/spawner.js +27 -15
- package/dist/permissions/allowlist.js +19 -4
- package/dist/permissions/checker.js +37 -20
- package/dist/permissions/kernel-sandbox.js +32 -10
- package/dist/permissions/rules.js +173 -0
- package/dist/permissions/shell-classify.js +173 -0
- package/dist/plan.js +6 -2
- package/dist/repl.js +16 -1
- package/dist/session/persist.js +9 -4
- package/dist/settings.js +14 -0
- package/dist/structured-output.js +85 -0
- package/dist/system-prompt.js +117 -14
- package/dist/tools/apply-patch.js +15 -1
- package/dist/tools/edit-file.js +8 -1
- package/dist/tools/file-state.js +88 -0
- package/dist/tools/glob.js +53 -35
- package/dist/tools/grep.js +139 -53
- package/dist/tools/lint-test.js +24 -0
- package/dist/tools/read-file.js +2 -0
- package/dist/tools/registry.js +8 -1
- package/dist/tools/search-support.js +141 -0
- package/dist/tools/shell.js +3 -1
- package/dist/tools/spawn-agent.js +15 -3
- package/dist/tools/syntax-check.js +116 -0
- package/dist/tools/write-file.js +11 -3
- package/dist/tui/components/App.js +5 -4
- package/dist/tui/components/Banner.js +1 -1
- package/dist/tui/components/ListPicker.js +32 -0
- package/dist/tui/ink-entry.js +57 -16
- package/dist/user-hooks.js +26 -4
- package/package.json +3 -2
package/dist/multi/spawner.js
CHANGED
|
@@ -22,18 +22,27 @@ const CHILD_ENTRY = join(__dirname, "child-entry.js");
|
|
|
22
22
|
/** Providers that reach a configurable endpoint (--base-url). */
|
|
23
23
|
const ENDPOINT_PROVIDERS = new Set(["openai-compat", "deepseek"]);
|
|
24
24
|
/**
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
25
|
+
* Which provider a child runs on. A child that names no provider, or the
|
|
26
|
+
* parent's, runs the parent's: same provider, the parent's model unless it
|
|
27
|
+
* asked for another, the parent's reasoning effort, and for an endpoint
|
|
28
|
+
* provider the parent's base URL (openai-compat can't be found by
|
|
29
|
+
* auto-detection at all). Left to auto-detect, a child of an Anthropic or
|
|
30
|
+
* OpenRouter session could land on whatever key the environment had first.
|
|
31
|
+
* A child that names another provider gets exactly what it asked for.
|
|
29
32
|
*/
|
|
30
|
-
export function
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
return undefined;
|
|
33
|
+
export function childProvider(parent, provider, model) {
|
|
34
|
+
// A replayed recording is scripted for one process; its children resolve their own.
|
|
35
|
+
if (!parent || parent.name === "replay" || (provider !== undefined && provider !== parent.name))
|
|
36
|
+
return { provider, model };
|
|
35
37
|
const childModel = model ?? parent.model;
|
|
36
|
-
|
|
38
|
+
const sameModel = childModel === parent.model;
|
|
39
|
+
return {
|
|
40
|
+
provider: parent.name,
|
|
41
|
+
...(childModel !== undefined ? { model: childModel } : {}),
|
|
42
|
+
...(parent.baseUrl && ENDPOINT_PROVIDERS.has(parent.name) ? { baseUrl: parent.baseUrl } : {}),
|
|
43
|
+
// Effort levels differ between models; carry it only with the same model.
|
|
44
|
+
...(sameModel && parent.reasoningEffort ? { reasoning: parent.reasoningEffort } : {}),
|
|
45
|
+
};
|
|
37
46
|
}
|
|
38
47
|
/** Keys forwarded from the parent env into child processes. */
|
|
39
48
|
const ENV_FORWARD_KEYS = [
|
|
@@ -42,7 +51,7 @@ const ENV_FORWARD_KEYS = [
|
|
|
42
51
|
"OPENAI_API_KEY",
|
|
43
52
|
"DEEPSEEK_API_KEY",
|
|
44
53
|
// Key for an openai-compat endpoint; the endpoint itself goes in the
|
|
45
|
-
// spawn payload (
|
|
54
|
+
// spawn payload (childProvider). Env only: never argv or logs.
|
|
46
55
|
"PHREN_AGENT_API_KEY",
|
|
47
56
|
"PHREN_AGENT_PROVIDER",
|
|
48
57
|
"PHREN_AGENT_MODEL",
|
|
@@ -86,7 +95,7 @@ export class AgentSpawner extends EventEmitter {
|
|
|
86
95
|
}
|
|
87
96
|
const agentId = `agent-${this.nextId++}`;
|
|
88
97
|
const defaults = this.getPermissionDefaults?.();
|
|
89
|
-
const
|
|
98
|
+
const chosen = childProvider(this.getParentProvider?.(), opts.provider, opts.model);
|
|
90
99
|
// Build forwarded env
|
|
91
100
|
const childEnv = {};
|
|
92
101
|
for (const key of ENV_FORWARD_KEYS) {
|
|
@@ -100,9 +109,10 @@ export class AgentSpawner extends EventEmitter {
|
|
|
100
109
|
agentId,
|
|
101
110
|
task: opts.task,
|
|
102
111
|
cwd: opts.cwd ?? defaults?.projectRoot ?? process.cwd(),
|
|
103
|
-
provider:
|
|
104
|
-
model:
|
|
105
|
-
...(
|
|
112
|
+
provider: chosen.provider,
|
|
113
|
+
model: chosen.model,
|
|
114
|
+
...(chosen.baseUrl ? { baseUrl: chosen.baseUrl } : {}),
|
|
115
|
+
...(chosen.reasoning ? { reasoning: chosen.reasoning } : {}),
|
|
106
116
|
project: opts.project,
|
|
107
117
|
modelOverrides: scopedModelOverrides(),
|
|
108
118
|
permissions: opts.permissions ?? defaults?.mode ?? "auto-confirm",
|
|
@@ -114,7 +124,9 @@ export class AgentSpawner extends EventEmitter {
|
|
|
114
124
|
agentType: opts.agentType,
|
|
115
125
|
depth: this.depth + 1,
|
|
116
126
|
sandboxMode: opts.sandboxMode ?? defaults?.sandboxMode,
|
|
127
|
+
network: defaults?.network,
|
|
117
128
|
allowedPaths: opts.allowedPaths ?? defaults?.allowedPaths ?? [],
|
|
129
|
+
rules: defaults?.rules,
|
|
118
130
|
};
|
|
119
131
|
const entry = {
|
|
120
132
|
id: agentId,
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
import * as fs from "fs";
|
|
9
9
|
import * as os from "os";
|
|
10
10
|
import * as path from "path";
|
|
11
|
+
import { commandPattern, splitCommandLine } from "./shell-classify.js";
|
|
11
12
|
export const PERSISTED_ALLOWLIST_FILE = path.join(os.homedir(), ".phren-agent", "permissions.json");
|
|
12
13
|
const sessionAllowlist = [];
|
|
13
14
|
const persistentAllowlist = [];
|
|
@@ -20,9 +21,11 @@ let persistentProjectRoot = null;
|
|
|
20
21
|
*/
|
|
21
22
|
export function extractPattern(toolName, input) {
|
|
22
23
|
if (toolName === "shell") {
|
|
24
|
+
// The binary, with the subcommand for git, npm and the like: approving
|
|
25
|
+
// `git status` must not approve `git push --force`.
|
|
23
26
|
const cmd = (input.command || "").trim();
|
|
24
|
-
|
|
25
|
-
return
|
|
27
|
+
const first = splitCommandLine(cmd)?.[0] ?? cmd.split(/\s+/);
|
|
28
|
+
return commandPattern(first);
|
|
26
29
|
}
|
|
27
30
|
const filePath = input.path || input.file_path || "";
|
|
28
31
|
if (filePath)
|
|
@@ -37,13 +40,25 @@ function matches(entry, toolName, pattern) {
|
|
|
37
40
|
// For file paths: exact match or child path (boundary-aware to prevent prefix collisions)
|
|
38
41
|
if (pattern === entry.pattern || pattern.startsWith(entry.pattern.endsWith("/") ? entry.pattern : entry.pattern + "/"))
|
|
39
42
|
return true;
|
|
40
|
-
// For shell commands:
|
|
41
|
-
|
|
43
|
+
// For shell commands: the entry's words start the command's pattern, so an
|
|
44
|
+
// older binary-only entry ("git") still covers every subcommand.
|
|
45
|
+
return toolName === "shell" && pattern.startsWith(`${entry.pattern} `);
|
|
42
46
|
}
|
|
43
47
|
/** Check if a tool call is in the session allowlist. */
|
|
44
48
|
export function isAllowed(toolName, input) {
|
|
45
49
|
if (sessionAllowlist.length === 0 && persistentAllowlist.length === 0)
|
|
46
50
|
return false;
|
|
51
|
+
if (toolName === "shell") {
|
|
52
|
+
// Every command on the line must be approved: an approved `git status`
|
|
53
|
+
// must not carry `git status && rm -rf src` through.
|
|
54
|
+
const segments = splitCommandLine((input.command || "").trim());
|
|
55
|
+
if (!segments || segments.length === 0)
|
|
56
|
+
return false;
|
|
57
|
+
return segments.every((tokens) => {
|
|
58
|
+
const pattern = commandPattern(tokens);
|
|
59
|
+
return [...sessionAllowlist, ...persistentAllowlist].some((entry) => matches(entry, toolName, pattern));
|
|
60
|
+
});
|
|
61
|
+
}
|
|
47
62
|
const pattern = extractPattern(toolName, input);
|
|
48
63
|
return (sessionAllowlist.some((entry) => matches(entry, toolName, pattern)) ||
|
|
49
64
|
persistentAllowlist.some((entry) => matches(entry, toolName, pattern)));
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { checkShellSafety } from "./shell-safety.js";
|
|
2
|
+
import { isAutoApprovableCommand } from "./shell-classify.js";
|
|
3
|
+
import { evaluateRules } from "./rules.js";
|
|
2
4
|
import { validatePath, checkSensitivePath } from "./sandbox.js";
|
|
3
5
|
import { isAllowed } from "./allowlist.js";
|
|
4
6
|
import { parsePatch, patchPaths } from "../tools/apply-patch.js";
|
|
@@ -50,6 +52,24 @@ export function checkPermission(config, toolName, input) {
|
|
|
50
52
|
if (DENY_LIST_TOOLS.has(toolName)) {
|
|
51
53
|
return { verdict: "deny", reason: `Tool "${toolName}" is on the deny list.` };
|
|
52
54
|
}
|
|
55
|
+
// apply_patch names its paths inside the patch text.
|
|
56
|
+
let patchFiles = [];
|
|
57
|
+
if (toolName === "apply_patch") {
|
|
58
|
+
try {
|
|
59
|
+
patchFiles = patchPaths(parsePatch(String(input.patch ?? "")));
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
// Unparseable: the tool itself reports the error without writing.
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
// Declarative rules (settings files, --allowedTools / --disallowedTools).
|
|
66
|
+
// A deny rule wins at once; ask and allow apply below, after the checks no
|
|
67
|
+
// rule may override (blocked commands, secret files, paths outside the
|
|
68
|
+
// project).
|
|
69
|
+
const rule = evaluateRules(config.rules, toolName, input, config.projectRoot, patchFiles);
|
|
70
|
+
if (rule?.verdict === "deny") {
|
|
71
|
+
return { verdict: "deny", reason: `Denied by the permission rule "${rule.rule}".` };
|
|
72
|
+
}
|
|
53
73
|
// Shell commands get extra scrutiny
|
|
54
74
|
if (toolName === "shell") {
|
|
55
75
|
const cmd = input.command || "";
|
|
@@ -57,11 +77,11 @@ export function checkPermission(config, toolName, input) {
|
|
|
57
77
|
if (!safety.safe && safety.severity === "block") {
|
|
58
78
|
return { verdict: "deny", reason: safety.reason };
|
|
59
79
|
}
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
}
|
|
80
|
+
// A warn pattern (command substitution, env, sudo, a force push) asks in
|
|
81
|
+
// every mode but full-auto, which means allow: --yolo in a headless run,
|
|
82
|
+
// where every ask is a denial, must not refuse `echo $(git rev-parse HEAD)`.
|
|
83
|
+
if (!safety.safe && safety.severity === "warn" && config.mode !== "full-auto" && rule?.verdict !== "allow") {
|
|
84
|
+
return { verdict: "ask", reason: safety.reason };
|
|
65
85
|
}
|
|
66
86
|
// Check cwd for shell
|
|
67
87
|
const cwd = input.cwd || config.projectRoot;
|
|
@@ -89,16 +109,9 @@ export function checkPermission(config, toolName, input) {
|
|
|
89
109
|
}
|
|
90
110
|
}
|
|
91
111
|
}
|
|
92
|
-
// apply_patch
|
|
112
|
+
// apply_patch: check every path the patch names.
|
|
93
113
|
if (toolName === "apply_patch") {
|
|
94
|
-
|
|
95
|
-
try {
|
|
96
|
-
paths = patchPaths(parsePatch(String(input.patch ?? "")));
|
|
97
|
-
}
|
|
98
|
-
catch {
|
|
99
|
-
// Unparseable: the tool itself reports the error without writing.
|
|
100
|
-
}
|
|
101
|
-
for (const p of paths) {
|
|
114
|
+
for (const p of patchFiles) {
|
|
102
115
|
const sensitive = checkSensitivePath(p);
|
|
103
116
|
if (sensitive.sensitive) {
|
|
104
117
|
return { verdict: "deny", reason: `Sensitive path: ${sensitive.reason}` };
|
|
@@ -109,10 +122,16 @@ export function checkPermission(config, toolName, input) {
|
|
|
109
122
|
}
|
|
110
123
|
}
|
|
111
124
|
}
|
|
125
|
+
if (rule?.verdict === "ask") {
|
|
126
|
+
return { verdict: "ask", reason: `The permission rule "${rule.rule}" asks first.` };
|
|
127
|
+
}
|
|
112
128
|
// Always-safe tools pass in all modes
|
|
113
129
|
if (READ_ONLY_TOOLS.has(toolName)) {
|
|
114
130
|
return { verdict: "allow", reason: "Read-only tool, always allowed." };
|
|
115
131
|
}
|
|
132
|
+
if (rule?.verdict === "allow") {
|
|
133
|
+
return { verdict: "allow", reason: `Allowed by the permission rule "${rule.rule}".` };
|
|
134
|
+
}
|
|
116
135
|
// Session allowlist — user previously approved this tool+pattern via (a)llow-tool or (s)ession-allow.
|
|
117
136
|
// Placed after deny-list, shell-safety blocks, and sensitive-path denials so those are never bypassed.
|
|
118
137
|
if (isAllowed(toolName, input)) {
|
|
@@ -131,12 +150,10 @@ export function checkPermission(config, toolName, input) {
|
|
|
131
150
|
if (toolName === "shell") {
|
|
132
151
|
const cwd = input.cwd || config.projectRoot;
|
|
133
152
|
const cwdResult = validatePath(cwd, config.projectRoot, config.allowedPaths);
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
return { verdict: "allow", reason: "Safe shell command within sandbox." };
|
|
139
|
-
}
|
|
153
|
+
// Only commands that read, build or test; anything else (rm, git
|
|
154
|
+
// push, npm publish, a redirect into a file) asks.
|
|
155
|
+
if (cwdResult.ok && isAutoApprovableCommand(input.command || "")) {
|
|
156
|
+
return { verdict: "allow", reason: "Read, build or test command within sandbox." };
|
|
140
157
|
}
|
|
141
158
|
}
|
|
142
159
|
return { verdict: "ask", reason: `Auto-confirm mode requires confirmation for "${toolName}".` };
|
|
@@ -17,6 +17,12 @@
|
|
|
17
17
|
* profiles are easy to get subtly wrong); without it auto degrades
|
|
18
18
|
* visibly with the same notice as before.
|
|
19
19
|
* require — fail closed: no working backend ⇒ the command errors.
|
|
20
|
+
*
|
|
21
|
+
* Network: with `network: false` (--no-network) the same backends also cut
|
|
22
|
+
* the command off from the network, bwrap with its own empty network
|
|
23
|
+
* namespace and Seatbelt by denying outbound IP; local sockets still work.
|
|
24
|
+
* Asking for that turns the Seatbelt backend on without the opt-in, since
|
|
25
|
+
* the user chose isolation explicitly.
|
|
20
26
|
*/
|
|
21
27
|
import { execFileSync } from "child_process";
|
|
22
28
|
import * as fs from "fs";
|
|
@@ -55,8 +61,8 @@ export function isBwrapAvailable() {
|
|
|
55
61
|
}
|
|
56
62
|
return probeResult;
|
|
57
63
|
}
|
|
58
|
-
export function isSeatbeltAvailable() {
|
|
59
|
-
if (!seatbeltEnabled())
|
|
64
|
+
export function isSeatbeltAvailable(force = false) {
|
|
65
|
+
if (process.platform !== "darwin" || (!force && !seatbeltEnabled()))
|
|
60
66
|
return false;
|
|
61
67
|
if (seatbeltProbeResult !== null)
|
|
62
68
|
return seatbeltProbeResult;
|
|
@@ -94,13 +100,14 @@ function realpathOrNull(p) {
|
|
|
94
100
|
}
|
|
95
101
|
}
|
|
96
102
|
/** Build the bwrap argv prefix for the given writable roots. */
|
|
97
|
-
export function buildBwrapArgv(argv, writableRoots) {
|
|
103
|
+
export function buildBwrapArgv(argv, writableRoots, opts = {}) {
|
|
98
104
|
const wrapped = [
|
|
99
105
|
"bwrap",
|
|
100
106
|
"--ro-bind", "/", "/",
|
|
101
107
|
"--dev", "/dev",
|
|
102
108
|
"--proc", "/proc",
|
|
103
109
|
"--tmpfs", "/tmp",
|
|
110
|
+
...(opts.network === false ? ["--unshare-net"] : []),
|
|
104
111
|
];
|
|
105
112
|
const seen = new Set();
|
|
106
113
|
for (const root of writableRoots) {
|
|
@@ -120,7 +127,7 @@ export function buildBwrapArgv(argv, writableRoots) {
|
|
|
120
127
|
function sbplQuote(value) {
|
|
121
128
|
return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
|
|
122
129
|
}
|
|
123
|
-
export function buildSeatbeltProfile(writableRoots) {
|
|
130
|
+
export function buildSeatbeltProfile(writableRoots, opts = {}) {
|
|
124
131
|
const rules = [];
|
|
125
132
|
const seen = new Set();
|
|
126
133
|
for (const root of writableRoots) {
|
|
@@ -143,25 +150,33 @@ export function buildSeatbeltProfile(writableRoots) {
|
|
|
143
150
|
"(allow default)",
|
|
144
151
|
"(deny file-write*)",
|
|
145
152
|
`(allow file-write* ${rules.join(" ")})`,
|
|
153
|
+
...(opts.network === false ? ["(deny network-outbound (remote ip))"] : []),
|
|
146
154
|
].join("\n");
|
|
147
155
|
}
|
|
148
|
-
export function buildSeatbeltArgv(argv, writableRoots) {
|
|
149
|
-
return ["sandbox-exec", "-p", buildSeatbeltProfile(writableRoots), ...argv];
|
|
156
|
+
export function buildSeatbeltArgv(argv, writableRoots, opts = {}) {
|
|
157
|
+
return ["sandbox-exec", "-p", buildSeatbeltProfile(writableRoots, opts), ...argv];
|
|
150
158
|
}
|
|
151
159
|
/**
|
|
152
160
|
* Decide how to run a shell argv under the given sandbox mode.
|
|
153
161
|
* Throws SandboxRequiredError only in `require` mode with no working backend.
|
|
154
162
|
*/
|
|
155
163
|
export function wrapWithSandbox(argv, opts) {
|
|
156
|
-
|
|
164
|
+
const isolateNetwork = opts.network === false;
|
|
165
|
+
// Network isolation needs a backend, so it overrides --sandbox off.
|
|
166
|
+
if (opts.mode === "off" && !isolateNetwork) {
|
|
157
167
|
return { argv, sandboxed: false };
|
|
158
168
|
}
|
|
159
169
|
const writable = [opts.workspaceRoot, os.tmpdir(), ...(opts.extraWritable ?? [])];
|
|
170
|
+
const net = { network: opts.network };
|
|
160
171
|
if (isBwrapAvailable()) {
|
|
161
|
-
return { argv: buildBwrapArgv(argv, writable), sandboxed: true };
|
|
172
|
+
return { argv: buildBwrapArgv(argv, writable, net), sandboxed: true };
|
|
173
|
+
}
|
|
174
|
+
if (isSeatbeltAvailable(isolateNetwork)) {
|
|
175
|
+
return { argv: buildSeatbeltArgv(argv, writable, net), sandboxed: true };
|
|
162
176
|
}
|
|
163
|
-
if (
|
|
164
|
-
|
|
177
|
+
if (isolateNetwork) {
|
|
178
|
+
// Asked for no network and can't give it: fail closed, whatever the mode.
|
|
179
|
+
throw new SandboxRequiredError(`--no-network needs a kernel sandbox, and none works on this ${process.platform} system.`);
|
|
165
180
|
}
|
|
166
181
|
if (opts.mode === "require") {
|
|
167
182
|
throw new SandboxRequiredError(process.platform === "linux"
|
|
@@ -185,6 +200,13 @@ export function wrapWithSandbox(argv, opts) {
|
|
|
185
200
|
}
|
|
186
201
|
// ── Denial classification ────────────────────────────────────────────────────
|
|
187
202
|
const DENIAL_RE = /read-only file system|operation not permitted/i;
|
|
203
|
+
const NETWORK_DENIAL_RE = /network is unreachable|could not resolve host|name or service not known|temporary failure in name resolution|getaddrinfo|ENETUNREACH|EAI_AGAIN|connect EPERM|failed to connect|could(?:n't| not) connect to server/i;
|
|
204
|
+
/** When a command without network fails for want of it, say so. */
|
|
205
|
+
export function classifyNetworkDenial(output) {
|
|
206
|
+
if (!NETWORK_DENIAL_RE.test(output))
|
|
207
|
+
return null;
|
|
208
|
+
return "\n[sandbox] Network blocked: this session runs shell commands with --no-network. Work offline, or the user can rerun without it.";
|
|
209
|
+
}
|
|
188
210
|
/**
|
|
189
211
|
* When a sandboxed command fails with a write-fence error, return an
|
|
190
212
|
* annotation explaining WHY so the model redirects instead of retrying.
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Declarative permission rules: allow, ask and deny lists in settings files
|
|
3
|
+
* and on the command line (`--allowedTools`, `--disallowedTools`), in Claude
|
|
4
|
+
* Code's shape.
|
|
5
|
+
*
|
|
6
|
+
* "read_file" the tool, any input
|
|
7
|
+
* "mcp_github_*" tool names with * globs
|
|
8
|
+
* "shell(npm test)" a shell command; * matches anything, so
|
|
9
|
+
* "shell(git log *)" covers git log with any arguments
|
|
10
|
+
* "edit_file(src/**)" a file tool on paths under the project root
|
|
11
|
+
*
|
|
12
|
+
* A shell rule is matched against each simple command on the line: a deny or
|
|
13
|
+
* ask rule applies when any command matches it, an allow rule only when
|
|
14
|
+
* every command matches one, and a line this reader can't vouch for
|
|
15
|
+
* (substitution, a redirect into a file) is never allowed by a rule.
|
|
16
|
+
*/
|
|
17
|
+
import * as fs from "fs";
|
|
18
|
+
import * as os from "os";
|
|
19
|
+
import * as path from "path";
|
|
20
|
+
import { splitCommandLine } from "./shell-classify.js";
|
|
21
|
+
export function emptyRules() {
|
|
22
|
+
return { allow: [], ask: [], deny: [] };
|
|
23
|
+
}
|
|
24
|
+
function globToRegExp(glob, opts) {
|
|
25
|
+
let re = "";
|
|
26
|
+
for (let i = 0; i < glob.length; i++) {
|
|
27
|
+
const c = glob[i];
|
|
28
|
+
if (c === "*") {
|
|
29
|
+
if (glob[i + 1] === "*") {
|
|
30
|
+
re += ".*";
|
|
31
|
+
i++;
|
|
32
|
+
if (glob[i + 1] === "/")
|
|
33
|
+
i++;
|
|
34
|
+
}
|
|
35
|
+
else {
|
|
36
|
+
re += opts.slashes ? "[^/]*" : ".*";
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
else if (c === "?") {
|
|
40
|
+
re += opts.slashes ? "[^/]" : ".";
|
|
41
|
+
}
|
|
42
|
+
else {
|
|
43
|
+
re += c.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return new RegExp(`^${re}$`);
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* A shell rule's command glob. A trailing " *" or Claude Code's ":*" also
|
|
50
|
+
* matches the bare command, so "git log *" and "git log:*" cover `git log`.
|
|
51
|
+
*/
|
|
52
|
+
function shellPatternRegExp(pattern) {
|
|
53
|
+
const prefix = /^(.*?)(?: \*|:\*)$/.exec(pattern);
|
|
54
|
+
if (!prefix)
|
|
55
|
+
return globToRegExp(pattern, { slashes: false });
|
|
56
|
+
const head = globToRegExp(prefix[1], { slashes: false }).source.slice(1, -1);
|
|
57
|
+
return new RegExp(`^${head}(?: .*)?$`);
|
|
58
|
+
}
|
|
59
|
+
function parseRule(rule) {
|
|
60
|
+
const m = /^\s*([A-Za-z0-9_*.-]+)\s*(?:\((.*)\))?\s*$/s.exec(rule);
|
|
61
|
+
if (!m)
|
|
62
|
+
return null;
|
|
63
|
+
return { tool: globToRegExp(m[1], { slashes: false }), ...(m[2] !== undefined ? { pattern: m[2].trim() } : {}) };
|
|
64
|
+
}
|
|
65
|
+
const PATH_TOOLS = new Set(["read_file", "write_file", "edit_file", "multi_edit", "glob", "grep", "read_image"]);
|
|
66
|
+
/** The paths a call touches, relative to the project root when inside it. */
|
|
67
|
+
function callPaths(toolName, input, projectRoot, patchPaths) {
|
|
68
|
+
const raw = toolName === "apply_patch" ? (patchPaths ?? []) : PATH_TOOLS.has(toolName) ? [String(input.path ?? ".")] : [];
|
|
69
|
+
return raw.map((p) => {
|
|
70
|
+
const abs = path.resolve(projectRoot, p);
|
|
71
|
+
const rel = path.relative(projectRoot, abs);
|
|
72
|
+
return rel && !rel.startsWith("..") && !path.isAbsolute(rel) ? rel.split(path.sep).join("/") : abs;
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
/** Does this rule cover this call? For shell, `segments` decides per simple command. */
|
|
76
|
+
function ruleMatches(rule, toolName, subject, mode) {
|
|
77
|
+
if (!rule.tool.test(toolName))
|
|
78
|
+
return false;
|
|
79
|
+
if (rule.pattern === undefined || rule.pattern === "*")
|
|
80
|
+
return true;
|
|
81
|
+
if (toolName === "shell") {
|
|
82
|
+
const re = shellPatternRegExp(rule.pattern);
|
|
83
|
+
if (!subject.command || subject.command.length === 0)
|
|
84
|
+
return false;
|
|
85
|
+
return mode === "any" ? subject.command.some((c) => re.test(c)) : subject.command.every((c) => re.test(c));
|
|
86
|
+
}
|
|
87
|
+
if (subject.paths.length === 0)
|
|
88
|
+
return false;
|
|
89
|
+
const re = globToRegExp(rule.pattern.replace(/^\.\//, ""), { slashes: true });
|
|
90
|
+
return mode === "any" ? subject.paths.some((p) => re.test(p)) : subject.paths.every((p) => re.test(p));
|
|
91
|
+
}
|
|
92
|
+
/** Deny, then ask, then allow; null when no rule speaks to this call. */
|
|
93
|
+
export function evaluateRules(rules, toolName, input, projectRoot, patchPaths) {
|
|
94
|
+
if (!rules || (rules.allow.length + rules.ask.length + rules.deny.length === 0))
|
|
95
|
+
return null;
|
|
96
|
+
const subject = {
|
|
97
|
+
command: toolName === "shell" ? splitCommandLine(String(input.command ?? "").trim())?.map((t) => t.join(" ")) : undefined,
|
|
98
|
+
paths: callPaths(toolName, input, projectRoot, patchPaths),
|
|
99
|
+
};
|
|
100
|
+
// A shell line the reader can't split is matched whole by deny and ask rules.
|
|
101
|
+
const denySubject = toolName === "shell" && !subject.command ? { ...subject, command: [String(input.command ?? "").trim()] } : subject;
|
|
102
|
+
for (const verdict of ["deny", "ask"]) {
|
|
103
|
+
for (const raw of rules[verdict]) {
|
|
104
|
+
const rule = parseRule(raw);
|
|
105
|
+
if (rule && ruleMatches(rule, toolName, denySubject, "any"))
|
|
106
|
+
return { verdict, rule: raw };
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
if (toolName === "shell") {
|
|
110
|
+
// Every command on the line must be allowed, each by some rule.
|
|
111
|
+
if (!subject.command || subject.command.length === 0)
|
|
112
|
+
return null;
|
|
113
|
+
const parsed = rules.allow.map((raw) => ({ raw, rule: parseRule(raw) }));
|
|
114
|
+
const covering = subject.command.map((c) => parsed.find(({ rule }) => rule && ruleMatches(rule, toolName, { command: [c], paths: [] }, "all")));
|
|
115
|
+
return covering.every(Boolean) ? { verdict: "allow", rule: covering.map((c) => c.raw).join(", ") } : null;
|
|
116
|
+
}
|
|
117
|
+
for (const raw of rules.allow) {
|
|
118
|
+
const rule = parseRule(raw);
|
|
119
|
+
if (rule && ruleMatches(rule, toolName, subject, "all"))
|
|
120
|
+
return { verdict: "allow", rule: raw };
|
|
121
|
+
}
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
/** Split a `--allowedTools` value: commas outside parentheses. */
|
|
125
|
+
export function parseRuleList(value) {
|
|
126
|
+
const out = [];
|
|
127
|
+
let depth = 0;
|
|
128
|
+
let current = "";
|
|
129
|
+
for (const c of value) {
|
|
130
|
+
if (c === "(")
|
|
131
|
+
depth++;
|
|
132
|
+
if (c === ")")
|
|
133
|
+
depth = Math.max(0, depth - 1);
|
|
134
|
+
if (c === "," && depth === 0) {
|
|
135
|
+
if (current.trim())
|
|
136
|
+
out.push(current.trim());
|
|
137
|
+
current = "";
|
|
138
|
+
}
|
|
139
|
+
else {
|
|
140
|
+
current += c;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
if (current.trim())
|
|
144
|
+
out.push(current.trim());
|
|
145
|
+
return out;
|
|
146
|
+
}
|
|
147
|
+
function readRules(file) {
|
|
148
|
+
try {
|
|
149
|
+
const data = JSON.parse(fs.readFileSync(file, "utf-8"));
|
|
150
|
+
const list = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === "string") : []);
|
|
151
|
+
return { allow: list(data.permissions?.allow), ask: list(data.permissions?.ask), deny: list(data.permissions?.deny) };
|
|
152
|
+
}
|
|
153
|
+
catch {
|
|
154
|
+
return emptyRules();
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* The rules for a session: `~/.phren-agent/settings.json`, then the
|
|
159
|
+
* project's `.phren-agent/settings.json`, then the command line. Lists are
|
|
160
|
+
* concatenated; deny always wins over allow, wherever it came from.
|
|
161
|
+
*/
|
|
162
|
+
export function loadPermissionRules(projectRoot, cli, home = os.homedir()) {
|
|
163
|
+
const sources = [
|
|
164
|
+
readRules(path.join(home, ".phren-agent", "settings.json")),
|
|
165
|
+
readRules(path.join(projectRoot, ".phren-agent", "settings.json")),
|
|
166
|
+
{ ...emptyRules(), ...cli },
|
|
167
|
+
];
|
|
168
|
+
return {
|
|
169
|
+
allow: sources.flatMap((s) => s.allow ?? []),
|
|
170
|
+
ask: sources.flatMap((s) => s.ask ?? []),
|
|
171
|
+
deny: sources.flatMap((s) => s.deny ?? []),
|
|
172
|
+
};
|
|
173
|
+
}
|