@phren/agent 0.3.58 → 0.3.59

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.
@@ -0,0 +1,434 @@
1
+ /**
2
+ * The options a read-only command may take and still be auto-approved, and a
3
+ * parser that reads a command's arguments the way the command itself does:
4
+ * short clusters (`-rn`), a short option's value attached or next (`-n5`,
5
+ * `-n 5`), `--opt=value` and `--opt value`, `-NUM` counts, `--` ending the
6
+ * options (unless it is an option's value: `rg -e -- --pre=x`), and options
7
+ * after operands. An option that isn't listed for the command makes the
8
+ * command not auto-approvable: a command's writing or executing options
9
+ * (`sort -o`, `rg --pre`, `git grep -O`) are left off, so a flag nobody
10
+ * thought of asks instead of running (it replaced a deny-list that every
11
+ * review found another flag missing from).
12
+ */
13
+ /** `args` read as `spec`'s command reads them, or null when any option is not on its list. */
14
+ export function parseOptions(args, spec) {
15
+ if (spec.anyArgs)
16
+ return { options: [], operands: [...args] };
17
+ const options = [], operands = [];
18
+ let dashdash;
19
+ const has = (set, c) => !!set && set.includes(c);
20
+ for (let i = 0; i < args.length; i++) {
21
+ const arg = args[i];
22
+ if (arg === "--") {
23
+ dashdash = operands.length;
24
+ operands.push(...args.slice(i + 1));
25
+ break;
26
+ }
27
+ if (arg.startsWith("--")) {
28
+ const eq = arg.indexOf("=");
29
+ const name = eq === -1 ? arg.slice(2) : arg.slice(2, eq);
30
+ if (spec.long?.includes(name)) {
31
+ if (eq !== -1)
32
+ return null;
33
+ options.push({ name: `--${name}` });
34
+ continue;
35
+ }
36
+ if (spec.longOptional?.includes(name)) {
37
+ options.push({ name: `--${name}`, ...(eq !== -1 ? { value: arg.slice(eq + 1) } : {}) });
38
+ continue;
39
+ }
40
+ if (spec.longValued?.includes(name)) {
41
+ if (eq !== -1) {
42
+ options.push({ name: `--${name}`, value: arg.slice(eq + 1) });
43
+ continue;
44
+ }
45
+ if (i + 1 >= args.length)
46
+ return null;
47
+ options.push({ name: `--${name}`, value: args[++i] });
48
+ continue;
49
+ }
50
+ return null;
51
+ }
52
+ if (arg.startsWith("-") && arg.length > 1) {
53
+ if (spec.numeric && /^-\d+$/.test(arg)) {
54
+ options.push({ name: "-NUM", value: arg.slice(1) });
55
+ continue;
56
+ }
57
+ for (let j = 1; j < arg.length; j++) {
58
+ const c = arg[j];
59
+ if (has(spec.flags, c)) {
60
+ options.push({ name: `-${c}` });
61
+ continue;
62
+ }
63
+ if (has(spec.attached, c)) {
64
+ const rest = arg.slice(j + 1);
65
+ options.push({ name: `-${c}`, ...(rest ? { value: rest } : {}) });
66
+ break;
67
+ }
68
+ if (has(spec.valued, c)) {
69
+ const rest = arg.slice(j + 1);
70
+ if (rest) {
71
+ options.push({ name: `-${c}`, value: rest });
72
+ break;
73
+ }
74
+ if (i + 1 >= args.length)
75
+ return null;
76
+ options.push({ name: `-${c}`, value: args[++i] });
77
+ break;
78
+ }
79
+ return null;
80
+ }
81
+ continue;
82
+ }
83
+ operands.push(arg);
84
+ }
85
+ if (spec.maxOperands !== undefined && operands.length > spec.maxOperands)
86
+ return null;
87
+ return { options, operands, ...(dashdash !== undefined ? { dashdash } : {}) };
88
+ }
89
+ /** A parsed option written back as one argument (`--name=value`, `-xVALUE`, `-NUM`). */
90
+ export function optionArg(o) {
91
+ if (o.name === "-NUM")
92
+ return `-${o.value}`;
93
+ if (o.value === undefined)
94
+ return o.name;
95
+ return o.name.startsWith("--") ? `${o.name}=${o.value}` : `${o.name}${o.value}`;
96
+ }
97
+ /** The arguments of a parsed command that name files it reads. */
98
+ export function parsedPaths(parsed, spec) {
99
+ const paths = parsed.options.filter((o) => o.value !== undefined && spec.pathOptions?.includes(o.name)).map((o) => o.value);
100
+ if (spec.noPaths)
101
+ return paths;
102
+ let operands = parsed.operands;
103
+ const patternGiven = spec.patternOptions && parsed.options.some((o) => spec.patternOptions.includes(o.name));
104
+ if ((spec.patternOptions && !patternGiven) || spec.firstOperandNotPath)
105
+ operands = operands.slice(1);
106
+ return [...paths, ...operands];
107
+ }
108
+ /** `table[key]` only when `key` is the table's own entry: a command or subcommand name is the model's text,
109
+ * and `constructor` or `__proto__` must not find Object's members. */
110
+ export function own(table, key) {
111
+ return Object.hasOwn(table, key) ? table[key] : undefined;
112
+ }
113
+ const GREP = {
114
+ flags: "EFGPiyvwxcLloqsbHhnTZzraIRU", valued: "ABCmefdD", numeric: true,
115
+ long: ["extended-regexp", "fixed-strings", "basic-regexp", "perl-regexp", "ignore-case", "no-ignore-case", "invert-match",
116
+ "word-regexp", "line-regexp", "count", "files-with-matches", "files-without-match", "only-matching", "quiet", "silent",
117
+ "no-messages", "byte-offset", "with-filename", "no-filename", "line-number", "initial-tab", "null", "null-data", "text",
118
+ "recursive", "dereference-recursive", "line-buffered"],
119
+ longValued: ["regexp", "file", "max-count", "after-context", "before-context", "context", "include", "exclude", "exclude-dir",
120
+ "exclude-from", "binary-files", "devices", "directories", "label"],
121
+ longOptional: ["color", "colour"],
122
+ patternOptions: ["-e", "--regexp", "-f", "--file"], pathOptions: ["-f", "--file", "--exclude-from"],
123
+ };
124
+ /** Read-only commands and the options each may take unprompted. */
125
+ export const READ_ONLY_SPECS = {
126
+ ls: { flags: "1aAbBcCdfFgGhHiklLmnopqQrRsStuUvxX@eOT", valued: "Iw",
127
+ long: ["all", "almost-all", "human-readable", "recursive", "reverse", "size", "directory", "classify", "inode",
128
+ "numeric-uid-gid", "dereference", "group-directories-first", "full-time", "literal", "si"],
129
+ longValued: ["ignore", "hide", "width", "sort", "time", "format", "time-style", "block-size", "tabsize", "indicator-style"],
130
+ longOptional: ["color", "colour", "hyperlink"] },
131
+ cat: { flags: "AbeEnstTuv", long: ["show-all", "number-nonblank", "show-ends", "number", "squeeze-blank", "show-tabs", "show-nonprinting"] },
132
+ head: { flags: "qvz", valued: "nc", numeric: true, long: ["quiet", "silent", "verbose", "zero-terminated"], longValued: ["lines", "bytes"] },
133
+ // No -f / -F: following never ends.
134
+ tail: { flags: "qvzr", valued: "ncb", numeric: true, long: ["quiet", "silent", "verbose", "zero-terminated"], longValued: ["lines", "bytes"] },
135
+ // No --files0-from here or on sort: the files it names come from a list no check here reads.
136
+ wc: { flags: "clmwL", long: ["bytes", "chars", "lines", "words", "max-line-length"] },
137
+ grep: GREP, egrep: GREP, fgrep: GREP,
138
+ // No --pre (runs a program on every file) and no -z / --search-zip (runs decompressors).
139
+ rg: { flags: "abcFHhiIlLnNopqsSuUvwx0.P", valued: "efgtTmABCMjrEd",
140
+ long: ["hidden", "no-ignore", "no-ignore-vcs", "no-ignore-parent", "no-ignore-dot", "files", "count", "count-matches", "json",
141
+ "line-number", "no-line-number", "column", "no-heading", "heading", "with-filename", "no-filename", "fixed-strings",
142
+ "ignore-case", "smart-case", "case-sensitive", "word-regexp", "line-regexp", "invert-match", "files-with-matches",
143
+ "files-without-match", "only-matching", "quiet", "follow", "vimgrep", "stats", "trim", "unrestricted", "text", "null",
144
+ "no-messages", "sort-files", "multiline", "pcre2", "byte-offset", "no-config", "passthru", "glob-case-insensitive", "type-list"],
145
+ longValued: ["regexp", "file", "glob", "iglob", "type", "type-not", "max-count", "max-depth", "max-filesize", "after-context",
146
+ "before-context", "context", "context-separator", "field-match-separator", "replace", "sort", "sortr", "threads", "color",
147
+ "colors", "encoding", "pre-glob", "type-add", "ignore-file", "path-separator", "max-columns"],
148
+ patternOptions: ["-e", "--regexp", "-f", "--file"], pathOptions: ["-f", "--file", "--ignore-file"] },
149
+ // No -o / --output (writes a file), -T (temporary files) or --compress-program (runs one).
150
+ sort: { flags: "bdfgiMhnRrsuVcCmz", valued: "ktS",
151
+ long: ["ignore-leading-blanks", "dictionary-order", "ignore-case", "general-numeric-sort", "ignore-nonprinting", "month-sort",
152
+ "human-numeric-sort", "numeric-sort", "random-sort", "reverse", "version-sort", "check", "merge", "stable", "unique",
153
+ "zero-terminated", "debug"],
154
+ longValued: ["key", "field-separator", "buffer-size", "parallel", "random-source"],
155
+ pathOptions: ["--random-source"] },
156
+ // `uniq IN OUT` writes OUT.
157
+ uniq: { flags: "cdDiuz", valued: "fsw", maxOperands: 1, long: ["count", "repeated", "ignore-case", "unique", "zero-terminated"],
158
+ longValued: ["skip-fields", "skip-chars", "check-chars"], longOptional: ["all-repeated", "group"] },
159
+ cut: { flags: "snz", valued: "bcdf", long: ["only-delimited", "complement", "zero-terminated"],
160
+ longValued: ["bytes", "characters", "delimiter", "fields", "output-delimiter"] },
161
+ tr: { flags: "cCdst", noPaths: true, long: ["complement", "delete", "squeeze-repeats", "truncate-set1"] },
162
+ diff: { flags: "abBdeEilnNpqrsStTuwy", valued: "CUxXIFW",
163
+ long: ["brief", "report-identical-files", "recursive", "new-file", "text", "ignore-case", "ignore-all-space",
164
+ "ignore-space-change", "ignore-blank-lines", "side-by-side", "minimal", "strip-trailing-cr", "suppress-common-lines"],
165
+ longValued: ["context", "exclude", "exclude-from", "ignore-matching-lines", "label", "width"], longOptional: ["unified", "color"],
166
+ pathOptions: ["-X", "--exclude-from"] },
167
+ cmp: { flags: "blsv", valued: "in", long: ["print-bytes", "verbose", "quiet", "silent"], longValued: ["ignore-initial", "bytes"] },
168
+ echo: { anyArgs: true, noPaths: true },
169
+ // printf -v assigns a variable (PATH among them): refused in shell-classify.ts.
170
+ printf: { anyArgs: true, noPaths: true },
171
+ test: { anyArgs: true, noPaths: true },
172
+ "[": { anyArgs: true, noPaths: true },
173
+ true: { anyArgs: true, noPaths: true },
174
+ false: { anyArgs: true, noPaths: true },
175
+ pwd: { flags: "LP", maxOperands: 0 },
176
+ which: { flags: "as", noPaths: true },
177
+ type: { flags: "afptP", noPaths: true },
178
+ // No -C (compiles a magic file) and no -f (reads the names to test from a file).
179
+ file: { flags: "bcdhiLNnprsvzZk0", valued: "mF", long: ["brief", "mime", "mime-type", "mime-encoding", "dereference",
180
+ "no-dereference", "keep-going", "raw", "special-files", "uncompress"], pathOptions: ["-m"] },
181
+ stat: { flags: "LtFlnqrsx", valued: "cf", long: ["dereference", "terse", "file-system"], longValued: ["format", "printf"] },
182
+ du: { flags: "aAbcghHklLmPsSx0", valued: "dBtI", long: ["all", "apparent-size", "bytes", "total", "human-readable", "si",
183
+ "dereference", "summarize", "one-file-system", "null", "count-links", "separate-dirs"],
184
+ longValued: ["max-depth", "block-size", "threshold", "exclude", "exclude-from"], pathOptions: ["--exclude-from"] },
185
+ df: { flags: "ahHiklmPTgx", valued: "tB", long: ["all", "human-readable", "si", "inodes", "local", "portability", "print-type", "total"],
186
+ longValued: ["type", "exclude-type", "block-size"], longOptional: ["output"] },
187
+ // No -o (writes its listing to a file).
188
+ tree: { flags: "adfFgilnNpqrsuCDhJQSAXtvxUc", valued: "LIPH", long: ["noreport", "dirsfirst", "gitignore", "prune", "du", "si"],
189
+ longValued: ["charset", "filelimit", "timefmt", "sort"] },
190
+ basename: { flags: "az", valued: "s", noPaths: true, long: ["multiple", "zero"], longValued: ["suffix"] },
191
+ dirname: { flags: "z", noPaths: true, long: ["zero"] },
192
+ realpath: { flags: "esqLPmz", long: ["canonicalize-existing", "canonicalize-missing", "logical", "physical", "quiet", "strip",
193
+ "no-symlinks", "zero"], longValued: ["relative-to", "relative-base"] },
194
+ readlink: { flags: "fenmqsvz", long: ["canonicalize", "canonicalize-existing", "canonicalize-missing", "no-newline", "quiet",
195
+ "silent", "verbose", "zero"] },
196
+ // No -s / --set (sets the clock) and no -f (GNU: reads a file and echoes its lines); operands are
197
+ // +FORMAT (a bare one would set the clock).
198
+ date: { flags: "uRjn", valued: "dr", noPaths: true, long: ["utc", "universal", "rfc-email"], longValued: ["date", "reference"],
199
+ longOptional: ["iso-8601", "rfc-3339"], pathOptions: ["-r", "--reference"] },
200
+ // No --arg / --argjson / --slurpfile: they take two values.
201
+ // No -f: a filter file can `import` data files no check here reads (the filter given inline is checked
202
+ // for import and include in shell-classify.ts).
203
+ jq: { flags: "rjacnsSeCMR", firstOperandNotPath: true, long: ["raw-output", "join-output", "ascii-output",
204
+ "compact-output", "null-input", "slurp", "sort-keys", "exit-status", "color-output", "monochrome-output", "raw-input", "tab"],
205
+ longValued: ["indent"] },
206
+ nl: { flags: "p", valued: "bdfhilnsvw" },
207
+ column: { flags: "txne", valued: "cso" },
208
+ // No -c / --check: the files checked are named inside the sum file.
209
+ sha256sum: { flags: "btz", long: ["binary", "text", "tag", "zero"] },
210
+ md5sum: { flags: "btz", long: ["binary", "text", "tag", "zero"] },
211
+ shasum: { flags: "btUp0", valued: "a", long: ["binary", "text", "portable", "tag"], longValued: ["algorithm"] },
212
+ whoami: { maxOperands: 0 },
213
+ uname: { flags: "amnrsvpio", maxOperands: 0 },
214
+ // An operand would set the host name.
215
+ hostname: { flags: "fsid", maxOperands: 0 },
216
+ cd: { flags: "LP", maxOperands: 1 },
217
+ };
218
+ const GIT_DIFF_LONG = ["numstat", "shortstat", "summary", "name-only", "name-status", "patch-with-stat", "raw", "minimal",
219
+ "patience", "histogram", "ignore-all-space", "ignore-space-change", "ignore-blank-lines", "ignore-space-at-eol", "check",
220
+ "exit-code", "quiet", "no-color", "no-renames", "text", "binary", "full-index", "no-ext-diff", "patch", "no-patch",
221
+ "function-context", "irreversible-delete", "cumulative", "no-prefix", "ita-invisible-in-index"];
222
+ const GIT_DIFF_OPTIONAL = ["stat", "dirstat", "color", "word-diff", "color-words", "find-renames", "find-copies", "relative",
223
+ "abbrev", "color-moved", "ignore-submodules"];
224
+ const GIT_DIFF_VALUED = ["diff-filter", "src-prefix", "dst-prefix", "unified", "inter-hunk-context", "diff-algorithm", "anchored",
225
+ "stat-width", "word-diff-regex"];
226
+ const GIT_LOG_LONG = ["oneline", "graph", "all", "reverse", "merges", "no-merges", "first-parent", "abbrev-commit", "follow",
227
+ "left-right", "cherry-pick", "cherry-mark", "boundary", "topo-order", "date-order", "author-date-order", "source", "full-history",
228
+ "simplify-by-decoration", "ancestry-path", "no-decorate", "remotes", "tags", "mailmap", "relative-date", "parents", "children",
229
+ "no-abbrev-commit", "regexp-ignore-case", "all-match", "invert-grep", "use-mailmap"];
230
+ const GIT_LOG_VALUED = ["since", "after", "until", "before", "author", "committer", "grep", "max-count", "skip", "date", "min-parents",
231
+ "max-parents", "encoding"];
232
+ const GIT_LOG_OPTIONAL = ["decorate", "format", "pretty", "branches", "no-walk", "notes"];
233
+ /** The read-only git subcommands and the options each may take. No `--output` anywhere (writes a file), no
234
+ * `--ext-diff` or `--textconv` (run configured programs), no `git grep -O` (opens the matches in a program). */
235
+ export const GIT_SPECS = {
236
+ status: { flags: "sbvz", attached: "u", long: ["short", "branch", "long", "verbose", "show-stash", "ahead-behind",
237
+ "no-ahead-behind", "renames", "no-renames", "no-column", "null"],
238
+ longOptional: ["porcelain", "ignored", "untracked-files", "ignore-submodules", "find-renames", "column"] },
239
+ diff: { flags: "pusRawbBzW", valued: "SGlO", attached: "UMCBX", long: [...GIT_DIFF_LONG, "cached", "staged", "no-index", "merge-base"],
240
+ longOptional: GIT_DIFF_OPTIONAL, longValued: GIT_DIFF_VALUED, pathOptions: ["-O"] },
241
+ // No -L: its `START,END:FILE` prints a file's lines, and the file is inside the value.
242
+ log: { flags: "pqsuzw", valued: "nSG", attached: "UMC", numeric: true, long: [...GIT_LOG_LONG, ...GIT_DIFF_LONG],
243
+ longOptional: [...GIT_LOG_OPTIONAL, ...GIT_DIFF_OPTIONAL], longValued: [...GIT_LOG_VALUED, ...GIT_DIFF_VALUED] },
244
+ show: { flags: "pqsuzw", valued: "nSG", attached: "UMC", numeric: true, long: [...GIT_LOG_LONG, ...GIT_DIFF_LONG],
245
+ longOptional: [...GIT_LOG_OPTIONAL, ...GIT_DIFF_OPTIONAL], longValued: [...GIT_LOG_VALUED, ...GIT_DIFF_VALUED] },
246
+ "rev-parse": { flags: "q", long: ["verify", "quiet", "show-toplevel", "git-dir", "git-common-dir", "absolute-git-dir",
247
+ "is-inside-work-tree", "is-inside-git-dir", "is-bare-repository", "is-shallow-repository", "show-prefix", "show-cdup",
248
+ "symbolic", "symbolic-full-name", "all", "local-env-vars", "show-superproject-working-tree"],
249
+ longOptional: ["abbrev-ref", "short", "branches", "tags", "remotes"], longValued: ["git-path", "since", "until"] },
250
+ "ls-files": { flags: "cdmoiskutvfz", valued: "xX", long: ["cached", "deleted", "modified", "others", "ignored", "stage", "killed",
251
+ "unmerged", "directory", "no-empty-directory", "exclude-standard", "full-name", "recurse-submodules", "error-unmatch",
252
+ "eol", "deduplicate", "sparse"], longOptional: ["abbrev"], longValued: ["exclude", "exclude-from", "exclude-per-directory",
253
+ "with-tree", "format"], pathOptions: ["-X", "--exclude-from"] },
254
+ blame: { flags: "bclstfnpwe", valued: "LS", attached: "MC", long: ["porcelain", "line-porcelain", "incremental", "root",
255
+ "show-stats", "show-name", "show-number", "show-email", "reverse", "first-parent", "minimal"],
256
+ longValued: ["date", "ignore-rev", "ignore-revs-file", "contents", "abbrev"], longOptional: ["color-lines", "color-by-age"],
257
+ pathOptions: ["-S", "--ignore-revs-file", "--contents"] },
258
+ grep: { flags: "aIiwvhHlLcnbzFEGPWqro", valued: "efABCm", numeric: true,
259
+ long: ["cached", "untracked", "no-index", "no-exclude-standard", "exclude-standard", "recurse-submodules", "text",
260
+ "ignore-case", "word-regexp", "invert-match", "full-name", "extended-regexp", "basic-regexp", "perl-regexp",
261
+ "fixed-strings", "line-number", "column", "files-with-matches", "name-only", "files-without-match", "count", "no-color",
262
+ "break", "heading", "show-function", "function-context", "quiet", "all-match", "and", "or", "not", "only-matching", "null"],
263
+ longValued: ["max-depth", "threads", "after-context", "before-context", "context", "max-count"], longOptional: ["color"],
264
+ patternOptions: ["-e", "-f"], pathOptions: ["-f"] },
265
+ describe: { long: ["tags", "all", "always", "long", "exact-match", "contains", "first-parent"],
266
+ longOptional: ["abbrev", "dirty", "broken"], longValued: ["candidates", "match", "exclude"] },
267
+ shortlog: { flags: "nsec", long: ["numbered", "summary", "email", "committer"], longValued: ["group"], longOptional: ["format"] },
268
+ };
269
+ /** git's own options before the subcommand that keep it `git <subcommand>` (no -c, -C, --git-dir, --exec-path…). */
270
+ export const GIT_GLOBAL_SAFE = new Set(["--no-pager", "-P", "--no-optional-locks", "--literal-pathspecs", "--no-replace-objects"]);
271
+ /** find's tests and actions that only test or print, with the number of arguments each takes. Not -exec,
272
+ * -execdir, -ok, -okdir, -delete or -fprint* (run programs, delete or write files). */
273
+ export const FIND_PRIMARIES = {
274
+ "-print": 0, "-print0": 0, "-prune": 0, "-empty": 0, "-true": 0, "-false": 0, "-o": 0, "-or": 0, "-a": 0, "-and": 0,
275
+ "-not": 0, "!": 0, "(": 0, ")": 0, "-depth": 0, "-xdev": 0, "-mount": 0, "-follow": 0, "-ls": 0, "-quit": 0,
276
+ "-nouser": 0, "-nogroup": 0, "-readable": 0, "-writable": 0, "-executable": 0, "-d": 0, "-x": 0,
277
+ "-name": 1, "-iname": 1, "-path": 1, "-ipath": 1, "-wholename": 1, "-iwholename": 1, "-regex": 1, "-iregex": 1,
278
+ "-type": 1, "-xtype": 1, "-maxdepth": 1, "-mindepth": 1, "-size": 1, "-mtime": 1, "-mmin": 1, "-atime": 1, "-amin": 1,
279
+ "-ctime": 1, "-cmin": 1, "-newer": 1, "-anewer": 1, "-cnewer": 1, "-newermt": 1, "-user": 1, "-group": 1, "-perm": 1,
280
+ "-links": 1, "-inum": 1, "-samefile": 1, "-uid": 1, "-gid": 1, "-lname": 1, "-ilname": 1, "-printf": 1, "-regextype": 1, "-fstype": 1,
281
+ };
282
+ /** find's start paths, or null when its expression has anything but FIND_PRIMARIES. */
283
+ export function parseFind(args) {
284
+ let i = 0;
285
+ while (i < args.length && /^-[HLP]+$/.test(args[i]))
286
+ i++;
287
+ const paths = [];
288
+ while (i < args.length && !args[i].startsWith("-") && args[i] !== "(" && args[i] !== "!")
289
+ paths.push(args[i++]);
290
+ while (i < args.length) {
291
+ const arity = own(FIND_PRIMARIES, args[i]);
292
+ if (arity === undefined || (arity > 0 && i + arity >= args.length))
293
+ return null;
294
+ i += 1 + arity;
295
+ }
296
+ return paths;
297
+ }
298
+ /** sed's options: -i (edits in place) and -f (a script this reader can't see) are not on the list. */
299
+ export const SED_SPEC = { flags: "nErsuz", valued: "e", long: ["quiet", "silent", "regexp-extended", "posix",
300
+ "separate", "unbuffered", "null-data", "sandbox", "debug"], longValued: ["expression", "line-length"] };
301
+ /** sed commands that only print or edit the stream (no w/W write a file, e runs one, r/R read one in). */
302
+ const SED_PLAIN = "pdDgGhHxnNPlzF=";
303
+ /**
304
+ * Whether a sed script only prints or edits the stream: each command, after its addresses (`1`, `$`,
305
+ * `/re/`, `1,5`, `0~2`, `!`), is one of SED_PLAIN, a block, a label or branch, q/Q, a/i/c text, y, or
306
+ * s/// whose flags neither write (w) nor run (e). Anything else, w, W, e, r and R among them, is not.
307
+ */
308
+ export function sedScriptIsPlain(script) {
309
+ const s = script;
310
+ let i = 0;
311
+ const regex = (delim) => {
312
+ for (; i < s.length; i++) {
313
+ if (s[i] === "\\") {
314
+ i++;
315
+ continue;
316
+ }
317
+ if (s[i] === delim) {
318
+ i++;
319
+ return true;
320
+ }
321
+ }
322
+ return false;
323
+ };
324
+ const address = () => {
325
+ if (/[0-9]/.test(s[i] ?? "")) {
326
+ while (/[0-9~]/.test(s[i] ?? ""))
327
+ i++;
328
+ return true;
329
+ }
330
+ if (s[i] === "$") {
331
+ i++;
332
+ return true;
333
+ }
334
+ if (s[i] === "/") {
335
+ i++;
336
+ if (!regex("/"))
337
+ return false;
338
+ while (s[i] === "I" || s[i] === "M")
339
+ i++;
340
+ return true;
341
+ }
342
+ if (s[i] === "\\" && s[i + 1]) {
343
+ const delim = s[i + 1];
344
+ i += 2;
345
+ if (!regex(delim))
346
+ return false;
347
+ while (s[i] === "I" || s[i] === "M")
348
+ i++;
349
+ return true;
350
+ }
351
+ return true;
352
+ };
353
+ const skipSpace = () => { while (s[i] === " " || s[i] === "\t")
354
+ i++; };
355
+ const toLineEnd = (stopAtSemicolon) => { while (i < s.length && s[i] !== "\n" && !(stopAtSemicolon && s[i] === ";"))
356
+ i++; };
357
+ while (i < s.length) {
358
+ while (i < s.length && /[\s;]/.test(s[i]))
359
+ i++;
360
+ if (i >= s.length)
361
+ break;
362
+ const start = i;
363
+ if (!address())
364
+ return false;
365
+ if (s[i] === "," && i !== start) {
366
+ i++;
367
+ skipSpace();
368
+ if (s[i] === "+" || s[i] === "~")
369
+ i++;
370
+ if (!address())
371
+ return false;
372
+ }
373
+ skipSpace();
374
+ while (s[i] === "!") {
375
+ i++;
376
+ skipSpace();
377
+ }
378
+ const c = s[i++];
379
+ if (c === undefined)
380
+ return false;
381
+ if (c === "{" || c === "}")
382
+ continue;
383
+ if (c === "#") {
384
+ toLineEnd(false);
385
+ continue;
386
+ }
387
+ if (c === ":" || c === "b" || c === "t" || c === "T") {
388
+ toLineEnd(true);
389
+ continue;
390
+ }
391
+ if (c === "q" || c === "Q") {
392
+ skipSpace();
393
+ while (/[0-9]/.test(s[i] ?? ""))
394
+ i++;
395
+ continue;
396
+ }
397
+ if (SED_PLAIN.includes(c))
398
+ continue;
399
+ // Text to append, insert or change: printed, never a file.
400
+ if (c === "a" || c === "i" || c === "c") {
401
+ toLineEnd(false);
402
+ continue;
403
+ }
404
+ if (c === "y" || c === "s") {
405
+ const delim = s[i++];
406
+ if (!delim || delim === "\n" || delim === "\\")
407
+ return false;
408
+ if (!regex(delim) || !regex(delim))
409
+ return false;
410
+ if (c === "s") {
411
+ while (/[gpiImM0-9]/.test(s[i] ?? ""))
412
+ i++;
413
+ }
414
+ // A flag left over (w writes a file, e runs the pattern space) or anything glued on.
415
+ skipSpace();
416
+ if (i < s.length && !/[;\n}]/.test(s[i]))
417
+ return false;
418
+ continue;
419
+ }
420
+ return false;
421
+ }
422
+ return true;
423
+ }
424
+ /** sed's input files, or null when it edits in place, reads a script file, or its script writes, runs or reads a file. */
425
+ export function parseSed(args) {
426
+ const parsed = parseOptions(args, SED_SPEC);
427
+ if (!parsed)
428
+ return null;
429
+ const given = parsed.options.filter((o) => o.name === "-e" || o.name === "--expression").map((o) => o.value);
430
+ const scripts = given.length ? given : parsed.operands.slice(0, 1);
431
+ if (!scripts.length || !scripts.every(sedScriptIsPlain))
432
+ return null;
433
+ return given.length ? parsed.operands : parsed.operands.slice(1);
434
+ }
@@ -100,3 +100,29 @@ export function scrubEnv() {
100
100
  }
