@allansantos-dev/smart-tool 0.9.80 → 0.9.82
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +129 -0
- package/NOTICE +1 -1
- package/README.md +59 -14
- package/agent_redirect.py +32 -0
- package/autostart.py +32 -25
- package/browser_bridge.py +320 -0
- package/browser_control.py +76 -39
- package/browser_service_client.py +1 -7
- package/client_hooks.py +42 -41
- package/code_graph.py +56 -15
- package/code_graph_java.mjs +21 -12
- package/code_health.py +19 -12
- package/code_impact.py +1 -1
- package/codex_config.py +3 -0
- package/config.py +35 -0
- package/daemon_launcher.py +37 -5
- package/doc_candidates.py +63 -0
- package/doc_check.py +9 -3
- package/doc_extras.py +2 -3
- package/doc_insights.py +26 -2
- package/doc_prose.py +59 -11
- package/doc_registry.py +241 -0
- package/doc_scope.py +205 -39
- package/doc_turn.py +205 -0
- package/doc_validate.py +52 -9
- package/document_read.py +4 -2
- package/dossier.py +40 -5
- package/edit_shape.py +119 -0
- package/endpoint_sync.py +3 -21
- package/engine_home.py +95 -0
- package/hook_call.py +132 -0
- package/hook_decision.py +337 -23
- package/hooks/pretool_router.py +36 -29
- package/hooks/turn_end.py +40 -0
- package/index_views.py +5 -0
- package/install.py +90 -36
- package/install_runtime.py +24 -10
- package/lazy_mcp_proxy.py +10 -9
- package/link_check.py +69 -0
- package/local_embedder.py +9 -2
- package/locales/pt-BR.json +72 -4
- package/model_breaker.py +6 -5
- package/model_client.py +1 -1
- package/model_health.py +24 -6
- package/notice_action.py +9 -0
- package/package.json +2 -2
- package/pr_comment.py +94 -0
- package/pr_impact.py +216 -35
- package/process_limits.py +17 -3
- package/project_admission.py +17 -15
- package/project_identity.py +19 -1
- package/project_scan.py +98 -0
- package/removed_callers.py +146 -0
- package/scout_access.py +48 -0
- package/setup_ui.py +33 -4
- package/shell_reads.py +67 -0
- package/smart_tool_daemon.py +149 -39
- package/tray.py +60 -9
- package/update_splash.py +2 -2
- package/venv_launch.py +67 -0
- package/version.py +1 -1
- package/web_adapters/node/engine-home.mjs +42 -0
- package/web_adapters/node/package-lock.json +13 -0
- package/web_adapters/node/package.json +1 -0
- package/web_document_graph.py +12 -1
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""Callers that still name a function an edit removed or renamed, or whose signature it changed.
|
|
2
|
+
|
|
3
|
+
The functions the text before the edit defines and the text after lacks (`doc_check.functions`) are looked up in the code
|
|
4
|
+
graph: calls the graph resolved to them (a graph of the text before the edit, as in the edit hook), calls it left
|
|
5
|
+
unresolved under that name (a graph of the text after the edit, as in a diff already on disk), imports of the name, and
|
|
6
|
+
the calls still in the edited file. Names are compared by their last segment, so a name the file still defines
|
|
7
|
+
elsewhere (a method of another class) is not reported. For a function that stays with another signature the callers are
|
|
8
|
+
the calls from other files, resolved or unresolved by name; imports and calls in the edited file are left out.
|
|
9
|
+
"""
|
|
10
|
+
import posixpath
|
|
11
|
+
import re
|
|
12
|
+
|
|
13
|
+
import code_graph
|
|
14
|
+
import code_impact
|
|
15
|
+
import doc_check
|
|
16
|
+
import doc_scope
|
|
17
|
+
|
|
18
|
+
MAX_CALLERS = 5
|
|
19
|
+
MAX_SITES = 200
|
|
20
|
+
UNRESOLVED_CAP = 1000
|
|
21
|
+
_IDENTIFIER = re.compile(r"[A-Za-z_$][\w$]*")
|
|
22
|
+
_COMMENT = re.compile(r"^\s*(#|//|\*|/\*)")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _short(name):
|
|
26
|
+
return name.rpartition(".")[2]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _gone(rel, before, after):
|
|
30
|
+
"""Functions of `before` whose last name segment the functions of `after` no longer carry: {short name: qualified name}."""
|
|
31
|
+
kept = {_short(function["name"]) for function in doc_check.functions(rel, after)}
|
|
32
|
+
old = {}
|
|
33
|
+
for function in doc_check.functions(rel, before):
|
|
34
|
+
short = _short(function["name"])
|
|
35
|
+
if short not in kept and not (short.startswith("__") and short.endswith("__")):
|
|
36
|
+
old.setdefault(short, function["name"])
|
|
37
|
+
return old
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _resigned(rel, before, after):
|
|
41
|
+
"""Qualified names of the functions both texts define once whose signature differs; a name a text defines more than once
|
|
42
|
+
(overloads) is not compared."""
|
|
43
|
+
def hashes(text):
|
|
44
|
+
found = {}
|
|
45
|
+
for function in doc_check.functions(rel, text):
|
|
46
|
+
found.setdefault(function["name"], []).append(doc_scope.signature_hash(function["signature"]))
|
|
47
|
+
return found
|
|
48
|
+
old, new = hashes(before), hashes(after)
|
|
49
|
+
return [name for name, signed in old.items()
|
|
50
|
+
if len(signed) == 1 and len(new.get(name, ())) == 1 and new[name] != signed
|
|
51
|
+
and not (_short(name).startswith("__") and _short(name).endswith("__"))]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _names(expression, short, stem, method):
|
|
55
|
+
"""Whether a call expression can mean the removed function: its last name is the function's, and for a plain function
|
|
56
|
+
it is bare or reached through the module (`stem.name`); a method is reached through any receiver."""
|
|
57
|
+
parts = _IDENTIFIER.findall(expression)
|
|
58
|
+
return bool(parts) and parts[-1] == short and (len(parts) == 1 or method or parts[-2] == stem)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _sites(root, data, rel, name, short, after, removed=True):
|
|
62
|
+
"""The (path, line) pairs that reference one function, from the graph; for a removed function also the imports of its
|
|
63
|
+
name and the calls left in the edited file (`after`)."""
|
|
64
|
+
method, stem = "." in name, posixpath.splitext(posixpath.basename(rel))[0]
|
|
65
|
+
sites = set()
|
|
66
|
+
try:
|
|
67
|
+
found = code_impact.impact(root, f"{rel}::{name}", limit=MAX_SITES)
|
|
68
|
+
sites.update((site["path"], site["line"]) for site in found["callers"] if site["path"] != rel)
|
|
69
|
+
except ValueError:
|
|
70
|
+
pass
|
|
71
|
+
sites.update((call["path"], call["line"]) for call in data.get("unresolved") or []
|
|
72
|
+
if call["path"] != rel and _names(call["expression"], short, stem, method))
|
|
73
|
+
if not removed:
|
|
74
|
+
return sorted(sites)
|
|
75
|
+
sites.update((dep["source"], dep["line"]) for dep in data.get("dependencies") or []
|
|
76
|
+
if dep.get("target") == rel and dep["source"] != rel and _names(dep.get("specifier") or "", short, stem, False))
|
|
77
|
+
called = re.compile(rf"\b{re.escape(short)}\s*\(")
|
|
78
|
+
sites.update((rel, number) for number, line in enumerate(after.splitlines(), 1)
|
|
79
|
+
if called.search(line) and not _COMMENT.match(line))
|
|
80
|
+
return sorted(sites)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _note(data):
|
|
84
|
+
parts = []
|
|
85
|
+
cut = code_graph.left_out_sentence(data)
|
|
86
|
+
if cut:
|
|
87
|
+
parts.append(f"{cut} Callers beyond the cut are not listed.")
|
|
88
|
+
if len(data.get("unresolved") or []) >= UNRESOLVED_CAP:
|
|
89
|
+
parts.append(f"The graph keeps at most {UNRESOLVED_CAP} unresolved calls and this one reached it, so calls by name "
|
|
90
|
+
"beyond them may be missing.")
|
|
91
|
+
if not data.get("symbols") and not data.get("dependencies"):
|
|
92
|
+
parts.append("The code graph is empty: index the project (project_manage action=index) to find the callers.")
|
|
93
|
+
return " ".join(parts)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def review(root, rel, before, after):
|
|
97
|
+
"""The callers that still reference the functions an edit removed or renamed in one file.
|
|
98
|
+
|
|
99
|
+
Parameters: root (str) project folder; rel (str) project-relative path of the edited file; before (str or None) text
|
|
100
|
+
before the edit; after (str) text after it.
|
|
101
|
+
Returns: dict {"removed": [qualified names], "findings": [{"name", "path", "callers": [{"path", "line"}] (up to
|
|
102
|
+
MAX_CALLERS), "total", "also_defined_in": [paths]}], "note": str}; `note` says what the graph cut, "" when it cut
|
|
103
|
+
nothing. The graph is read only when a function is gone; findings hold the removed functions something still calls.
|
|
104
|
+
Raises: RuntimeError when the graph cannot be built, ValueError when the project has no index.
|
|
105
|
+
"""
|
|
106
|
+
gone = _gone(rel, before, after) if before and doc_check.supported(rel) else {}
|
|
107
|
+
if not gone:
|
|
108
|
+
return {"removed": [], "findings": [], "note": ""}
|
|
109
|
+
return {"removed": list(gone.values()), **_findings(root, rel, list(gone.items()), after, True)}
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _findings(root, rel, functions, after, removed):
|
|
113
|
+
"""The callers of each (short name, qualified name) pair, as `review` and `signature_review` return them."""
|
|
114
|
+
data = code_graph.build_current(root, None, shared=True)
|
|
115
|
+
defined = {}
|
|
116
|
+
for symbol in data.get("symbols") or []:
|
|
117
|
+
defined.setdefault(_short(symbol["name"]), set()).add(symbol["path"])
|
|
118
|
+
findings = []
|
|
119
|
+
for short, name in functions:
|
|
120
|
+
sites = _sites(root, data, rel, name, short, after, removed)
|
|
121
|
+
if sites:
|
|
122
|
+
findings.append({"name": name, "path": rel, "callers": [{"path": p, "line": n} for p, n in sites[:MAX_CALLERS]],
|
|
123
|
+
"total": len(sites), "also_defined_in": sorted(defined.get(short, set()) - {rel})})
|
|
124
|
+
return {"findings": findings, "note": _note(data)}
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def signature_review(root, rel, before, after):
|
|
128
|
+
"""The callers in other files of the functions an edit left with another signature (parameters, order, defaults, return
|
|
129
|
+
annotation) in one file.
|
|
130
|
+
|
|
131
|
+
Parameters: as `review`.
|
|
132
|
+
Returns: dict {"changed": [qualified names], "findings": as `review`, "note": str}; the callers are those outside
|
|
133
|
+
`rel`. The graph is read only when a signature changed.
|
|
134
|
+
Raises: RuntimeError when the graph cannot be built, ValueError when the project has no index.
|
|
135
|
+
"""
|
|
136
|
+
changed = _resigned(rel, before, after) if before and doc_check.supported(rel) else []
|
|
137
|
+
if not changed:
|
|
138
|
+
return {"changed": [], "findings": [], "note": ""}
|
|
139
|
+
return {"changed": changed, **_findings(root, rel, [(_short(name), name) for name in changed], after, False)}
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def sites_text(finding):
|
|
143
|
+
"""`app/api.py:6, app/cli.py:3 (+2 more)` for one finding."""
|
|
144
|
+
shown = ", ".join(f"{site['path']}:{site['line']}" for site in finding["callers"])
|
|
145
|
+
more = f" (+{finding['total'] - len(finding['callers'])} more)" if finding["total"] > len(finding["callers"]) else ""
|
|
146
|
+
return shown + more
|
package/scout_access.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Whether `smart_scout` can be called in a Claude Code session without stopping for a permission decision.
|
|
2
|
+
|
|
3
|
+
The hook payload carries the permission mode but not the session's allow rules, so the rules are read from the same
|
|
4
|
+
settings files Claude Code merges: user, project and project-local. Where the answer cannot be shown to be yes, it is no:
|
|
5
|
+
a hook that sends an agent to a tool it may not call leaves the work waiting on a prompt nobody answers."""
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
|
|
9
|
+
import endpoint_sync
|
|
10
|
+
|
|
11
|
+
TOOL = "mcp__smart-tool__smart_scout"
|
|
12
|
+
SERVER_RULES = frozenset({TOOL, "mcp__smart-tool__*", "mcp__smart-tool"})
|
|
13
|
+
OPEN_MODES = frozenset({"bypassPermissions"})
|
|
14
|
+
SETTINGS_FILES = ("settings.json", "settings.local.json")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _settings(cwd):
|
|
18
|
+
"""The parsed permission blocks of the settings files that exist; an unreadable or malformed file is skipped as
|
|
19
|
+
Claude Code skips it, and counts as no allow rule."""
|
|
20
|
+
folders = [endpoint_sync.claude_dir(), os.path.join(cwd or "", ".claude")] if cwd else [endpoint_sync.claude_dir()]
|
|
21
|
+
found = []
|
|
22
|
+
for folder in folders:
|
|
23
|
+
for name in SETTINGS_FILES:
|
|
24
|
+
try:
|
|
25
|
+
with open(os.path.join(folder, name), encoding="utf-8") as stream:
|
|
26
|
+
data = json.load(stream)
|
|
27
|
+
except (OSError, ValueError):
|
|
28
|
+
continue
|
|
29
|
+
if isinstance(data, dict) and isinstance(data.get("permissions"), dict):
|
|
30
|
+
found.append(data["permissions"])
|
|
31
|
+
return found
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def callable_in(payload):
|
|
35
|
+
"""True when the session runs in a mode that allows every tool or an allow rule names `smart_scout` (the tool, its
|
|
36
|
+
server or the server wildcard) and no deny rule does."""
|
|
37
|
+
if not isinstance(payload, dict):
|
|
38
|
+
return False
|
|
39
|
+
permissions = _settings(payload.get("cwd"))
|
|
40
|
+
|
|
41
|
+
def rules(key):
|
|
42
|
+
return {rule for block in permissions for rule in (block.get(key) or []) if isinstance(rule, str)}
|
|
43
|
+
|
|
44
|
+
if rules("deny") & SERVER_RULES:
|
|
45
|
+
return False
|
|
46
|
+
if payload.get("permission_mode") in OPEN_MODES or any(block.get("defaultMode") in OPEN_MODES for block in permissions):
|
|
47
|
+
return True
|
|
48
|
+
return bool(rules("allow") & SERVER_RULES)
|
package/setup_ui.py
CHANGED
|
@@ -309,6 +309,18 @@ def handle_integration_get():
|
|
|
309
309
|
layer_mode, layer_error = config.layer_mode(), ""
|
|
310
310
|
except ValueError as exc:
|
|
311
311
|
layer_mode, layer_error = "", str(exc)
|
|
312
|
+
try:
|
|
313
|
+
link_mode, link_error = config.link_mode(), ""
|
|
314
|
+
except ValueError as exc:
|
|
315
|
+
link_mode, link_error = "", str(exc)
|
|
316
|
+
try:
|
|
317
|
+
pr_comment, pr_comment_error = config.pr_comment(), ""
|
|
318
|
+
except ValueError as exc:
|
|
319
|
+
pr_comment, pr_comment_error = "", str(exc)
|
|
320
|
+
try:
|
|
321
|
+
decision_mode, decision_error = config.decision_mode(), ""
|
|
322
|
+
except ValueError as exc:
|
|
323
|
+
decision_mode, decision_error = "", str(exc)
|
|
312
324
|
try:
|
|
313
325
|
proposals_mode, proposals_error = config.pattern_proposals(), ""
|
|
314
326
|
except ValueError as exc:
|
|
@@ -325,6 +337,10 @@ def handle_integration_get():
|
|
|
325
337
|
"dependency_mode": dependency_mode, "dependency_mode_error": dependency_error,
|
|
326
338
|
"dependency_modes": list(config.DEPENDENCY_MODES),
|
|
327
339
|
"layer_mode": layer_mode, "layer_mode_error": layer_error, "layer_modes": list(config.LAYER_MODES),
|
|
340
|
+
"link_mode": link_mode, "link_mode_error": link_error, "link_modes": list(config.LINK_MODES),
|
|
341
|
+
"pr_comment": pr_comment, "pr_comment_error": pr_comment_error, "pr_comment_modes": list(config.PR_COMMENT_MODES),
|
|
342
|
+
"decision_mode": decision_mode, "decision_mode_error": decision_error,
|
|
343
|
+
"decision_modes": list(config.DECISION_MODES),
|
|
328
344
|
"pattern_proposals": proposals_mode, "pattern_proposals_error": proposals_error,
|
|
329
345
|
"block_patterns": {"proposals": stored["proposals"], "accepted": stored["accepted"],
|
|
330
346
|
"rejected": len(stored["rejected"]), "error": patterns_error},
|
|
@@ -343,11 +359,12 @@ def handle_integration_save(body):
|
|
|
343
359
|
except (OSError, ValueError) as exc:
|
|
344
360
|
raise SetupError(str(exc))
|
|
345
361
|
return handle_integration_get()
|
|
346
|
-
if isinstance(body, dict) and body.get("action") in ("hook_mode", "doc_mode", "comment_mode", "duplicate_mode", "dependency_mode", "layer_mode", "pattern_proposals"):
|
|
362
|
+
if isinstance(body, dict) and body.get("action") in ("hook_mode", "doc_mode", "comment_mode", "duplicate_mode", "dependency_mode", "layer_mode", "link_mode", "pr_comment", "decision_mode", "pattern_proposals"):
|
|
347
363
|
action = body["action"]
|
|
348
364
|
allowed = {"hook_mode": config.HOOK_MODES, "doc_mode": config.DOC_MODES, "comment_mode": config.COMMENT_MODES,
|
|
349
365
|
"duplicate_mode": config.DUPLICATE_MODES, "dependency_mode": config.DEPENDENCY_MODES,
|
|
350
|
-
"layer_mode": config.LAYER_MODES,
|
|
366
|
+
"layer_mode": config.LAYER_MODES, "link_mode": config.LINK_MODES, "pr_comment": config.PR_COMMENT_MODES,
|
|
367
|
+
"decision_mode": config.DECISION_MODES,
|
|
351
368
|
"pattern_proposals": config.PATTERN_PROPOSAL_MODES}[action]
|
|
352
369
|
if body.get("mode") not in allowed:
|
|
353
370
|
raise SetupError(f"Invalid mode: use {', '.join(allowed)}.")
|
|
@@ -836,7 +853,7 @@ __I18N__
|
|
|
836
853
|
|
|
837
854
|
<div class="card" id="health-card">
|
|
838
855
|
<div class="card-head"><h3>Model failures (last 24 h)</h3><span class="pill" id="health-pill" data-tone="busy">Checking</span></div>
|
|
839
|
-
<p class="lede">Failed calls to a gateway model, grouped by type (429, 503, timeout, ...) and role, with the latest lines of each group. A model that fails half of its calls (5 or more) also raises a Windows notification.</p>
|
|
856
|
+
<p class="lede">Failed calls to a gateway model, grouped by type (429, 503, timeout, ...) and role, with the latest lines of each group. A model that fails half of its calls (5 or more) also raises a Windows notification. Calls refused while a model is paused show as Circuit open and do not count toward that limit.</p>
|
|
840
857
|
<div id="health-table"></div>
|
|
841
858
|
</div>
|
|
842
859
|
|
|
@@ -1276,7 +1293,7 @@ for (const [id, action] of [["btn-upgrade-apply", "apply"], ["btn-upgrade-declin
|
|
|
1276
1293
|
});
|
|
1277
1294
|
}
|
|
1278
1295
|
const FAILURE_TYPES = { "429": "429 Too Many Requests", "503": "503 Service Unavailable", "5xx": "Other 5xx", timeout: "Timeout",
|
|
1279
|
-
connection: "Connection", auth: "Authentication (401/403)", other: "Other" };
|
|
1296
|
+
connection: "Connection", circuit_open: "Circuit open", auth: "Authentication (401/403)", other: "Other" };
|
|
1280
1297
|
const PURPOSE_LABELS = { index_embedding: "Indexing", query_embedding: "Query", rerank: "Rerank", embedding_probe: "Model check", scope: "Scope" };
|
|
1281
1298
|
function healthHtml(data) {
|
|
1282
1299
|
const when = (at) => esc(new Date(at * 1000).toLocaleString());
|
|
@@ -1463,6 +1480,18 @@ const RULES = [
|
|
|
1463
1480
|
intro: "When the project has confirmed layers (.smart-tool/layers.json), warns about a call an edit adds from a lower layer to a function of a higher one. A project without layers is never checked. It never blocks.",
|
|
1464
1481
|
options: [["warn", "Warn", "The edit runs; the agent is told which new calls go up the layers.", true],
|
|
1465
1482
|
["off", "Off", "No layer checks."]] },
|
|
1483
|
+
{ key: "link_mode", title: "Broken local links on edit", applies: "Applies on the next edit.",
|
|
1484
|
+
intro: "Checks the relative links (href, src, Markdown link targets) an edit of an HTML or Markdown file adds or changes against the files on disk, and says which ones it could not check. Links that were already broken are left alone. It never blocks.",
|
|
1485
|
+
options: [["warn", "Warn", "The edit runs; the agent is told which new links point to a file that does not exist.", true],
|
|
1486
|
+
["off", "Off", "No link checks."]] },
|
|
1487
|
+
{ key: "pr_comment", title: "Impact report as a pull request comment", applies: "Applies on the next request of an agent.",
|
|
1488
|
+
intro: "Lets Smart Tool post the impact report as a comment on a pull request through the gh CLI, with your own gh login. This writes to GitHub: nothing is ever posted while this is off, and each post is one agent request (project_manage action=pr_impact_comment). A rerun replaces the previous Smart Tool comment instead of adding another.",
|
|
1489
|
+
options: [["off", "Off", "Nothing is posted to GitHub.", true],
|
|
1490
|
+
["on", "On", "Agents may post the impact report as a comment on a pull request through the gh CLI."]] },
|
|
1491
|
+
{ key: "decision_mode", title: "Recorded decisions on edit", applies: "Applies on the next edit.",
|
|
1492
|
+
intro: "Looks up the notes of the project (docs/research, the backlog, CLAUDE.md and AGENTS.md) and its commit messages for the functions an edit touches, and names the ones that record a decision about them. A single-word function name counts only when a note qualifies it with its module or class. It never blocks.",
|
|
1493
|
+
options: [["warn", "Warn", "The edit runs; the agent is told which notes and commits record a decision about a touched function.", true],
|
|
1494
|
+
["off", "Off", "No decision lookup."]] },
|
|
1466
1495
|
{ key: "pattern_proposals", title: "Block patterns proposed by a model", applies: "Applies to the next review.",
|
|
1467
1496
|
intro: "Afterwards, never delaying a call, the scope model (else the router model) reviews searches the fixed rule let through and may propose block patterns. Nothing blocks until you accept it on the Redirects page.",
|
|
1468
1497
|
options: [["on", "On", "Review in the background and list proposals for you.", true],
|
package/shell_reads.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Source files read through the shell (`cat`, `head`, `sed -n`), counted per session so a run of them can be answered
|
|
2
|
+
with a tip.
|
|
3
|
+
|
|
4
|
+
One read of a known file is what the shell is for, and `smart_search` cannot return its exact lines, so no single read
|
|
5
|
+
is touched. A burst of them is an investigation done by reading, which `smart_scout` answers with only the lines that
|
|
6
|
+
matter: the third read inside the window carries the tip, then the tip waits before it repeats."""
|
|
7
|
+
import collections
|
|
8
|
+
import os
|
|
9
|
+
import threading
|
|
10
|
+
import time
|
|
11
|
+
|
|
12
|
+
import redirect_rule
|
|
13
|
+
|
|
14
|
+
READERS = frozenset({"cat", "head", "sed"})
|
|
15
|
+
SOURCE_SUFFIXES = frozenset({
|
|
16
|
+
".py", ".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx", ".java", ".kt", ".go", ".rs", ".c", ".cc", ".cpp", ".h", ".hpp",
|
|
17
|
+
".cs", ".rb", ".php", ".swift", ".scala", ".vue", ".svelte", ".sh", ".ps1", ".sql", ".lua", ".dart"})
|
|
18
|
+
BURST_READS = 3
|
|
19
|
+
WINDOW_S = 600
|
|
20
|
+
TIP_EVERY_S = 600
|
|
21
|
+
MAX_SESSIONS = 256
|
|
22
|
+
TIP = ("You have read {count} source files through the shell in the last minutes. For a question that spans several "
|
|
23
|
+
"files call mcp__smart-tool__smart_scout(project_root, question) (it returns only the lines that answer); keep "
|
|
24
|
+
"cat, head and sed -n for a file you already know and need verbatim.")
|
|
25
|
+
|
|
26
|
+
_LOCK = threading.Lock()
|
|
27
|
+
_READS = collections.OrderedDict()
|
|
28
|
+
_TIPPED = {}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def source_files(command, cwd):
|
|
32
|
+
"""The existing source files, inside the session's reach, that the reading commands of a shell command print: `cat`,
|
|
33
|
+
`head` and `sed -n` at the start of a command, not a filter after a pipe."""
|
|
34
|
+
found = []
|
|
35
|
+
for segment, after_pipe in redirect_rule.segments(command or ""):
|
|
36
|
+
if after_pipe:
|
|
37
|
+
continue
|
|
38
|
+
tokens = redirect_rule._unwrap(redirect_rule._split(segment, False), {})
|
|
39
|
+
if not tokens or tokens[0].lower() not in READERS or (tokens[0].lower() == "sed" and "-n" not in tokens):
|
|
40
|
+
continue
|
|
41
|
+
for raw in redirect_rule._reader_files(tokens[0].lower(), tokens[1:]):
|
|
42
|
+
path = redirect_rule.resolve_path(os.path.expanduser(raw), cwd)
|
|
43
|
+
if path and os.path.splitext(path)[1].lower() in SOURCE_SUFFIXES and os.path.isfile(path) \
|
|
44
|
+
and redirect_rule._in_project(path, cwd):
|
|
45
|
+
found.append(path)
|
|
46
|
+
return found
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def note(session_id, command, cwd, now=None):
|
|
50
|
+
"""Counts the source reads of one shell call for the session and returns the tip when this call is the third inside
|
|
51
|
+
the window and no tip went out in the last TIP_EVERY_S; None otherwise."""
|
|
52
|
+
files = source_files(command, cwd)
|
|
53
|
+
if not files or not session_id:
|
|
54
|
+
return None
|
|
55
|
+
now = time.time() if now is None else now
|
|
56
|
+
with _LOCK:
|
|
57
|
+
reads = _READS.setdefault(session_id, collections.deque())
|
|
58
|
+
_READS.move_to_end(session_id)
|
|
59
|
+
while len(_READS) > MAX_SESSIONS:
|
|
60
|
+
_TIPPED.pop(_READS.popitem(last=False)[0], None)
|
|
61
|
+
reads.extend([now] * len(files))
|
|
62
|
+
while reads and now - reads[0] > WINDOW_S:
|
|
63
|
+
reads.popleft()
|
|
64
|
+
if len(reads) < BURST_READS or now - _TIPPED.get(session_id, -TIP_EVERY_S) < TIP_EVERY_S:
|
|
65
|
+
return None
|
|
66
|
+
_TIPPED[session_id] = now
|
|
67
|
+
return TIP.format(count=len(reads))
|