@phren/agent 0.3.45 → 0.3.46

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.
@@ -68,6 +68,12 @@ class StdioTransport {
68
68
  if (!this.closed)
69
69
  onError(err);
70
70
  });
71
+ // EPIPE after the server closes its stdin arrives as a stream error; with
72
+ // no listener it would be an unhandled error that crashes the agent.
73
+ this.proc.stdin?.on("error", (err) => {
74
+ if (!this.closed)
75
+ onError(err);
76
+ });
71
77
  this.proc.on("exit", (code, signal) => {
72
78
  if (!this.closed) {
73
79
  onError(new Error(`MCP server exited (code ${code ?? "null"}, signal ${signal ?? "none"})`));
@@ -1,7 +1,10 @@
1
+ import * as fs from "fs";
2
+ import * as os from "os";
3
+ import * as path from "path";
1
4
  import { checkShellSafety } from "./shell-safety.js";
2
- import { isAutoApprovableCommand } from "./shell-classify.js";
5
+ import { isAutoApprovableCommand, splitCommandLine } from "./shell-classify.js";
3
6
  import { evaluateRules } from "./rules.js";
4
- import { validatePath, checkSensitivePath } from "./sandbox.js";
7
+ import { validatePath, checkSensitivePath, checkSensitiveTarget } from "./sandbox.js";
5
8
  import { isAllowed } from "./allowlist.js";
6
9
  import { parsePatch, patchPaths } from "../tools/apply-patch.js";
7
10
  /** Tools that are safe in all modes — read-only, no side effects. */
@@ -44,6 +47,70 @@ const AUTO_CONFIRM_TOOLS = new Set([
44
47
  const DENY_LIST_TOOLS = new Set([
45
48
  // Reserved for future use — e.g. "delete_project"
46
49
  ]);
50
+ /** Search tools whose first positional is a pattern, not a file. */
51
+ const PATTERN_FIRST = new Set(["grep", "egrep", "fgrep", "rg"]);
52
+ /** A search tool's options that give the pattern (so no operand is one). */
53
+ const PATTERN_OPTION = /^(-e|--regexp)$/;
54
+ const PATTERN_OPTION_JOINED = /^(-e.|--regexp=)/;
55
+ /** Options whose value is a file of patterns: a path. */
56
+ const PATTERN_FILE_OPTION = /^(-f|--file)$/;
57
+ /** Is this path-like argument a secret file, under its own name or where it leads? */
58
+ function secretPath(value, cwd) {
59
+ const looksLikePath = /[/\\]/.test(value) || value.startsWith(".") || value.startsWith("~")
60
+ || fs.existsSync(path.resolve(cwd, value));
61
+ if (!looksLikePath)
62
+ return false;
63
+ const expanded = value === "~" || value.startsWith("~/") ? path.join(os.homedir(), value.slice(1)) : value;
64
+ // Resolved against cwd, so `.aws/config` matches "/.aws/" like the absolute spelling.
65
+ const abs = path.resolve(cwd, expanded);
66
+ let real;
67
+ try {
68
+ real = fs.realpathSync(abs);
69
+ }
70
+ catch { /* not there (yet) */ }
71
+ return checkSensitivePath(value).sensitive || checkSensitiveTarget(abs, real).sensitive;
72
+ }
73
+ /**
74
+ * Whether a simple command names a secret file. Only arguments that look like
75
+ * paths count (they exist, contain a separator, or start with `.` or `~`), and
76
+ * a search tool's pattern is skipped, so `rg 'credentials.json' src` doesn't
77
+ * ask. After `--` every argument is an operand.
78
+ */
79
+ function namesSecretFile(tokens, cwd) {
80
+ const [binary, ...args] = tokens;
81
+ const end = args.indexOf("--");
82
+ const options = end === -1 ? args : args.slice(0, end);
83
+ const searchTool = PATTERN_FIRST.has(binary ?? "");
84
+ // A pattern given by -e/--regexp or -f/--file: every operand is a path.
85
+ let patternPending = searchTool && !options.some((a) => PATTERN_OPTION.test(a) || PATTERN_OPTION_JOINED.test(a) || PATTERN_FILE_OPTION.test(a) || /^--file=/.test(a));
86
+ for (let i = 0; i < args.length; i++) {
87
+ const arg = args[i];
88
+ if (end === -1 || i < end) {
89
+ if (arg.startsWith("-")) {
90
+ // An explicit pattern is not a path; skip it and its value.
91
+ if (searchTool && PATTERN_OPTION.test(arg)) {
92
+ i++;
93
+ continue;
94
+ }
95
+ if (searchTool && PATTERN_OPTION_JOINED.test(arg))
96
+ continue;
97
+ const eq = arg.indexOf("=");
98
+ if (eq !== -1 && secretPath(arg.slice(eq + 1), cwd))
99
+ return true;
100
+ continue;
101
+ }
102
+ }
103
+ else if (i === end)
104
+ continue;
105
+ if (patternPending && !PATTERN_FILE_OPTION.test(args[i - 1] ?? "")) {
106
+ patternPending = false;
107
+ continue;
108
+ }
109
+ if (secretPath(arg, cwd))
110
+ return true;
111
+ }
112
+ return false;
113
+ }
47
114
  /**
48
115
  * Check whether a tool call should be allowed, asked about, or denied.
49
116
  */
@@ -107,6 +174,11 @@ export function checkPermission(config, toolName, input) {
107
174
  if (!pathResult.ok) {
108
175
  return { verdict: "ask", reason: `Path outside sandbox: ${pathResult.error}` };
109
176
  }
177
+ // A harmless name can link to a secret file.
178
+ const target = checkSensitivePath(pathResult.resolved);
179
+ if (target.sensitive) {
180
+ return { verdict: "deny", reason: `Sensitive path: ${target.reason}` };
181
+ }
110
182
  }
111
183
  }
112
184
  // apply_patch: check every path the patch names.
@@ -120,6 +192,10 @@ export function checkPermission(config, toolName, input) {
120
192
  if (!pathResult.ok) {
121
193
  return { verdict: "ask", reason: `Path outside sandbox: ${pathResult.error}` };
122
194
  }
195
+ const target = checkSensitivePath(pathResult.resolved);
196
+ if (target.sensitive) {
197
+ return { verdict: "deny", reason: `Sensitive path: ${target.reason}` };
198
+ }
123
199
  }
124
200
  }
125
201
  if (rule?.verdict === "ask") {
@@ -152,7 +228,11 @@ export function checkPermission(config, toolName, input) {
152
228
  const cwdResult = validatePath(cwd, config.projectRoot, config.allowedPaths);
153
229
  // Only commands that read, build or test; anything else (rm, git
154
230
  // push, npm publish, a redirect into a file) asks.
155
- if (cwdResult.ok && isAutoApprovableCommand(input.command || "")) {
231
+ // A read-only command still asks before it touches a secret file
232
+ // (`cat .env`), as read_file would be refused.
233
+ const command = input.command || "";
234
+ const touchesSecret = (splitCommandLine(command) ?? []).some((tokens) => namesSecretFile(tokens, cwd));
235
+ if (cwdResult.ok && !touchesSecret && isAutoApprovableCommand(command)) {
156
236
  return { verdict: "allow", reason: "Read, build or test command within sandbox." };
157
237
  }
158
238
  }
@@ -116,3 +116,13 @@ export function checkSensitivePath(resolved) {
116
116
  }
117
117
  return { sensitive: false };
118
118
  }
119
+ /**
120
+ * Sensitive-path check over a requested path and its canonical target, so a
121
+ * harmless-looking name that links to a secret file is still refused.
122
+ */
123
+ export function checkSensitiveTarget(requested, canonical) {
124
+ const lexical = checkSensitivePath(requested);
125
+ if (lexical.sensitive || canonical === undefined)
126
+ return lexical;
127
+ return checkSensitivePath(canonical);
128
+ }
@@ -37,8 +37,31 @@ const WRITING_ARGS = {
37
37
  // -i edits in place; a script's w command writes a file and e runs one.
38
38
  sed: /^(-i|--in-place)|(^|[;{}\n]|\/[gpIiMm0-9]*)\s*[we](\s|$)/,
39
39
  eslint: /^--fix/,
40
- git: /^(-o|--output)/,
40
+ // git grep -O / --open-files-in-pager runs a program on the matches.
41
+ git: /^(-o|--output|-[A-Za-z]*O|--open-files-in-pager)/,
42
+ // sort -o writes its output file, also inside a cluster (-ro); --compress-program runs one.
43
+ sort: /^(-[A-Za-z]*o|--output|--compress-program)/,
44
+ tree: /^-[A-Za-z]*o/,
45
+ // rg --pre runs a program on every file it searches.
46
+ rg: /^--pre(=|$)/,
41
47
  };
48
+ /**
49
+ * git options before the subcommand that set config (core.fsmonitor and
50
+ * diff.external run programs), swap git's own executables, or point it at
51
+ * another repository: `git -c… status` is not `git status`.
52
+ */
53
+ const GIT_GLOBAL_UNSAFE = /^(-c|-C|--config-env|--exec-path|--git-dir|--work-tree)/;
54
+ /** uniq options whose value is the next argument, not a file. */
55
+ const UNIQ_VALUE_OPTION = /^(-f|-s|-w|--skip-fields|--skip-chars|--check-chars)$/;
56
+ function gitGlobalOptionsUnsafe(args) {
57
+ for (const a of args) {
58
+ if (!a.startsWith("-"))
59
+ return false;
60
+ if (GIT_GLOBAL_UNSAFE.test(a))
61
+ return true;
62
+ }
63
+ return false;
64
+ }
42
65
  /** Package scripts that `npm run` and friends may run unprompted. */
43
66
  const SAFE_SCRIPT = /^(test|build|lint|check|typecheck|type-check|tsc|compile)(:[\w:-]+)?$/;
44
67
  const SCRIPT_RUNNERS = new Set(["npm", "pnpm", "yarn", "bun"]);
@@ -135,8 +158,21 @@ function segmentIsSafe(tokens) {
135
158
  if (!binary || /^[A-Za-z_][A-Za-z0-9_]*=/.test(binary))
136
159
  return false;
137
160
  const name = binary.includes("/") ? "" : binary;
161
+ // After `--` every argument is an operand, never an option (find's
162
+ // expression and sed's script are checked whole).
163
+ const end = name === "find" || name === "sed" ? -1 : args.indexOf("--");
164
+ const options = end === -1 ? args : args.slice(0, end);
138
165
  const writing = WRITING_ARGS[name];
139
- if (writing && args.some((a) => writing.test(a)))
166
+ if (writing && options.some((a) => writing.test(a)))
167
+ return false;
168
+ // uniq IN OUT overwrites OUT.
169
+ if (name === "uniq") {
170
+ const operands = options.filter((a, i) => !a.startsWith("-") && !UNIQ_VALUE_OPTION.test(options[i - 1] ?? "")).length
171
+ + (end === -1 ? 0 : args.length - end - 1);
172
+ if (operands > 1)
173
+ return false;
174
+ }
175
+ if (name === "git" && gitGlobalOptionsUnsafe(args))
140
176
  return false;
141
177
  if (READ_ONLY.has(name) || RUNNERS.has(name))
142
178
  return true;
@@ -164,6 +200,9 @@ export function commandPattern(tokens) {
164
200
  const [binary, ...args] = tokens;
165
201
  if (!binary)
166
202
  return "*";
203
+ // Such a git line is its own pattern, so approving `git status` doesn't approve it.
204
+ if (binary === "git" && gitGlobalOptionsUnsafe(args))
205
+ return tokens.join(" ");
167
206
  if (MULTI_COMMAND_TOOLS.has(binary)) {
168
207
  const sub = args.find((a) => !a.startsWith("-"));
169
208
  if (sub)
@@ -22,7 +22,7 @@
22
22
  */
23
23
  import * as fs from "fs";
24
24
  import * as path from "path";
25
- import { checkSensitivePath, validatePath } from "../permissions/sandbox.js";
25
+ import { checkSensitivePath, checkSensitiveTarget, validatePath } from "../permissions/sandbox.js";
26
26
  import { describeNotFound } from "./edit-engine.js";
27
27
  import { forgetFileState, recordFileState, staleFileError } from "./file-state.js";
28
28
  import { syntaxCheckNote } from "./syntax-check.js";
@@ -258,11 +258,15 @@ export function applyChunks(content, chunks, filePath) {
258
258
  const joined = `${out.join("\n")}\n`;
259
259
  return crlf ? joined.replace(/\n/g, "\r\n") : joined;
260
260
  }
261
- /** Compute every file change for a patch without writing anything. */
262
- export function planPatch(ops, cwd) {
261
+ /**
262
+ * Compute every file change for a patch without writing anything. `resolve`
263
+ * maps a patch path to its file on disk; the tool passes the sandbox's
264
+ * canonical path, so planning and writes act on the file that was validated.
265
+ */
266
+ export function planPatch(ops, cwd, resolve = (p) => path.resolve(cwd, p)) {
263
267
  const state = new Map();
264
268
  const read = (p) => {
265
- const abs = path.resolve(cwd, p);
269
+ const abs = resolve(p);
266
270
  if (state.has(abs))
267
271
  return state.get(abs);
268
272
  if (!fs.existsSync(abs))
@@ -273,8 +277,9 @@ export function planPatch(ops, cwd) {
273
277
  };
274
278
  const writes = [];
275
279
  const record = (p, content, before, status) => {
276
- state.set(path.resolve(cwd, p), content);
277
- writes.push({ path: p, content, before, status });
280
+ const abs = resolve(p);
281
+ state.set(abs, content);
282
+ writes.push({ path: p, abs, content, before, status });
278
283
  };
279
284
  for (const op of ops) {
280
285
  if (op.kind === "add") {
@@ -324,8 +329,15 @@ export const applyPatchTool = {
324
329
  }
325
330
  const cwd = process.cwd();
326
331
  let writes;
332
+ // What a deletion removes: the directory entry the patch names, in its
333
+ // canonical parent, so deleting a link removes the link, not its target.
334
+ const entries = new Map();
327
335
  try {
328
336
  const ops = parsePatch(text);
337
+ // Validation follows links and `..` on disk; everything after it uses
338
+ // that canonical path, never a lexical fold of the patch's path.
339
+ const canonical = new Map();
340
+ const removed = new Set(ops.flatMap((op) => op.kind === "delete" || (op.kind === "update" && op.moveTo) ? [op.path] : []));
329
341
  for (const p of patchPaths(ops)) {
330
342
  const sensitive = checkSensitivePath(path.resolve(cwd, p));
331
343
  if (sensitive.sensitive)
@@ -333,24 +345,41 @@ export const applyPatchTool = {
333
345
  const sandbox = validatePath(p, cwd, []);
334
346
  if (!sandbox.ok)
335
347
  return { output: `Path outside sandbox: ${sandbox.error}`, is_error: true };
348
+ const target = checkSensitiveTarget(p, sandbox.resolved);
349
+ if (target.sensitive)
350
+ return { output: `Access denied: ${p}: ${target.reason}`, is_error: true };
351
+ canonical.set(p, sandbox.resolved);
352
+ const base = path.basename(p);
353
+ const parent = base === "." || base === ".." ? null : validatePath(path.dirname(p), cwd, []);
354
+ if (parent?.ok)
355
+ entries.set(p, path.join(parent.resolved, base));
356
+ else if (removed.has(p)) {
357
+ // The entry itself lives outside the project (a link's real parent),
358
+ // even if what it points at is inside: never delete the target instead.
359
+ return { output: `Path outside sandbox: ${p}: its folder is outside the project.`, is_error: true };
360
+ }
336
361
  }
362
+ const resolve = (p) => canonical.get(p);
337
363
  for (const op of ops) {
338
- // Add File over an existing file is a whole-file overwrite.
339
- const stale = staleFileError(path.resolve(cwd, op.path), { requireRead: op.kind === "add" });
364
+ // Add File over an existing file is a whole-file overwrite, and so is
365
+ // a move onto an existing file.
366
+ const stale = staleFileError(resolve(op.path), { requireRead: op.kind === "add" })
367
+ ?? (op.kind === "update" && op.moveTo ? staleFileError(resolve(op.moveTo), { requireRead: true }) : null);
340
368
  if (stale)
341
369
  throw new PatchError(stale);
342
370
  }
343
- writes = planPatch(ops, cwd);
371
+ writes = planPatch(ops, cwd, resolve);
344
372
  }
345
373
  catch (err) {
346
374
  const msg = err instanceof Error ? err.message : String(err);
347
375
  return { output: `apply_patch failed; no files were changed.\n${msg}`, is_error: true };
348
376
  }
349
377
  for (const w of writes) {
350
- const abs = path.resolve(cwd, w.path);
378
+ const abs = w.abs;
351
379
  if (w.content === null) {
352
- if (fs.existsSync(abs))
353
- fs.rmSync(abs);
380
+ const entry = entries.get(w.path);
381
+ if (entry && fs.lstatSync(entry, { throwIfNoEntry: false }))
382
+ fs.rmSync(entry);
354
383
  forgetFileState(abs);
355
384
  }
356
385
  else {
@@ -1,7 +1,7 @@
1
1
  import * as fs from "fs";
2
2
  import * as path from "path";
3
3
  import { encodeDiffPayload } from "../multi/diff-renderer.js";
4
- import { checkSensitivePath, validatePath } from "../permissions/sandbox.js";
4
+ import { checkSensitivePath, checkSensitiveTarget, validatePath } from "../permissions/sandbox.js";
5
5
  import { applyEdits, snippetAround } from "./edit-engine.js";
6
6
  import { recordFileState, staleFileError } from "./file-state.js";
7
7
  import { syntaxCheckNote } from "./syntax-check.js";
@@ -16,6 +16,9 @@ function openForEdit(filePath) {
16
16
  const sandboxResult = validatePath(filePath, process.cwd(), []);
17
17
  if (!sandboxResult.ok)
18
18
  return { ok: false, result: { output: `Path outside sandbox: ${sandboxResult.error}`, is_error: true } };
19
+ const target = checkSensitiveTarget(filePath, sandboxResult.resolved);
20
+ if (target.sensitive)
21
+ return { ok: false, result: { output: `Access denied: ${target.reason}`, is_error: true } };
19
22
  if (!fs.existsSync(filePath)) {
20
23
  return { ok: false, result: { output: `File not found: ${filePath}. Use write_file to create a new file.`, is_error: true } };
21
24
  }
@@ -1,6 +1,6 @@
1
1
  import * as fs from "fs";
2
2
  import * as path from "path";
3
- import { checkSensitivePath, validatePath } from "../permissions/sandbox.js";
3
+ import { checkSensitivePath, checkSensitiveTarget, validatePath } from "../permissions/sandbox.js";
4
4
  import { recordFileState } from "./file-state.js";
5
5
  /** Minified bundles and data files can have megabyte lines; cap each one. */
6
6
  const MAX_LINE_CHARS = 2000;
@@ -31,6 +31,10 @@ export const readFileTool = {
31
31
  if (!sandboxResult.ok) {
32
32
  return { output: `Path outside sandbox: ${sandboxResult.error}`, is_error: true };
33
33
  }
34
+ // A harmless name can link to a secret file.
35
+ const target = checkSensitiveTarget(resolved, sandboxResult.resolved);
36
+ if (target.sensitive)
37
+ return { output: `Access denied: ${target.reason}`, is_error: true };
34
38
  if (!fs.existsSync(filePath))
35
39
  return { output: `File not found: ${filePath}`, is_error: true };
36
40
  if (fs.statSync(filePath).isDirectory()) {
@@ -1,7 +1,7 @@
1
1
  import * as fs from "fs";
2
2
  import * as path from "path";
3
3
  import { modelSupportsVision } from "../models.js";
4
- import { checkSensitivePath, validatePath } from "../permissions/sandbox.js";
4
+ import { checkSensitivePath, checkSensitiveTarget, validatePath } from "../permissions/sandbox.js";
5
5
  /** Anthropic rejects images over 5MB; the other providers are in the same range. */
6
6
  const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
7
7
  const MEDIA_TYPES = {
@@ -47,6 +47,9 @@ export function createReadImageTool(provider) {
47
47
  if (!sandboxResult.ok) {
48
48
  return { output: `Path outside sandbox: ${sandboxResult.error}`, is_error: true };
49
49
  }
50
+ const target = checkSensitiveTarget(resolved, sandboxResult.resolved);
51
+ if (target.sensitive)
52
+ return { output: `Access denied: ${target.reason}`, is_error: true };
50
53
  const mediaType = MEDIA_TYPES[path.extname(filePath).toLowerCase()];
51
54
  if (!mediaType) {
52
55
  return {
@@ -1,7 +1,7 @@
1
1
  import * as fs from "fs";
2
2
  import * as path from "path";
3
3
  import { encodeDiffPayload } from "../multi/diff-renderer.js";
4
- import { checkSensitivePath, validatePath } from "../permissions/sandbox.js";
4
+ import { checkSensitivePath, checkSensitiveTarget, validatePath } from "../permissions/sandbox.js";
5
5
  import { recordFileState, staleFileError } from "./file-state.js";
6
6
  import { syntaxCheckNote } from "./syntax-check.js";
7
7
  export const writeFileTool = {
@@ -29,6 +29,9 @@ export const writeFileTool = {
29
29
  if (!sandboxResult.ok) {
30
30
  return { output: `Path outside sandbox: ${sandboxResult.error}`, is_error: true };
31
31
  }
32
+ const target = checkSensitiveTarget(resolved, sandboxResult.resolved);
33
+ if (target.sensitive)
34
+ return { output: `Access denied: ${target.reason}`, is_error: true };
32
35
  const stale = staleFileError(filePath, { requireRead: true });
33
36
  if (stale)
34
37
  return { output: stale, is_error: true };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phren/agent",
3
- "version": "0.3.45",
3
+ "version": "0.3.46",
4
4
  "description": "phren's coding agent: starts every session knowing your project's memory, tasks and decisions",
5
5
  "type": "module",
6
6
  "bin": {
@@ -15,7 +15,7 @@
15
15
  ],
16
16
  "dependencies": {
17
17
  "@modelcontextprotocol/sdk": "^1.32.0",
18
- "@phren/cli": "0.3.45",
18
+ "@phren/cli": "0.3.46",
19
19
  "ajv": "^8.20.0",
20
20
  "ink": "^8.0.0",
21
21
  "react": "^19.3.0"