@allansantos-dev/smart-tool 0.9.81 → 0.9.83

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 (59) hide show
  1. package/CHANGELOG.md +115 -0
  2. package/NOTICE +1 -1
  3. package/README.md +73 -14
  4. package/affected_tests.py +9 -8
  5. package/agent_redirect.py +32 -0
  6. package/autostart.py +32 -25
  7. package/browser_bridge.py +320 -0
  8. package/browser_control.py +76 -39
  9. package/browser_service_client.py +1 -7
  10. package/client_hooks.py +41 -42
  11. package/code_graph.py +66 -21
  12. package/code_graph_java.mjs +21 -12
  13. package/code_health.py +14 -9
  14. package/codex_config.py +3 -0
  15. package/commit_check.py +184 -0
  16. package/daemon_launcher.py +37 -5
  17. package/doc_candidates.py +63 -0
  18. package/doc_check.py +9 -3
  19. package/doc_extras.py +2 -3
  20. package/doc_insights.py +26 -2
  21. package/doc_prose.py +59 -11
  22. package/doc_registry.py +241 -0
  23. package/doc_scope.py +205 -39
  24. package/doc_turn.py +205 -0
  25. package/doc_validate.py +52 -9
  26. package/document_converter.py +4 -4
  27. package/document_read.py +19 -11
  28. package/document_url.py +107 -0
  29. package/edit_shape.py +119 -0
  30. package/endpoint_sync.py +3 -21
  31. package/engine_home.py +95 -0
  32. package/hook_call.py +133 -0
  33. package/hook_decision.py +142 -7
  34. package/hooks/pre_commit.py +45 -0
  35. package/hooks/pretool_router.py +36 -30
  36. package/hooks/turn_end.py +40 -0
  37. package/index_views.py +5 -0
  38. package/install.py +24 -9
  39. package/lazy_mcp_proxy.py +10 -9
  40. package/local_embedder.py +8 -1
  41. package/locales/pt-BR.json +1 -2
  42. package/model_breaker.py +6 -5
  43. package/package.json +2 -2
  44. package/process_limits.py +17 -3
  45. package/project_identity.py +19 -1
  46. package/project_scan.py +98 -0
  47. package/release_notes.py +125 -0
  48. package/rename_preview.py +95 -0
  49. package/requester.py +1 -1
  50. package/scout_access.py +48 -0
  51. package/shell_reads.py +67 -0
  52. package/smart_tool_daemon.py +245 -50
  53. package/tray.py +31 -0
  54. package/venv_launch.py +67 -0
  55. package/version.py +1 -1
  56. package/web_adapters/node/engine-home.mjs +42 -0
  57. package/web_adapters/node/package-lock.json +13 -0
  58. package/web_adapters/node/package.json +1 -0
  59. package/web_fetch_many.py +61 -0
@@ -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
@@ -55,10 +57,13 @@ import index_inventory
55
57
  import usage_meter
56
58
  import document_read
57
59
  import document_text
60
+ import document_url
58
61
  import dependency_notice
59
62
  import dossier
60
63
  import scout
64
+ import scout_access
61
65
  import embedding_cache
66
+ import engine_home
62
67
  import model_defaults
63
68
  import model_health
64
69
  import project_admission
@@ -80,6 +85,7 @@ import local_embedder
80
85
  import low_priority
81
86
  import web_search_health
82
87
  import web_fetch
88
+ import web_fetch_many
83
89
  import version
84
90
  import update_check
85
91
  import gateway
@@ -384,10 +390,10 @@ SERVER_INSTRUCTIONS = (
384
390
  TOOLS = [
385
391
  {
386
392
  "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.",
393
+ "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. rename_preview lists, before a rename of the function in symbol, its definitions with file and lines, its callers with line (also the calls the graph left unresolved under that name), the tests that reach it, the files importing its module, the anchors of docs/scope and the lines of the README and docs text that name it, each list capped by limit with the totals in counts; it fails when the symbol is not found and writes nothing. release_notes drafts the notes of the next release in Markdown under a `## Draft since <base>` heading without a model: the commit subjects since base (default the latest tag), the public functions the diff touches with their caller and test counts, the decision notes that name them and the documentation entries the diff leaves out of date; it writes nothing and fails when there is no tag and no base. commit_check reviews the staged change (git diff --cached, not the working tree) with the notes the edit hook gives a finished diff (credentials, commented-out code, missing docstrings, duplicates, dependency advisories, link and edit notes), for edits the agent hook never saw (an IDE, hand edits, another agent); it writes nothing. commit_hook_install writes a git pre-commit hook in the project that prints that review to stderr at every commit and never blocks it (exit 0 always; a daemon that is down is one line, a check that fails is printed); it is opt-in, and refuses, naming what it found and changing nothing, when core.hooksPath is set, husky is used or a pre-commit that is not Smart Tool's exists; commit_hook_uninstall removes only that hook and puts back a backed-up hook that is not ours. 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
394
  "inputSchema": {
389
395
  "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"]},
396
+ "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", "rename_preview", "release_notes", "commit_check", "commit_hook_install", "commit_hook_uninstall", "setup_audit", "redirect_proposals", "redirect_decide", "junk", "deps"]},
391
397
  "ids": {"type": "array", "items": {"type": "string"}, "description": "redirect_decide: proposal ids from redirect_proposals (accepted ids for remove)"},
