@allansantos-dev/smart-tool 0.9.81 → 0.9.82

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/NOTICE +1 -1
  3. package/README.md +41 -13
  4. package/agent_redirect.py +32 -0
  5. package/autostart.py +32 -25
  6. package/browser_bridge.py +320 -0
  7. package/browser_control.py +76 -39
  8. package/browser_service_client.py +1 -7
  9. package/client_hooks.py +41 -42
  10. package/code_graph.py +56 -15
  11. package/code_graph_java.mjs +21 -12
  12. package/code_health.py +14 -9
  13. package/codex_config.py +3 -0
  14. package/daemon_launcher.py +37 -5
  15. package/doc_candidates.py +63 -0
  16. package/doc_check.py +9 -3
  17. package/doc_extras.py +2 -3
  18. package/doc_insights.py +26 -2
  19. package/doc_prose.py +59 -11
  20. package/doc_registry.py +241 -0
  21. package/doc_scope.py +205 -39
  22. package/doc_turn.py +205 -0
  23. package/doc_validate.py +52 -9
  24. package/document_read.py +4 -2
  25. package/edit_shape.py +119 -0
  26. package/endpoint_sync.py +3 -21
  27. package/engine_home.py +95 -0
  28. package/hook_call.py +132 -0
  29. package/hook_decision.py +100 -6
  30. package/hooks/pretool_router.py +36 -30
  31. package/hooks/turn_end.py +40 -0
  32. package/index_views.py +5 -0
  33. package/install.py +24 -9
  34. package/lazy_mcp_proxy.py +10 -9
  35. package/local_embedder.py +8 -1
  36. package/locales/pt-BR.json +1 -2
  37. package/model_breaker.py +6 -5
  38. package/package.json +2 -2
  39. package/process_limits.py +17 -3
  40. package/project_identity.py +19 -1
  41. package/project_scan.py +98 -0
  42. package/scout_access.py +48 -0
  43. package/shell_reads.py +67 -0
  44. package/smart_tool_daemon.py +144 -39
  45. package/tray.py +31 -0
  46. package/venv_launch.py +67 -0
  47. package/version.py +1 -1
  48. package/web_adapters/node/engine-home.mjs +42 -0
  49. package/web_adapters/node/package-lock.json +13 -0
  50. package/web_adapters/node/package.json +1 -0
