@allansantos-dev/smart-tool 0.9.16 → 0.9.18
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 +19 -0
- package/README.md +18 -4
- package/client_hooks.py +122 -4
- 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 +73 -1
- package/smart_tool_daemon.py +76 -5
- package/tray.py +37 -9
- package/update_check.py +102 -11
- package/version.py +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,24 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.9.18 - beta
|
|
4
|
+
|
|
5
|
+
- Updates are no longer applied only at logon. The tray checks npm at start and every 24 h and installs a newer
|
|
6
|
+
version as soon as it sees it (on by default); a version that failed to install is tried again 24 h later instead of
|
|
7
|
+
never. `SMART_TOOL_AUTO_UPDATE=off` turns automatic updates off, like the tray switch.
|
|
8
|
+
- Nothing about updates is hidden. The tray notifies when a newer version is available, when it starts updating, when
|
|
9
|
+
Smart Tool was updated (from which version to which) and when an update failed. Agent sessions get the same line once
|
|
10
|
+
on their first `smart_search`, with the link to the changes, and the SessionStart report (when on) shows it to you
|
|
11
|
+
at session start.
|
|
12
|
+
|
|
13
|
+
## 0.9.17 - beta
|
|
14
|
+
|
|
15
|
+
- The agent learns the setup audit result without asking for it. On its first `smart_search` of a session, once per
|
|
16
|
+
folder, it gets one short line when the stored audit has errors or warnings (nothing when clean, nothing is run).
|
|
17
|
+
`project_manage action=setup_audit mode=last` returns the stored report without auditing again.
|
|
18
|
+
- Optional **Report at session start (Claude Code)** on the Setup audit page: off by default; it previews the exact
|
|
19
|
+
SessionStart entry, writes it to Claude Code's settings after you confirm (backup first), and **Turn off** removes
|
|
20
|
+
only that entry. While it is on, the search no longer repeats the line.
|
|
21
|
+
|
|
3
22
|
## 0.9.16 - beta
|
|
4
23
|
|
|
5
24
|
- New setup screen. It opens on an **Overview** that checks everything Smart Tool needs on this machine (model
|
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.18 beta. Windows only. What changed in each version: [CHANGELOG.md](CHANGELOG.md).
|
|
19
19
|
|
|
20
20
|
## How it works
|
|
21
21
|
|
|
@@ -76,9 +76,13 @@ gateway such as Ollama, nothing about your code leaves the machine.
|
|
|
76
76
|
npx @allansantos-dev/smart-tool@latest install
|
|
77
77
|
```
|
|
78
78
|
|
|
79
|
-
Updates install themselves:
|
|
80
|
-
a
|
|
81
|
-
|
|
79
|
+
Updates install themselves, on by default: the tray checks npm when it starts (at logon) and every 24 h, and when there
|
|
80
|
+
is a newer version it runs this same command in a visible console (once per version; a failed version is tried again
|
|
81
|
+
after 24 h, with the previous version kept). You are told each time: a Windows notification from the tray (newer version,
|
|
82
|
+
updating, updated, update failed), and agent sessions get the same line on their first `smart_search` (and at session
|
|
83
|
+
start when the SessionStart report is on, shown to you too) with the link to the changes. The tray menu has "Update to
|
|
84
|
+
X" (or "Check for updates") on demand and an "Update automatically" switch; `SMART_TOOL_AUTO_UPDATE=off` also turns
|
|
85
|
+
automatic updates off, and the newer-version notice then carries the command to run. Running the command by hand also updates; `~/.smart-tool` is kept. It downloads [uv](https://docs.astral.sh/uv/) (checksum
|
|
82
86
|
verified) and a private Python 3.12 into `~/.smart-tool/runtime`, with nothing added to `PATH` or the registry, then
|
|
83
87
|
copies Smart Tool to `%LOCALAPPDATA%\Programs\SmartTool` with its own virtual environment,
|
|
84
88
|
installs the web runtime, registers a per-user Scheduled Task that starts the tray at logon and starts the daemon on
|
|
@@ -173,6 +177,16 @@ Redirects) and Maintenance (Setup audit, Startup).
|
|
|
173
177
|
and their result reused for 6 hours; Run now always contacts them again), and the setup screen's **Setup audit**
|
|
174
178
|
panel shows each project's last report: findings by severity, what is new, what was resolved, the tokens each MCP
|
|
175
179
|
server's tools cost and what was not verified.
|
|
180
|
+
|
|
181
|
+
The agent hears about it without asking for it. `setup_audit` with `mode=last` returns the stored report for the
|
|
182
|
+
folder (or the nearest audited parent) without auditing again, and fails with what to do when none is stored. On
|
|
183
|
+
its first `smart_search` of a session, and once per folder, the agent also gets one short line (under 100 tokens)
|
|
184
|
+
when the stored report holds errors or warnings; a clean report adds nothing. Optionally, **Report at session
|
|
185
|
+
start (Claude Code)** on the Setup audit page moves that line to the start of every new session: it previews the
|
|
186
|
+
exact SessionStart entry, adds it to `~/.claude/settings.json` only after you confirm (backup first), and **Turn
|
|
187
|
+
off** removes only that entry. It is off by default; while it is on, the search no longer repeats the line. The
|
|
188
|
+
hook script (`hooks/session_audit.py`) only reads the stored report from the running service and prints nothing
|
|
189
|
+
when the service is down.
|
|
176
190
|
4. **Local models** (optional): if the mcp-memory embedding sidecar is installed on the machine, its local embedder
|
|
177
191
|
can serve as a fallback (or preferred) embedding model.
|
|
178
192
|
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("~")
|
|
@@ -202,6 +206,8 @@ def preview(client_info):
|
|
|
202
206
|
|
|
203
207
|
|
|
204
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}."""
|
|
205
211
|
planned = _PREVIEWS.pop(token or "", None)
|
|
206
212
|
client, spec, path, data, groups, entry = _plan(client_info)
|
|
207
213
|
if confirm is not True or not planned or planned["client"] != client or time.time() - planned["at"] > PREVIEW_TTL_S:
|
|
@@ -209,6 +215,14 @@ def install(client_info, token, confirm):
|
|
|
209
215
|
if installed(client):
|
|
210
216
|
return {"client": client, "installed": True, "changed": False, "file": path}
|
|
211
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)."""
|
|
212
226
|
backup = None
|
|
213
227
|
if os.path.exists(path):
|
|
214
228
|
backup = f"{path}.smart-tool-backup-{time.strftime('%Y%m%d-%H%M%S')}"
|
|
@@ -218,9 +232,113 @@ def install(client_info, token, confirm):
|
|
|
218
232
|
with open(temporary, "w", encoding="utf-8") as stream:
|
|
219
233
|
json.dump(data, stream, indent=2, ensure_ascii=False)
|
|
220
234
|
os.replace(temporary, path)
|
|
221
|
-
if not
|
|
235
|
+
if not verify():
|
|
222
236
|
if backup:
|
|
223
237
|
shutil.copy2(backup, path)
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
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.18",
|
|
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:
|
package/setup_ui.py
CHANGED
|
@@ -261,11 +261,21 @@ def handle_integration_save(body):
|
|
|
261
261
|
def handle_audit(body):
|
|
262
262
|
"""Setup audit panel: `index` lists the registered projects with their last audit summary; `report` returns the
|
|
263
263
|
last stored report of one of them; `run` audits it now (MCP servers contacted unless probe is false). Only
|
|
264
|
-
registered project folders are accepted.
|
|
264
|
+
registered project folders are accepted. The opt-in session-start report in Claude Code: `hook_state`,
|
|
265
|
+
`hook_preview` (the exact entry and a token), `hook_install` (with that token, after a backup) and `hook_remove`
|
|
266
|
+
(only Smart Tool's entry, after a backup)."""
|
|
265
267
|
if not isinstance(body, dict):
|
|
266
268
|
raise SetupError("Invalid request.")
|
|
267
269
|
roots = sorted({p["root"] for p in project_store.all_projects() if p.get("root")}, key=str.casefold)
|
|
268
270
|
try:
|
|
271
|
+
if body.get("action") == "hook_state":
|
|
272
|
+
return {"state": client_hooks.audit_state(), "file": client_hooks.CLIENTS["claude"]["files"][0]}
|
|
273
|
+
if body.get("action") == "hook_preview":
|
|
274
|
+
return client_hooks.audit_preview()
|
|
275
|
+
if body.get("action") == "hook_install":
|
|
276
|
+
return client_hooks.audit_install(body.get("token"), True)
|
|
277
|
+
if body.get("action") == "hook_remove":
|
|
278
|
+
return client_hooks.audit_remove()
|
|
269
279
|
if body.get("action") == "index":
|
|
270
280
|
stored = setup_audit.index()
|
|
271
281
|
found = {root: stored[setup_audit.index_key(root)] for root in roots if setup_audit.index_key(root) in stored}
|
|
@@ -714,6 +724,17 @@ _PAGE_TEMPLATE = """<!doctype html>
|
|
|
714
724
|
<section class="page" data-page="audit" aria-labelledby="h-audit" hidden>
|
|
715
725
|
<header class="page-head"><h2 id="h-audit" tabindex="-1">Setup audit</h2>
|
|
716
726
|
<p>What Claude Code and Codex load for a project, and where they collide: hooks deciding on the same tool at once, hooks or MCP servers that do not work, tools offered twice, skills and instructions one agent never sees. It runs on its own for the registered projects and never changes anything.</p></header>
|
|
727
|
+
<div class="card">
|
|
728
|
+
<div class="card-head"><h3>Report at session start (Claude Code)</h3><span class="pill" id="audit-hook-pill" data-tone="busy">Checking</span></div>
|
|
729
|
+
<p class="lede">Off by default. When on, every new Claude Code session starts with one short line about the stored audit of its folder (errors and warnings only, nothing runs). It adds a SessionStart entry to <span class="mono" id="audit-hook-file"></span>, written after a backup, and turning it off removes only that entry. Without it, the agent gets the same line once, on its first search.</p>
|
|
730
|
+
<div class="actions"><button type="button" class="primary" id="btn-audit-hook-on" hidden>Turn on</button><button type="button" id="btn-audit-hook-off" hidden>Turn off</button></div>
|
|
731
|
+
<div id="audit-hook-confirm" hidden>
|
|
732
|
+
<p class="hint" id="audit-hook-where"></p>
|
|
733
|
+
<pre class="mono" id="audit-hook-preview"></pre>
|
|
734
|
+
<div class="actions"><button type="button" class="primary" id="btn-audit-hook-write">Write it</button><button type="button" id="btn-audit-hook-cancel">Cancel</button></div>
|
|
735
|
+
</div>
|
|
736
|
+
<div class="msg" id="audit-hook-msg" role="status"></div>
|
|
737
|
+
</div>
|
|
717
738
|
<div class="card">
|
|
718
739
|
<div class="field"><label for="sel-audit-project">Project</label>
|
|
719
740
|
<select id="sel-audit-project"></select>
|
|
@@ -1716,6 +1737,56 @@ async function loadAudit() {
|
|
|
1716
1737
|
}
|
|
1717
1738
|
renderOverview();
|
|
1718
1739
|
}
|
|
1740
|
+
async function loadAuditHook() {
|
|
1741
|
+
try {
|
|
1742
|
+
const hook = await post("/setup/audit", { action: "hook_state" });
|
|
1743
|
+
$("audit-hook-file").textContent = hook.file;
|
|
1744
|
+
const on = hook.state === "current";
|
|
1745
|
+
const pillEl = $("audit-hook-pill");
|
|
1746
|
+
pillEl.textContent = on ? "On" : hook.state === "outdated" ? "Outdated" : "Off";
|
|
1747
|
+
pillEl.dataset.tone = on ? "ok" : hook.state === "outdated" ? "warn" : "idle";
|
|
1748
|
+
$("btn-audit-hook-on").hidden = on;
|
|
1749
|
+
$("btn-audit-hook-on").textContent = hook.state === "outdated" ? "Update" : "Turn on";
|
|
1750
|
+
$("btn-audit-hook-off").hidden = hook.state === "missing";
|
|
1751
|
+
} catch (error) {
|
|
1752
|
+
setMsg("audit-hook-msg", "error", "Session-start report state unavailable: " + error.message);
|
|
1753
|
+
}
|
|
1754
|
+
}
|
|
1755
|
+
$("btn-audit-hook-on").addEventListener("click", async () => {
|
|
1756
|
+
setMsg("audit-hook-msg", "", "Preparing the change…");
|
|
1757
|
+
try {
|
|
1758
|
+
const plan = await post("/setup/audit", { action: "hook_preview" });
|
|
1759
|
+
setMsg("audit-hook-msg", "", "");
|
|
1760
|
+
$("audit-hook-where").textContent = "Adds this entry under " + plan.event + " in " + plan.file + ".";
|
|
1761
|
+
$("audit-hook-preview").textContent = JSON.stringify(plan.change, null, 2);
|
|
1762
|
+
$("audit-hook-confirm").hidden = false;
|
|
1763
|
+
$("btn-audit-hook-write").onclick = async () => {
|
|
1764
|
+
$("btn-audit-hook-write").disabled = true;
|
|
1765
|
+
try {
|
|
1766
|
+
const result = await post("/setup/audit", { action: "hook_install", token: plan.token });
|
|
1767
|
+
$("audit-hook-confirm").hidden = true;
|
|
1768
|
+
await loadAuditHook();
|
|
1769
|
+
setMsg("audit-hook-msg", "ok", "Turned on. Backup: " + (result.backup || "none, the file was new") + ".");
|
|
1770
|
+
} catch (error) {
|
|
1771
|
+
setMsg("audit-hook-msg", "error", error.message);
|
|
1772
|
+
} finally {
|
|
1773
|
+
$("btn-audit-hook-write").disabled = false;
|
|
1774
|
+
}
|
|
1775
|
+
};
|
|
1776
|
+
} catch (error) {
|
|
1777
|
+
setMsg("audit-hook-msg", "error", error.message);
|
|
1778
|
+
}
|
|
1779
|
+
});
|
|
1780
|
+
$("btn-audit-hook-cancel").addEventListener("click", () => { $("audit-hook-confirm").hidden = true; });
|
|
1781
|
+
$("btn-audit-hook-off").addEventListener("click", async () => {
|
|
1782
|
+
try {
|
|
1783
|
+
const result = await post("/setup/audit", { action: "hook_remove" });
|
|
1784
|
+
await loadAuditHook();
|
|
1785
|
+
setMsg("audit-hook-msg", "ok", "Turned off. Backup: " + (result.backup || "none") + ".");
|
|
1786
|
+
} catch (error) {
|
|
1787
|
+
setMsg("audit-hook-msg", "error", error.message);
|
|
1788
|
+
}
|
|
1789
|
+
});
|
|
1719
1790
|
$("sel-audit-project").addEventListener("change", () => showAudit($("sel-audit-project").value));
|
|
1720
1791
|
$("btn-audit-run").addEventListener("click", async () => {
|
|
1721
1792
|
const run = $("btn-audit-run");
|
|
@@ -1739,6 +1810,7 @@ loadIntegration();
|
|
|
1739
1810
|
loadAutostart();
|
|
1740
1811
|
loadProviders();
|
|
1741
1812
|
loadAudit();
|
|
1813
|
+
loadAuditHook();
|
|
1742
1814
|
setInterval(refreshStatus, 15000);
|
|
1743
1815
|
</script>
|
|
1744
1816
|
</body>
|
package/smart_tool_daemon.py
CHANGED
|
@@ -68,6 +68,7 @@ import local_embedder
|
|
|
68
68
|
import web_search_health
|
|
69
69
|
import web_fetch
|
|
70
70
|
import version
|
|
71
|
+
import update_check
|
|
71
72
|
import gateway
|
|
72
73
|
import hook_decision
|
|
73
74
|
import endpoint_sync
|
|
@@ -327,7 +328,7 @@ SERVER_INSTRUCTIONS = (
|
|
|
327
328
|
TOOLS = [
|
|
328
329
|
{
|
|
329
330
|
"name": "project_manage",
|
|
330
|
-
"description": "Manages folders and indexing. Every action takes project_root (the folder) or project_id. list gives a short line per project; status shows storage, scope and jobs. graph with symbol (function, Class.method, class name, or path::name when the name repeats) answers what an edit touches: definition, callers with line, calls, tests that reach it through static calls (depth hops, default 3) and files importing it; use it before changing a function to know what to update. affected_tests answers which tests to run after editing: every test file importing a changed file (git diff against base, default HEAD, untracked included) plus changed tests, likeliest failures first, with the command to run them and run_all when config or unanalyzed code changed. graph without symbol reads the indexed view: coverage, references and static calls in Java, Angular, Python and JS/TS/JSX/TSX; includes HTML/CSS/Markdown references and TXT/DOCX coverage; with file_path, narrows to that file's symbols, imports and calls (lists capped by limit). inspect lists the files of a view_id; with file_path, returns only that file's chunks. usage shows consumption and reuse; docs lists public functions without a docstring (Python docstring, JSDoc, Javadoc; private, nested and override functions excluded) with coverage percent, excluding tests unless include_tests=true, for documenting a project that started without it; duplicates lists duplicated functions (identical, near-identical and semantic bodies, min_similarity default 0.90; below that most pairs measured were false positives), excluding tests unless include_tests=true; fix real duplicates; only dismiss with duplicates_dismiss (finding_id, reason=false_positive|intentional, note) what is not a duplicate or is a copy kept on purpose: the finding stays hidden until the code changes, and duplicates_restore reopens it; integration shows the MCP client, hook and tool usage metrics; install_hook_preview shows the change that would install the hook redirecting Grep/Read to smart_search and WebSearch/WebFetch to web_search/web_fetch in this session's client and returns a plan_id; install_hook writes it with that plan_id and confirm=true, with a backup, only after the user approves the change; search_limits saves the project's default top_k per block ({code, test, doc}, each 1-20, total at most 20); storage shows disk usage and views; pin_view protects a view; cleanup_preview and cleanup_commit remove selected views after confirmation; compare compares two stored views, without checkout or embeddings. register adds a folder; preview checks the scope; index/rebuild update; pause/cancel keep checkpoints; resume continues; policy picks on_search/eager; scope adjusts the scope; remove deletes only the local index. setup_audit (project_root) reports what Claude Code and Codex actually load for that folder (settings layers, plugins, hooks, MCP servers, skills, CLAUDE.md/AGENTS.md) and where they collide: hooks deciding on the same tool in parallel, missing hook scripts, silenced hooks, MCP servers down or offering duplicate tools, skill name and budget problems, AGENTS.md that only Codex reads, broken @imports; what could not be checked is listed as not verified. Jobs via smart_search_result.",
|
|
331
|
+
"description": "Manages folders and indexing. Every action takes project_root (the folder) or project_id. list gives a short line per project; status shows storage, scope and jobs. graph with symbol (function, Class.method, class name, or path::name when the name repeats) answers what an edit touches: definition, callers with line, calls, tests that reach it through static calls (depth hops, default 3) and files importing it; use it before changing a function to know what to update. affected_tests answers which tests to run after editing: every test file importing a changed file (git diff against base, default HEAD, untracked included) plus changed tests, likeliest failures first, with the command to run them and run_all when config or unanalyzed code changed. graph without symbol reads the indexed view: coverage, references and static calls in Java, Angular, Python and JS/TS/JSX/TSX; includes HTML/CSS/Markdown references and TXT/DOCX coverage; with file_path, narrows to that file's symbols, imports and calls (lists capped by limit). inspect lists the files of a view_id; with file_path, returns only that file's chunks. usage shows consumption and reuse; docs lists public functions without a docstring (Python docstring, JSDoc, Javadoc; private, nested and override functions excluded) with coverage percent, excluding tests unless include_tests=true, for documenting a project that started without it; duplicates lists duplicated functions (identical, near-identical and semantic bodies, min_similarity default 0.90; below that most pairs measured were false positives), excluding tests unless include_tests=true; fix real duplicates; only dismiss with duplicates_dismiss (finding_id, reason=false_positive|intentional, note) what is not a duplicate or is a copy kept on purpose: the finding stays hidden until the code changes, and duplicates_restore reopens it; integration shows the MCP client, hook and tool usage metrics; install_hook_preview shows the change that would install the hook redirecting Grep/Read to smart_search and WebSearch/WebFetch to web_search/web_fetch in this session's client and returns a plan_id; install_hook writes it with that plan_id and confirm=true, with a backup, only after the user approves the change; search_limits saves the project's default top_k per block ({code, test, doc}, each 1-20, total at most 20); storage shows disk usage and views; pin_view protects a view; cleanup_preview and cleanup_commit remove selected views after confirmation; compare compares two stored views, without checkout or embeddings. register adds a folder; preview checks the scope; index/rebuild update; pause/cancel keep checkpoints; resume continues; policy picks on_search/eager; scope adjusts the scope; remove deletes only the local index. setup_audit (project_root) reports what Claude Code and Codex actually load for that folder (settings layers, plugins, hooks, MCP servers, skills, CLAUDE.md/AGENTS.md) and where they collide: hooks deciding on the same tool in parallel, missing hook scripts, silenced hooks, MCP servers down or offering duplicate tools, skill name and budget problems, AGENTS.md that only Codex reads, broken @imports; what could not be checked is listed as not verified; mode=last returns the stored report instead of auditing again. Jobs via smart_search_result.",
|
|
331
332
|
"inputSchema": {
|
|
332
333
|
"type": "object", "properties": {
|
|
333
334
|
"action": {"type": "string", "enum": ["list", "status", "register", "preview", "index", "rebuild", "pause", "cancel", "resume", "watch", "scope", "remove", "relocate", "probe", "policy", "inspect", "graph", "usage", "storage", "pin_view", "cleanup_preview", "cleanup_commit", "compare", "search_limits", "integration", "install_hook_preview", "install_hook", "duplicates", "duplicates_dismiss", "duplicates_restore", "docs", "affected_tests", "setup_audit"]},
|
|
@@ -349,6 +350,7 @@ TOOLS = [
|
|
|
349
350
|
"left_view":{"type":"string"},"right_view":{"type":"string"},"relations":{"type":"boolean"},
|
|
350
351
|
"update_mode": {"type": "string", "enum": ["on_search", "eager"]},
|
|
351
352
|
"view_id": {"type": "string"}, "file_path": {"type": "string"},
|
|
353
|
+
"mode": {"type": "string", "enum": ["run", "last"], "default": "run", "description": "setup_audit: run audits now; last reads the stored report (the service audits registered projects every 30 minutes) without running anything, and fails when none is stored"},
|
|
352
354
|
"probe": {"type": "boolean", "default": True, "description": "setup_audit: start/call each MCP server (initialize + tools/list); false reads configs only"},
|
|
353
355
|
"base": {"type": "string", "default": "HEAD", "description": "affected_tests: git revision the changes are compared with (HEAD = uncommitted work; main or origin/main for a branch)"},
|
|
354
356
|
"symbol": {"type": "string", "description": "graph: function, Class.method, class name or path::name to get its callers, calls, tests and importers"},
|
|
@@ -1299,8 +1301,36 @@ def _mark_notice_delivered(job_id):
|
|
|
1299
1301
|
session, _client = _session_client()
|
|
1300
1302
|
with _JOBS_LOCK:
|
|
1301
1303
|
job = _jobs.get(job_id) or {}
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
+
keys = (job.get("arguments") or {}).get("setup_notice_keys")
|
|
1305
|
+
if session and job.get("status") == "done" and keys:
|
|
1306
|
+
session.setdefault("notices_delivered", set()).update(keys)
|
|
1307
|
+
|
|
1308
|
+
|
|
1309
|
+
def _pending_notices(session, client, project_root):
|
|
1310
|
+
"""[(key, text)] the session has not been told yet: the hook state (once) and the stored setup audit of the
|
|
1311
|
+
searched folder (once per folder, only with errors or warnings, and not when the SessionStart audit hook already
|
|
1312
|
+
reports it at the start of the session)."""
|
|
1313
|
+
delivered = session.get("notices_delivered") or set()
|
|
1314
|
+
pending = []
|
|
1315
|
+
if session["hook_notice"] and "hook" not in delivered:
|
|
1316
|
+
pending.append(("hook", session["hook_notice"]))
|
|
1317
|
+
pending += [(key, f"{text} Tell the user.") for key, text in _update_notices() if key not in delivered]
|
|
1318
|
+
key = "audit:" + setup_audit.index_key(project_root)
|
|
1319
|
+
if key not in delivered and not client_hooks.audit_hook_installed(client):
|
|
1320
|
+
text = setup_audit.session_notice(project_root)
|
|
1321
|
+
if text:
|
|
1322
|
+
pending.append((key, text))
|
|
1323
|
+
return pending
|
|
1324
|
+
|
|
1325
|
+
|
|
1326
|
+
def _update_notices():
|
|
1327
|
+
"""Update notices (updated, failed, newer version on npm); an unreadable state file is logged, not raised, so a
|
|
1328
|
+
search never fails over it."""
|
|
1329
|
+
try:
|
|
1330
|
+
return update_check.notices()
|
|
1331
|
+
except Exception as exc:
|
|
1332
|
+
_log(f"update notices unavailable: {type(exc).__name__}: {exc}")
|
|
1333
|
+
return []
|
|
1304
1334
|
|
|
1305
1335
|
|
|
1306
1336
|
def _smart_search_arguments(arguments):
|
|
@@ -1348,8 +1378,11 @@ def _smart_search_arguments(arguments):
|
|
|
1348
1378
|
state = client_hooks.status(client)
|
|
1349
1379
|
_metric("hook_status", installed=state["installed"], client_name=state["name"], error=state["error"])
|
|
1350
1380
|
session["hook_notice"] = client_hooks.notice(state) or ""
|
|
1351
|
-
if session is not None
|
|
1352
|
-
|
|
1381
|
+
if session is not None:
|
|
1382
|
+
notices = _pending_notices(session, client, project_root)
|
|
1383
|
+
if notices:
|
|
1384
|
+
arguments["setup_notice"] = " ".join(text for _key, text in notices)
|
|
1385
|
+
arguments["setup_notice_keys"] = [key for key, _text in notices]
|
|
1353
1386
|
_metric("search", group=group, top_k=limits, query_comments=bool(comments), single_language_reason=reason)
|
|
1354
1387
|
return arguments
|
|
1355
1388
|
|
|
@@ -1493,6 +1526,16 @@ def _project_action(arguments):
|
|
|
1493
1526
|
root = arguments.get("project_root")
|
|
1494
1527
|
if not isinstance(root, str) or not os.path.isdir(root):
|
|
1495
1528
|
raise ValueError("setup_audit needs project_root: the folder whose Claude Code and Codex setup to audit.")
|
|
1529
|
+
mode = arguments.get("mode", "run")
|
|
1530
|
+
if mode not in ("run", "last"):
|
|
1531
|
+
raise ValueError("setup_audit mode must be run (audit now) or last (read the stored report).")
|
|
1532
|
+
if mode == "last":
|
|
1533
|
+
report = setup_audit.stored_for(root)
|
|
1534
|
+
if report is None:
|
|
1535
|
+
raise ValueError(f"No stored setup audit covers {root}: call setup_audit with mode=run once "
|
|
1536
|
+
"(the service also audits registered projects every 30 minutes).")
|
|
1537
|
+
return {"summary": report["summary"], "snapshot_key": report["snapshot_key"],
|
|
1538
|
+
"checked_at": report["checked_at"], "stored": True, "report": setup_audit.markdown(report)}
|
|
1496
1539
|
report = setup_audit.run(root, probe=arguments.get("probe", True) is not False)
|
|
1497
1540
|
return {"summary": report["summary"], "snapshot_key": report["snapshot_key"],
|
|
1498
1541
|
"report": setup_audit.markdown(report)}
|
|
@@ -3355,6 +3398,27 @@ def _pretool_hook(handler):
|
|
|
3355
3398
|
return output
|
|
3356
3399
|
|
|
3357
3400
|
|
|
3401
|
+
def _session_audit_hook(handler):
|
|
3402
|
+
"""SessionStart output for the audit report hook: the stored audit notice of the session's folder as
|
|
3403
|
+
additionalContext, and the update notices both as systemMessage (shown to the user) and as context; `{}` when
|
|
3404
|
+
there is nothing to say. Never runs an audit."""
|
|
3405
|
+
try:
|
|
3406
|
+
payload = json.loads(handler._read_body(HOOK_MAX_BODY_BYTES) or b"{}")
|
|
3407
|
+
cwd = payload.get("cwd")
|
|
3408
|
+
text = setup_audit.session_notice(cwd) if isinstance(cwd, str) and os.path.isdir(cwd) else ""
|
|
3409
|
+
except Exception as exc:
|
|
3410
|
+
_log(f"SessionStart audit hook without a report: {type(exc).__name__}: {exc}")
|
|
3411
|
+
text = ""
|
|
3412
|
+
updates = " ".join(notice for _key, notice in _update_notices())
|
|
3413
|
+
context = " ".join(part for part in (updates, text) if part)
|
|
3414
|
+
if not context:
|
|
3415
|
+
return {}
|
|
3416
|
+
output = {"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": context}}
|
|
3417
|
+
if updates:
|
|
3418
|
+
output["systemMessage"] = updates
|
|
3419
|
+
return output
|
|
3420
|
+
|
|
3421
|
+
|
|
3358
3422
|
_TOOL_HANDLERS = {
|
|
3359
3423
|
"web_fetch": _handle_web_fetch,
|
|
3360
3424
|
"project_manage": _handle_project_manage,
|
|
@@ -3663,6 +3727,9 @@ class MCPHandler(BaseHTTPRequestHandler):
|
|
|
3663
3727
|
if urllib.parse.urlsplit(self.path).path == "/hooks/pretool":
|
|
3664
3728
|
self._write_json(200, _pretool_hook(self))
|
|
3665
3729
|
return
|
|
3730
|
+
if urllib.parse.urlsplit(self.path).path == "/hooks/session-audit":
|
|
3731
|
+
self._write_json(200, _session_audit_hook(self))
|
|
3732
|
+
return
|
|
3666
3733
|
save = _SETUP_SAVES.get(self.path)
|
|
3667
3734
|
if save:
|
|
3668
3735
|
self._post_setup(save)
|
|
@@ -3774,6 +3841,10 @@ def main():
|
|
|
3774
3841
|
server = _bind_server()
|
|
3775
3842
|
_BOUND_PORT = server.server_address[1]
|
|
3776
3843
|
threading.Thread(target=_probe_capabilities, daemon=True).start()
|
|
3844
|
+
try:
|
|
3845
|
+
update_check.note_running_version()
|
|
3846
|
+
except Exception as exc:
|
|
3847
|
+
_log(f"running version not recorded: {type(exc).__name__}: {exc}")
|
|
3777
3848
|
_write_registry(_BOUND_PORT)
|
|
3778
3849
|
atexit.register(_remove_registry)
|
|
3779
3850
|
try:
|
package/tray.py
CHANGED
|
@@ -111,24 +111,48 @@ def _poll_loop(icon):
|
|
|
111
111
|
time.sleep(POLL_INTERVAL_S)
|
|
112
112
|
|
|
113
113
|
|
|
114
|
+
def _announce_start(icon):
|
|
115
|
+
"""Tells the user, once per start, that Smart Tool was just updated or that the last automatic update failed."""
|
|
116
|
+
updated = update_check.note_running_version()
|
|
117
|
+
if updated:
|
|
118
|
+
icon.notify(f"Smart Tool updated from {updated['from']} to {updated['to']}.", "Smart Tool")
|
|
119
|
+
failed = update_check.failed_update()
|
|
120
|
+
if failed:
|
|
121
|
+
icon.notify(f"The update to {failed} failed; Smart Tool {version.VERSION} is still installed. "
|
|
122
|
+
"It is tried again in 24 h, or now from this menu.", "Smart Tool")
|
|
123
|
+
|
|
124
|
+
|
|
114
125
|
def _update_loop(icon):
|
|
115
|
-
"""Checks npm at start and every 24 h.
|
|
116
|
-
|
|
117
|
-
|
|
126
|
+
"""Checks npm at start and every 24 h. A newer version is installed right away when automatic updates are on (once
|
|
127
|
+
per version, again 24 h after a failed try); otherwise the user is told and the menu offers it."""
|
|
128
|
+
try:
|
|
129
|
+
_announce_start(icon)
|
|
130
|
+
except Exception as exc:
|
|
131
|
+
icon.notify(f"Could not read the update state: {exc}", "Smart Tool")
|
|
118
132
|
while True:
|
|
119
133
|
try:
|
|
120
134
|
latest = update_check.newer_version()
|
|
121
135
|
except Exception:
|
|
122
136
|
latest = None
|
|
123
|
-
|
|
137
|
+
else:
|
|
138
|
+
try:
|
|
139
|
+
update_check.record_check(latest)
|
|
140
|
+
except Exception as exc:
|
|
141
|
+
icon.notify(f"Could not save the update check: {exc}", "Smart Tool")
|
|
142
|
+
if latest:
|
|
143
|
+
known = latest == _state["update"]
|
|
124
144
|
_state["update"] = latest
|
|
125
145
|
icon.update_menu()
|
|
126
|
-
|
|
127
|
-
|
|
146
|
+
try:
|
|
147
|
+
automatic = update_check.automatic_enabled() and update_check.should_auto_update(latest)
|
|
148
|
+
except Exception as exc:
|
|
149
|
+
automatic = False
|
|
150
|
+
icon.notify(f"Automatic update skipped: {exc}", "Smart Tool")
|
|
151
|
+
if automatic:
|
|
152
|
+
icon.notify(f"Updating Smart Tool from {version.VERSION} to {latest}...", "Smart Tool")
|
|
128
153
|
update_check.run_update(latest, automatic=True)
|
|
129
|
-
|
|
154
|
+
elif not known:
|
|
130
155
|
icon.notify(f"Smart Tool {latest} is available: use \"Update to {latest}\" in this menu.", "Smart Tool")
|
|
131
|
-
first = False
|
|
132
156
|
time.sleep(UPDATE_CHECK_INTERVAL_S)
|
|
133
157
|
|
|
134
158
|
|
|
@@ -162,12 +186,16 @@ def _update_now(icon, item):
|
|
|
162
186
|
|
|
163
187
|
def _auto_update_checked(item):
|
|
164
188
|
try:
|
|
165
|
-
return
|
|
189
|
+
return update_check.automatic_enabled()
|
|
166
190
|
except Exception:
|
|
167
191
|
return False
|
|
168
192
|
|
|
169
193
|
|
|
170
194
|
def _toggle_auto_update(icon, item):
|
|
195
|
+
if update_check.env_opted_out():
|
|
196
|
+
icon.notify(f"{update_check.ENV_OPT_OUT}=off is set: automatic updates stay off until it is removed.",
|
|
197
|
+
"Smart Tool")
|
|
198
|
+
return
|
|
171
199
|
try:
|
|
172
200
|
config.update_config(lambda cfg: cfg.__setitem__("auto_update", not config.auto_update(cfg)))
|
|
173
201
|
except Exception as exc:
|
package/update_check.py
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
|
-
"""Newer Smart Tool release on npm and the update itself: the tray
|
|
2
|
-
|
|
1
|
+
"""Newer Smart Tool release on npm and the update itself: the tray checks npm at start and every 24 h and, when
|
|
2
|
+
automatic updates are on (the default), runs the same install command a user would, in a visible console. A failed
|
|
3
|
+
version is tried again after 24 h. What happened (newer version available, updated, update failed) is told to the
|
|
4
|
+
user by the tray and to agent sessions by the daemon, from the state file, without contacting npm again.
|
|
5
|
+
|
|
6
|
+
Automatic updates are turned off by the tray switch (config `auto_update`) or by SMART_TOOL_AUTO_UPDATE=off; the
|
|
7
|
+
newer-version notice still shows then, with the command to update by hand."""
|
|
3
8
|
import json
|
|
4
9
|
import os
|
|
5
10
|
import subprocess
|
|
@@ -7,13 +12,18 @@ import time
|
|
|
7
12
|
import urllib.request
|
|
8
13
|
|
|
9
14
|
import atomic_io
|
|
15
|
+
import config
|
|
10
16
|
import paths
|
|
11
17
|
import version
|
|
12
18
|
|
|
13
19
|
PACKAGE = "@allansantos-dev/smart-tool"
|
|
14
20
|
REGISTRY_URL = "https://registry.npmjs.org/@allansantos-dev%2Fsmart-tool/latest"
|
|
15
21
|
UPDATE_COMMAND = f"npx --yes {PACKAGE}@latest install"
|
|
22
|
+
CHANGELOG_URL = "https://github.com/AllanSantos-DV/smart-tool-dist/blob/main/CHANGELOG.md"
|
|
16
23
|
STATE_PATH = os.path.join(paths.DATA_DIR, "update-state.json")
|
|
24
|
+
ENV_OPT_OUT = "SMART_TOOL_AUTO_UPDATE"
|
|
25
|
+
RETRY_AFTER_S = 24 * 3600
|
|
26
|
+
UPDATED_NOTICE_S = 24 * 3600
|
|
17
27
|
|
|
18
28
|
|
|
19
29
|
def _parts(value):
|
|
@@ -29,27 +39,108 @@ def newer_version(timeout=10):
|
|
|
29
39
|
return latest if _parts(latest) > _parts(version.VERSION) else None
|
|
30
40
|
|
|
31
41
|
|
|
32
|
-
def
|
|
33
|
-
"""
|
|
42
|
+
def env_opted_out():
|
|
43
|
+
"""SMART_TOOL_AUTO_UPDATE set to off, 0, false or no."""
|
|
44
|
+
return os.environ.get(ENV_OPT_OUT, "").strip().lower() in ("off", "0", "false", "no")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def automatic_enabled(cfg=None):
|
|
48
|
+
"""Automatic updates are on: the tray switch (config `auto_update`, on by default) and no environment opt-out."""
|
|
49
|
+
return not env_opted_out() and config.auto_update(cfg)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _state():
|
|
34
53
|
try:
|
|
35
54
|
with open(STATE_PATH, encoding="utf-8") as stream:
|
|
36
|
-
return json.load(stream)
|
|
55
|
+
return json.load(stream)
|
|
37
56
|
except FileNotFoundError:
|
|
57
|
+
return {}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _save(state):
|
|
61
|
+
os.makedirs(os.path.dirname(STATE_PATH), exist_ok=True)
|
|
62
|
+
atomic_io.write_secret_text(STATE_PATH, json.dumps(state))
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def attempted():
|
|
66
|
+
"""Version the last automatic update went for, or None."""
|
|
67
|
+
return _state().get("attempted")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def should_auto_update(latest, now=None):
|
|
71
|
+
"""An automatic update runs once per version and again 24 h after a failed try: when it fails, the installer
|
|
72
|
+
restores the previous version and restarts the tray, which would otherwise try the same version on every start."""
|
|
73
|
+
if not latest:
|
|
74
|
+
return False
|
|
75
|
+
state = _state()
|
|
76
|
+
if state.get("attempted") != latest:
|
|
77
|
+
return True
|
|
78
|
+
return (now or time.time()) - state.get("at", 0) >= RETRY_AFTER_S
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def record_check(latest):
|
|
82
|
+
"""Stores the result of an npm check (the newer version, or None) for the notices read without network."""
|
|
83
|
+
state = _state()
|
|
84
|
+
state.update(latest=latest, checked_at=time.time())
|
|
85
|
+
_save(state)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def note_running_version(now=None):
|
|
89
|
+
"""Called when the tray and the daemon start: a version different from the one that ran last is recorded as an
|
|
90
|
+
update (from, to, at) for the updated notice; the very first run records nothing. Returns the update record when
|
|
91
|
+
this call found it, else None."""
|
|
92
|
+
state = _state()
|
|
93
|
+
running = state.get("running")
|
|
94
|
+
if running == version.VERSION:
|
|
38
95
|
return None
|
|
96
|
+
state["running"] = version.VERSION
|
|
97
|
+
found = None
|
|
98
|
+
if running:
|
|
99
|
+
found = state["updated"] = {"from": running, "to": version.VERSION, "at": now or time.time()}
|
|
100
|
+
_save(state)
|
|
101
|
+
return found
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def failed_update():
|
|
105
|
+
"""The version an automatic update went for and did not install (the previous version is still running), else
|
|
106
|
+
None."""
|
|
107
|
+
target = _state().get("attempted")
|
|
108
|
+
return target if target and _parts(target) > _parts(version.VERSION) else None
|
|
39
109
|
|
|
40
110
|
|
|
41
|
-
def
|
|
42
|
-
"""
|
|
43
|
-
|
|
44
|
-
|
|
111
|
+
def notices(now=None):
|
|
112
|
+
"""[(key, text)] about updates, for the user and the agent: Smart Tool updated in the last 24 h, the last
|
|
113
|
+
automatic update failed, or a newer version is on npm. Reads only the state file."""
|
|
114
|
+
now = now or time.time()
|
|
115
|
+
state = _state()
|
|
116
|
+
found = []
|
|
117
|
+
updated = state.get("updated") or {}
|
|
118
|
+
if updated.get("to") == version.VERSION and now - updated.get("at", 0) < UPDATED_NOTICE_S:
|
|
119
|
+
found.append((f"updated:{version.VERSION}",
|
|
120
|
+
f"Smart Tool was updated from {updated['from']} to {version.VERSION}. Changes: {CHANGELOG_URL}"))
|
|
121
|
+
failed = failed_update()
|
|
122
|
+
latest = state.get("latest")
|
|
123
|
+
if failed:
|
|
124
|
+
retry = ("the tray tries again 24 h after the failed try" if automatic_enabled()
|
|
125
|
+
else "automatic updates are now off")
|
|
126
|
+
found.append((f"failed:{failed}",
|
|
127
|
+
f"The automatic update of Smart Tool to {failed} failed; {version.VERSION} is still installed "
|
|
128
|
+
f"and {retry}. To update now, run: {UPDATE_COMMAND}"))
|
|
129
|
+
elif latest and _parts(latest) > _parts(version.VERSION):
|
|
130
|
+
how = ("the tray installs it automatically" if automatic_enabled()
|
|
131
|
+
else f"automatic updates are off (tray switch or {ENV_OPT_OUT}=off); to update, run: {UPDATE_COMMAND}")
|
|
132
|
+
found.append((f"available:{latest}",
|
|
133
|
+
f"Smart Tool {latest} is available on npm (installed: {version.VERSION}); {how}."))
|
|
134
|
+
return found
|
|
45
135
|
|
|
46
136
|
|
|
47
137
|
def run_update(latest, automatic):
|
|
48
138
|
"""Starts the install command in its own visible console, detached from the tray (the installer stops and restarts
|
|
49
139
|
the tray). The console closes on success and stays open with the error on failure."""
|
|
50
140
|
if automatic:
|
|
51
|
-
|
|
52
|
-
|
|
141
|
+
state = _state()
|
|
142
|
+
state.update(attempted=latest, at=time.time())
|
|
143
|
+
_save(state)
|
|
53
144
|
flags = getattr(subprocess, "CREATE_NEW_CONSOLE", 0) | getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
|
|
54
145
|
command = f'title Smart Tool update to {latest} && {UPDATE_COMMAND} || pause'
|
|
55
146
|
subprocess.Popen(["cmd.exe", "/c", command], creationflags=flags, close_fds=True,
|
package/version.py
CHANGED