@phren/agent 0.3.19 → 0.3.21

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.
Files changed (67) hide show
  1. package/dist/agent-loop/index.js +185 -47
  2. package/dist/agent-loop/stream.js +74 -66
  3. package/dist/agent-loop/types.js +2 -3
  4. package/dist/attach-images.js +57 -0
  5. package/dist/bin.js +7 -2
  6. package/dist/commands/info.js +7 -3
  7. package/dist/commands/model.js +55 -13
  8. package/dist/commands/session.js +79 -18
  9. package/dist/commands.js +24 -3
  10. package/dist/config.js +89 -10
  11. package/dist/context/clear-tool-results.js +43 -0
  12. package/dist/context/compactor.js +13 -3
  13. package/dist/context/pruner.js +29 -11
  14. package/dist/context/usage.js +26 -0
  15. package/dist/cost.js +68 -10
  16. package/dist/headless.js +47 -1
  17. package/dist/index.js +335 -127
  18. package/dist/mcp-client.js +38 -1
  19. package/dist/mcp-prompts.js +94 -0
  20. package/dist/memory/chat.js +70 -0
  21. package/dist/memory/context.js +1 -1
  22. package/dist/model-overrides.js +17 -0
  23. package/dist/models-list.js +73 -0
  24. package/dist/models.js +42 -15
  25. package/dist/multi/child-entry.js +18 -28
  26. package/dist/multi/ipc-hooks.js +34 -0
  27. package/dist/multi/spawner.js +49 -3
  28. package/dist/permissions/allowlist.js +19 -4
  29. package/dist/permissions/checker.js +37 -20
  30. package/dist/permissions/kernel-sandbox.js +32 -10
  31. package/dist/permissions/rules.js +173 -0
  32. package/dist/permissions/shell-classify.js +173 -0
  33. package/dist/plan.js +6 -2
  34. package/dist/providers/anthropic.js +119 -75
  35. package/dist/providers/codex.js +10 -9
  36. package/dist/providers/ollama.js +5 -2
  37. package/dist/providers/openai-compat.js +219 -92
  38. package/dist/providers/openrouter.js +12 -7
  39. package/dist/providers/resolve.js +47 -1
  40. package/dist/providers/retry.js +20 -7
  41. package/dist/providers/types.js +31 -0
  42. package/dist/repl.js +17 -1
  43. package/dist/session/persist.js +9 -4
  44. package/dist/session/preview.js +99 -0
  45. package/dist/settings.js +14 -0
  46. package/dist/structured-output.js +85 -0
  47. package/dist/system-prompt.js +117 -14
  48. package/dist/tools/apply-patch.js +15 -1
  49. package/dist/tools/edit-file.js +8 -1
  50. package/dist/tools/file-state.js +88 -0
  51. package/dist/tools/glob.js +53 -35
  52. package/dist/tools/grep.js +139 -53
  53. package/dist/tools/lint-test.js +24 -0
  54. package/dist/tools/read-file.js +2 -0
  55. package/dist/tools/registry.js +8 -1
  56. package/dist/tools/search-support.js +141 -0
  57. package/dist/tools/shell.js +266 -41
  58. package/dist/tools/spawn-agent.js +15 -3
  59. package/dist/tools/syntax-check.js +116 -0
  60. package/dist/tools/write-file.js +11 -3
  61. package/dist/tui/components/App.js +5 -4
  62. package/dist/tui/components/Banner.js +1 -1
  63. package/dist/tui/components/ListPicker.js +32 -0
  64. package/dist/tui/ink-entry.js +79 -15
  65. package/dist/user-hooks.js +26 -4
  66. package/package.json +3 -2
  67. package/dist/memory/context-flush.js +0 -24
@@ -13,16 +13,46 @@ import { fileURLToPath } from "node:url";
13
13
  import { dirname, join } from "node:path";
14
14
  import { EventEmitter } from "node:events";
15
15
  import { MAX_SPAWN_DEPTH } from "./types.js";
16
+ import { scopedModelOverrides } from "../model-overrides.js";
16
17
  import { createWorktree, hasWorktreeChanges, removeWorktree, } from "./worktree.js";
17
18
  const __filename = fileURLToPath(import.meta.url);
18
19
  const __dirname = dirname(__filename);
19
20
  /** Resolved path to the child-entry module. */
20
21
  const CHILD_ENTRY = join(__dirname, "child-entry.js");
22
+ /** Providers that reach a configurable endpoint (--base-url). */
23
+ const ENDPOINT_PROVIDERS = new Set(["openai-compat", "deepseek"]);
24
+ /**
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.
32
+ */
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 };
37
+ const childModel = model ?? parent.model;
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
+ };
46
+ }
21
47
  /** Keys forwarded from the parent env into child processes. */
22
48
  const ENV_FORWARD_KEYS = [
23
49
  "OPENROUTER_API_KEY",
24
50
  "ANTHROPIC_API_KEY",
25
51
  "OPENAI_API_KEY",
52
+ "DEEPSEEK_API_KEY",
53
+ // Key for an openai-compat endpoint; the endpoint itself goes in the
54
+ // spawn payload (childProvider). Env only: never argv or logs.
55
+ "PHREN_AGENT_API_KEY",
26
56
  "PHREN_AGENT_PROVIDER",
27
57
  "PHREN_AGENT_MODEL",
28
58
  "PHREN_OLLAMA_URL",
@@ -43,12 +73,14 @@ export class AgentSpawner extends EventEmitter {
43
73
  depth;
44
74
  maxDepth;
45
75
  getPermissionDefaults;
76
+ getParentProvider;
46
77
  constructor(opts = {}) {
47
78
  super();
48
79
  this.costTracker = opts.costTracker ?? null;
49
80
  this.depth = opts.depth ?? 0;
50
81
  this.maxDepth = opts.maxDepth ?? MAX_SPAWN_DEPTH;
51
82
  this.getPermissionDefaults = opts.getPermissionDefaults;
83
+ this.getParentProvider = opts.getParentProvider;
52
84
  }
53
85
  canSpawn() {
54
86
  return this.depth < this.maxDepth;
@@ -63,6 +95,7 @@ export class AgentSpawner extends EventEmitter {
63
95
  }
64
96
  const agentId = `agent-${this.nextId++}`;
65
97
  const defaults = this.getPermissionDefaults?.();
98
+ const chosen = childProvider(this.getParentProvider?.(), opts.provider, opts.model);
66
99
  // Build forwarded env
67
100
  const childEnv = {};
68
101
  for (const key of ENV_FORWARD_KEYS) {
@@ -76,9 +109,12 @@ export class AgentSpawner extends EventEmitter {
76
109
  agentId,
77
110
  task: opts.task,
78
111
  cwd: opts.cwd ?? defaults?.projectRoot ?? process.cwd(),
79
- provider: opts.provider,
80
- model: opts.model,
112
+ provider: chosen.provider,
113
+ model: chosen.model,
114
+ ...(chosen.baseUrl ? { baseUrl: chosen.baseUrl } : {}),
115
+ ...(chosen.reasoning ? { reasoning: chosen.reasoning } : {}),
81
116
  project: opts.project,
117
+ modelOverrides: scopedModelOverrides(),
82
118
  permissions: opts.permissions ?? defaults?.mode ?? "auto-confirm",
83
119
  maxTurns: opts.maxTurns ?? 50,
84
120
  budget: opts.budget ?? null,
@@ -88,7 +124,9 @@ export class AgentSpawner extends EventEmitter {
88
124
  agentType: opts.agentType,
89
125
  depth: this.depth + 1,
90
126
  sandboxMode: opts.sandboxMode ?? defaults?.sandboxMode,
127
+ network: defaults?.network,
91
128
  allowedPaths: opts.allowedPaths ?? defaults?.allowedPaths ?? [],
129
+ rules: defaults?.rules,
92
130
  };
93
131
  const entry = {
94
132
  id: agentId,
@@ -173,6 +211,9 @@ export class AgentSpawner extends EventEmitter {
173
211
  case "text_block":
174
212
  this.emit("text_block", msg.agentId, msg.text);
175
213
  break;
214
+ case "stream_retry":
215
+ this.emit("stream_retry", msg.agentId, msg.discard);
216
+ break;
176
217
  case "tool_start":
177
218
  this.emit("tool_start", msg.agentId, msg.toolName, msg.input, msg.count);
178
219
  break;
@@ -211,17 +252,22 @@ export class AgentSpawner extends EventEmitter {
211
252
  break;
212
253
  }
213
254
  }
255
+ /** Fold a child's usage into the parent's tracker (its cost already priced by the child). */
214
256
  aggregateChildCost(result) {
215
257
  const tracker = this.costTracker;
216
258
  if (!tracker)
217
259
  return;
218
260
  const inputTokens = result.inputTokens ?? 0;
219
261
  const outputTokens = result.outputTokens ?? 0;
262
+ const cacheReadTokens = result.cacheReadTokens ?? 0;
263
+ const cacheWriteTokens = result.cacheWriteTokens ?? 0;
220
264
  const costUsd = result.costUsd ?? 0;
221
- if (inputTokens === 0 && outputTokens === 0 && costUsd === 0)
265
+ if (inputTokens === 0 && outputTokens === 0 && cacheReadTokens === 0 && cacheWriteTokens === 0 && costUsd === 0)
222
266
  return;
223
267
  tracker.totalInputTokens += inputTokens;
224
268
  tracker.totalOutputTokens += outputTokens;
269
+ tracker.totalCacheReadTokens += cacheReadTokens;
270
+ tracker.totalCacheWriteTokens += cacheWriteTokens;
225
271
  tracker.totalCost += costUsd;
226
272
  }
227
273
  /** Route a direct message from one agent to another. */
@@ -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
- // Use the first token (the binary) as the pattern
25
- return cmd.split(/\s+/)[0] || "*";
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: match the binary name
41
- return entry.pattern === pattern;
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
- if (!safety.safe && safety.severity === "warn") {
61
- // In full-auto, warn becomes ask. In other modes, it's already going to ask.
62
- if (config.mode === "full-auto") {
63
- return { verdict: "ask", reason: safety.reason };
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 names its paths inside the patch text: check every one.
112
+ // apply_patch: check every path the patch names.
93
113
  if (toolName === "apply_patch") {
94
- let paths = [];
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
- if (cwdResult.ok) {
135
- const cmd = input.command || "";
136
- const safety = checkShellSafety(cmd);
137
- if (safety.safe) {
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
- if (opts.mode === "off") {
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 (isSeatbeltAvailable()) {
164
- return { argv: buildSeatbeltArgv(argv, writable), sandboxed: true };
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
+ }