@@ -0,0 +1,98 @@
1
+ """Whole-project scans of the files git tracks, read from disk: credentials committed earlier or sitting in a `.env`
2
+ file (the edit hook only sees the lines an edit writes, and the indexer skips secret files) and relative links of HTML
3
+ and Markdown files that point to nothing. Nothing is written and no value of a credential is returned.
4
+ """
5
+ import os
6
+ import subprocess
7
+
8
+ import credential_check
9
+ import link_check
10
+
11
+ DEFAULT_LIMIT = 25
12
+ MAX_BYTES = 2_000_000
13
+
14
+
15
+ def tracked_files(root):
16
+ """Project-relative paths of the files git tracks under `root` that exist on disk.
17
+
18
+ Parameters: root (str) project folder.
19
+ Returns: list of str with forward slashes, in git's order.
20
+ Raises: ValueError when git cannot list the folder (not a repository, git missing, timeout).
21
+ """
22
+ try:
23
+ listed = subprocess.run(["git", "ls-files", "-z"], cwd=root, capture_output=True, timeout=30,
24
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
25
+ except (OSError, subprocess.TimeoutExpired) as exc:
26
+ raise ValueError(f"git ls-files could not run in {root}: {exc}") from exc
27
+ if listed.returncode:
28
+ raise ValueError(f"git ls-files failed in {root}: {listed.stderr.decode('utf-8', 'replace').strip()[:300]}")
29
+ return [rel for rel in listed.stdout.decode("utf-8", "replace").split("\0")
30
+ if rel and os.path.isfile(os.path.join(root, rel))]
31
+
32
+
33
+ def _text(path):
34
+ """Contents of a file as UTF-8 text; None for a binary, oversized, non-UTF-8 or unreadable file."""
35
+ try:
36
+ if os.path.getsize(path) > MAX_BYTES:
37
+ return None
38
+ with open(path, "rb") as stream:
39
+ data = stream.read()
40
+ return None if b"\0" in data else data.decode("utf-8")
41
+ except (OSError, UnicodeDecodeError):
42
+ return None
43
+
44
+
45
+ def tracked_texts(root, extensions=None):
46
+ """The tracked files of the project with their text, one at a time.
47
+
48
+ Parameters: root (str) project folder; extensions (tuple of str or None) lowercase suffixes to keep, all files when None.
49
+ Returns: iterator of (path, text); text is None for a file that is not readable text.
50
+ Raises: ValueError when git cannot list the folder.
51
+ """
52
+ for rel in tracked_files(root):
53
+ if extensions is None or rel.lower().endswith(extensions):
54
+ yield rel, _text(os.path.join(root, rel))
55
+
56
+
57
+ def credentials(root, limit=DEFAULT_LIMIT):
58
+ """Credential shapes in every tracked text file, with the file and line and never the value.
59
+
60
+ Parameters: root (str) project folder; limit (int) findings returned.
61
+ Returns: dict {"findings": [{"path", "line", "kind"}], "total": int, "by_kind": {kind: count}, "files_checked": int,
62
+ "files_skipped": int}; skipped files are binary, over `MAX_BYTES` or not UTF-8.
63
+ Raises: ValueError when git cannot list the folder.
64
+ """
65
+ findings, checked, skipped = [], 0, 0
66
+ for rel, text in tracked_texts(root):
67
+ if text is None:
68
+ skipped += 1
69
+ continue
70
+ checked += 1
71
+ findings += [{"path": rel, **item} for item in credential_check.review(None, text)]
72
+ by_kind = {}
73
+ for item in findings:
74
+ by_kind[item["kind"]] = by_kind.get(item["kind"], 0) + 1
75
+ return {"findings": findings[:limit], "total": len(findings), "by_kind": by_kind, "files_checked": checked,
76
+ "files_skipped": skipped}
77
+
78
+
79
+ def links(root, limit=DEFAULT_LIMIT):
80
+ """Relative links of the tracked HTML and Markdown files that point to a missing file, and the links that could not
81
+ be decided (root-relative, template expressions, pages with a base element, unparsable files).
82
+
83
+ Parameters: root (str) project folder; limit (int) rows returned in each list.
84
+ Returns: dict {"broken": [{"path", "line", "link"}], "unchecked": [{"path", "line", "link", "why"}],
85
+ "total_broken": int, "total_unchecked": int, "files_checked": int, "files_skipped": int}.
86
+ Raises: ValueError when git cannot list the folder.
87
+ """
88
+ broken, unchecked, checked, skipped = [], [], 0, 0
89
+ for rel, text in tracked_texts(root, link_check.EXTENSIONS):
90
+ if text is None:
91
+ skipped += 1
92
+ continue
93
+ checked += 1
94
+ found = link_check.review(os.path.join(root, rel), None, text)
95
+ broken += [{"path": rel, **item} for item in found["broken"]]
96
+ unchecked += [{"path": rel, **item} for item in found["unchecked"]]
97
+ return {"broken": broken[:limit], "unchecked": unchecked[:limit], "total_broken": len(broken),
98
+ "total_unchecked": len(unchecked), "files_checked": checked, "files_skipped": skipped}
@@ -0,0 +1,48 @@
1
+ """Whether `smart_scout` can be called in a Claude Code session without stopping for a permission decision.
2
+
3
+ The hook payload carries the permission mode but not the session's allow rules, so the rules are read from the same
4
+ settings files Claude Code merges: user, project and project-local. Where the answer cannot be shown to be yes, it is no:
5
+ a hook that sends an agent to a tool it may not call leaves the work waiting on a prompt nobody answers."""
6
+ import json
7
+ import os
8
+
9
+ import endpoint_sync
10
+
11
+ TOOL = "mcp__smart-tool__smart_scout"
12
+ SERVER_RULES = frozenset({TOOL, "mcp__smart-tool__*", "mcp__smart-tool"})
13
+ OPEN_MODES = frozenset({"bypassPermissions"})
14
+ SETTINGS_FILES = ("settings.json", "settings.local.json")
15
+
16
+
17
+ def _settings(cwd):
18
+ """The parsed permission blocks of the settings files that exist; an unreadable or malformed file is skipped as
19
+ Claude Code skips it, and counts as no allow rule."""
20
+ folders = [endpoint_sync.claude_dir(), os.path.join(cwd or "", ".claude")] if cwd else [endpoint_sync.claude_dir()]
21
+ found = []
22
+ for folder in folders:
23
+ for name in SETTINGS_FILES:
24
+ try:
25
+ with open(os.path.join(folder, name), encoding="utf-8") as stream:
26
+ data = json.load(stream)
27
+ except (OSError, ValueError):
28
+ continue
29
+ if isinstance(data, dict) and isinstance(data.get("permissions"), dict):
30
+ found.append(data["permissions"])
31
+ return found
32
+
33
+
34
+ def callable_in(payload):
35
+ """True when the session runs in a mode that allows every tool or an allow rule names `smart_scout` (the tool, its
36
+ server or the server wildcard) and no deny rule does."""
37
+ if not isinstance(payload, dict):
38
+ return False
39
+ permissions = _settings(payload.get("cwd"))
40
+
41
+ def rules(key):
42
+ return {rule for block in permissions for rule in (block.get(key) or []) if isinstance(rule, str)}
43
+
44
+ if rules("deny") & SERVER_RULES:
45
+ return False
46
+ if payload.get("permission_mode") in OPEN_MODES or any(block.get("defaultMode") in OPEN_MODES for block in permissions):
47
+ return True
48
+ return bool(rules("allow") & SERVER_RULES)
package/shell_reads.py ADDED
@@ -0,0 +1,67 @@
1
+ """Source files read through the shell (`cat`, `head`, `sed -n`), counted per session so a run of them can be answered
2
+ with a tip.
3
+
4
+ One read of a known file is what the shell is for, and `smart_search` cannot return its exact lines, so no single read
5
+ is touched. A burst of them is an investigation done by reading, which `smart_scout` answers with only the lines that
6
+ matter: the third read inside the window carries the tip, then the tip waits before it repeats."""
7
+ import collections
8
+ import os
9
+ import threading
10
+ import time
11
+
12
+ import redirect_rule
13
+
14
+ READERS = frozenset({"cat", "head", "sed"})
15
+ SOURCE_SUFFIXES = frozenset({
16
+ ".py", ".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx", ".java", ".kt", ".go", ".rs", ".c", ".cc", ".cpp", ".h", ".hpp",
17
+ ".cs", ".rb", ".php", ".swift", ".scala", ".vue", ".svelte", ".sh", ".ps1", ".sql", ".lua", ".dart"})
18
+ BURST_READS = 3
19
+ WINDOW_S = 600
20
+ TIP_EVERY_S = 600
21
+ MAX_SESSIONS = 256
22
+ TIP = ("You have read {count} source files through the shell in the last minutes. For a question that spans several "
23
+ "files call mcp__smart-tool__smart_scout(project_root, question) (it returns only the lines that answer); keep "
24
+ "cat, head and sed -n for a file you already know and need verbatim.")
25
+
26
+ _LOCK = threading.Lock()
27
+ _READS = collections.OrderedDict()
28
+ _TIPPED = {}
29
+
30
+
31
+ def source_files(command, cwd):
32
+ """The existing source files, inside the session's reach, that the reading commands of a shell command print: `cat`,
33
+ `head` and `sed -n` at the start of a command, not a filter after a pipe."""
34
+ found = []
35
+ for segment, after_pipe in redirect_rule.segments(command or ""):
36
+ if after_pipe:
37
+ continue
38
+ tokens = redirect_rule._unwrap(redirect_rule._split(segment, False), {})
39
+ if not tokens or tokens[0].lower() not in READERS or (tokens[0].lower() == "sed" and "-n" not in tokens):
40
+ continue
41
+ for raw in redirect_rule._reader_files(tokens[0].lower(), tokens[1:]):
42
+ path = redirect_rule.resolve_path(os.path.expanduser(raw), cwd)
43
+ if path and os.path.splitext(path)[1].lower() in SOURCE_SUFFIXES and os.path.isfile(path) \
44
+ and redirect_rule._in_project(path, cwd):
45
+ found.append(path)
46
+ return found
47
+
48
+
49
+ def note(session_id, command, cwd, now=None):
50
+ """Counts the source reads of one shell call for the session and returns the tip when this call is the third inside
51
+ the window and no tip went out in the last TIP_EVERY_S; None otherwise."""
52
+ files = source_files(command, cwd)
53
+ if not files or not session_id:
54
+ return None
55
+ now = time.time() if now is None else now
56
+ with _LOCK:
57
+ reads = _READS.setdefault(session_id, collections.deque())
58
+ _READS.move_to_end(session_id)
59
+ while len(_READS) > MAX_SESSIONS:
60
+ _TIPPED.pop(_READS.popitem(last=False)[0], None)
61
+ reads.extend([now] * len(files))
62
+ while reads and now - reads[0] > WINDOW_S:
63
+ reads.popleft()
64
+ if len(reads) < BURST_READS or now - _TIPPED.get(session_id, -TIP_EVERY_S) < TIP_EVERY_S:
65
+ return None
66
+ _TIPPED[session_id] = now
67
+ return TIP.format(count=len(reads))
@@ -36,12 +36,14 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
36
36
 
37
37
  sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
38
38
  import atomic_io
39
+ import browser_bridge
39
40
  import browser_control
40
41
  import capabilities
41
42
  import client_hooks
42
43
  import install_runtime
43
44
  import integration_metrics
44
45
  import node_locator
46
+ import doc_turn
45
47
  import config
46
48
  import disk_cleanup
47
49
  import project_storage
@@ -58,7 +60,9 @@ import document_text
58
60
  import dependency_notice
59
61
  import dossier
60
62
  import scout
63
+ import scout_access
61
64
  import embedding_cache
65
+ import engine_home
62
66
  import model_defaults
63
67
  import model_health
64
68
  import project_admission
@@ -384,10 +388,10 @@ SERVER_INSTRUCTIONS = (
384
388
  TOOLS = [
385
389
  {
386
390
  "name": "project_manage",
387
- "description": "Manages folders and indexing. Every action takes project_root (the folder) or project_id. list gives a short line per project (a project whose folder is gone shows as unavailable with the reason); status shows storage, scope and jobs, and with a path inside a registered project answers for the deepest one that holds it (resolved_from). deps lists the known OSV advisories of every dependency the manifests of the project declare (package.json, requirements*.txt, pyproject.toml, go.mod), not only the ones an edit changed, at the version a package-lock.json beside a package.json resolved when it satisfies the range; only package names and versions leave the machine. 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. pr_impact (base, default HEAD; main or origin/main for a branch) returns a Markdown report of the change for a pull request: the functions the diff touches with their callers and the tests that reach them (those no test reaches are listed apart), the documentation entries it leaves out of date, the notes the edit hook would have added to the whole diff (comments, copies, dependency advisories) and the tests to run with their command; it publishes nothing. pr_impact_comment (pr, base required) posts that report as a comment on pull request pr through the gh CLI, from the project folder, and returns the comment URL; a rerun replaces the previous Smart Tool comment (marked by a hidden HTML marker) instead of stacking another, and the body carries no local path; it is a write to GitHub, so it refuses unless the user turned pr_comment on in the setup screen (Agent rules, off by default), and when gh is missing or not logged in; never call it without the user asking for the comment. hotspots (limit) ranks the code files by commits times lines, the riskiest to change; dead_code lists the functions no code calls and those only tests call (static call graph, candidates); import_cycles lists the groups of files that import each other; comments lists comments in the wrong place (commented-out code, history tags, loose docs, long inline blocks) across the code files, not only in an edit. graph without symbol reads the indexed view: coverage, references and static calls in Java, Angular, Python, Go 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, Go doc comment starting with the name; private, nested and override functions excluded) with coverage percent, excluding tests unless include_tests=true, for documenting a project that started without it; docs generate=true writes the documentation scope to docs/scope in the project in three levels tied to the code: technical pages by folder (an entry per public function anchored on path::name with signature, first doc line, layer, callers, calls and tests, plus a Mermaid flow by layer), functional.md (each entry point and the functions its flow reaches, by layer) and simple.md; the prose between the prose markers is kept by regeneration; docs write_prose=true writes the empty prose blocks with the Docs model of the setup (each paragraph checked against the code first) within about 40 s and says how many are left, call it again until none is; docs check=true reports anchors whose function changed signature or is gone and broken links; docs validate=true checks every claim of docs/scope against the code (anchors, links, line numbers, callers and tests, coverage, entry points, command-line options, prose names, counts, glossary, navigation, versions) and writes docs/scope/validation.md with pass/fail per check, the evidence, a score and the verdict (generate runs it too); docs with symbol lists where that function is documented; layers declares the project's layers (ordered highest first, each with path globs and annotations): without layers it returns the saved rule or a suggestion read from folder names and annotations, with files, symbols and calls between layers (direction down or up); pass layers to preview a rule and the same layers with confirm=true to save it in the project (.smart-tool/layers.json); 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; each view carries stale (not updated for 30 days, the test of the daily cleanup that removes them) and stale_bytes sums them; 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; each finding carries its fix (the file to edit or the command to run), applied by the agent when the user agrees, never by Smart Tool; mode=last returns the stored report instead of auditing again. redirect_proposals (no project_root) lists the redirect patterns proposed from allowed searches, most matched first, with a guide; redirect_decide decides them by ids: accept, instruct (tip without blocking), reject, or remove an accepted one. junk (no project_root) lists the registered projects that were never projects: a personal, system, application-data or build folder, a subfolder of a repository or of another project, a folder of projects, or a folder that no longer exists (on a drive or share that is mounted); with confirm=true it unregisters them and deletes only their index files, and the manifest says what went. A project is the folder where the session started, so smart_search and register refuse a folder that is not a project and index a new one only from the session that started in it. Jobs via smart_search_result.",
391
+ "description": "Manages folders and indexing. Every action takes project_root (the folder) or project_id. list gives a short line per project (a project whose folder is gone shows as unavailable with the reason); status shows storage, scope and jobs, and with a path inside a registered project answers for the deepest one that holds it (resolved_from). deps lists the known OSV advisories of every dependency the manifests of the project declare (package.json, requirements*.txt, pyproject.toml, go.mod), not only the ones an edit changed, at the version a package-lock.json beside a package.json resolved when it satisfies the range; only package names and versions leave the machine. 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. pr_impact (base, default HEAD; main or origin/main for a branch) returns a Markdown report of the change for a pull request: the functions the diff touches with their callers and the tests that reach them (those no test reaches are listed apart), the documentation entries it leaves out of date, the notes the edit hook would have added to the whole diff (comments, copies, dependency advisories) and the tests to run with their command; it publishes nothing. pr_impact_comment (pr, base required) posts that report as a comment on pull request pr through the gh CLI, from the project folder, and returns the comment URL; a rerun replaces the previous Smart Tool comment (marked by a hidden HTML marker) instead of stacking another, and the body carries no local path; it is a write to GitHub, so it refuses unless the user turned pr_comment on in the setup screen (Agent rules, off by default), and when gh is missing or not logged in; never call it without the user asking for the comment. hotspots (limit) ranks the code files by commits times lines, the riskiest to change; dead_code lists the functions no code calls and those only tests call (static call graph, candidates); import_cycles lists the groups of files that import each other; comments lists comments in the wrong place (commented-out code, history tags, loose docs, long inline blocks) across the code files, not only in an edit; credentials lists, per git-tracked text file (read from disk, so .env files and old commits count), the file and line of each credential shape (provider tokens, AWS keys, private-key headers), never the value, and skips lines that say they are an example; links lists the relative links of the tracked HTML and Markdown files that point to a missing file, plus the links it could not decide (root-relative, template expressions, pages with a base element), reported as unchecked, not broken. graph without symbol reads the indexed view: coverage, references and static calls in Java, Angular, Python, Go 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, Go doc comment starting with the name; private, nested and override functions excluded) with coverage percent, excluding tests unless include_tests=true, for documenting a project that started without it; docs generate=true writes the documentation scope to docs/scope in the project in three levels tied to the code: technical pages by folder (an entry per public function anchored on path::name with signature, first doc line, layer, callers, calls and tests, plus a Mermaid flow by layer), functional.md (each entry point and the functions its flow reaches, by layer) and simple.md; the prose between the prose markers is kept by regeneration; docs write_prose=true writes the empty prose blocks with the Docs model of the setup (each paragraph checked against the code first) within about 40 s and says how many are left, call it again until none is; docs check=true reports anchors whose function changed signature or is gone and broken links; docs validate=true checks every claim of docs/scope against the code (anchors, links, line numbers, callers and tests, coverage, entry points, command-line options, prose names, counts, glossary, navigation, versions) and writes docs/scope/validation.md with pass/fail per check, the evidence, a score and the verdict (generate runs it too); docs with symbol lists where that function is documented; layers declares the project's layers (ordered highest first, each with path globs and annotations): without layers it returns the saved rule or a suggestion read from folder names and annotations, with files, symbols and calls between layers (direction down or up); pass layers to preview a rule and the same layers with confirm=true to save it in the project (.smart-tool/layers.json); 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; each view carries stale (not updated for 30 days, the test of the daily cleanup that removes them) and stale_bytes sums them; 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; each finding carries its fix (the file to edit or the command to run), applied by the agent when the user agrees, never by Smart Tool; mode=last returns the stored report instead of auditing again. redirect_proposals (no project_root) lists the redirect patterns proposed from allowed searches, most matched first, with a guide; redirect_decide decides them by ids: accept, instruct (tip without blocking), reject, or remove an accepted one. junk (no project_root) lists the registered projects that were never projects: a personal, system, application-data or build folder, a subfolder of a repository or of another project, a folder of projects, or a folder that no longer exists (on a drive or share that is mounted); with confirm=true it unregisters them and deletes only their index files, and the manifest says what went. A project is the folder where the session started, so smart_search and register refuse a folder that is not a project and index a new one only from the session that started in it. Jobs via smart_search_result.",
388
392
  "inputSchema": {
389
393
  "type": "object", "properties": {
390
- "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", "layers", "affected_tests", "pr_impact", "pr_impact_comment", "hotspots", "dead_code", "import_cycles", "comments", "setup_audit", "redirect_proposals", "redirect_decide", "junk", "deps"]},
394
+ "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", "layers", "affected_tests", "pr_impact", "pr_impact_comment", "hotspots", "dead_code", "import_cycles", "comments", "credentials", "links", "setup_audit", "redirect_proposals", "redirect_decide", "junk", "deps"]},
391
395
  "ids": {"type": "array", "items": {"type": "string"}, "description": "redirect_decide: proposal ids from redirect_proposals (accepted ids for remove)"},
392
396
  "decision": {"type": "string", "enum": ["accept", "instruct", "reject", "remove"], "description": "redirect_decide: accept redirects matching calls to smart_search; instruct lets them run with a tip naming smart_search; reject discards; remove deletes an accepted pattern"},
393
397
  "finding_id": {"type": "string"},
@@ -1321,8 +1325,29 @@ def _grouped_yaml(profile, blocks, warning):
1321
1325
  return "\n".join(lines) + "\n"
1322
1326
 
1323
1327
 
1324
- HOME_DOWN_WARNING = ("The embeddings home is not running: index and search are lexical only until it answers (start or "
1325
- "reinstall casa-de-embeddings; it announces itself in ~/.casa-de-embeddings/run/daemon.json).")
1328
+ HOME_DOWN_WARNING = ("The embeddings home is not running: index and search are lexical only until it answers; Smart Tool "
1329
+ "installs, updates and starts it through the engine registry.")
1330
+
1331
+
1332
+ def _home_down_warning():
1333
+ """The lexical-only warning with the reason the last attempt to bring the embeddings home up gave."""
1334
+ return f"{HOME_DOWN_WARNING} {engine_home.explain(engine_home.ENGINES[0])}"
1335
+
1336
+
1337
+ def _maintain_engine_homes():
1338
+ """One pass over the engines Smart Tool consumes: the embeddings home is installed, updated and started when it is the
1339
+ chosen embedder. A failure is logged and shows in the search warnings; it never stops the loop."""
1340
+ try:
1341
+ if config.embedder() == "home":
1342
+ engine_home.ensure_when_due(engine_home.ENGINES[0])
1343
+ except Exception as exc:
1344
+ _log(f"engine home maintenance failed: {type(exc).__name__}: {exc}")
1345
+
1346
+
1347
+ def _engine_homes_loop():
1348
+ while True:
1349
+ _maintain_engine_homes()
1350
+ time.sleep(engine_home.RETRY_AFTER_S)
1326
1351
  RERANK_MISSING_WARNING = {
1327
1352
  "gateway": "Rerank not configured: hybrid lexical/vector order, less precise at the top. Configure a rerank_model.",
1328
1353
  "home": ("Rerank not configured: hybrid lexical/vector order, less precise at the top. Configure a rerank host in the "
@@ -1450,7 +1475,7 @@ def _perform_smart_search_isolated(arguments, job_id):
1450
1475
  source = "index+disk" if overlay else source
1451
1476
  warnings.append(notice)
1452
1477
  elif model == indexer.LEXICAL_MODEL:
1453
- warnings.append(HOME_DOWN_WARNING if config.embedder(cfg) == "home" else LEXICAL_WARNING)
1478
+ warnings.append(_home_down_warning() if config.embedder(cfg) == "home" else LEXICAL_WARNING)
1454
1479
  try:
1455
1480
  if not arguments.get("_existing_index_only"):
1456
1481
  _prepare_project_index(arguments, job_id, cfg, token, model=model)
@@ -2508,7 +2533,7 @@ def _project_action(arguments):
2508
2533
  action = arguments.get("action", "list")
2509
2534
  if action == "probe":
2510
2535
  return _probe_index_models()
2511
- if action in ('graph','compare','duplicates','duplicates_dismiss','duplicates_restore','docs','layers','affected_tests','pr_impact','pr_impact_comment','hotspots','dead_code','import_cycles','comments'):
2536
+ if action in ('graph','compare','duplicates','duplicates_dismiss','duplicates_restore','docs','layers','affected_tests','pr_impact','pr_impact_comment','hotspots','dead_code','import_cycles','comments','credentials','links'):
2512
2537
  # Análise somente leitura pode demorar; não prende o lock global de ações.
2513
2538
  key=arguments.get('project_id')
2514
2539
  if not isinstance(key,str) or not re.fullmatch(r'[a-f0-9]{16}',key):
@@ -2549,9 +2574,12 @@ def _project_action(arguments):
2549
2574
  if action=='layers':
2550
2575
  import layers
2551
2576
  return layers.report(project['root'],arguments.get('layers'),arguments.get('confirm',False),arguments.get('view_id'))
2552
- if action in ('hotspots','dead_code','import_cycles','comments'):
2577
+ if action in ('hotspots','dead_code','import_cycles','comments','credentials','links'):
2553
2578
  import code_health
2579
+ import project_scan
2554
2580
  limit=_parse_bounded_int(arguments.get('limit'),default=25,min_v=1,max_v=200,field_name='limit')
2581
+ if action in ('credentials','links'):
2582
+ return getattr(project_scan,action)(project['root'],limit)
2555
2583
  return getattr(code_health,action)(project['root'],arguments.get('view_id'),limit)
2556
2584
  if action=='pr_impact':
2557
2585
  import pr_impact
@@ -2625,7 +2653,7 @@ def _probe_index_models():
2625
2653
  result[kind] = {"status": "not_configured"}
2626
2654
  continue
2627
2655
  if kind == "embedding" and home_down:
2628
- result[kind] = {"status": "error", "error": HOME_DOWN_WARNING, "elapsed_s": 0.0}
2656
+ result[kind] = {"status": "error", "error": _home_down_warning(), "elapsed_s": 0.0}
2629
2657
  continue
2630
2658
  start = time.monotonic()
2631
2659
  try:
@@ -4501,7 +4529,7 @@ def _posttool_hook(handler):
4501
4529
 
4502
4530
 
4503
4531
  def _pretool_hook(handler):
4504
- """PreToolUse decision for the hook (Claude Code `type: "http"`, Codex via the thin command). Always 200 with `{}`,
4532
+ """PreToolUse decision for the hook (Claude Code and Codex, through the thin command). Always 200 with `{}`,
4505
4533
  `updatedInput`, `deny`, or `allow` only for the command the hook wrote to print a Smart Tool answer in Codex: a
4506
4534
  non-2xx answer would show as a hook error on every tool call, and any other `allow` would skip the user's
4507
4535
  permission prompt."""
@@ -4512,6 +4540,10 @@ def _pretool_hook(handler):
4512
4540
  _note_edit(payload)
4513
4541
  except Exception as exc:
4514
4542
  _log(f"edit index update skipped: {type(exc).__name__}: {exc}")
4543
+ try:
4544
+ doc_turn.note_tool(payload)
4545
+ except Exception as exc:
4546
+ _log(f"documentation registry note failed: {type(exc).__name__}: {exc}")
4515
4547
  output = _decide_within_budget(payload, client or None)
4516
4548
  except Exception as exc:
4517
4549
  _log(f"PreToolUse hook without a decision: {type(exc).__name__}: {exc}")
@@ -4527,6 +4559,38 @@ def _pretool_hook(handler):
4527
4559
  return output
4528
4560
 
4529
4561
 
4562
+ SUBAGENT_SCOUT_CONTEXT = ("Smart Tool is installed: for a question that spans several files, your first tool call is "
4563
+ "mcp__smart-tool__smart_scout(project_root, question) (project_root is your working directory); it "
4564
+ "returns the lines that answer, so do not Grep or Read before it. To find where a name is defined or used, call "
4565
+ "mcp__smart-tool__smart_search. Read only a file you already know.")
4566
+
4567
+
4568
+ def _subagent_start_hook(handler):
4569
+ """SubagentStart output: one sentence of context so every subagent knows smart_scout, in redirect and advise mode, and
4570
+ nothing in off mode or where smart_scout needs a permission prompt (the subagent would wait on it). It never denies:
4571
+ SubagentStart cannot block a launch."""
4572
+ try:
4573
+ payload = json.loads(handler._read_body(HOOK_MAX_BODY_BYTES) or b"{}")
4574
+ if config.hook_mode() == "off" or not scout_access.callable_in(payload):
4575
+ return {}
4576
+ except Exception as exc:
4577
+ _log(f"SubagentStart hook without context: {type(exc).__name__}: {exc}")
4578
+ return {}
4579
+ return {"hookSpecificOutput": {"hookEventName": "SubagentStart", "additionalContext": SUBAGENT_SCOUT_CONTEXT}}
4580
+
4581
+
4582
+ def _stop_hook(handler):
4583
+ """Stop output of the end-of-turn documentation step (doc_turn.on_stop), run in this request thread and never in
4584
+ the search executor; a failure reaches the user as a systemMessage naming the hook's origin, never silently."""
4585
+ try:
4586
+ payload = json.loads(handler._read_body(HOOK_MAX_BODY_BYTES) or b"{}")
4587
+ return doc_turn.on_stop(payload if isinstance(payload, dict) else {})
4588
+ except Exception as exc:
4589
+ _log(f"Stop hook failed: {type(exc).__name__}: {exc}")
4590
+ return {"systemMessage": f"[hook-origin=smart-tool] the end-of-turn documentation step failed: "
4591
+ f"{type(exc).__name__}: {_sanitize_text(str(exc))}"}
4592
+
4593
+
4530
4594
  def _session_audit_hook(handler):
4531
4595
  """SessionStart output of the session-start hook: the update notices both as systemMessage (shown to the user) and
4532
4596
  as additionalContext, plus the redirect proposals waiting for a decision as context; `{}` when there is nothing to
@@ -4811,28 +4875,61 @@ class MCPHandler(BaseHTTPRequestHandler):
4811
4875
  raise RequestTooLarge(f"Request body over {max_bytes} bytes")
4812
4876
  return self.rfile.read(length) if length else b""
4813
4877
 
4814
- def _mcp_method_not_allowed(self):
4815
- """405 for GET and DELETE on /mcp: no server-initiated stream and no client-ended sessions. The spec's answer for
4816
- both; the MCP SDK client treats any other status, 404 included, as a broken connection."""
4817
- self.send_response(405)
4818
- self.send_header("Allow", "POST")
4878
+ def _write_empty(self, status, allow=None):
4879
+ self.send_response(status)
4880
+ if allow:
4881
+ self.send_header("Allow", allow)
4819
4882
  self.send_header("Content-Length", "0")
4820
4883
  self.end_headers()
4821
4884
 
4885
+ def _mcp_method_not_allowed(self, allow="POST"):
4886
+ """405 for GET (and DELETE on /mcp): no server-initiated stream and, on /mcp, no client-ended sessions. The
4887
+ spec's answer for both; the MCP SDK client treats any other status, 404 included, as a broken connection."""
4888
+ self._write_empty(405, allow)
4889
+
4890
+ def _read_mcp_request(self):
4891
+ """The JSON-RPC object a POST to an MCP endpoint carries; None after answering the request itself when it is not
4892
+ one (not JSON by Content-Type, too large, not parseable, not an object)."""
4893
+ # A cross-origin <form> cannot send JSON and skips preflight, so requiring JSON shuts that path even without Origin.
4894
+ if "application/json" not in (self.headers.get("Content-Type") or "").lower():
4895
+ self._write_json(415, {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "Content-Type must be application/json"}})
4896
+ return None
4897
+ try:
4898
+ raw = self._read_body(MCP_MAX_REQUEST_BYTES)
4899
+ except ValueError as exc:
4900
+ status = 413 if isinstance(exc, RequestTooLarge) else 400
4901
+ self._write_json(status, {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": str(exc)}})
4902
+ return None
4903
+ try:
4904
+ request = json.loads(raw or b"{}")
4905
+ except json.JSONDecodeError:
4906
+ self._write_json(400, {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "parse error"}})
4907
+ return None
4908
+ if not isinstance(request, dict):
4909
+ self._write_json(400, {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "invalid request: expected a JSON object"}})
4910
+ return None
4911
+ return request
4912
+
4822
4913
  def do_DELETE(self):
4823
- """Routes a DELETE: 405 on /mcp, 404 elsewhere."""
4914
+ """Routes a DELETE: ends a Playwright bridge session, 405 on /mcp, 404 elsewhere."""
4824
4915
  if self._reject_foreign_origin():
4825
4916
  return
4917
+ if self.path == browser_bridge.PATH:
4918
+ self._write_empty(browser_bridge.BRIDGE.delete(self.headers.get("Mcp-Session-Id")))
4919
+ return
4826
4920
  if self.path == "/mcp":
4827
4921
  self._mcp_method_not_allowed()
4828
4922
  return
4829
4923
  self._write_json(404, {"error": "not found"})
4830
4924
 
4831
4925
  def do_GET(self):
4832
- """Routes a GET: 405 on /mcp, the health and status probes, the setup and project pages and their data; 404
4833
- elsewhere."""
4926
+ """Routes a GET: 405 on the MCP endpoints, the health and status probes, the setup and project pages and their
4927
+ data; 404 elsewhere."""
4834
4928
  if self._reject_foreign_origin():
4835
4929
  return
4930
+ if self.path == browser_bridge.PATH:
4931
+ self._mcp_method_not_allowed("POST, DELETE")
4932
+ return
4836
4933
  if self.path == "/mcp":
4837
4934
  self._mcp_method_not_allowed()
4838
4935
  return
@@ -4938,10 +5035,19 @@ class MCPHandler(BaseHTTPRequestHandler):
4938
5035
  self._write_json(200, result)
4939
5036
 
4940
5037
  def do_POST(self):
4941
- """Routes a POST: setup actions, the hook routes (/hooks/pretool, /hooks/posttool, /hooks/session-audit) and
4942
- the MCP endpoint (/mcp); anything else is 404."""
5038
+ """Routes a POST: the Playwright bridge, setup actions, the hook routes (/hooks/pretool, /hooks/posttool,
5039
+ /hooks/session-audit) and the MCP endpoint (/mcp); anything else is 404."""
4943
5040
  if self._reject_foreign_origin():
4944
5041
  return
5042
+ if self.path == browser_bridge.PATH:
5043
+ request = self._read_mcp_request()
5044
+ if request is not None:
5045
+ status, headers, payload = browser_bridge.BRIDGE.post(self.headers.get("Mcp-Session-Id"), request)
5046
+ if payload is None:
5047
+ self._write_empty(status)
5048
+ else:
5049
+ self._write_json(status, payload, headers)
5050
+ return
4945
5051
  if self.path == "/setup/projects":
4946
5052
  try:
4947
5053
  setup_ui.require_token(self.headers)
@@ -4965,6 +5071,12 @@ class MCPHandler(BaseHTTPRequestHandler):
4965
5071
  if urllib.parse.urlsplit(self.path).path == "/hooks/session-audit":
4966
5072
  self._write_json(200, _session_audit_hook(self))
4967
5073
  return
5074
+ if urllib.parse.urlsplit(self.path).path == "/hooks/subagent-start":
5075
+ self._write_json(200, _subagent_start_hook(self))
5076
+ return
5077
+ if urllib.parse.urlsplit(self.path).path == "/hooks/stop":
5078
+ self._write_json(200, _stop_hook(self))
5079
+ return
4968
5080
  if self.path == "/setup/notices":
4969
5081
  try:
4970
5082
  self._write_json(200, setup_ui.handle_notices())
@@ -4978,25 +5090,8 @@ class MCPHandler(BaseHTTPRequestHandler):
4978
5090
  if self.path != "/mcp":
4979
5091
  self._write_json(404, {"error": "not found"})
4980
5092
  return
4981
- # `<form>` de outra origem só consegue enviar urlencoded/multipart/text-plain e
4982
- # não é barrado por preflight: exigir JSON deixa esse caminho inutilizável mesmo
4983
- # que algum navegador entregue a requisição sem `Origin`.
4984
- if "application/json" not in (self.headers.get("Content-Type") or "").lower():
4985
- self._write_json(415, {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "Content-Type must be application/json"}})
4986
- return
4987
- try:
4988
- raw = self._read_body(MCP_MAX_REQUEST_BYTES)
4989
- except ValueError as exc:
4990
- status = 413 if isinstance(exc, RequestTooLarge) else 400
4991
- self._write_json(status, {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": str(exc)}})
4992
- return
4993
- try:
4994
- request = json.loads(raw or b"{}")
4995
- except json.JSONDecodeError:
4996
- self._write_json(400, {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "parse error"}})
4997
- return
4998
- if not isinstance(request, dict):
4999
- self._write_json(400, {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "invalid request: expected a JSON object"}})
5093
+ request = self._read_mcp_request()
5094
+ if request is None:
5000
5095
  return
5001
5096
 
5002
5097
  method = request.get("method")
@@ -5110,7 +5205,7 @@ def _probe_capabilities():
5110
5205
 
5111
5206
 
5112
5207
  def _heal_browser_control():
5113
- """Re-registers the Playwright MCP server when the Node it was registered with is gone (Node moved or reinstalled)."""
5208
+ """Re-registers the Playwright MCP server when its registration no longer works (browser_control.heal)."""
5114
5209
  try:
5115
5210
  browser_control.heal(_log)
5116
5211
  except Exception as exc:
@@ -5167,15 +5262,19 @@ def main():
5167
5262
  _log(f"running version not recorded: {type(exc).__name__}: {exc}")
5168
5263
  _write_registry(_BOUND_PORT)
5169
5264
  atexit.register(_remove_registry)
5265
+ _log(f"daemon started (pid {os.getpid()}, port {_BOUND_PORT})")
5170
5266
  try:
5171
5267
  for path in endpoint_sync.sync(f"http://127.0.0.1:{_BOUND_PORT}"):
5172
5268
  _log(f"port {_BOUND_PORT} written to {path}")
5173
5269
  except (OSError, ValueError) as exc:
5174
5270
  _log(f"clients not pointed to port {_BOUND_PORT}: {type(exc).__name__}: {exc}")
5175
5271
  atexit.register(BROWSER_SERVICE.close)
5272
+ atexit.register(browser_bridge.BRIDGE.stop)
5176
5273
  threading.Thread(target=_heal_browser_control, daemon=True).start()
5274
+ threading.Thread(target=_engine_homes_loop, daemon=True).start()
5177
5275
  try:
5178
5276
  recovered = project_store.recover_interrupted()
5277
+ _log(f"documentation registry: {doc_turn.resume_all()} interrupted function(s) back to pending")
5179
5278
  disk_cleanup.sweep([WEB_FETCH_VECTOR_ROOT], _log)
5180
5279
  project_store.import_known_legacy(indexer.INDEX_DIR)
5181
5280
  _PROJECT_MONITOR = project_monitor.ProjectMonitor(_enqueue_monitored_project)
@@ -5186,10 +5285,16 @@ def main():
5186
5285
  _log(f"project monitor unavailable: {_project_error(exc)}")
5187
5286
  audit = setup_audit.Scheduler(_audited_roots, _log)
5188
5287
  audit.start()
5288
+ reason = "the server loop returned"
5189
5289
  try:
5190
5290
  server.serve_forever()
5291
+ except BaseException as exc:
5292
+ reason = f"{type(exc).__name__}: {exc}"
5293
+ raise
5191
5294
  finally:
5295
+ _log(f"daemon stopping (pid {os.getpid()}): {reason}")
5192
5296
  audit.stop()
5297
+ browser_bridge.BRIDGE.stop()
5193
5298
  if _PROJECT_MONITOR:
5194
5299
  _PROJECT_MONITOR.stop()
5195
5300
  with _JOBS_LOCK:
package/tray.py CHANGED
@@ -31,6 +31,7 @@ import update_check
31
31
  import version
32
32
 
33
33
  POLL_INTERVAL_S = 45
34
+ SUPERVISE_RETRY_S = 2
34
35
  UPDATE_CHECK_INTERVAL_S = 24 * 3600
35
36
  NOTICE_INTERVAL_S = 600
36
37
  NOTICE_RETRY_S = 15
@@ -148,6 +149,35 @@ def _poll_loop(icon):
148
149
  time.sleep(POLL_INTERVAL_S)
149
150
 
150
151
 
152
+ def _supervise_daemon():
153
+ """Starts the daemon again as soon as it ends. Claude Code posts its hooks straight to the daemon's port, so every
154
+ tool call fails while nothing listens there, and the 45 s poll left that gap open. The process handle is waited on
155
+ (no polling while it runs); its end goes to the daemon log with the exit code, since a killed or crashed daemon
156
+ writes nothing itself. While the installer's marker is up it starts nothing: the installer starts the new build."""
157
+ while True:
158
+ try:
159
+ info = daemon_launcher.read_registry()
160
+ if not (info and daemon_launcher.health(info["url"], timeout=3)):
161
+ if daemon_launcher.updating():
162
+ time.sleep(SUPERVISE_RETRY_S)
163
+ continue
164
+ daemon_launcher.ensure_daemon_running()
165
+ info = daemon_launcher.read_registry()
166
+ pid = info.get("pid")
167
+ code = daemon_launcher.wait_for_exit(pid)
168
+ if code is None:
169
+ time.sleep(SUPERVISE_RETRY_S)
170
+ continue
171
+ if daemon_launcher.updating():
172
+ daemon_launcher.note_stop(f"daemon pid {pid} ended (exit code {code:#x}); the installer starts the new one")
173
+ time.sleep(SUPERVISE_RETRY_S)
174
+ continue
175
+ daemon_launcher.note_stop(f"daemon pid {pid} ended (exit code {code:#x}); the tray starts it again")
176
+ except Exception as exc:
177
+ _log(f"daemon supervision: {type(exc).__name__}: {exc}")
178
+ time.sleep(POLL_INTERVAL_S)
179
+
180
+
151
181
  def _toast(icon, title, lines, buttons, tag):
152
182
  """One notice: a toast Windows refuses goes to `tray.log` and, cut to what a balloon holds, to the tray balloon; a
153
183
  balloon that fails is logged too, and neither keeps the next notices from being shown."""
@@ -473,6 +503,7 @@ def main():
473
503
  ),
474
504
  )
475
505
  threading.Thread(target=_poll_loop, args=(icon,), daemon=True).start()
506
+ threading.Thread(target=_supervise_daemon, daemon=True).start()
476
507
  threading.Thread(target=_update_loop, args=(icon,), daemon=True).start()
477
508
  threading.Thread(target=_notice_loop, args=(icon,), daemon=True).start()
478
509
  try: