@allansantos-dev/smart-tool 0.9.70 → 0.9.71

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 CHANGED
@@ -1,5 +1,25 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.9.71 - beta
4
+
5
+ - `npx @allansantos-dev/smart-tool@0.9.71 uninstall [--target DIR] [--keep-data]` (`python uninstall.py`): silent uninstall that
6
+ removes what the install and the agent-side setup added: tray and daemon, logon task, Smart Tool's hook entries
7
+ (`client_hooks.remove`, `audit_remove`), the `smart-tool` MCP entry (`endpoint_sync.unregister`) and the `playwright`
8
+ entry Smart Tool registered (`browser_control.unregister`), the program folder and `~/.smart-tool`. Projects are never
9
+ touched; the exit code is 1 when a step fails. Tests: `tests/test_uninstall.py`.
10
+ - `install.py` and `uninstall.py` refuse to run (`paths.refuse_overridden_folders`) when USERPROFILE or LOCALAPPDATA differ from the
11
+ folders Windows reports, because the logon task, the process table and the registry they act on are shared with the real
12
+ installation. The release gate runs the tests that read `.github` from the repository, not from the installed copy.
13
+
14
+ - A redirected search (the hook that answers the agent's Grep/Read) no longer waits behind an index update of the same
15
+ project: it answers from the last ready index plus the files read from disk, so a reindex never makes the hook fail.
16
+ Searches and index updates are counted apart (a queue of one never rejects the other; the message names which is
17
+ full), and a search waiting for a folder runs before the index updates queued for it. Tests:
18
+ `tests/test_interactive_priority.py`, `tests/test_warm_search.py`.
19
+ - `setup_audit` reads the MCP servers a Claude Code plugin declares in `.claude-plugin/plugin.json` (inline object or a path
20
+ to a JSON file), not only its `.mcp.json`: 23 `hook_unknown_server` errors reported for a plugin whose hooks call its own
21
+ server were false findings. Tests: `tests/test_setup_audit.py`.
22
+
3
23
  ## 0.9.70 - beta
4
24
 
5
25
  - `project_manage list` no longer fails as a whole when a registered folder was deleted inside a Git repository (a removed
package/README.md CHANGED
@@ -17,7 +17,7 @@ registered as the `playwright` server where this machine lets a browser be drive
17
17
  An optional hook routes the agent's native Grep/Glob/Read/Bash/WebSearch/WebFetch calls to these tools when they
18
18
  are cheaper, or just tells the agent what Smart Tool would do.
19
19
 
20
- **Status:** 0.9.70 beta. Windows only. What changed in each version: [CHANGELOG.md](CHANGELOG.md).
20
+ **Status:** 0.9.71 beta. Windows only. What changed in each version: [CHANGELOG.md](CHANGELOG.md).
21
21
 
22
22
  ## How it works
23
23
 
@@ -83,7 +83,7 @@ gateway such as Ollama, nothing about your code leaves the machine.
83
83
  ## Install
84
84
 
85
85
  ```powershell
86
- npx @allansantos-dev/smart-tool@0.9.70 install
86
+ npx @allansantos-dev/smart-tool@0.9.71 install
87
87
  ```
88
88
 
89
89
  Updates install themselves, on by default: the tray checks npm when it starts (at logon) and every 24 h, and when there
@@ -381,11 +381,20 @@ fails to load is listed in the setup screen with its error and does not affect t
381
381
 
382
382
  ## Uninstall
383
383
 
384
- Turn off "Start automatically" in the setup screen, quit from the tray, remove the hook entries from
385
- `~/.claude/settings.json` / `~/.codex/hooks.json` (the setup screen shows them), run `claude mcp remove smart-tool -s
386
- user` / `codex mcp remove smart-tool`, then delete `%LOCALAPPDATA%\Programs\SmartTool` and `~/.smart-tool`. Turning off "Start automatically" also removes the
387
- two per-user registry keys of the notification buttons (`HKCU\Software\Classes\smart-tool-action` and
388
- `HKCU\Software\Classes\AppUserModelId\SmartTool.Notifications`); they come back the next time a notification is shown.
384
+ ```powershell
385
+ npx @allansantos-dev/smart-tool@0.9.71 uninstall [--target DIR] [--keep-data]
386
+ ```
387
+
388
+ It asks nothing and opens no window. It stops the tray and the daemon, removes the logon task, the hook entries of Smart
389
+ Tool in `~/.claude/settings.json` and `~/.codex/hooks.json` (other hooks stay), the `smart-tool` MCP entry and the
390
+ `playwright` entry Smart Tool registered (one you registered yourself stays) in Claude Code and Codex, the program
391
+ folder (`%LOCALAPPDATA%\Programs\SmartTool`), the old copies beside it, and `~/.smart-tool` (settings, indexes, saved
392
+ keys; `--keep-data` keeps it). Your projects are never touched. The Camoufox browser cache in
393
+ `%LOCALAPPDATA%\camoufox` is left in place: other tools use it too. The exit code is 0 when everything is gone (or was
394
+ never there) and 1 when a step failed, with each failure named on stderr; running it again retries. Turning off "Start
395
+ automatically" in the setup screen also removes the two per-user registry keys of the notification buttons
396
+ (`HKCU\Software\Classes\smart-tool-action` and `HKCU\Software\Classes\AppUserModelId\SmartTool.Notifications`); the
397
+ uninstall removes them too, and they come back the next time a notification is shown.
389
398
 
390
399
  ## License
391
400
 
@@ -20,7 +20,12 @@ const USAGE = `Usage: npx @allansantos-dev/smart-tool@<version> install [--targe
20
20
 
21
21
  Installs or updates Smart Tool for this Windows user. To update, run it again with the version to install in place of
22
22
  <version>: a pinned version keeps npx from reusing an older package from its cache. For a version published minutes
23
- ago, add --prefer-online before the package name so npm asks the registry instead of its cached version list.`;
23
+ ago, add --prefer-online before the package name so npm asks the registry instead of its cached version list.
24
+
25
+ Usage: npx @allansantos-dev/smart-tool@<version> uninstall [--target DIR] [--keep-data]
26
+
27
+ Removes Smart Tool silently (no prompts): the program folder, autostart, the agent hooks, the MCP registrations and
28
+ ~/.smart-tool (kept with --keep-data). Your projects are never touched. Exit code 0 when everything is gone, 1 when a step failed.`;
24
29
 
25
30
  function fail(message) {
26
31
  throw new Failure(message);
@@ -84,7 +89,7 @@ async function main() {
84
89
  console.log(JSON.parse(readFileSync(join(PACKAGE_DIR, "package.json"), "utf8")).version);
85
90
  return;
86
91
  }
87
- if (command !== "install") {
92
+ if (command !== "install" && command !== "uninstall") {
88
93
  console.log(USAGE);
89
94
  process.exitCode = command === undefined || command === "--help" || command === "-h" ? 0 : 1;
90
95
  return;
@@ -96,7 +101,8 @@ async function main() {
96
101
  return;
97
102
  }
98
103
  const python = ensurePython();
99
- const installer = spawnSync(python, [join(PACKAGE_DIR, "install.py"), "--skip-tests", ...rest], {
104
+ const script = command === "install" ? ["install.py", "--skip-tests"] : ["uninstall.py"];
105
+ const installer = spawnSync(python, [join(PACKAGE_DIR, script[0]), ...script.slice(1), ...rest], {
100
106
  stdio: "inherit",
101
107
  cwd: PACKAGE_DIR,
102
108
  env: { ...process.env, PYTHONUTF8: "1", PYTHONIOENCODING: "utf-8" },
@@ -323,15 +323,6 @@ def register_command(client, command):
323
323
  raise ValueError(f"Client without MCP registration: {client!r}")
324
324
 
325
325
 
326
- def remove_command(client):
327
- """Official CLI command that removes the server registered by register_command."""
328
- if client == "claude":
329
- return ["claude", "mcp", "remove", SERVER, "--scope", "user"]
330
- if client == "codex":
331
- return ["codex", "mcp", "remove", SERVER]
332
- raise ValueError(f"Client without MCP registration: {client!r}")
333
-
334
-
335
326
  def status():
336
327
  """Last outcome per client: {"claude": {"state": "registered"|"unavailable"|"kept"|"undenied", "reason", "at"}}."""
337
328
  try:
@@ -374,7 +365,22 @@ def _remove(client):
374
365
  if client == "codex":
375
366
  codex_config.remove_server(_codex_config(), SERVER)
376
367
  else:
377
- endpoint_sync.run_cli(remove_command(client))
368
+ endpoint_sync.run_cli(endpoint_sync.remove_command(client, SERVER))
369
+
370
+
371
+ def unregister(client):
372
+ """Takes the `playwright` MCP server Smart Tool registered (and, in Claude Code, its DENIED_TOOLS rules) out of the
373
+ client; a server the user registered is kept. Raises RuntimeError when it is still registered afterwards. Returns
374
+ a sentence saying what was done."""
375
+ if status().get(client, {}).get("state") not in ("registered", "undenied"):
376
+ return f"{client}: no {SERVER} server of Smart Tool's"
377
+ if registered().get(client):
378
+ _remove(client)
379
+ if registered().get(client):
380
+ raise RuntimeError(f"The {SERVER} server of {client} is still registered after removing it.")
381
+ if client == "claude":
382
+ set_claude_deny(False)
383
+ return f"{client}: {SERVER} server removed"
378
384
 
379
385
 
380
386
  def ensure(client, log=None):
@@ -411,7 +417,7 @@ def ensure(client, log=None):
411
417
  try:
412
418
  _remove(client)
413
419
  except (OSError, RuntimeError, ValueError) as removal:
414
- return _record(client, "undenied", f"remove it with `{' '.join(remove_command(client))}`: {problem} "
420
+ return _record(client, "undenied", f"remove it with `{' '.join(endpoint_sync.remove_command(client, SERVER))}`: {problem} "
415
421
  f"and removing it failed ({removal})"[:300], log)
416
422
  return _record(client, "unavailable", f"{problem}, so the server was removed"[:300], log)
417
423
  except (OSError, RuntimeError, ValueError) as exc:
package/client_hooks.py CHANGED
@@ -284,6 +284,40 @@ def install(client_info, token, confirm):
284
284
  "after_install": spec.get("after_install")}
285
285
 
286
286
 
287
+ def remove(client):
288
+ """Takes every redirect hook entry of ours (PreToolUse, and the PostToolUse of Claude Code) out of the client's hooks
289
+ file after a backup; other hooks stay, in Codex at the approval of their new index. Returns {client, changed, file,
290
+ backup}."""
291
+ path = os.path.realpath(CLIENTS[client]["files"][0])
292
+ try:
293
+ with open(path, encoding="utf-8") as stream:
294
+ data = json.load(stream)
295
+ except FileNotFoundError:
296
+ return {"client": client, "changed": False, "file": path, "backup": None}
297
+ hooks = data.get("hooks") if isinstance(data, dict) else None
298
+ if not isinstance(hooks, dict):
299
+ raise ValueError(f"{path} does not have the expected format (object with 'hooks'); nothing was changed.")
300
+ moved = {}
301
+ spec = CLIENTS[client]
302
+ for event in (spec["event"], *(["PostToolUse"] if spec.get("post_matcher") else [])):
303
+ groups = hooks.get(event)
304
+ if not isinstance(groups, list) or not any(_ours(group) for group in groups):
305
+ continue
306
+ kept = _without_ours(groups)
307
+ moved[event] = (list(groups), kept)
308
+ if kept:
309
+ hooks[event] = kept
310
+ else:
311
+ del hooks[event]
312
+ if not moved:
313
+ return {"client": client, "changed": False, "file": path, "backup": None}
314
+ backup = _write_checked(path, data, lambda: inspect(client, trust=False)["state"] == "missing", "The removal")
315
+ if client == "codex":
316
+ for event, (before, kept) in moved.items():
317
+ record_codex_trust(_codex_trust(event, before, kept))
318
+ return {"client": client, "changed": True, "file": path, "backup": backup}
319
+
320
+
287
321
  def _write_checked(path, data, verify, what):
288
322
  """Writes data as JSON to path through a temp file after a timestamped backup; when verify() fails on the written
289
323
  file, restores the backup (or removes the new file) and raises. Returns the backup path (None for a new file)."""
package/endpoint_sync.py CHANGED
@@ -130,12 +130,12 @@ def register_command(client, base):
130
130
  raise ValueError(f"Client without MCP registration: {client!r}")
131
131
 
132
132
 
133
- def remove_command(client):
134
- """Official CLI command that removes the smart-tool MCP server a client holds."""
133
+ def remove_command(client, server=SERVER):
134
+ """Official CLI command that removes an MCP server a client holds (default: the smart-tool one)."""
135
135
  if client == "claude":
136
- return ["claude", "mcp", "remove", SERVER, "--scope", "user"]
136
+ return ["claude", "mcp", "remove", server, "--scope", "user"]
137
137
  if client == "codex":
138
- return ["codex", "mcp", "remove", SERVER]
138
+ return ["codex", "mcp", "remove", server]
139
139
  raise ValueError(f"Client without MCP registration: {client!r}")
140
140
 
141
141
 
@@ -164,6 +164,24 @@ def register(client, base):
164
164
  return " ".join(command)
165
165
 
166
166
 
167
+ def unregister(client):
168
+ """Removes the client's smart-tool MCP entry the way `register` made it (Claude Code through its CLI, Codex by
169
+ editing its table) and checks it is gone. Nothing runs when the client holds no entry. Returns what was done."""
170
+ if not registrations().get(client):
171
+ return f"nothing to remove: {client} holds no {SERVER} entry"
172
+ if client == "codex":
173
+ path = os.path.join(codex_dir(), "config.toml")
174
+ codex_config.remove_server(path, SERVER)
175
+ done = f"edited {path}: removed [mcp_servers.{SERVER}]"
176
+ else:
177
+ command = remove_command(client)
178
+ run_cli(command)
179
+ done = " ".join(command)
180
+ if registrations().get(client):
181
+ raise RuntimeError(f"{done} finished, but the {SERVER} entry is still in the client's configuration.")
182
+ return done
183
+
184
+
167
185
  def cli_folders():
168
186
  """Where the native installers of the clients put their CLI, for a PATH that does not list them."""
169
187
  home, local, roaming = os.path.expanduser("~"), os.environ.get("LOCALAPPDATA"), os.environ.get("APPDATA")
package/install.py CHANGED
@@ -33,7 +33,7 @@ DEPENDENCY_STAMP = ".dependencies.sha256"
33
33
  REGISTRY = Path(paths.DATA_DIR) / "daemon.json"
34
34
  BLOCKED = {"__pycache__", ".token-guard", ".git", ".pytest_cache", ".data", ".artifacts", ".claude", ".vscode",
35
35
  ".impeccable", "tests", "sessions", "results", "dist", "node_modules", ".node-runtime", ".venv",
36
- ".scratch", ".memory", "docs", "reports", "site", "design", "release", "npm", ".github", "AGENTS.md", "CLAUDE.md", "DESIGN.md", "PRODUCT.md", "install.py", ".gitignore", ".gitattributes", MANIFEST}
36
+ ".scratch", ".memory", "docs", "reports", "site", "design", "release", "npm", ".github", "AGENTS.md", "CLAUDE.md", "DESIGN.md", "PRODUCT.md", "install.py", "uninstall.py", ".gitignore", ".gitattributes", MANIFEST}
37
37
  PACKAGE_ONLY = {"bin", "package.json", ".npmignore"}
38
38
  REQUIRED_TOOLS = {"smart_search", "smart_search_result", "web_search", "project_manage"}
39
39
  _OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))
@@ -408,6 +408,7 @@ def main():
408
408
  if args.expect_version and args.expect_version != version.VERSION:
409
409
  raise SystemExit(f"This package is Smart Tool {version.VERSION}, not the {args.expect_version} requested; "
410
410
  "nothing was changed.")
411
+ paths.refuse_overridden_folders("install")
411
412
  target = args.target.resolve()
412
413
  if target == SOURCE:
413
414
  raise SystemExit("The target cannot be the source folder itself.")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@allansantos-dev/smart-tool",
3
- "version": "0.9.70",
3
+ "version": "0.9.71",
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": "Smart Tool contributors",
package/paths.py CHANGED
@@ -4,3 +4,42 @@ import os
4
4
 
5
5
  HOME_DIR = os.path.join(os.path.expanduser("~"), ".smart-tool")
6
6
  DATA_DIR = os.path.join(HOME_DIR, "data")
7
+
8
+ _KNOWN_FOLDERS = {"USERPROFILE": "{5E6C858F-0E22-4760-9AFE-EA3317B67173}",
9
+ "LOCALAPPDATA": "{F1B32785-6FBA-4FCF-9D55-7B8E7F157091}"}
10
+
11
+
12
+ def _windows_folder(folder_id):
13
+ """The folder Windows itself reports for a known-folder id; it does not follow environment variables."""
14
+ import ctypes
15
+ import uuid
16
+ guid = uuid.UUID(folder_id)
17
+ raw = (ctypes.c_byte * 16).from_buffer_copy(guid.bytes_le)
18
+ out = ctypes.c_wchar_p()
19
+ if ctypes.windll.shell32.SHGetKnownFolderPath(ctypes.byref(raw), 0, None, ctypes.byref(out)) != 0:
20
+ raise OSError(f"Windows did not report the known folder {folder_id}.")
21
+ try:
22
+ return out.value
23
+ finally:
24
+ ctypes.windll.ole32.CoTaskMemFree(out)
25
+
26
+
27
+ def overridden_folders():
28
+ """USERPROFILE and LOCALAPPDATA values that differ from the folders Windows reports for the user, as sentences.
29
+ The scheduler, the process table and the registry are machine-wide and ignore these variables, so a run under
30
+ redirected folders would still reach the real installation."""
31
+ found = []
32
+ for name, folder_id in _KNOWN_FOLDERS.items():
33
+ real, given = _windows_folder(folder_id), os.environ.get(name, "")
34
+ if os.path.normcase(os.path.normpath(given or real)) != os.path.normcase(os.path.normpath(real)):
35
+ found.append(f"{name}={given} (Windows reports {real})")
36
+ return found
37
+
38
+
39
+ def refuse_overridden_folders(action):
40
+ """Stops `action` (an installer or uninstaller run) before it changes anything when the user folders are redirected."""
41
+ found = overridden_folders()
42
+ if found:
43
+ raise SystemExit(f"Refusing to {action}: " + "; ".join(found) + ". The logon task, the running processes and the "
44
+ "registry are shared with the real installation, so the run would reach it. Run it with the "
45
+ "real user folders.")
@@ -1,4 +1,5 @@
1
- """Fila justa entre raízes; jobs aguardando a mesma pasta não ocupam workers."""
1
+ """Fila justa entre raízes; jobs aguardando a mesma pasta não ocupam workers. Um job de prioridade maior passa à frente
2
+ dos de prioridade menor ainda na fila (o que já está rodando não é interrompido)."""
2
3
  import collections
3
4
  import concurrent.futures
4
5
  import threading
@@ -15,21 +16,24 @@ class ProjectScheduler:
15
16
  self._running = set()
16
17
  self._closed = False
17
18
 
18
- def submit(self, root, function, *args):
19
+ def submit(self, root, function, *args, priority=0):
19
20
  key = project_identity.canonical_root(root)
20
21
  future = concurrent.futures.Future()
21
22
  with self._lock:
22
23
  if self._closed:
23
24
  raise RuntimeError("Project queue closed.")
24
- self._queues.setdefault(key, collections.deque()).append((future, function, args))
25
+ queue = self._queues.setdefault(key, collections.deque())
26
+ at = next((index for index, item in enumerate(queue) if item[3] < priority), len(queue))
27
+ queue.insert(at, (future, function, args, priority))
25
28
  self._dispatch()
26
29
  return future
27
30
 
28
31
  def _dispatch(self):
29
32
  while len(self._running) < self.workers:
30
- key = next((root for root in self._queues if root not in self._running), None)
31
- if key is None:
33
+ waiting = [root for root in self._queues if root not in self._running]
34
+ if not waiting:
32
35
  break
36
+ key = max(waiting, key=lambda root: self._queues[root][0][3])
33
37
  task = self._queues[key].popleft()
34
38
  if not self._queues[key]:
35
39
  self._queues.pop(key)
@@ -39,7 +43,7 @@ class ProjectScheduler:
39
43
  self._pool.submit(self._run, key, task)
40
44
 
41
45
  def _run(self, key, task):
42
- future, function, args = task
46
+ future, function, args, _priority = task
43
47
  try:
44
48
  if future.set_running_or_notify_cancel():
45
49
  try:
@@ -55,7 +59,7 @@ class ProjectScheduler:
55
59
  with self._lock:
56
60
  self._closed = True
57
61
  for queue in self._queues.values():
58
- for future, _fn, _args in queue:
62
+ for future, _fn, _args, _priority in queue:
59
63
  future.cancel()
60
64
  self._queues.clear()
61
65
  self._pool.shutdown(wait=wait, cancel_futures=True)
package/setup_audit.py CHANGED
@@ -274,9 +274,7 @@ def collect_claude(project, snapshot):
274
274
  plugins.append({"id": plugin_id, "path": root})
275
275
  hook_file = os.path.join(root, "hooks", "hooks.json")
276
276
  hooks += _hooks_from(snapshot.json(hook_file), f"plugin:{name}", hook_file, root)
277
- plugin_mcp = snapshot.json(os.path.join(root, ".mcp.json")) or {}
278
- mcp += _mcp_entries(plugin_mcp.get("mcpServers", plugin_mcp), f"plugin:{name}",
279
- os.path.join(root, ".mcp.json"), f"plugin:{name}:", {"CLAUDE_PLUGIN_ROOT": root})
277
+ mcp += _claude_plugin_mcp(snapshot, root, name)
280
278
  skills += [{**s, "name": f"{name}:{s['name']}"} for s in
281
279
  _skills(snapshot, os.path.join(root, "skills"), f"plugin:{name}")]
282
280
  instructions = []
@@ -290,6 +288,24 @@ def collect_claude(project, snapshot):
290
288
  "instructions": instructions, "unapproved_mcp": unapproved}
291
289
 
292
290
 
291
+ def _claude_plugin_mcp(snapshot, root, name):
292
+ """MCP server entries of a Claude Code plugin: its `.mcp.json`, plus the servers its manifest declares in
293
+ `.claude-plugin/plugin.json` (`mcpServers` as an inline object or as a path to a JSON file)."""
294
+ manifest_path = os.path.join(root, ".claude-plugin", "plugin.json")
295
+ declared = (snapshot.json(manifest_path) or {}).get("mcpServers")
296
+ sources = [(os.path.join(root, ".mcp.json"), None)]
297
+ if isinstance(declared, dict):
298
+ sources.append((manifest_path, declared))
299
+ elif isinstance(declared, str):
300
+ sources.append((os.path.join(root, declared), None))
301
+ entries = []
302
+ for path, inline in sources:
303
+ found = inline if inline is not None else (snapshot.json(path) or {})
304
+ entries += _mcp_entries(found.get("mcpServers", found), f"plugin:{name}", path, f"plugin:{name}:",
305
+ {"CLAUDE_PLUGIN_ROOT": root})
306
+ return entries
307
+
308
+
293
309
  def _codex_plugin_root(market, name):
294
310
  """Newest installed version folder of a Codex plugin (`plugins/cache/<marketplace>/<name>/<version>/`), skipping
295
311
  the `latest` alias unless it is all there is; None when the plugin is not in the cache."""
@@ -200,6 +200,8 @@ EDIT_INDEX_DELAY_S = 8
200
200
  # p75 10.7 s).
201
201
  SMART_SEARCH_RESULT_WAIT_S = 15
202
202
  SMART_SEARCH_MAX_PENDING = 8
203
+ BACKGROUND_MAX_PENDING = 8
204
+ INTERACTIVE_PRIORITY = 1
203
205
  SMART_SEARCH_EXECUTOR = project_scheduler.ProjectScheduler(workers=3)
204
206
  _PROJECT_LOCKS = {}
205
207
  _PROJECT_LOCKS_LOCK = threading.Lock()
@@ -1264,7 +1266,8 @@ def _perform_smart_search_isolated(arguments, job_id):
1264
1266
  warnings.append(LOCAL_EMBEDDER_DOWN_WARNING if local_embedder.configured() and config.local_models_mode(cfg) != "off"
1265
1267
  else LEXICAL_WARNING)
1266
1268
  try:
1267
- _prepare_project_index(arguments, job_id, cfg, token, model=model)
1269
+ if not arguments.get("_existing_index_only"):
1270
+ _prepare_project_index(arguments, job_id, cfg, token, model=model)
1268
1271
  except ProjectJobCancelled:
1269
1272
  raise
1270
1273
  except Exception as exc:
@@ -1302,7 +1305,7 @@ def _perform_smart_search_isolated(arguments, job_id):
1302
1305
  overlay, notice = _lag_overlay(root, lag)
1303
1306
  source = "index+disk" if overlay else source
1304
1307
  warnings += [text for text in (notice, _refresh_in_background(root, lag)) if text]
1305
- else:
1308
+ elif not arguments.get("_existing_index_only"):
1306
1309
  try:
1307
1310
  _prepare_project_index(arguments, job_id, cfg, token, query_vector=next(iter(vectors.values())),
1308
1311
  model=model)
@@ -1505,8 +1508,12 @@ def _submit_project_job_locked(kind, arguments):
1505
1508
  and value.get("status") == "pending" and value.get("request_key") == request_key), None)
1506
1509
  if existing:
1507
1510
  return existing, None
1508
- if sum(value.get("kind") in _PROJECT_KINDS and value.get("status") == "pending" for value in _jobs.values()) >= SMART_SEARCH_MAX_PENDING:
1509
- raise RuntimeError("Too many project operations in progress; wait for one to finish.")
1511
+ interactive = kind == "smart_search"
1512
+ pending = sum(value.get("status") == "pending" and (value.get("kind") == "smart_search") == interactive
1513
+ for value in _jobs.values() if value.get("kind") in _PROJECT_KINDS)
1514
+ if pending >= (SMART_SEARCH_MAX_PENDING if interactive else BACKGROUND_MAX_PENDING):
1515
+ raise RuntimeError("Too many " + ("searches" if interactive else "index updates") +
1516
+ " in progress; wait for one to finish.")
1510
1517
  payload = {"kind": kind, "project_id": project["id"], "status": "pending", "phase": "queued",
1511
1518
  "created_at": time.time(), "request_key": request_key, "arguments": arguments,
1512
1519
  "processed_files": None, "total_files": None, "result": None, "error": None}
@@ -1515,7 +1522,8 @@ def _submit_project_job_locked(kind, arguments):
1515
1522
  project_store.update(project["id"], status="queued", last_job_id=job_id,
1516
1523
  enabled=kind != "project_preview" or project.get("enabled", False))
1517
1524
  try:
1518
- future = SMART_SEARCH_EXECUTOR.submit(root, _run_project_job, job_id, arguments, kind)
1525
+ future = SMART_SEARCH_EXECUTOR.submit(root, _run_project_job, job_id, arguments, kind,
1526
+ priority=INTERACTIVE_PRIORITY if interactive else 0)
1519
1527
  with _JOBS_LOCK:
1520
1528
  if not future.done():
1521
1529
  _JOB_FUTURES[job_id] = future
@@ -4112,6 +4120,15 @@ def _cold_index_building(root):
4112
4120
  and job.get("project_id") == project_id for job in _jobs.values())
4113
4121
 
4114
4122
 
4123
+ def _index_update_running(root):
4124
+ """Whether an index update of the folder is queued or running. A search job of that folder would wait behind it in the
4125
+ per-folder queue, longer than a hook may wait."""
4126
+ project_id = project_identity.project_id(root)
4127
+ with _JOBS_LOCK:
4128
+ return any(job.get("kind") == "project_index" and job.get("status") == "pending"
4129
+ and job.get("project_id") == project_id for job in _jobs.values())
4130
+
4131
+
4115
4132
  def _redirected_search(arguments):
4116
4133
  """smart_search text for a redirected native search, waiting up to SMART_SEARCH_SYNC_WAIT_S; raises when the search
4117
4134
  is rejected, fails or is still running then. The hook's single_language_reason only passes the language check, it is
@@ -4121,6 +4138,8 @@ def _redirected_search(arguments):
4121
4138
  checked.pop("single_language_reason", None)
4122
4139
  if _cold_index_building(checked["project_root"]):
4123
4140
  return f"{tool_redirect.search_notice(True)}\n{_perform_smart_search(checked, '')}"
4141
+ if _index_update_running(checked["project_root"]):
4142
+ return f"{tool_redirect.search_notice(True)}\n{_perform_smart_search({**checked, '_existing_index_only': True}, '')}"
4124
4143
  job_id, _future = _submit_project_job("smart_search", checked)
4125
4144
  deadline = time.monotonic() + SMART_SEARCH_SYNC_WAIT_S
4126
4145
  payload = _smart_search_job_payload(job_id)
package/uninstall.py ADDED
@@ -0,0 +1,144 @@
1
+ #!/usr/bin/env python3
2
+ """Silent uninstall: removes what install.py and the agent-side setup added, never a user's project folder.
3
+
4
+ Usage: python uninstall.py [--target DIR] [--keep-data] (npm: npx @allansantos-dev/smart-tool@<version> uninstall)
5
+
6
+ It never asks anything. Exit code 0 means everything is gone (or was never there); 1 means a step failed, each failure
7
+ named on stderr, and the steps that could run did run.
8
+ """
9
+ import argparse
10
+ import os
11
+ import shutil
12
+ import subprocess
13
+ import sys
14
+ import time
15
+ from pathlib import Path
16
+
17
+ import autostart
18
+ import browser_control
19
+ import client_hooks
20
+ import endpoint_sync
21
+ import install
22
+ import paths
23
+
24
+ CLIENTS = ("claude", "codex")
25
+ RUNTIME_DIR = Path(paths.HOME_DIR) / "runtime"
26
+ DELETE_RETRY_S = 15
27
+
28
+
29
+ def _delete(folder):
30
+ """Deletes folder, retrying while a process that was just stopped still holds a file; raises the last OSError."""
31
+ deadline = time.monotonic() + DELETE_RETRY_S
32
+ while True:
33
+ try:
34
+ shutil.rmtree(folder)
35
+ return
36
+ except FileNotFoundError:
37
+ return
38
+ except OSError:
39
+ if time.monotonic() > deadline:
40
+ raise
41
+ time.sleep(0.5)
42
+
43
+
44
+ def _inside(path, folder):
45
+ try:
46
+ return Path(path).resolve().is_relative_to(Path(folder).resolve())
47
+ except OSError:
48
+ return False
49
+
50
+
51
+ def _delete_after_exit(folders):
52
+ """Windows cannot delete the interpreter that is running this script: a detached, windowless cmd removes folders
53
+ once the process has ended."""
54
+ commands = " & ".join(f'rmdir /s /q "{folder}"' for folder in folders)
55
+ subprocess.Popen(["cmd.exe", "/c", f"ping -n 4 127.0.0.1 >nul & {commands}"], stdin=subprocess.DEVNULL,
56
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
57
+ creationflags=subprocess.DETACHED_PROCESS | subprocess.CREATE_NO_WINDOW)
58
+
59
+
60
+ def remove_hooks():
61
+ """Our hook entries (redirect and session-start) out of Claude Code's and Codex's hooks files."""
62
+ for client in CLIENTS:
63
+ for result in (client_hooks.remove(client), client_hooks.audit_remove(client)):
64
+ if result["changed"]:
65
+ print(f"Hooks removed from {result['file']} (backup {result['backup']}).")
66
+
67
+
68
+ def remove_registrations():
69
+ """The smart-tool MCP entry, and the playwright one Smart Tool registered, out of each client."""
70
+ for client in CLIENTS:
71
+ print(endpoint_sync.unregister(client))
72
+ print(browser_control.unregister(client))
73
+
74
+
75
+ def remove_state(keep_data):
76
+ """~/.smart-tool: everything unless keep_data; the downloaded runtime always, afterwards when this very
77
+ interpreter runs from it."""
78
+ home = Path(paths.HOME_DIR)
79
+ if not home.is_dir():
80
+ return
81
+ pending = []
82
+ for entry in sorted(home.iterdir()):
83
+ if entry == RUNTIME_DIR:
84
+ if _inside(sys.executable, entry):
85
+ pending.append(entry)
86
+ else:
87
+ _delete(entry)
88
+ elif not keep_data:
89
+ _delete(entry) if entry.is_dir() else entry.unlink()
90
+ if not keep_data and not pending and not any(home.iterdir()):
91
+ home.rmdir()
92
+ if pending:
93
+ _delete_after_exit([home] if not keep_data else pending)
94
+ print(f"{pending[0]} is in use by this run; it is removed as soon as the run ends.")
95
+
96
+
97
+ def run(target, keep_data):
98
+ """Runs every step, collecting failures instead of stopping at the first. Returns the list of failure messages."""
99
+ failures = []
100
+ steps = [("stop the running Smart Tool", lambda: install.stop_processes(target)),
101
+ ("remove the autostart", lambda: print("Autostart removed:", autostart.remove()["removed"])),
102
+ ("remove the agent hooks", remove_hooks),
103
+ ("remove the MCP registrations", remove_registrations)]
104
+ install.mark_updating(True)
105
+ try:
106
+ for name, step in steps:
107
+ try:
108
+ step()
109
+ except Exception as exc:
110
+ failures.append(f"Could not {name}: {type(exc).__name__}: {exc}")
111
+ if failures:
112
+ return failures
113
+ for name, step in (("delete the program folder", lambda: _delete(target)),
114
+ ("delete the old copies beside it", lambda: install.prune_backups(target)),
115
+ ("delete Smart Tool's state", lambda: remove_state(keep_data))):
116
+ try:
117
+ step()
118
+ except Exception as exc:
119
+ failures.append(f"Could not {name}: {type(exc).__name__}: {exc}")
120
+ finally:
121
+ if keep_data or failures:
122
+ install.mark_updating(False)
123
+ return failures
124
+
125
+
126
+ def main():
127
+ parser = argparse.ArgumentParser(description="Uninstall Smart Tool silently.")
128
+ parser.add_argument("--target", type=Path, default=install.DEFAULT_TARGET)
129
+ parser.add_argument("--keep-data", action="store_true", help="keep ~/.smart-tool (settings, indexes, saved keys)")
130
+ args = parser.parse_args()
131
+ paths.refuse_overridden_folders("uninstall")
132
+ target = args.target.resolve()
133
+ if target == install.SOURCE:
134
+ raise SystemExit("The target cannot be the folder this script runs from.")
135
+ failures = run(target, args.keep_data)
136
+ for failure in failures:
137
+ print(failure, file=sys.stderr)
138
+ if failures:
139
+ raise SystemExit(1)
140
+ print(f"Smart Tool removed from {target}.")
141
+
142
+
143
+ if __name__ == "__main__":
144
+ main()
package/version.py CHANGED
@@ -1,7 +1,7 @@
1
1
  """Single source of the Smart Tool version and of the User-Agent sent to public APIs."""
2
2
  import re
3
3
 
4
- VERSION = "0.9.70"
4
+ VERSION = "0.9.71"
5
5
  _CONTACT_RE = re.compile(r"^(?:[^\s@()<>;]+@[^\s@()<>;]+\.[^\s@()<>;]+|https?://[^\s()<>;]+)$")
6
6
 
7
7