@allansantos-dev/smart-tool 0.9.15 → 0.9.17
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 +25 -0
- package/README.md +17 -3
- package/client_hooks.py +167 -15
- package/hooks/session_audit.py +39 -0
- package/install.py +5 -4
- package/package.json +1 -1
- package/setup_audit.py +29 -0
- package/setup_ui.py +1056 -727
- package/smart_tool_daemon.py +54 -5
- package/version.py +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,30 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.9.17 - beta
|
|
4
|
+
|
|
5
|
+
- The agent learns the setup audit result without asking for it. On its first `smart_search` of a session, once per
|
|
6
|
+
folder, it gets one short line when the stored audit has errors or warnings (nothing when clean, nothing is run).
|
|
7
|
+
`project_manage action=setup_audit mode=last` returns the stored report without auditing again.
|
|
8
|
+
- Optional **Report at session start (Claude Code)** on the Setup audit page: off by default; it previews the exact
|
|
9
|
+
SessionStart entry, writes it to Claude Code's settings after you confirm (backup first), and **Turn off** removes
|
|
10
|
+
only that entry. While it is on, the search no longer repeats the line.
|
|
11
|
+
|
|
12
|
+
## 0.9.16 - beta
|
|
13
|
+
|
|
14
|
+
- New setup screen. It opens on an **Overview** that checks everything Smart Tool needs on this machine (model
|
|
15
|
+
gateway, each agent's connection and hook, block patterns waiting, the service, web search, the setup audit) and
|
|
16
|
+
lists what needs you first, each with a button that takes you to the fix. A side menu replaces the long scroll:
|
|
17
|
+
Connect (Agents, Models, Web search), Behavior (Agent rules, Redirects) and Maintenance (Setup audit, Startup),
|
|
18
|
+
with a count of open items next to each. Every section says what it is for; choices apply as soon as they are
|
|
19
|
+
picked, and typed values keep a save button next to them. Light and dark follow the system; under 860 px the menu
|
|
20
|
+
becomes a row of tabs.
|
|
21
|
+
- An outdated hook says so. The setup screen compares each agent's Smart Tool hook entry with the one this version
|
|
22
|
+
writes and lists what the old one misses (tools not covered, an old address or timeout). **Update hook** shows the
|
|
23
|
+
exact entry first and, after you confirm, rewrites only Smart Tool's entry (other hooks stay, the file is backed up).
|
|
24
|
+
The tray notice also names an outdated hook.
|
|
25
|
+
- Agent rules (redirect behavior, documentation and duplicate checks on edit, block pattern proposals) moved off the
|
|
26
|
+
Agents section into their own, with the recommended choice marked.
|
|
27
|
+
|
|
3
28
|
## 0.9.15 - beta
|
|
4
29
|
|
|
5
30
|
- The hook redirects the folder searches that slipped past it in a shell: wrapped (`bash -c`, `sh -lc`,
|
package/README.md
CHANGED
|
@@ -15,7 +15,7 @@ registered as the `playwright` server where this machine lets a browser be drive
|
|
|
15
15
|
An optional hook routes the agent's native Grep/Glob/Read/Bash/WebSearch/WebFetch calls to these tools when they
|
|
16
16
|
are cheaper, or just tells the agent what Smart Tool would do.
|
|
17
17
|
|
|
18
|
-
**Status:** 0.9.
|
|
18
|
+
**Status:** 0.9.17 beta. Windows only. What changed in each version: [CHANGELOG.md](CHANGELOG.md).
|
|
19
19
|
|
|
20
20
|
## How it works
|
|
21
21
|
|
|
@@ -89,7 +89,10 @@ State lives in `~/.smart-tool`: `config.json`, your model adapters in `adapters/
|
|
|
89
89
|
|
|
90
90
|
## Set up
|
|
91
91
|
|
|
92
|
-
Open the setup screen from the tray icon ("Open settings") or at `http://127.0.0.1:8765/setup`.
|
|
92
|
+
Open the setup screen from the tray icon ("Open settings") or at `http://127.0.0.1:8765/setup`. It opens on
|
|
93
|
+
**Overview**: everything Smart Tool needs, checked on this machine, with what needs you first and a button that takes
|
|
94
|
+
you to the fix. The side menu groups the rest under Connect (Agents, Models, Web search), Behavior (Agent rules,
|
|
95
|
+
Redirects) and Maintenance (Setup audit, Startup).
|
|
93
96
|
|
|
94
97
|
1. **Model gateway**: pick an adapter and fill its fields. The built-in **OpenAI-compatible** adapter takes a base
|
|
95
98
|
URL ending where the API starts, like the OpenAI SDK `base_url` (`https://api.openai.com/v1`,
|
|
@@ -98,7 +101,8 @@ Open the setup screen from the tray icon ("Open settings") or at `http://127.0.0
|
|
|
98
101
|
reasoning: web search tier order and result checks), the index classification model (also reviews block patterns) and the research model. Any id the gateway
|
|
99
102
|
accepts works; the catalog is shown as suggestions.
|
|
100
103
|
3. **Agents**: register the MCP server in Claude Code or Codex (runs their official `mcp add` command), install the
|
|
101
|
-
hook and choose its behavior
|
|
104
|
+
hook and choose its behavior under **Agent rules**. A hook written by an older Smart Tool shows as outdated, with
|
|
105
|
+
what an update changes; updating previews the entry and rewrites only Smart Tool's, after a backup.
|
|
102
106
|
|
|
103
107
|
**Browser control** comes with the registration, and with every update for clients where smart-tool is registered:
|
|
104
108
|
the official Playwright MCP (pinned in `web_adapters/node`) is registered as the `playwright` server, driving the
|
|
@@ -169,6 +173,16 @@ Open the setup screen from the tray icon ("Open settings") or at `http://127.0.0
|
|
|
169
173
|
and their result reused for 6 hours; Run now always contacts them again), and the setup screen's **Setup audit**
|
|
170
174
|
panel shows each project's last report: findings by severity, what is new, what was resolved, the tokens each MCP
|
|
171
175
|
server's tools cost and what was not verified.
|
|
176
|
+
|
|
177
|
+
The agent hears about it without asking for it. `setup_audit` with `mode=last` returns the stored report for the
|
|
178
|
+
folder (or the nearest audited parent) without auditing again, and fails with what to do when none is stored. On
|
|
179
|
+
its first `smart_search` of a session, and once per folder, the agent also gets one short line (under 100 tokens)
|
|
180
|
+
when the stored report holds errors or warnings; a clean report adds nothing. Optionally, **Report at session
|
|
181
|
+
start (Claude Code)** on the Setup audit page moves that line to the start of every new session: it previews the
|
|
182
|
+
exact SessionStart entry, adds it to `~/.claude/settings.json` only after you confirm (backup first), and **Turn
|
|
183
|
+
off** removes only that entry. It is off by default; while it is on, the search no longer repeats the line. The
|
|
184
|
+
hook script (`hooks/session_audit.py`) only reads the stored report from the running service and prints nothing
|
|
185
|
+
when the service is down.
|
|
172
186
|
4. **Local models** (optional): if the mcp-memory embedding sidecar is installed on the machine, its local embedder
|
|
173
187
|
can serve as a fallback (or preferred) embedding model.
|
|
174
188
|
5. **Web search providers** work without keys on their free public tiers; add your own key for more volume. Set your
|
package/client_hooks.py
CHANGED
|
@@ -10,6 +10,10 @@ import endpoint_sync
|
|
|
10
10
|
|
|
11
11
|
HOOK_SCRIPT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "hooks", "pretool_router.py")
|
|
12
12
|
MARKER = "pretool_router.py"
|
|
13
|
+
AUDIT_SCRIPT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "hooks", "session_audit.py")
|
|
14
|
+
AUDIT_MARKER = "session_audit.py"
|
|
15
|
+
AUDIT_MATCHER = "startup|resume|clear"
|
|
16
|
+
AUDIT_TIMEOUT_S = 10
|
|
13
17
|
HTTP_PATH = "/hooks/pretool"
|
|
14
18
|
HTTP_TIMEOUT_S = 15
|
|
15
19
|
HOME = os.path.expanduser("~")
|
|
@@ -55,8 +59,13 @@ def _without_ours(groups):
|
|
|
55
59
|
return kept
|
|
56
60
|
|
|
57
61
|
|
|
58
|
-
def
|
|
59
|
-
""
|
|
62
|
+
def _target(handler):
|
|
63
|
+
return handler.get("url") or handler.get("command") or ""
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def inspect(client):
|
|
67
|
+
"""Our hook in the client's config: `current`, `missing`, or `outdated` (an older entry of ours) with `changes`,
|
|
68
|
+
plain sentences saying what an update rewrites (tools the old matcher leaves out, an old address or timeout)."""
|
|
60
69
|
spec = CLIENTS[client]
|
|
61
70
|
for path in spec["files"]:
|
|
62
71
|
try:
|
|
@@ -67,30 +76,56 @@ def installed(client):
|
|
|
67
76
|
if MARKER not in text and HTTP_PATH not in text:
|
|
68
77
|
continue
|
|
69
78
|
if not path.endswith(".json"):
|
|
70
|
-
return
|
|
79
|
+
return {"state": "current", "changes": []}
|
|
71
80
|
data = json.loads(text)
|
|
72
81
|
hooks = data.get("hooks") if isinstance(data, dict) else None
|
|
73
82
|
groups = hooks.get(spec["event"]) if isinstance(hooks, dict) else None
|
|
83
|
+
ours = [group for group in groups if _ours(group)] if isinstance(groups, list) else []
|
|
84
|
+
if not ours:
|
|
85
|
+
return {"state": "outdated", "changes": [f"Smart Tool's entry is not under {spec['event']}."]}
|
|
74
86
|
expected = _handler(client)
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
87
|
+
if any(group.get("matcher") == spec["matcher"] and expected in group["hooks"] for group in ours):
|
|
88
|
+
return {"state": "current", "changes": []}
|
|
89
|
+
group = ours[0]
|
|
90
|
+
changes = []
|
|
91
|
+
covered = str(group.get("matcher") or "").split("|")
|
|
92
|
+
left_out = [tool for tool in spec["matcher"].split("|") if tool not in covered]
|
|
93
|
+
if left_out:
|
|
94
|
+
changes.append("It does not cover " + ", ".join(left_out) + ".")
|
|
95
|
+
found = next(hook for hook in group["hooks"] if _our_hook(hook))
|
|
96
|
+
if _target(found) != _target(expected):
|
|
97
|
+
changes.append(f"It calls {_target(found)} instead of {_target(expected)}.")
|
|
98
|
+
elif found != expected:
|
|
99
|
+
changes.append("Its timeout or type is older than the current one.")
|
|
100
|
+
if not changes:
|
|
101
|
+
changes.append("Its tool list is ordered or written differently from the current one.")
|
|
102
|
+
return {"state": "outdated", "changes": changes}
|
|
103
|
+
return {"state": "missing", "changes": []}
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def installed(client):
|
|
107
|
+
"""Our hook is present and current; an older entry of ours counts as not installed."""
|
|
108
|
+
return inspect(client)["state"] == "current"
|
|
78
109
|
|
|
79
110
|
|
|
80
111
|
def status(client_info):
|
|
112
|
+
"""Hook state for an MCP client's clientInfo: `installed` (bool, None when unreadable or unknown client), `state`
|
|
113
|
+
(current/outdated/missing), `changes` an update would make, `error`, the config `files` and `docs`."""
|
|
81
114
|
client = identify(client_info)
|
|
82
115
|
if client is None:
|
|
83
116
|
return {"client": None, "name": (client_info or {}).get("name"), "installed": None, "error": None}
|
|
84
117
|
spec = CLIENTS[client]
|
|
85
118
|
try:
|
|
86
|
-
|
|
119
|
+
found, error = inspect(client), None
|
|
87
120
|
except (OSError, ValueError) as exc:
|
|
88
|
-
|
|
89
|
-
return {"client": client, "name": client_info.get("name"),
|
|
90
|
-
"
|
|
121
|
+
found, error = {"state": None, "changes": []}, f"{type(exc).__name__}: {exc}"[:200]
|
|
122
|
+
return {"client": client, "name": client_info.get("name"),
|
|
123
|
+
"installed": None if found["state"] is None else found["state"] == "current", "state": found["state"],
|
|
124
|
+
"changes": found["changes"], "error": error, "files": spec["files"], "docs": spec["docs"]}
|
|
91
125
|
|
|
92
126
|
|
|
93
127
|
def notice(state):
|
|
128
|
+
"""Sentence for the agent when the hook is not current (from `status`), or None when nothing needs saying."""
|
|
94
129
|
if state["client"] is None:
|
|
95
130
|
return (f"Unrecognized MCP client ({state['name'] or 'no clientInfo'}): Smart Tool does not check the hook "
|
|
96
131
|
"that redirects Grep/Read to smart_search and WebSearch/WebFetch to web_search/web_fetch in this client.")
|
|
@@ -101,7 +136,10 @@ def notice(state):
|
|
|
101
136
|
return None
|
|
102
137
|
action = spec.get("blocked") or ("If the user asks, use project_manage action=install_hook_preview, show the "
|
|
103
138
|
"change and confirm with action=install_hook (makes a backup).")
|
|
104
|
-
|
|
139
|
+
if state.get("state") == "outdated":
|
|
140
|
+
return (f"Smart Tool hook outdated in {spec['label']} ({spec['files'][0]}): {' '.join(state['changes'])} "
|
|
141
|
+
f"{action} Docs: {spec['docs']}")
|
|
142
|
+
return (f"Smart Tool hook missing in {spec['label']} ({spec['files'][0]}): Grep/Read/Bash are not "
|
|
105
143
|
f"redirected to smart_search, nor WebSearch/WebFetch to web_search/web_fetch. {action} Docs: {spec['docs']}")
|
|
106
144
|
|
|
107
145
|
|
|
@@ -168,6 +206,8 @@ def preview(client_info):
|
|
|
168
206
|
|
|
169
207
|
|
|
170
208
|
def install(client_info, token, confirm):
|
|
209
|
+
"""Writes the redirect hook for client_info's client with a backup; needs the `preview` token of this session
|
|
210
|
+
(10 min) and confirm=True. Returns {client, installed, changed, file, backup}."""
|
|
171
211
|
planned = _PREVIEWS.pop(token or "", None)
|
|
172
212
|
client, spec, path, data, groups, entry = _plan(client_info)
|
|
173
213
|
if confirm is not True or not planned or planned["client"] != client or time.time() - planned["at"] > PREVIEW_TTL_S:
|
|
@@ -175,6 +215,14 @@ def install(client_info, token, confirm):
|
|
|
175
215
|
if installed(client):
|
|
176
216
|
return {"client": client, "installed": True, "changed": False, "file": path}
|
|
177
217
|
groups.append(entry)
|
|
218
|
+
backup = _write_checked(path, data, lambda: installed(client), "The hook")
|
|
219
|
+
return {"client": client, "installed": True, "changed": True, "file": path, "backup": backup,
|
|
220
|
+
"after_install": spec.get("after_install")}
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _write_checked(path, data, verify, what):
|
|
224
|
+
"""Writes data as JSON to path through a temp file after a timestamped backup; when verify() fails on the written
|
|
225
|
+
file, restores the backup (or removes the new file) and raises. Returns the backup path (None for a new file)."""
|
|
178
226
|
backup = None
|
|
179
227
|
if os.path.exists(path):
|
|
180
228
|
backup = f"{path}.smart-tool-backup-{time.strftime('%Y%m%d-%H%M%S')}"
|
|
@@ -184,9 +232,113 @@ def install(client_info, token, confirm):
|
|
|
184
232
|
with open(temporary, "w", encoding="utf-8") as stream:
|
|
185
233
|
json.dump(data, stream, indent=2, ensure_ascii=False)
|
|
186
234
|
os.replace(temporary, path)
|
|
187
|
-
if not
|
|
235
|
+
if not verify():
|
|
188
236
|
if backup:
|
|
189
237
|
shutil.copy2(backup, path)
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
238
|
+
else:
|
|
239
|
+
os.remove(path)
|
|
240
|
+
raise RuntimeError(f"{what} does not appear in {path} after writing; the file was restored.")
|
|
241
|
+
return backup
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _audit_hook(hook):
|
|
245
|
+
return isinstance(hook, dict) and AUDIT_MARKER in str(hook.get("command", ""))
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _audit_ours(group):
|
|
249
|
+
return isinstance(group, dict) and isinstance(group.get("hooks"), list) and any(map(_audit_hook, group["hooks"]))
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _audit_entry():
|
|
253
|
+
return {"matcher": AUDIT_MATCHER,
|
|
254
|
+
"hooks": [{"type": "command", "command": f"{_shell_safe(sys.executable)} {_shell_safe(AUDIT_SCRIPT)}",
|
|
255
|
+
"timeout": AUDIT_TIMEOUT_S}]}
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _audit_plan():
|
|
259
|
+
"""(path, data, groups) of Claude Code's settings with our SessionStart entry already removed from groups."""
|
|
260
|
+
path = os.path.realpath(CLIENTS["claude"]["files"][0])
|
|
261
|
+
try:
|
|
262
|
+
with open(path, encoding="utf-8") as stream:
|
|
263
|
+
data = json.load(stream)
|
|
264
|
+
except FileNotFoundError:
|
|
265
|
+
data = {}
|
|
266
|
+
if not isinstance(data, dict) or not isinstance(data.setdefault("hooks", {}), dict):
|
|
267
|
+
raise ValueError(f"{path} does not have the expected format (object with 'hooks'); nothing was changed.")
|
|
268
|
+
groups = data["hooks"].setdefault("SessionStart", [])
|
|
269
|
+
if not isinstance(groups, list):
|
|
270
|
+
raise ValueError(f"{path}: hooks.SessionStart is not a list; nothing was changed.")
|
|
271
|
+
kept = []
|
|
272
|
+
for group in groups:
|
|
273
|
+
if not _audit_ours(group):
|
|
274
|
+
kept.append(group)
|
|
275
|
+
continue
|
|
276
|
+
others = [hook for hook in group["hooks"] if not _audit_hook(hook)]
|
|
277
|
+
if others:
|
|
278
|
+
kept.append({**group, "hooks": others})
|
|
279
|
+
groups[:] = kept
|
|
280
|
+
return path, data, groups
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def audit_state():
|
|
284
|
+
"""The SessionStart audit hook in Claude Code's settings: `current` (our entry equals this version's), `outdated`
|
|
285
|
+
(an entry of ours that differs) or `missing`."""
|
|
286
|
+
path = CLIENTS["claude"]["files"][0]
|
|
287
|
+
try:
|
|
288
|
+
with open(path, encoding="utf-8") as stream:
|
|
289
|
+
data = json.load(stream)
|
|
290
|
+
except FileNotFoundError:
|
|
291
|
+
return "missing"
|
|
292
|
+
groups = ((data.get("hooks") or {}).get("SessionStart") or []) if isinstance(data, dict) else []
|
|
293
|
+
found = [group for group in groups if _audit_ours(group)] if isinstance(groups, list) else []
|
|
294
|
+
if not found:
|
|
295
|
+
return "missing"
|
|
296
|
+
return "current" if _audit_entry() in found else "outdated"
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def audit_hook_installed(client):
|
|
300
|
+
"""The Claude Code session-start audit report is on, so a search need not repeat it. An unreadable settings file
|
|
301
|
+
counts as off here; `audit_state` raises for it on the setup screen."""
|
|
302
|
+
if client != "claude":
|
|
303
|
+
return False
|
|
304
|
+
try:
|
|
305
|
+
return audit_state() == "current"
|
|
306
|
+
except (OSError, ValueError):
|
|
307
|
+
return False
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def audit_preview():
|
|
311
|
+
"""The change that turns the SessionStart audit report on in Claude Code, with a token for `audit_install`."""
|
|
312
|
+
path, _data, _groups = _audit_plan()
|
|
313
|
+
entry = _audit_entry()
|
|
314
|
+
if audit_state() == "current":
|
|
315
|
+
return {"installed": True, "file": path, "change": None}
|
|
316
|
+
token = secrets.token_urlsafe(12)
|
|
317
|
+
_PREVIEWS[token] = {"client": "audit", "at": time.time()}
|
|
318
|
+
return {"installed": False, "file": path, "event": "SessionStart", "change": entry, "token": token,
|
|
319
|
+
"expires_s": PREVIEW_TTL_S}
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def audit_install(token, confirm):
|
|
323
|
+
"""Writes the SessionStart audit entry into Claude Code's settings with a backup; needs the `audit_preview` token
|
|
324
|
+
(10 min) and confirm=True. Returns {installed, changed, file, backup}."""
|
|
325
|
+
planned = _PREVIEWS.pop(token or "", None)
|
|
326
|
+
if confirm is not True or not planned or planned["client"] != "audit" or time.time() - planned["at"] > PREVIEW_TTL_S:
|
|
327
|
+
raise ValueError("Turning the audit report on requires the preview token (valid for 10 min) and confirm=true.")
|
|
328
|
+
path, data, groups = _audit_plan()
|
|
329
|
+
if audit_state() == "current":
|
|
330
|
+
return {"installed": True, "changed": False, "file": path}
|
|
331
|
+
groups.append(_audit_entry())
|
|
332
|
+
backup = _write_checked(path, data, lambda: audit_state() == "current", "The audit hook")
|
|
333
|
+
return {"installed": True, "changed": True, "file": path, "backup": backup}
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def audit_remove():
|
|
337
|
+
"""Takes only our SessionStart entry out of Claude Code's settings (after a backup); nothing else is touched."""
|
|
338
|
+
path, data, groups = _audit_plan()
|
|
339
|
+
if audit_state() == "missing":
|
|
340
|
+
return {"installed": False, "changed": False, "file": path}
|
|
341
|
+
if not groups:
|
|
342
|
+
del data["hooks"]["SessionStart"]
|
|
343
|
+
backup = _write_checked(path, data, lambda: audit_state() == "missing", "The removal")
|
|
344
|
+
return {"installed": False, "changed": True, "file": path, "backup": backup}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""SessionStart hook of Claude Code (opt-in, from the setup screen): forwards the payload to the Smart Tool daemon
|
|
3
|
+
(POST /hooks/session-audit) and prints its answer, the stored setup audit notice of the session folder as additional
|
|
4
|
+
context. Never starts the daemon or an audit: daemon down or any error means empty output, so a session start is
|
|
5
|
+
never delayed or blocked.
|
|
6
|
+
"""
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import sys
|
|
10
|
+
import urllib.request
|
|
11
|
+
|
|
12
|
+
sys.stdin.reconfigure(encoding="utf-8")
|
|
13
|
+
sys.stdout.reconfigure(encoding="utf-8")
|
|
14
|
+
|
|
15
|
+
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
|
|
16
|
+
import daemon_launcher
|
|
17
|
+
|
|
18
|
+
TIMEOUT_S = 5
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def main():
|
|
22
|
+
"""Posts the SessionStart payload read from stdin to the running daemon and prints its JSON answer if not empty."""
|
|
23
|
+
raw = sys.stdin.buffer.read()
|
|
24
|
+
base = daemon_launcher.daemon_url_if_up()
|
|
25
|
+
if not base:
|
|
26
|
+
return
|
|
27
|
+
request = urllib.request.Request(f"{base}/hooks/session-audit", data=raw,
|
|
28
|
+
headers={"Content-Type": "application/json"}, method="POST")
|
|
29
|
+
with urllib.request.urlopen(request, timeout=TIMEOUT_S) as response:
|
|
30
|
+
output = json.loads(response.read() or b"{}")
|
|
31
|
+
if output:
|
|
32
|
+
print(json.dumps(output, ensure_ascii=False))
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
if __name__ == "__main__":
|
|
36
|
+
try:
|
|
37
|
+
main()
|
|
38
|
+
except BaseException:
|
|
39
|
+
pass
|
package/install.py
CHANGED
|
@@ -17,7 +17,8 @@ import paths
|
|
|
17
17
|
SOURCE = Path(__file__).resolve().parent
|
|
18
18
|
DEFAULT_TARGET = Path(os.environ.get("LOCALAPPDATA", str(Path.home() / "AppData" / "Local"))) / "Programs" / "SmartTool"
|
|
19
19
|
TASK_NAME = "SmartTool-Tray"
|
|
20
|
-
ENTRY_SCRIPTS = ("tray.py", "smart_tool_daemon.py", "pretool_router.py")
|
|
20
|
+
ENTRY_SCRIPTS = ("tray.py", "smart_tool_daemon.py", "pretool_router.py", "session_audit.py")
|
|
21
|
+
HOOK_SCRIPTS = ("pretool_router.py", "session_audit.py")
|
|
21
22
|
STARTUP_SCRIPT = Path(os.environ.get("APPDATA", str(Path.home() / "AppData" / "Roaming"))) / "Microsoft" / "Windows" / \
|
|
22
23
|
"Start Menu" / "Programs" / "Startup" / "SmartTool-Tray.vbs"
|
|
23
24
|
MANIFEST = ".install-manifest.json"
|
|
@@ -65,7 +66,7 @@ def _processes():
|
|
|
65
66
|
|
|
66
67
|
def _script_folder(script):
|
|
67
68
|
path = Path(script)
|
|
68
|
-
return path.parent.parent if path.name
|
|
69
|
+
return path.parent.parent if path.name in HOOK_SCRIPTS else path.parent
|
|
69
70
|
|
|
70
71
|
|
|
71
72
|
def _same_folder(path, folder):
|
|
@@ -79,7 +80,7 @@ def _same_folder(path, folder):
|
|
|
79
80
|
def stop_processes(target):
|
|
80
81
|
def running():
|
|
81
82
|
return [pid for pid, line in _processes() for script in _script_paths(line)
|
|
82
|
-
if Path(script).name
|
|
83
|
+
if Path(script).name not in HOOK_SCRIPTS and _same_folder(_script_folder(script), target)]
|
|
83
84
|
|
|
84
85
|
for pid in running():
|
|
85
86
|
powershell(f"Stop-Process -Id {pid} -Force -ErrorAction SilentlyContinue")
|
|
@@ -169,7 +170,7 @@ def other_installs(target):
|
|
|
169
170
|
def _repointed(text, folder, target):
|
|
170
171
|
"""text with each spelling of folder found in front of an entry script (long, 8.3 or mixed) replaced by target."""
|
|
171
172
|
for script in set(_script_paths(text)):
|
|
172
|
-
cut = len(Path(script).name) + 1 + (len("hooks") + 1 if Path(script).name
|
|
173
|
+
cut = len(Path(script).name) + 1 + (len("hooks") + 1 if Path(script).name in HOOK_SCRIPTS else 0)
|
|
173
174
|
spelled = script[:-cut]
|
|
174
175
|
if _same_folder(Path(spelled), folder):
|
|
175
176
|
text = text.replace(spelled, target.as_posix() if "/" in spelled else str(target))
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@allansantos-dev/smart-tool",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.17",
|
|
4
4
|
"description": "Local MCP server that gives coding agents (Claude Code, Codex) cheaper, sharper tools than their built-in search. Windows.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Allan Santos",
|
package/setup_audit.py
CHANGED
|
@@ -671,6 +671,35 @@ def last_report(project):
|
|
|
671
671
|
return None
|
|
672
672
|
|
|
673
673
|
|
|
674
|
+
def stored_for(path):
|
|
675
|
+
"""The last stored report of path or of its nearest audited ancestor folder, or None when none was audited."""
|
|
676
|
+
folder = os.path.abspath(path)
|
|
677
|
+
while True:
|
|
678
|
+
report = last_report(folder)
|
|
679
|
+
if report is not None:
|
|
680
|
+
return report
|
|
681
|
+
parent = os.path.dirname(folder)
|
|
682
|
+
if parent == folder:
|
|
683
|
+
return None
|
|
684
|
+
folder = parent
|
|
685
|
+
|
|
686
|
+
|
|
687
|
+
def session_notice(path):
|
|
688
|
+
"""One short line for the agent about the stored audit of path (nothing is run), or "" when there is no stored
|
|
689
|
+
report or it holds no error or warning."""
|
|
690
|
+
report = stored_for(path)
|
|
691
|
+
if report is None:
|
|
692
|
+
return ""
|
|
693
|
+
summary = report["summary"]
|
|
694
|
+
if not summary["error"] and not summary["warn"]:
|
|
695
|
+
return ""
|
|
696
|
+
new = sum(1 for f in report["findings"] if f.get("new") and f["severity"] in ("error", "warn"))
|
|
697
|
+
age = max(0, int((time.time() - report["checked_at"]) // 60))
|
|
698
|
+
return (f"Setup audit of {report['project']} ({age} min ago): {summary['error']} errors, {summary['warn']} "
|
|
699
|
+
f"warnings" + (f", {new} new" if new else "") + " in the agent configuration. Details without rerunning: "
|
|
700
|
+
"project_manage action=setup_audit mode=last.")
|
|
701
|
+
|
|
702
|
+
|
|
674
703
|
def index():
|
|
675
704
|
"""{project: {summary, new, resolved, checked_at, trigger}} of every audited project (the periodic summary)."""
|
|
676
705
|
try:
|