101
101
  return env;
102
102
  }
103
+ /** git config every agent shell command runs with, so a read never starts a program the repository's config
104
+ * names: no fsmonitor hook, no pager, no gpg for signatures. Passed as GIT_CONFIG_COUNT entries, which win
105
+ * over every config file. The helpers no override can switch off (external diff, diff drivers, textconv,
106
+ * filters) make an auto-approved git command ask instead (checker.ts `gitRunsHelpers`). */
107
+ export const GIT_HARDENING = [
108
+ ["core.fsmonitor", "false"],
109
+ ["core.pager", "cat"],
110
+ ["log.showSignature", "false"],
111
+ ];
112
+ /** scrubEnv, plus GIT_HARDENING after any GIT_CONFIG_* entries already set. git takes no optional locks (a
113
+ * `git status` doesn't rewrite the index, so no index hook runs), and there is no CDPATH: `cd name` goes
114
+ * where the permission check resolved it. */
115
+ export function shellEnv() {
116
+ const env = scrubEnv();
117
+ env.GIT_OPTIONAL_LOCKS = "0";
118
+ delete env.CDPATH;
119
+ const given = Number(env.GIT_CONFIG_COUNT);
120
+ let count = Number.isInteger(given) && given > 0 ? given : 0;
121
+ for (const [key, value] of GIT_HARDENING) {
122
+ env[`GIT_CONFIG_KEY_${count}`] = key;
123
+ env[`GIT_CONFIG_VALUE_${count}`] = value;
124
+ count++;
125
+ }
126
+ env.GIT_CONFIG_COUNT = String(count);
127
+ return env;
128
+ }
@@ -21,13 +21,19 @@ import { createHash } from "crypto";
21
21
  import * as fs from "fs";