392
398
  "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
399
  "finding_id": {"type": "string"},
@@ -419,9 +425,9 @@ TOOLS = [
419
425
  "view_id": {"type": "string"}, "file_path": {"type": "string"},
420
426
  "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"},
421
427
  "probe": {"type": "boolean", "default": True, "description": "setup_audit: start/call each MCP server (initialize + tools/list); false reads configs only"},
422
- "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)"},
428
+ "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); release_notes: tag, branch or commit the draft starts from (default: the latest tag, and it fails when there is none)"},
423
429
  "pr": {"type": "integer", "minimum": 1, "description": "pr_impact_comment: number of the pull request to comment on"},
424
- "symbol": {"type": "string", "description": "graph: function, Class.method, class name or path::name to get its callers, calls, tests and importers; docs: where that function is documented"},
430
+ "symbol": {"type": "string", "description": "graph: function, Class.method, class name or path::name to get its callers, calls, tests and importers; docs: where that function is documented; rename_preview: the function to rename"},
425
431
  "depth": {"type": "integer", "minimum": 1, "maximum": 4, "default": 3, "description": "graph with symbol: call hops searched for tests"},
426
432
  "project_root": {"type": "string"}, "project_id": {"type": "string"},
427
433
  "job_id": {"type": "string"}, "watch": {"type": "boolean"},
