-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsupertool.py
More file actions
executable file
·11766 lines (10754 loc) · 496 KB
/
Copy pathsupertool.py
File metadata and controls
executable file
·11766 lines (10754 loc) · 496 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
supertool — Batch file operations for autonomous Claude Code runs.
WHY THIS EXISTS
---------------
Each separate tool round-trip re-pays the cached prefix (system prompt +
rules + tool schemas + prior turns). Anthropic prompt caching is real and
billed at 10% of input price, so re-pay is NOT free but also NOT full
re-pay. Still worth batching.
Per saved round-trip (3 separate reads vs 1 SuperTool call, 50K prefix,
2K per file):
Cache reads: 156.9K → 50K (-106.9K raw, -10.7K effective at 10%)
Output tokens: 900 → 400 (not cached, billed at 5x input rate)
Round-trips: 3 → 1 (-2-6s wall time)
Final context: identical (same file bytes either way)
Dollars per batch: ~$0.04 Sonnet, ~$0.19 Opus. Compounds across many
batches per autonomous run.
USAGE — BATCH AS MANY OPS AS YOU CAN ANTICIPATE
-----------------------------------------------
There is no limit on ops per call. Pack every read, grep, and glob you
expect to need this turn. Two ops is NOT the cap — six is routine.
Realistic batch (7 ops, 1 round-trip) — ALWAYS quote args to prevent
shell glob expansion:
supertool \\
'read:src/SiX/SiXModule.py' \\
'read:src/SiX/SiXPermissions.py' \\
'read:src/SiX/SiXOptions.py' \\
'grep:extends:src/SiX/:20' \\
'grep:@related:src/SiX/:10' \\
'glob:src/SiX/Components/**/*.xml' \\
'glob:src/SiX/EventsManagers/*.py'
OPERATIONS
----------
read:PATH Read file (first 300 lines, 20KB cap)
read:PATH:OFFSET:LIMIT Read with offset and line limit
grep:PATTERN:PATH Search pattern (10 results default).
Auto-reads full file if PATH is a concrete
file < 20KB with a match.
grep:PATTERN:PATH:LIMIT Search with custom result limit
grep:PATTERN:PATH:LIMIT:CONTEXT
Search with context lines (like grep -C).
Match lines: path:lineno:content
Context lines: path-lineno-content
Groups separated by -- when non-adjacent.
grep:PATTERN:PATH:LIMIT:CONTEXT:count
Return match counts per file instead of content.
Output: filepath:COUNT per line.
read:PATH:OFFSET:LIMIT:grep=PATTERN
Read with inline filter — only show lines matching
PATTERN (original line numbers preserved).
glob:PATTERN Find files matching pattern (** supported).
Auto-reads if PATTERN is a concrete file
path with no wildcards.
ls:PATH List directory entries
tail:PATH:N Last N lines (default 20)
head:PATH:N First N lines (default 20)
wc:PATH Line/word/char count (like unix wc)
check:PRESET:PATH Run a named validation from ops section in .supertool.json.
Config maps preset names to shell commands with {file}.
around:PATTERN:PATH Show 10 lines around the first match in FILE
around:PATTERN:PATH:N Show N lines around the first match in FILE
grep_around:PATTERN:PATH Every match + 3 ctx lines, limit 10 (alias for
grep with sane defaults — bulk usage scan)
grep_around:PATTERN:PATH:N:LIMIT
Every match + N ctx lines, custom limit
map:PATH Symbol map of a file or directory. Shows
classes, functions, methods, constants as an
indented tree with line numbers.
Three-tier: tree-sitter → ctags → regex.
replace_dry:OLD:NEW:PATH Preview replacements without modifying files.
Shows diff-style output (- old / + new) per
occurrence with file paths and line numbers.
replace:OLD:NEW:PATH Find and replace OLD with NEW across all files
in PATH. Returns receipt: files modified and
replacement count per file.
Output: structured text with --- separators per operation.
Calls logged to {tempdir}/supertool-calls.log for per-turn analysis
(macOS: /var/folders/.../T/, Linux: /tmp/, Windows: %TEMP%).
"""
from __future__ import annotations
import atexit
import json
import difflib
import hashlib
import os
import stat
import re
import shlex
import shutil
import signal
import socket
import subprocess
import sys
import tempfile
import threading
import time
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
VERSION = "0.14.0"
def _fwd(p: str) -> str:
"""Normalize path separators to forward slashes for cross-platform output."""
return p.replace(os.sep, "/")
def _python_token() -> str:
"""Cross-platform shell-quoted Python interpreter for cmd templates.
Replaces ``{python}`` in custom op / formatter / validator cmd strings.
Authors used to hard-code ``python3`` (POSIX-only) or ``python`` (Windows)
in ``.supertool.json`` — neither was portable. ``{python}`` resolves to
``sys.executable`` so the same template runs on Linux, macOS, and Windows.
Backslashes in ``sys.executable`` on Windows would be eaten by
``shlex.split``'s POSIX backslash-escape; forward-slash normalisation
avoids that. Spaces in the install path (``C:/Program Files/...``) are
handled by ``shlex.quote``.
"""
return shlex.quote(sys.executable.replace(os.sep, "/"))
def _safe_relpath(path: str, start: str = ".") -> str:
"""os.path.relpath that survives cross-drive Windows paths.
On Windows, os.path.relpath raises ValueError when `path` and `start`
live on different drives (e.g. pytest tmp_path under C:\\Temp vs cwd
under D:\\). Falls back to the absolute path so traversal/exclude
logic keeps working — the prefix check downstream simply won't match
a cross-drive path, which is the correct behavior.
"""
try:
return os.path.relpath(path, start)
except ValueError:
return os.path.abspath(path)
MAX_READ_LINES = 300
# Hard cap on batch:@file op count — prevents DoS via huge payload
# (10k ops sequentially took ~390s on macOS, hung past timeout on Windows).
# Override via ops.batch.max_ops in .supertool.json for one-off bulk runs.
MAX_BATCH_OPS = 1000
MAX_READ_BYTES = 20000 # ~20KB cap — prevents Claude Code "Output too large"
MAX_AROUND_BYTES = 16000 # per-op cap for around:/grep_around: context windows (#241)
CHAR_WINDOW_CHARS = 1000 # head/tail peek window for minified single-line files
MINIFIED_LINE_CHARS = 5000 # a single line this long means line-based view is useless
MAX_GREP_RESULTS = 10
MAX_GLOB_RESULTS = 50
LOG_FILE = os.path.join(tempfile.gettempdir(), "supertool-calls.log")
GREP_FILE_INCLUDES = ("*.php", "*.xml", "*.py", "*.js", "*.ts", "*.md")
_GREP_EXTENSIONS_EFFECTIVE: Tuple[str, ...] | None = None
def _match_glob(path: str, pattern: str) -> bool:
"""fnmatch with brace expansion: `*.{a,b,c}` → match if any of `*.a / *.b / *.c`.
fnmatch.fnmatch doesn't understand `{a,b,c}` alternatives. This helper
expands them once (one level, no nesting) and tries each alternative.
Patterns without braces fall through to plain fnmatch unchanged.
"""
import fnmatch
if not pattern:
return True
if "{" not in pattern or "}" not in pattern:
return fnmatch.fnmatch(path, pattern)
# Expand a single brace group `{a,b,c}` into ["a", "b", "c"]. Multiple
# brace groups in the same pattern aren't supported (not needed by current
# consumers) — fall through to plain fnmatch in that case.
open_i = pattern.index("{")
close_i = pattern.index("}", open_i)
if pattern.count("{") > 1 or pattern.count("}") > 1:
return fnmatch.fnmatch(path, pattern)
prefix = pattern[:open_i]
suffix = pattern[close_i + 1:]
alternatives = pattern[open_i + 1:close_i].split(",")
for alt in alternatives:
if fnmatch.fnmatch(path, f"{prefix}{alt.strip()}{suffix}"):
return True
return False
def _expand_braces(pattern: str) -> List[str]:
"""Expand shell-style brace groups `{a,b,c}` into a list of patterns.
Supports multiple groups (`*.{a,b}.{x,y}` → 4 patterns) and nesting
(`{a,b{1,2}}` → `[a, b1, b2]`). Patterns without braces return `[pattern]`.
Unbalanced braces are returned unchanged (treated as a literal).
"""
if "{" not in pattern:
return [pattern]
open_i = pattern.index("{")
depth = 0
close_i = -1
for i in range(open_i, len(pattern)):
c = pattern[i]
if c == "{":
depth += 1
elif c == "}":
depth -= 1
if depth == 0:
close_i = i
break
if close_i == -1:
return [pattern]
prefix = pattern[:open_i]
suffix = pattern[close_i + 1:]
inner = pattern[open_i + 1:close_i]
parts: List[str] = []
depth = 0
last = 0
for i, c in enumerate(inner):
if c == "{":
depth += 1
elif c == "}":
depth -= 1
elif c == "," and depth == 0:
parts.append(inner[last:i])
last = i + 1
parts.append(inner[last:])
out: List[str] = []
seen = set()
for alt in parts:
for sub in _expand_braces(prefix + alt + suffix):
if sub not in seen:
seen.add(sub)
out.append(sub)
return out
# Default exclude-paths applied to all traversal ops (glob, grep, tree, map).
# These are pruned at the directory-walk boundary — the dirs are never opened.
# Match is prefix-relative-to-cwd; trailing slash is normalised in _get_exclude_paths.
_DEFAULT_EXCLUDE_PATHS: Tuple[str, ...] = (
".git/", "node_modules/", ".svn/", ".hg/", ".idea/", ".vscode/",
"__pycache__/", ".venv/", "venv/", "dist/", "build/",
"phpstan-result-cache/", ".phpunit.cache/", ".rector/",
# #146: credential/secret dirs and files. Pruned so grep/glob/tree/map
# don't accidentally surface tokens in their output (which then lands in
# an LLM's context). Override per-project via .supertool.json exclude-paths.
# Note: trailing slash matches dirs AND files of the same name —
# `_is_excluded` appends `/` to rel_path before prefix-matching, so `.env/`
# catches a FILE named `.env` and a DIR named `.env/`. Distinct entries
# are needed for `.env.local`, `.env.production`, etc. (each is its own name).
".env/", ".env.local/", ".env.production/", ".env.development/", ".env.test/",
".max/", ".ssh/", ".aws/", ".gnupg/", ".kube/", ".docker/",
".terraform/", ".chef/", ".npm/", "secrets/", "credentials/",
)
WILDCARD_CHARS = re.compile(r"[*?\[]")
# Patterns for lines that are "blank or comment-only" across common languages
_COMPACT_SKIP = re.compile(
r"^\s*$" # blank lines
r"|^\s*//" # PHP/JS/TS single-line comments
r"|^\s*#" # Python/shell comments
r"|^\s*\*" # Javadoc/PHPDoc continuation lines
r"|^\s*/\*" # block comment open
r"|^\s*\*/" # block comment close
r"|^\s*<!--" # XML/HTML comment open
r"|^\s*-->" # XML/HTML comment close
)
# Config file — .supertool.json in project root (or parent dirs)
_CONFIG: Dict[str, Any] | None = None
_CONFIG_CHECKED = False
# MCP server specs parsed from _CONFIG["mcp"] — populated by _load_config()
_mcp_specs: Dict[str, dict] = {}
# Supertool install directory (where supertool.py actually lives, following symlinks).
# Normalised to forward slashes so the directory survives `shlex.split(posix=True)`
# which would otherwise eat Windows backslashes as escape sequences when
# `{supertool_dir}` is substituted into validator / formatter / notifier cmd
# templates. Windows accepts forward-slash paths everywhere; POSIX is unaffected.
_INSTALL_DIR = os.path.dirname(os.path.realpath(__file__)).replace(os.sep, "/")
def _find_preset_file(name: str, project_dir: str) -> str | None:
"""Find a preset JSON file by name, checking three locations in order.
Resolution order:
1. {project_dir}/presets/{name}.json — project-level
2. ~/.config/supertool/presets/{name}.json — user-level
3. {supertool install dir}/presets/{name}.json — shipped
"""
candidates = [
os.path.join(project_dir, "presets", f"{name}.json"),
os.path.join(os.path.expanduser("~"), ".config", "supertool", "presets", f"{name}.json"),
os.path.join(_INSTALL_DIR, "presets", f"{name}.json"),
]
for path in candidates:
if os.path.isfile(path):
return path
return None
def _resolve_preset_cmd(cmd: str, preset_dir: str) -> str:
"""Replace {path} placeholder with the preset's directory (trailing slash).
Example: 'python3 {path}gitlab/issue.py {arg}'
becomes: 'python3 /home/user/.local/supertool/presets/gitlab/issue.py {arg}'
Normalises preset_dir to forward slashes — the cmd template flows through
`shlex.split(posix=True)` which would otherwise eat Windows backslashes
as escape sequences. Forward slashes work on every platform.
"""
path_prefix = preset_dir.replace(os.sep, "/").rstrip("/") + "/"
return cmd.replace("{path}", path_prefix)
def _merge_presets(config: Dict[str, Any], project_dir: str) -> None:
"""Load and merge preset ops into config. Project ops win on conflict."""
presets = config.get("presets")
if not presets or not isinstance(presets, list):
return
project_ops = config.get("ops", {})
merged_ops: Dict[str, Any] = {}
for name in presets:
if not isinstance(name, str):
continue
preset_path = _find_preset_file(name, project_dir)
if preset_path is None:
# Store warning in a list so callers can report it
config.setdefault("_preset_warnings", []).append(
f"preset {name!r} not found"
)
continue
try:
with open(preset_path) as f:
preset_data = json.load(f)
except (json.JSONDecodeError, OSError):
config.setdefault("_preset_warnings", []).append(
f"preset {name!r}: failed to load {preset_path}"
)
continue
preset_dir = os.path.dirname(preset_path)
preset_ops = preset_data.get("ops", {})
for op_name, op_def in preset_ops.items():
# Resolve script paths relative to where the preset JSON lives
if isinstance(op_def, dict) and "cmd" in op_def:
op_def = dict(op_def) # don't mutate original
op_def["cmd"] = _resolve_preset_cmd(op_def["cmd"], preset_dir)
elif isinstance(op_def, str):
op_def = _resolve_preset_cmd(op_def, preset_dir)
merged_ops[op_name] = op_def
# Project-level ops override preset ops
merged_ops.update(project_ops)
config["ops"] = merged_ops
def _load_config() -> Dict[str, Any]:
"""Load .supertool.json from cwd or parents. Cached.
After loading, merges any preset ops declared in "presets" key and
parses the optional "mcp" block into the module-level _mcp_specs dict.
"""
global _CONFIG, _CONFIG_CHECKED, _mcp_specs
if _CONFIG_CHECKED:
return _CONFIG or {}
_CONFIG_CHECKED = True
d = os.path.abspath(os.getcwd())
project_dir = d
while True:
candidate = os.path.join(d, ".supertool.json")
if os.path.isfile(candidate):
try:
with open(candidate) as f:
_CONFIG = json.load(f)
# JSON `null` parses to None; bare scalars / lists parse
# to non-dict. _merge_presets needs a dict — coerce to
# empty to keep the rest of the loader honest.
if not isinstance(_CONFIG, dict):
_CONFIG = {}
project_dir = d
_merge_presets(_CONFIG, project_dir)
# Parse MCP server specs from the optional "mcp" block.
mcp_block = _CONFIG.get("mcp")
if isinstance(mcp_block, dict):
for srv_name, spec in mcp_block.items():
if isinstance(spec, dict) and "cmd" in spec:
_mcp_specs[srv_name] = spec
return _CONFIG
except (json.JSONDecodeError, OSError):
pass
parent = os.path.dirname(d)
if parent == d:
break
d = parent
_CONFIG = {}
return _CONFIG
def _is_compact() -> bool:
"""Check if compact mode is enabled in .supertool.json."""
return bool(_load_config().get("compact", False))
def _notifier_debug_enabled() -> bool:
"""Env SUPERTOOL_NOTIFIER_DEBUG=1 wins over JSON `notifier_debug: true`."""
env = os.environ.get("SUPERTOOL_NOTIFIER_DEBUG")
if env is not None:
return env.strip().lower() in ("1", "true", "yes", "on")
return bool(_load_config().get("notifier_debug", False))
def _notifier_debug_log_path() -> str:
"""Override via SUPERTOOL_NOTIFIER_DEBUG_LOG; default /tmp/supertool-notifier-debug.log."""
return os.environ.get("SUPERTOOL_NOTIFIER_DEBUG_LOG") or "/tmp/supertool-notifier-debug.log"
def _notifier_log(msg: str) -> None:
"""Append a timestamped line to the notifier debug log when enabled. Silent otherwise."""
if not _notifier_debug_enabled():
return
try:
with open(_notifier_debug_log_path(), "a") as f:
ts = datetime.now().isoformat(timespec="milliseconds")
f.write(f"[{ts}] {msg}\n")
except OSError:
pass
def _parallel_workers() -> int:
"""Max worker count for parallel batched ops. 0 = sequential.
Env `SUPERTOOL_PARALLEL` wins over JSON. Accepts:
int N → up to N workers (0 disables)
true/false → 4 / 0 (back-compat with bool config)
Default: 0 (off).
"""
env = os.environ.get("SUPERTOOL_PARALLEL")
raw: object = env if env is not None else _load_config().get("parallel", 0)
if isinstance(raw, bool):
return 4 if raw else 0
if isinstance(raw, int):
return max(0, raw)
if isinstance(raw, str):
s = raw.strip().lower()
if s in ("true", "yes", "on"):
return 4
if s in ("false", "no", "off", ""):
return 0
try:
return max(0, int(s))
except ValueError:
return 0
return 0
def _get_op_int(op_name: str, key: str, default: int) -> int:
"""Read an integer setting from builtin-ops.<op_name>.<key>, with fallback.
Env var SUPERTOOL_<OP>_<KEY> takes precedence over JSON config.
Example: SUPERTOOL_READ_ABSTRACT_THRESHOLD_BYTES=12000
"""
env_key = f"SUPERTOOL_{op_name.upper()}_{key.upper()}"
env_val = os.environ.get(env_key)
if env_val:
try:
n = int(env_val)
if n > 0:
return n
except ValueError:
pass
cfg = _load_config()
op_cfg = cfg.get("builtin-ops", {}).get(op_name, {})
val = op_cfg.get(key)
if isinstance(val, int) and val > 0:
return val
return default
def _grep_file_includes() -> Tuple[str, ...] | None:
"""Return effective grep file extensions. Cached.
Reads builtin-ops.grep.extensions from .supertool.json.
- No config / empty list → None (search all files)
- Config with extensions → only those patterns
"""
global _GREP_EXTENSIONS_EFFECTIVE
if _GREP_EXTENSIONS_EFFECTIVE is not None:
return _GREP_EXTENSIONS_EFFECTIVE if _GREP_EXTENSIONS_EFFECTIVE != ("*",) else None
cfg = _load_config()
builtin_ops = cfg.get("builtin-ops", {})
op_cfg = builtin_ops.get("grep", {})
exts = op_cfg.get("extensions", [])
if exts and isinstance(exts, list):
valid = tuple(sorted(e for e in exts if isinstance(e, str) and e.startswith("*.")))
if valid:
_GREP_EXTENSIONS_EFFECTIVE = valid
return valid
# Default: search all files
_GREP_EXTENSIONS_EFFECTIVE = ("*",) # sentinel for "no filter"
return None
def _get_exclude_paths(op_name: str, no_exclude: bool = False) -> Tuple[str, ...]:
"""Return the effective set of exclude-path prefixes for a traversal op.
Merges _DEFAULT_EXCLUDE_PATHS with any project-level exclude-paths defined
under ops.<op_name>.exclude-paths in .supertool.json (additive union).
Returns an empty tuple when no_exclude=True (per-call escape hatch).
"""
if no_exclude:
return ()
defaults = set(_DEFAULT_EXCLUDE_PATHS)
cfg = _load_config()
project_paths = cfg.get("ops", {}).get(op_name, {})
if isinstance(project_paths, dict):
extra = project_paths.get("exclude-paths", [])
if isinstance(extra, list):
for p in extra:
if isinstance(p, str):
# Normalise: ensure trailing slash for directory prefix matching
defaults.add(p if p.endswith("/") else p + "/")
return tuple(sorted(defaults))
def _is_excluded(rel_path: str, exclude_paths: Tuple[str, ...]) -> bool:
"""Return True if rel_path matches any of the exclude prefixes.
Two match modes (matches `.gitignore` semantics):
1. **Prefix match** — `rel_path` literally starts with a prefix (catches
a `node_modules/` at the project root).
2. **Component match** — any single-segment prefix (`__pycache__/`,
`.git/`, `node_modules/`) matches that name appearing ANYWHERE in
the path (catches nested `presets/devto/__pycache__/foo.pyc`,
which the old prefix-only logic missed).
Multi-segment prefixes (`Dvsi/dvsi-private/libs/`) keep prefix-only
semantics — anchoring to repo root is the whole point of them.
rel_path should be relative to cwd and use os.sep. Comparison normalises
separators and strips a leading './'.
"""
if not exclude_paths:
return False
# Normalise to forward-slashes for consistent prefix matching
normalised = rel_path.replace(os.sep, "/")
# Strip leading "./" produced by os.path.join(".", name) or relpath at cwd
if normalised.startswith("./"):
normalised = normalised[2:]
if not normalised.endswith("/"):
normalised += "/"
# Component set for the "matches anywhere" check (skip empties).
components = {c for c in normalised.rstrip("/").split("/") if c}
for prefix in exclude_paths:
if normalised.startswith(prefix):
return True
# Single-segment prefixes also match anywhere in the path.
bare = prefix.rstrip("/")
if "/" not in bare and bare in components:
return True
return False
def _split_exclude_prefixes(
exclude_paths: Tuple[str, ...],
) -> Tuple[Tuple[str, ...], Tuple[str, ...]]:
"""Split exclude prefixes into single-segment names and multi-segment paths.
Single-segment ("node_modules/", ".git/") can be passed to grep's
--exclude-dir. Multi-segment ("Dvsi/dvsi-private/libs/") cannot — callers
that delegate to grep should fall back to native walking when any
multi-segment prefixes are present.
Returns (singles, multis), each tuple of trimmed names without trailing "/".
"""
singles: List[str] = []
multis: List[str] = []
for p in exclude_paths:
trimmed = p.rstrip("/")
if "/" in trimmed:
multis.append(trimmed)
else:
singles.append(trimmed)
return tuple(singles), tuple(multis)
def _rtk_enabled() -> bool:
"""Check if RTK delegation is enabled in .supertool.json. Default: true."""
return bool(_load_config().get("rtk", True))
# RTK integration — when rtk is installed, delegate read/grep/wc for compressed output
_RTK_PATH: str | None = None
_RTK_CHECKED = False
def _has_rtk() -> str | None:
"""Return rtk binary path if available, None otherwise. Cached.
Honours ``SUPERTOOL_NO_RTK=1`` — used by tests that spawn supertool in a
subprocess and need the unwrapped output format regardless of whether the
user has rtk on their PATH.
"""
global _RTK_PATH, _RTK_CHECKED
if not _RTK_CHECKED:
_RTK_CHECKED = True
if os.environ.get("SUPERTOOL_NO_RTK") == "1":
_RTK_PATH = None
else:
from shutil import which
_RTK_PATH = which("rtk")
return _RTK_PATH
def _rtk_run(args: List[str], timeout: int = 30) -> str | None:
"""Run rtk command, return stdout or None on failure."""
rtk = _has_rtk()
if not rtk:
return None
try:
result = subprocess.run(
[rtk] + args, capture_output=True, text=True, timeout=timeout
)
if result.returncode == 0:
return result.stdout
except (subprocess.TimeoutExpired, OSError):
pass
return None
# Built-in op names — custom ops/aliases with these names are ignored
_BUILTIN_OPS = {"read", "grep", "grep_around", "glob", "ls", "tail", "head", "wc", "check", "around", "map", "diff", "stat", "around_line", "tree", "replace", "replace_dry", "edit", "replace_lines", "paste", "vi", "validate", "format", "validate_staged", "format_staged", "workspace", "resolve", "diag", "hover", "rename"}
# Read-only built-in ops — safe to run in parallel across a batch.
# Excludes mutating ops (replace, edit, replace_lines) and custom ops
# (could shell out to anything). `between` is included — pure file read.
_PARALLEL_SAFE_OPS = {
"read", "grep", "glob", "ls", "head", "tail", "wc", "stat",
"map", "tree", "around", "around_line", "between", "diff", "blame",
"version", "validate", "validate_staged", "format_staged", "workspace",
"resolve", "diag", "hover",
}
def _is_parallel_safe(arg: str) -> bool:
"""Return True if the op name is in the read-only safe set.
Detects op name from `op:...` or `op:::...` prefix. Anything else —
custom ops, mutating ops, malformed args — is treated as unsafe.
"""
m = re.match(r"^([a-zA-Z_][a-zA-Z0-9_-]*)(:::|:|$)", arg)
if not m:
return False
return m.group(1) in _PARALLEL_SAFE_OPS
# ---------------------------------------------------------------------------
# Custom ops and aliases — config-driven dispatch extensions
# ---------------------------------------------------------------------------
class SecurityError(Exception):
"""Raised when a path arg violates the cwd containment policy."""
pass
# Hard cap on path length passed to _safe_path. Sized well above MAX_PATH (260)
# and the extended-length namespace (32767) is too permissive for an op arg —
# 4096 catches obvious abuse (1MB args from fuzz tests) while leaving every
# legitimate path well under the limit.
_MAX_SAFE_PATH_LEN = 4096
def _safe_path(p: str, *, allow_outside_cwd: Optional[bool] = None) -> str:
"""Resolve `p` and enforce repo-root containment (closes #146).
Strict mode (default): the realpath of `p` must equal cwd or live under
cwd. Symlinks crossing the boundary are rejected. `..` traversal that
escapes cwd is rejected. Returns the resolved absolute path.
Opt-out (any one is enough):
1. `allow_outside_cwd=True` per-call kwarg
2. `SUPERTOOL_ALLOW_OUTSIDE_CWD=1` env var (CI / one-off)
3. `"allow_outside_cwd": true` in `.supertool.json` (project-pinned)
Test suites set the env var via conftest.py so tmp_path-based fixtures
keep working; production deployments leave it unset.
Trust model note: lookup (3) reads from the project's `.supertool.json`,
same trust level as the other knobs there (validators, custom ops,
presets). A user cloning a hostile repo is already running its code via
supertool validators / ops; in-config opt-out adds no new attack
surface. The env var takes precedence for one-off overrides.
`~` and env-var expansion happen via os.path.expanduser / expandvars —
a user-supplied `~/.ssh/id_rsa` is resolved to the real path BEFORE
the cwd check, which is what catches the threat.
"""
if allow_outside_cwd is None:
if os.environ.get("SUPERTOOL_ALLOW_OUTSIDE_CWD") == "1":
allow_outside_cwd = True
else:
# Project config opt-in. Wrapped in try/except so a broken /
# missing config never raises out of a path check.
try:
allow_outside_cwd = bool(_load_config().get("allow_outside_cwd"))
except Exception:
allow_outside_cwd = False
# NUL byte rejection — os.path.* raises ValueError on embedded NULs which
# would leak as an uncaught traceback. Reject early with a clean message.
if "\x00" in p:
raise SecurityError(f"path contains NUL byte: {p!r}")
# Windows: paths longer than MAX_PATH (260) make _getfinalpathname raise
# ValueError("path too long for Windows") from inside os.path.realpath.
# Reject oversized paths up front with a clean SecurityError so dispatch
# returns a clean "ERROR: ..." instead of an uncaught traceback. 4096 is
# well above MAX_PATH (260) and extended-length (32767) workable values
# — any real op path stays well under it.
if len(p) > _MAX_SAFE_PATH_LEN:
raise SecurityError(
f"path too long ({len(p)} chars, max {_MAX_SAFE_PATH_LEN})"
)
expanded = os.path.expanduser(os.path.expandvars(p))
try:
abs_p = os.path.realpath(expanded)
except (ValueError, OSError) as e:
# Truncate path in the error message — matches existing SecurityError
# style of not echoing arbitrarily-large user input back verbatim.
shown = p if len(p) <= 120 else p[:120] + "…"
raise SecurityError(f"path cannot be resolved: {shown!r} ({e})")
if allow_outside_cwd:
return abs_p
# Windows: NTFS is case-insensitive (`C:\Users` == `c:\users`) and uses
# backslash separators. `os.path.normcase` lowercases + normalises
# separators on Windows; on POSIX it's a no-op so the check stays exact.
# This also handles drive-letter case (`c:\` vs `C:\`) and forward-slash
# variants (`C:/Users` vs `C:\Users`).
abs_p_cmp = os.path.normcase(abs_p)
root_cmp = os.path.normcase(os.path.realpath(os.getcwd()))
if abs_p_cmp == root_cmp:
return abs_p
if not abs_p_cmp.startswith(root_cmp + os.sep):
raise SecurityError(
f"path escapes cwd: {p!r} (resolved to {abs_p!r}). "
f"To allow: set SUPERTOOL_ALLOW_OUTSIDE_CWD=1 (env), or add "
f'`\"allow_outside_cwd\": true` to .supertool.json.'
)
return abs_p
def _extract_env_prefix(cmd: str) -> Tuple[Dict[str, str], str]:
"""Split a leading `KEY=VAL KEY2=VAL2 ...` shell env-prefix off `cmd`.
Returns ({KEY:VAL,...}, remaining_cmd_without_prefix). Mirrors POSIX shell
semantics: a `KEY=VAL` token before the command sets KEY in the child's
env. Stops at the first non-assignment token. Tokens are parsed via
shlex.split, so quoted values (`KEY='one two'`) work.
Needed because the argv-form fix (#145) broke shipped cmd templates that
set env this way — `subprocess.run(shlex.split(cmd), shell=False)` treats
the assignment as a literal argv[0], yielding ENOENT.
"""
env: Dict[str, str] = {}
tokens = shlex.split(cmd, posix=True)
idx = 0
_kv = re.compile(r"^([A-Za-z_][A-Za-z0-9_]*)=(.*)$")
while idx < len(tokens):
m = _kv.match(tokens[idx])
if not m:
break
env[m.group(1)] = m.group(2)
idx += 1
if not env:
return {}, cmd
# Rebuild remaining cmd as shell-safe string so callers can keep using
# shlex.split on it (the placeholder-substituted file path already
# passed through shlex.quote upstream, so it survives a second pass).
remaining = " ".join(shlex.quote(t) for t in tokens[idx:])
return env, remaining
def _check_vim_shell_allowed() -> Optional[str]:
"""Gate vim's `:!cmd`, `:%!cmd`, `:r !cmd` behind explicit opt-in (closes #147).
Returns None when allowed, else a clean ERROR string the caller returns
up the stack. Shell verbs in a vim macro are full RCE by design — a
prompt-injected vim payload like `:!rm -rf ~` runs verbatim. Default-off
keeps editor verbs (i/a/o/d/s/etc.) working unconditionally.
Opt-in (any one is enough):
1. `SUPERTOOL_ALLOW_VIM_SHELL=1` env var (one-off / CI)
2. `"allow_vim_shell": true` in `.supertool.json` (project-pinned)
"""
if os.environ.get("SUPERTOOL_ALLOW_VIM_SHELL") == "1":
return None
try:
if bool(_load_config().get("allow_vim_shell")):
return None
except Exception:
pass
return (
"ERROR: vim shell verbs (:!, :%!, :r !) are disabled by default. "
'To allow: set SUPERTOOL_ALLOW_VIM_SHELL=1 (env), or add '
'`"allow_vim_shell": true` to .supertool.json. '
"For one-off shell logic, prefer a wrapper script + custom op.\n"
)
def _expand_env(s: str, env: Dict[str, str]) -> str:
"""Safe $VAR / ${VAR} expansion from env (no shell).
Replaces $NAME and ${NAME} with values from env. Unknown vars are left
literal (vs shell which silently empties them). Used at all argv-form
dispatch sites (custom ops, validators, formatters, resolve) so users
can keep cmd templates that rely on env-var expansion without invoking
a shell.
"""
return re.sub(
r'\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)',
lambda m: env.get(m.group(1) or m.group(2), m.group(0)),
s,
)
def _resolve_custom_op(op: str, parts: List[str]) -> str | None:
"""Try to run op as a custom command from config["ops"].
Runs argv-form (shell=False) — shell metachars in the cmd template are
literal tokens, not shell operators. `$VAR` / `${VAR}` expansion from
the op's env is performed by supertool (see _expand_env below), no shell.
Returns formatted output string on match, None if op is not a custom op.
"""
config = _load_config()
ops = config.get("ops")
if not ops or op not in ops:
return None
entry = ops[op]
if isinstance(entry, str):
cmd_template = entry
timeout = config.get("timeout", 60)
elif isinstance(entry, dict):
cmd_template = entry.get("cmd", "")
timeout = entry.get("timeout", config.get("timeout", 60))
else:
return f"ERROR: invalid config for custom op {op!r}\n"
if not cmd_template:
return f"ERROR: empty command for custom op {op!r}\n"
# Build the command — replace {file}, {dir}, {arg}, {args}, {argjoin}, {python} placeholders
file_arg = parts[1] if len(parts) > 1 else ""
cmd = cmd_template.replace("{python}", _python_token())
cmd = cmd.replace("{file}", shlex.quote(file_arg))
dir_arg = os.path.dirname(file_arg) if file_arg else "."
cmd = cmd.replace("{dir}", shlex.quote(dir_arg))
cmd = cmd.replace("{arg}", shlex.quote(file_arg))
all_args = " ".join(shlex.quote(p) for p in parts[1:]) if len(parts) > 1 else ""
cmd = cmd.replace("{args}", all_args)
# {argjoin}: parts[1:] rejoined with ':::' as a single shell-quoted arg.
# Lets the receiving script split fields itself when they contain colons
# (e.g. XPath like .//ns:tag or [position()=1]).
arg_join = ":::".join(parts[1:]) if len(parts) > 1 else ""
cmd = cmd.replace("{argjoin}", shlex.quote(arg_join))
# Pass extra config keys as SUPERTOOL_ env vars
_RESERVED_KEYS = {"cmd", "timeout", "description", "syntax", "example", "status", "restartMcp"}
env = dict(os.environ)
if isinstance(entry, dict):
for k, v in entry.items():
if k not in _RESERVED_KEYS:
env[f"SUPERTOOL_{k.upper()}"] = str(v)
_prefix_env, cmd = _extract_env_prefix(cmd)
env.update(_prefix_env)
cmd = _expand_env(cmd, env)
t0 = time.monotonic()
try:
# argv-form (shell=False) — shell metachars in the template become
# literal tokens, not shell operators. Placeholder values are still
# shlex.quote'd above so values containing spaces survive shlex.split.
result = subprocess.run(
shlex.split(cmd), shell=False, capture_output=True, text=True, timeout=timeout,
env=env,
)
elapsed = time.monotonic() - t0
output = result.stdout
if result.returncode != 0:
if result.stderr:
output += result.stderr
return f"FAIL ({elapsed:.2f}s)\n{output}"
return f"PASS ({elapsed:.2f}s)\n{output}{_maybe_restart_mcp(entry)}"
except subprocess.TimeoutExpired:
elapsed = time.monotonic() - t0
return f"FAIL (timeout {elapsed:.1f}s > {timeout}s)\n"
except OSError as e:
return f"FAIL: {e}\n"
def _maybe_restart_mcp(entry: object) -> str:
"""SIGTERM the warm MCP daemons a custom op asks to restart via `restartMcp`.
A custom op that invalidates state the warm LSP daemons cache (autoload map,
PHPStan result cache, etc.) can declare `restartMcp` so the daemons are
stopped after the cmd succeeds; the next op that touches each server
cold-starts a fresh daemon that re-reads the cleared state. Accepts:
true -> every server in the config "mcp" block
["a","b"] -> only those servers
"name" -> a single server
Names not present in the config "mcp" block are reported separately instead
of being counted as restarted, so the status line never claims to have
stopped a daemon that was never configured. Returns a one-line status suffix
(empty when nothing to restart). Best-effort like the new-file path — a stop
failure never fails the op.
"""
if not isinstance(entry, dict):
return ""
spec = entry.get("restartMcp")
if not spec:
return ""
if spec is True:
names = list(_mcp_specs.keys())
elif isinstance(spec, list):
names = [str(n) for n in spec]
else:
names = [str(spec)]
known = [n for n in names if n in _mcp_specs]
unknown = [n for n in names if n not in _mcp_specs]
for name in known:
_mcp_stop_server(name)
note = ""
if known:
note += f"mcp: restarted {len(known)} daemon(s) ({', '.join(known)})\n"
if unknown:
note += f"mcp: unknown server(s) ignored ({', '.join(unknown)})\n"
return note
_IN_ALIAS = False # recursion guard — prevents alias-from-alias expansion
def _resolve_alias(op: str, parts: List[str]) -> str | None:
"""Try to expand op as an alias from config["aliases"].
Returns concatenated output of all expanded ops, None if not an alias.
Aliases expand to ops (built-in or custom) but NOT to other aliases.
"""
global _IN_ALIAS
if _IN_ALIAS:
return None # block recursive alias expansion
config = _load_config()
aliases = config.get("aliases")
if not aliases or op not in aliases:
return None
alias_def = aliases[op]
if not isinstance(alias_def, dict):
return f"ERROR: alias {op!r} must be an object with 'ops' key\n"
op_list = alias_def.get("ops", [])
if not isinstance(op_list, list):
return f"ERROR: alias {op!r} 'ops' must be a list\n"
if not op_list:
return ""
# Replace {file}, {dir}, {arg}, and {args} placeholders in each expanded op
file_arg = parts[1] if len(parts) > 1 else ""
dir_arg = os.path.dirname(file_arg) if file_arg else "."
all_args = " ".join(parts[1:]) if len(parts) > 1 else ""
_IN_ALIAS = True
try:
output_parts: List[str] = []
for expanded_op in op_list:
resolved = expanded_op.replace("{file}", file_arg)
resolved = resolved.replace("{dir}", dir_arg)
resolved = resolved.replace("{arg}", file_arg)
resolved = resolved.replace("{args}", all_args)
output_parts.append(dispatch(resolved))
return "".join(output_parts)
finally:
_IN_ALIAS = False
# ---------------------------------------------------------------------------
# Core operations (pure functions — all return the string to emit)
# ---------------------------------------------------------------------------
def render_file(path: str, offset: int = 0, limit: int = 0,
grep_filter: str = "", force_full: bool = False) -> str:
"""Emit a file's contents with line numbers, truncated at caps.
Shared by read: and by grep/glob auto-promote branches.
When grep_filter is set, only lines matching the regex are shown (with