22
22
  import * as path from "path";
23
23
  const records = new Map();
24
+ /** The file a path leads to, resolved as the kernel does: each symlink before the `..` after it
25
+ * (path.resolve and fs.realpathSync collapse `link/..` first, naming another file). */
24
26
  function key(filePath) {
25
- const abs = path.resolve(filePath);
27
+ const raw = path.isAbsolute(filePath) ? filePath : `${process.cwd()}${path.sep}${filePath}`;
26
28
  try {
27
- return fs.realpathSync(abs);
29
+ return fs.realpathSync.native(raw);
30
+ }
31
+ catch { /* not there */ }
32
+ try {
33
+ return path.join(fs.realpathSync.native(path.dirname(raw)), path.basename(raw));
28
34
  }
29
35
  catch {
30
- return abs;
36
+ return path.resolve(filePath);
31
37
  }
32
38
  }
33
39
  function hashOf(content) {
@@ -2,7 +2,7 @@ import { spawn } from "child_process";
2
2
  import * as fs from "fs";
3
3
  import * as path from "path";
4
4
  import * as os from "os";
5
- import { checkShellSafety, scrubEnv } from "../permissions/shell-safety.js";
5
+ import { checkShellSafety, shellEnv } from "../permissions/shell-safety.js";
6
6
  import { wrapWithSandbox, classifySandboxDenial, classifyNetworkDenial, SandboxRequiredError } from "../permissions/kernel-sandbox.js";
7
7
  /** A positive whole number from the environment, else the fallback. */
8
8
  function envPositiveInt(key, fallback) {
@@ -215,7 +215,7 @@ function runForeground(exe, args, opts) {
215
215
  try {
216
216
  child = spawn(exe, args, {
217
217
  cwd: opts.cwd,
218
- env: scrubEnv(),
218
+ env: shellEnv(),
219
219
  stdio: ["ignore", "pipe", "pipe"],
220
220
  detached: posix,
221
221
  });
@@ -327,7 +327,7 @@ export function createShellTool(getPermissions) {
327
327
  const child = spawn(exe, exeArgs, {
328
328
  cwd,
329
329
  stdio: ["ignore", fd, fd],
330
- env: scrubEnv(),
330
+ env: shellEnv(),
331
331
  detached: true,
332
332
  });
333
333
  const task = { pid: child.pid, outputFile, done: false, exitCode: null };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phren/agent",
3
- "version": "0.3.58",
3
+ "version": "0.3.59",
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.58",
18
+ "@phren/cli": "0.3.59",
19
19
  "ajv": "^8.20.0",
20
20
  "ink": "^8.0.0",
21
21
  "react": "^19.3.0"