@@ -579,7 +585,8 @@ TOOLS = [
579
585
  "description": (
580
586
  "Reads a known URL and returns only the answer to the prompt, written by the gateway's mini model - use instead of "
581
587
  "the native WebFetch. The page is cached for 24 h: another prompt on the same URL does not download it again. "
582
- "JavaScript-built pages are rendered in the browser. Reads PDFs as text, page by page; does not read localhost or internal networks."
588
+ "JavaScript-built pages are rendered in the browser. Reads PDFs as text, page by page; does not read localhost or internal networks. "
589
+ "For several URLs with the same prompt, use web_fetch_many."
583
590
  ),
584
591
  "inputSchema": {
585
592
  "type": "object",
@@ -590,6 +597,26 @@ TOOLS = [
590
597
  "required": ["url", "prompt"],
591
598
  },
592
599
  },
600
+ {
601
+ "name": "web_fetch_many",
602
+ "description": (
603
+ "Reads up to 8 known URLs in one call with the same prompt and returns one block per URL, in the order given: the "
604
+ "answer, or an ERROR line with the reason. Each URL is read exactly as web_fetch reads it (24 h cache, browser for "
605
+ "JavaScript-built pages, PDFs as text, no localhost or internal networks), 4 at a time, and a URL that fails never "
606
+ "hides the others; the call fails as a whole only when every URL failed. A URL repeated is read once. Use it "
607
+ "instead of several web_fetch calls when the same question applies to every page; use web_fetch for one URL or "
608
+ "a different prompt per page."
609
+ ),
610
+ "inputSchema": {
611
+ "type": "object",
612
+ "properties": {
613
+ "urls": {"type": "array", "items": {"type": "string"}, "minItems": 1, "maxItems": web_fetch_many.MAX_URLS,
614
+ "description": "Full http(s) URLs of the pages"},
615
+ "prompt": {"type": "string", "description": "What to extract or answer from each page"},
616
+ },
617
+ "required": ["urls", "prompt"],
618
+ },
619
+ },
593
620
  {
594
621
  "name": "read_document",
595
622
  "description": (
@@ -601,13 +628,16 @@ TOOLS = [
601
628
  "as markdown (headings, lists, tables) in parts of about 6,000 characters because a docx has no fixed "
602
629
  "pages; pptx per slide with the speaker notes; xlsx per sheet, one tab-separated line per row with the "
603
630
  "cached formula values; html as markdown in parts like a docx; csv as one sheet, one tab-separated line per row; "
604
- "epub per chapter in reading order. Use info_only first to size a large file and pick the pages you need. A scanned "
631
+ "epub per chapter in reading order. Use info_only first to size a large file and pick the pages you need. The path "
632
+ "may also be an http(s) URL of a PDF, docx, pptx, xlsx, csv or epub file: it is downloaded the way web_fetch "
633
+ "downloads (public addresses only, 5 MB cap), kept for 24 h and read the same way, with the same ranges; a URL "
634
+ "of a web page fails, read it with web_fetch. A scanned "
605
635
  "PDF (no text layer) fails with that reason; there is no OCR. Not for plain text or code: use Read."
606
636
  ),
607
637
  "inputSchema": {
608
638
  "type": "object",
609
639
  "properties": {
610
- "path": {"type": "string", "description": "Absolute path of the .pdf, .docx, .pptx, .xlsx, .html, .htm, .csv or .epub file"},
640
+ "path": {"type": "string", "description": "Absolute path of the .pdf, .docx, .pptx, .xlsx, .html, .htm, .csv or .epub file, or the http(s) URL of a PDF, docx, pptx, xlsx, csv or epub file"},
611
641
  "range": {"type": "string", "description": "Pages, slides, parts, chapters or sheets to read: `3`, `3-5`, `7-` (to the end), `-4` (the first four) or a comma list like `1,4-6`; a sheet name also works for a workbook. Default: from the first one"},
612
642
  "max_chars": {"type": "integer", "minimum": 1000, "maximum": document_read.MAX_CHARS_LIMIT, "default": document_read.DEFAULT_MAX_CHARS, "description": "Cap of the text returned (about four characters per token)"},
613
643
  "info_only": {"type": "boolean", "default": False, "description": "Return only the facts (type, size, counts, estimated tokens), no text"},
@@ -1321,8 +1351,29 @@ def _grouped_yaml(profile, blocks, warning):
1321
1351
  return "\n".join(lines) + "\n"
1322
1352
 
1323
1353
 
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).")
1354
+ HOME_DOWN_WARNING = ("The embeddings home is not running: index and search are lexical only until it answers; Smart Tool "
1355
+ "installs, updates and starts it through the engine registry.")
1356
+
1357
+
1358
+ def _home_down_warning():
1359
+ """The lexical-only warning with the reason the last attempt to bring the embeddings home up gave."""
1360
+ return f"{HOME_DOWN_WARNING} {engine_home.explain(engine_home.ENGINES[0])}"
1361
+
1362
+
1363
+ def _maintain_engine_homes():
1364
+ """One pass over the engines Smart Tool consumes: the embeddings home is installed, updated and started when it is the
1365
+ chosen embedder. A failure is logged and shows in the search warnings; it never stops the loop."""
1366
+ try:
1367
+ if config.embedder() == "home":
1368
+ engine_home.ensure_when_due(engine_home.ENGINES[0])
1369
+ except Exception as exc:
1370
+ _log(f"engine home maintenance failed: {type(exc).__name__}: {exc}")
1371
+
1372
+
1373
+ def _engine_homes_loop():
1374
+ while True:
1375
+ _maintain_engine_homes()
1376
+ time.sleep(engine_home.RETRY_AFTER_S)
1326
1377
  RERANK_MISSING_WARNING = {
1327
1378
  "gateway": "Rerank not configured: hybrid lexical/vector order, less precise at the top. Configure a rerank_model.",
1328
1379
  "home": ("Rerank not configured: hybrid lexical/vector order, less precise at the top. Configure a rerank host in the "
@@ -1450,7 +1501,7 @@ def _perform_smart_search_isolated(arguments, job_id):
1450
1501
  source = "index+disk" if overlay else source
1451
1502
  warnings.append(notice)
1452
1503
  elif model == indexer.LEXICAL_MODEL:
1453
- warnings.append(HOME_DOWN_WARNING if config.embedder(cfg) == "home" else LEXICAL_WARNING)
1504
+ warnings.append(_home_down_warning() if config.embedder(cfg) == "home" else LEXICAL_WARNING)
1454
1505
  try:
1455
1506
  if not arguments.get("_existing_index_only"):
1456
1507
  _prepare_project_index(arguments, job_id, cfg, token, model=model)
@@ -2508,7 +2559,7 @@ def _project_action(arguments):
2508
2559
  action = arguments.get("action", "list")
2509
2560
  if action == "probe":
2510
2561
  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'):
2562
+ 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','rename_preview','release_notes','commit_check'):
2512
2563
  # Análise somente leitura pode demorar; não prende o lock global de ações.
2513
2564
  key=arguments.get('project_id')
2514
2565
  if not isinstance(key,str) or not re.fullmatch(r'[a-f0-9]{16}',key):
@@ -2549,10 +2600,24 @@ def _project_action(arguments):
2549
2600
  if action=='layers':
2550
2601
  import layers
2551
2602
  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'):
2603
+ if action in ('hotspots','dead_code','import_cycles','comments','credentials','links'):
2553
2604
  import code_health
2605
+ import project_scan
2554
2606
  limit=_parse_bounded_int(arguments.get('limit'),default=25,min_v=1,max_v=200,field_name='limit')
2607
+ if action in ('credentials','links'):
2608
+ return getattr(project_scan,action)(project['root'],limit)
2555
2609
  return getattr(code_health,action)(project['root'],arguments.get('view_id'),limit)
2610
+ if action=='rename_preview':
2611
+ import rename_preview
2612
+ limit=_parse_bounded_int(arguments.get('limit'),default=30,min_v=1,max_v=200,field_name='limit')
2613
+ return rename_preview.preview(project['root'],arguments.get('symbol'),arguments.get('view_id'),limit)
2614
+ if action=='commit_check':
2615
+ import commit_check
2616
+ return commit_check.review(project['root'])
2617
+ if action=='release_notes':
2618
+ import release_notes
2619
+ limit=_parse_bounded_int(arguments.get('limit'),default=30,min_v=1,max_v=200,field_name='limit')
2620
+ return release_notes.draft(project['root'],arguments.get('base'),limit,arguments.get('view_id'))
2556
2621
  if action=='pr_impact':
2557
2622
  import pr_impact
2558
2623
  limit=_parse_bounded_int(arguments.get('limit'),default=30,min_v=1,max_v=200,field_name='limit')
@@ -2591,7 +2656,7 @@ def _project_action(arguments):
2591
2656
  root = project['root'] if project else arguments.get('project_root')
2592
2657
  with index_views.pin(root) if isinstance(root, str) and os.path.isdir(root) else contextlib.nullcontext():
2593
2658
  result = _project_action_locked(arguments)
2594
- if _PROJECT_MONITOR and arguments.get("action") not in (None, "list", "status", "inspect", "usage", "storage", "pin_view", "cleanup_preview", "cleanup_commit", "search_limits", "integration", "install_hook_preview", "install_hook"):
2659
+ if _PROJECT_MONITOR and arguments.get("action") not in (None, "list", "status", "inspect", "usage", "storage", "pin_view", "cleanup_preview", "cleanup_commit", "search_limits", "integration", "install_hook_preview", "install_hook", "commit_hook_install", "commit_hook_uninstall"):
2595
2660
  _PROJECT_MONITOR.refresh()
2596
2661
  return result
2597
2662
 
@@ -2625,7 +2690,7 @@ def _probe_index_models():
2625
2690
  result[kind] = {"status": "not_configured"}
2626
2691
  continue
2627
2692
  if kind == "embedding" and home_down:
2628
- result[kind] = {"status": "error", "error": HOME_DOWN_WARNING, "elapsed_s": 0.0}
2693
+ result[kind] = {"status": "error", "error": _home_down_warning(), "elapsed_s": 0.0}
2629
2694
  continue
2630
2695
  start = time.monotonic()
2631
2696
  try:
@@ -2684,6 +2749,9 @@ def _project_action_locked(arguments):
2684
2749
  project = project_store.get(key)
2685
2750
  if not project:
2686
2751
  raise ValueError("Project not registered.")
2752
+ if action in ("commit_hook_install", "commit_hook_uninstall"):
2753
+ import commit_check
2754
+ return (commit_check.install_hook if action == "commit_hook_install" else commit_check.uninstall_hook)(project["root"])
2687
2755
  if action == "status":
2688
2756
  if arguments.get("resolved_from"):
2689
2757
  return {"project": _project_payload(project), "resolved_from": arguments["resolved_from"],
@@ -4352,6 +4420,26 @@ def _handle_web_fetch(arguments):
4352
4420
  return _sanitize_text(f"Source: {page['final_url']} (read at {read_at}, {origin}{cut})\n\n{text}")
4353
4421
 
4354
4422
 
4423
+ def _handle_web_fetch_many(arguments):
4424
+ """Several URLs with one prompt, each through `_handle_web_fetch`: the per-URL report of web_fetch_many.render, and an
4425
+ error carrying that report when no URL could be read."""
4426
+ urls, prompt = arguments.get("urls"), arguments.get("prompt")
4427
+ started = time.monotonic()
4428
+ try:
4429
+ web_fetch_many.check(urls, prompt)
4430
+ except ValueError as exc:
4431
+ _metric("web_fetch_many", error=type(exc).__name__, elapsed_s=round(time.monotonic() - started, 2))
4432
+ raise
4433
+ results = web_fetch_many.read_many(urls, prompt, lambda url, text: _handle_web_fetch({"url": url, "prompt": text}))
4434
+ failed = sum(not result["ok"] for result in results)
4435
+ _metric("web_fetch_many", urls=len(results), distinct=len({web_fetch.normalize(url) for url in urls}), failed=failed,
4436
+ elapsed_s=round(time.monotonic() - started, 2))
4437
+ report = _sanitize_text(web_fetch_many.render(results))
4438
+ if failed == len(results):
4439
+ raise RuntimeError(report)
4440
+ return report
4441
+
4442
+
4355
4443
  def _web_route(tool, url):
4356
4444
  """Hook decision for native WebSearch/WebFetch: redirect to the Smart Tool only while it can answer."""
4357
4445
  if tool not in ("WebSearch", "WebFetch"):
@@ -4501,7 +4589,7 @@ def _posttool_hook(handler):
4501
4589
 
4502
4590
 
4503
4591
  def _pretool_hook(handler):
4504
- """PreToolUse decision for the hook (Claude Code `type: "http"`, Codex via the thin command). Always 200 with `{}`,
4592
+ """PreToolUse decision for the hook (Claude Code and Codex, through the thin command). Always 200 with `{}`,
4505
4593
  `updatedInput`, `deny`, or `allow` only for the command the hook wrote to print a Smart Tool answer in Codex: a
4506
4594
  non-2xx answer would show as a hook error on every tool call, and any other `allow` would skip the user's
4507
4595
  permission prompt."""
@@ -4512,6 +4600,10 @@ def _pretool_hook(handler):
4512
4600
  _note_edit(payload)
4513
4601
  except Exception as exc:
4514
4602
  _log(f"edit index update skipped: {type(exc).__name__}: {exc}")
4603
+ try:
4604
+ doc_turn.note_tool(payload)
4605
+ except Exception as exc:
4606
+ _log(f"documentation registry note failed: {type(exc).__name__}: {exc}")
4515
4607
  output = _decide_within_budget(payload, client or None)
4516
4608
  except Exception as exc:
4517
4609
  _log(f"PreToolUse hook without a decision: {type(exc).__name__}: {exc}")
@@ -4527,6 +4619,55 @@ def _pretool_hook(handler):
4527
4619
  return output
4528
4620
 
4529
4621
 
4622
+ SUBAGENT_SCOUT_CONTEXT = ("Smart Tool is installed: for a question that spans several files, your first tool call is "
4623
+ "mcp__smart-tool__smart_scout(project_root, question) (project_root is your working directory); it "
4624
+ "returns the lines that answer, so do not Grep or Read before it. To find where a name is defined or used, call "
4625
+ "mcp__smart-tool__smart_search. Read only a file you already know.")
4626
+
4627
+
4628
+ def _subagent_start_hook(handler):
4629
+ """SubagentStart output: one sentence of context so every subagent knows smart_scout, in redirect and advise mode, and
4630
+ nothing in off mode or where smart_scout needs a permission prompt (the subagent would wait on it). It never denies:
4631
+ SubagentStart cannot block a launch."""
4632
+ try:
4633
+ payload = json.loads(handler._read_body(HOOK_MAX_BODY_BYTES) or b"{}")
4634
+ if config.hook_mode() == "off" or not scout_access.callable_in(payload):
4635
+ return {}
4636
+ except Exception as exc:
4637
+ _log(f"SubagentStart hook without context: {type(exc).__name__}: {exc}")
4638
+ return {}
4639
+ return {"hookSpecificOutput": {"hookEventName": "SubagentStart", "additionalContext": SUBAGENT_SCOUT_CONTEXT}}
4640
+
4641
+
4642
+ def _stop_hook(handler):
4643
+ """Stop output of the end-of-turn documentation step (doc_turn.on_stop), run in this request thread and never in
4644
+ the search executor; a failure reaches the user as a systemMessage naming the hook's origin, never silently."""
4645
+ try:
4646
+ payload = json.loads(handler._read_body(HOOK_MAX_BODY_BYTES) or b"{}")
4647
+ return doc_turn.on_stop(payload if isinstance(payload, dict) else {})
4648
+ except Exception as exc:
4649
+ _log(f"Stop hook failed: {type(exc).__name__}: {exc}")
4650
+ return {"systemMessage": f"[hook-origin=smart-tool] the end-of-turn documentation step failed: "
4651
+ f"{type(exc).__name__}: {_sanitize_text(str(exc))}"}
4652
+
4653
+
4654
+ def _commit_check_hook(handler):
4655
+ """Answer of the git pre-commit hook (hooks/pre_commit.py): `{ok: True, files, notes}` with the review of the staged
4656
+ change of the registered project whose folder the hook sent, or `{ok: False, error}` naming why it could not run
4657
+ (an unregistered folder included); always 200, the hook prints the failure and lets the commit go."""
4658
+ try:
4659
+ import commit_check
4660
+ payload = json.loads(handler._read_body(HOOK_MAX_BODY_BYTES) or b"{}")
4661
+ root = payload.get("root") if isinstance(payload, dict) else None
4662
+ if not isinstance(root, str) or not os.path.isabs(root):
4663
+ raise ValueError("the hook sent no project folder")
4664
+ project = project_store.get(_with_project_id({"project_root": root})["project_id"])
4665
+ return {"ok": True, **commit_check.review(project["root"])}
4666
+ except Exception as exc:
4667
+ _log(f"Commit check failed: {type(exc).__name__}: {exc}")
4668
+ return {"ok": False, "error": f"{type(exc).__name__}: {_sanitize_text(str(exc))}"}
4669
+
4670
+
4530
4671
  def _session_audit_hook(handler):
4531
4672
  """SessionStart output of the session-start hook: the update notices both as systemMessage (shown to the user) and
4532
4673
  as additionalContext, plus the redirect proposals waiting for a decision as context; `{}` when there is nothing to
@@ -4552,19 +4693,28 @@ def _handle_read_document(arguments):
4552
4693
  """read_document: facts and a page, slide, sheet, part or chapter range of a PDF, docx, pptx, xlsx, html, csv or epub as compact text (see
4553
4694
  document_read). Fails loudly, with the reason, for a path that is not absolute or readable, an unsupported or
4554
4695
  oversized file, a password, a scanned PDF, a corrupt or hostile package and a range outside the document; one metric
4555
- row records the kind, the estimated tokens of the whole text and of the answer."""
4696
+ row records the kind, the estimated tokens of the whole text and of the answer. A `path` that starts with http:// or
4697
+ https:// is downloaded and read by document_url instead (the kind comes from the URL path: no query or credentials
4698
+ reach the metric); every other value takes the file path above."""
4556
4699
  started = time.monotonic()
4557
4700
  unknown = sorted(set(arguments) - {"path", "range", "max_chars", "info_only"})
4558
4701
  if unknown:
4559
4702
  raise ValueError(f"read_document does not take {', '.join(unknown)}")
4703
+ path = arguments.get("path")
4704
+ from_url = document_url.is_url(path)
4560
4705
  try:
4561
- text = document_read.read(arguments.get("path"), arguments.get("range") or None,
4562
- arguments.get("max_chars", document_read.DEFAULT_MAX_CHARS),
4563
- bool(arguments.get("info_only")))
4706
+ if from_url:
4707
+ text = document_url.read(path, arguments.get("range") or None,
4708
+ arguments.get("max_chars", document_read.DEFAULT_MAX_CHARS),
4709
+ bool(arguments.get("info_only")), started + WEB_FETCH_TIMEOUT_S)
4710
+ else:
4711
+ text = document_read.read(path, arguments.get("range") or None,
4712
+ arguments.get("max_chars", document_read.DEFAULT_MAX_CHARS),
4713
+ bool(arguments.get("info_only")))
4564
4714
  except Exception as exc:
4565
4715
  _metric("read_document", error=type(exc).__name__, elapsed_s=round(time.monotonic() - started, 2))
4566
4716
  raise
4567
- _metric("read_document", kind=os.path.splitext(str(arguments.get("path")))[1].lower(),
4717
+ _metric("read_document", kind=document_url.extension(path) if from_url else os.path.splitext(str(path))[1].lower(),
4568
4718
  answer_tokens=document_read.estimate_tokens(text), elapsed_s=round(time.monotonic() - started, 2))
4569
4719
  return _sanitize_text(text)
4570
4720
 
@@ -4572,6 +4722,7 @@ def _handle_read_document(arguments):
4572
4722
  _TOOL_HANDLERS = {
4573
4723
  "read_document": _handle_read_document,
4574
4724
  "web_fetch": _handle_web_fetch,
4725
+ "web_fetch_many": _handle_web_fetch_many,
4575
4726
  "project_manage": _handle_project_manage,
4576
4727
  "smart_search": _handle_smart_search,
4577
4728
  "smart_search_result": _handle_smart_search_result,
@@ -4811,28 +4962,61 @@ class MCPHandler(BaseHTTPRequestHandler):
4811
4962
  raise RequestTooLarge(f"Request body over {max_bytes} bytes")
4812
4963
  return self.rfile.read(length) if length else b""
4813
4964
 
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")
4965
+ def _write_empty(self, status, allow=None):
4966
+ self.send_response(status)
4967
+ if allow:
4968
+ self.send_header("Allow", allow)
4819
4969
  self.send_header("Content-Length", "0")
4820
4970
  self.end_headers()
4821
4971
 
4972
+ def _mcp_method_not_allowed(self, allow="POST"):
4973
+ """405 for GET (and DELETE on /mcp): no server-initiated stream and, on /mcp, no client-ended sessions. The
4974
+ spec's answer for both; the MCP SDK client treats any other status, 404 included, as a broken connection."""
4975
+ self._write_empty(405, allow)
4976
+
4977
+ def _read_mcp_request(self):
4978
+ """The JSON-RPC object a POST to an MCP endpoint carries; None after answering the request itself when it is not
4979
+ one (not JSON by Content-Type, too large, not parseable, not an object)."""
4980
+ # A cross-origin <form> cannot send JSON and skips preflight, so requiring JSON shuts that path even without Origin.
4981
+ if "application/json" not in (self.headers.get("Content-Type") or "").lower():
4982
+ self._write_json(415, {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "Content-Type must be application/json"}})
4983
+ return None
4984
+ try:
4985
+ raw = self._read_body(MCP_MAX_REQUEST_BYTES)
4986
+ except ValueError as exc:
4987
+ status = 413 if isinstance(exc, RequestTooLarge) else 400
4988
+ self._write_json(status, {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": str(exc)}})
4989
+ return None
4990
+ try:
4991
+ request = json.loads(raw or b"{}")
4992
+ except json.JSONDecodeError:
4993
+ self._write_json(400, {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "parse error"}})
4994
+ return None
4995
+ if not isinstance(request, dict):
4996
+ self._write_json(400, {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "invalid request: expected a JSON object"}})
4997
+ return None
4998
+ return request
4999
+
4822
5000
  def do_DELETE(self):
4823
- """Routes a DELETE: 405 on /mcp, 404 elsewhere."""
5001
+ """Routes a DELETE: ends a Playwright bridge session, 405 on /mcp, 404 elsewhere."""
4824
5002
  if self._reject_foreign_origin():
4825
5003
  return
5004
+ if self.path == browser_bridge.PATH:
5005
+ self._write_empty(browser_bridge.BRIDGE.delete(self.headers.get("Mcp-Session-Id")))
5006
+ return
4826
5007
  if self.path == "/mcp":
4827
5008
  self._mcp_method_not_allowed()
4828
5009
  return
4829
5010
  self._write_json(404, {"error": "not found"})
4830
5011
 
4831
5012
  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."""
5013
+ """Routes a GET: 405 on the MCP endpoints, the health and status probes, the setup and project pages and their
5014
+ data; 404 elsewhere."""
4834
5015
  if self._reject_foreign_origin():
4835
5016
  return
5017
+ if self.path == browser_bridge.PATH:
5018
+ self._mcp_method_not_allowed("POST, DELETE")
5019
+ return
4836
5020
  if self.path == "/mcp":
4837
5021
  self._mcp_method_not_allowed()
4838
5022
  return
@@ -4938,10 +5122,19 @@ class MCPHandler(BaseHTTPRequestHandler):
4938
5122
  self._write_json(200, result)
4939
5123
 
4940
5124
  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."""
5125
+ """Routes a POST: the Playwright bridge, setup actions, the hook routes (/hooks/pretool, /hooks/posttool,
5126
+ /hooks/session-audit, /hooks/commit-check) and the MCP endpoint (/mcp); anything else is 404."""
4943
5127
  if self._reject_foreign_origin():
4944
5128
  return
5129
+ if self.path == browser_bridge.PATH:
5130
+ request = self._read_mcp_request()
5131
+ if request is not None:
5132
+ status, headers, payload = browser_bridge.BRIDGE.post(self.headers.get("Mcp-Session-Id"), request)
5133
+ if payload is None:
5134
+ self._write_empty(status)
5135
+ else:
5136
+ self._write_json(status, payload, headers)
5137
+ return
4945
5138
  if self.path == "/setup/projects":
4946
5139
  try:
4947
5140
  setup_ui.require_token(self.headers)
@@ -4965,6 +5158,15 @@ class MCPHandler(BaseHTTPRequestHandler):
4965
5158
  if urllib.parse.urlsplit(self.path).path == "/hooks/session-audit":
4966
5159
  self._write_json(200, _session_audit_hook(self))
4967
5160
  return
5161
+ if urllib.parse.urlsplit(self.path).path == "/hooks/subagent-start":
5162
+ self._write_json(200, _subagent_start_hook(self))
5163
+ return
5164
+ if urllib.parse.urlsplit(self.path).path == "/hooks/stop":
5165
+ self._write_json(200, _stop_hook(self))
5166
+ return
5167
+ if urllib.parse.urlsplit(self.path).path == "/hooks/commit-check":
5168
+ self._write_json(200, _commit_check_hook(self))
5169
+ return
4968
5170
  if self.path == "/setup/notices":
4969
5171
  try:
4970
5172
  self._write_json(200, setup_ui.handle_notices())
@@ -4978,25 +5180,8 @@ class MCPHandler(BaseHTTPRequestHandler):
4978
5180
  if self.path != "/mcp":
4979
5181
  self._write_json(404, {"error": "not found"})
4980
5182
  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"}})
5183
+ request = self._read_mcp_request()
5184
+ if request is None:
5000
5185
  return
5001
5186
 
5002
5187
  method = request.get("method")
@@ -5110,7 +5295,7 @@ def _probe_capabilities():
5110
5295
 
5111
5296
 
5112
5297
  def _heal_browser_control():
5113
- """Re-registers the Playwright MCP server when the Node it was registered with is gone (Node moved or reinstalled)."""
5298
+ """Re-registers the Playwright MCP server when its registration no longer works (browser_control.heal)."""
5114
5299
  try:
5115
5300
  browser_control.heal(_log)
5116
5301
  except Exception as exc:
@@ -5167,15 +5352,19 @@ def main():
5167
5352
  _log(f"running version not recorded: {type(exc).__name__}: {exc}")
5168
5353
  _write_registry(_BOUND_PORT)
5169
5354
  atexit.register(_remove_registry)
5355
+ _log(f"daemon started (pid {os.getpid()}, port {_BOUND_PORT})")
5170
5356
  try:
5171
5357
  for path in endpoint_sync.sync(f"http://127.0.0.1:{_BOUND_PORT}"):
5172
5358
  _log(f"port {_BOUND_PORT} written to {path}")
5173
5359
  except (OSError, ValueError) as exc:
5174
5360
  _log(f"clients not pointed to port {_BOUND_PORT}: {type(exc).__name__}: {exc}")
5175
5361
  atexit.register(BROWSER_SERVICE.close)
5362
+ atexit.register(browser_bridge.BRIDGE.stop)
5176
5363
  threading.Thread(target=_heal_browser_control, daemon=True).start()
5364
+ threading.Thread(target=_engine_homes_loop, daemon=True).start()
5177
5365
  try:
5178
5366
  recovered = project_store.recover_interrupted()
5367
+ _log(f"documentation registry: {doc_turn.resume_all()} interrupted function(s) back to pending")
5179
5368
  disk_cleanup.sweep([WEB_FETCH_VECTOR_ROOT], _log)
5180
5369
  project_store.import_known_legacy(indexer.INDEX_DIR)
5181
5370
  _PROJECT_MONITOR = project_monitor.ProjectMonitor(_enqueue_monitored_project)
@@ -5186,10 +5375,16 @@ def main():
5186
5375
  _log(f"project monitor unavailable: {_project_error(exc)}")
5187
5376
  audit = setup_audit.Scheduler(_audited_roots, _log)
5188
5377
  audit.start()
5378
+ reason = "the server loop returned"
5189
5379
  try:
5190
5380
  server.serve_forever()
5381
+ except BaseException as exc:
5382
+ reason = f"{type(exc).__name__}: {exc}"
5383
+ raise
5191
5384
  finally:
5385
+ _log(f"daemon stopping (pid {os.getpid()}): {reason}")
5192
5386
  audit.stop()
5387
+ browser_bridge.BRIDGE.stop()
5193
5388
  if _PROJECT_MONITOR:
5194
5389
  _PROJECT_MONITOR.stop()
5195
5390
  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: