@allansantos-dev/smart-tool 0.9.80 → 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.
- package/CHANGELOG.md +129 -0
- package/NOTICE +1 -1
- package/README.md +59 -14
- package/agent_redirect.py +32 -0
- package/autostart.py +32 -25
- package/browser_bridge.py +320 -0
- package/browser_control.py +76 -39
- package/browser_service_client.py +1 -7
- package/client_hooks.py +42 -41
- package/code_graph.py +56 -15
- package/code_graph_java.mjs +21 -12
- package/code_health.py +19 -12
- package/code_impact.py +1 -1
- package/codex_config.py +3 -0
- package/config.py +35 -0
- package/daemon_launcher.py +37 -5
- package/doc_candidates.py +63 -0
- package/doc_check.py +9 -3
- package/doc_extras.py +2 -3
- package/doc_insights.py +26 -2
- package/doc_prose.py +59 -11
- package/doc_registry.py +241 -0
- package/doc_scope.py +205 -39
- package/doc_turn.py +205 -0
- package/doc_validate.py +52 -9
- package/document_read.py +4 -2
- package/dossier.py +40 -5
- package/edit_shape.py +119 -0
- package/endpoint_sync.py +3 -21
- package/engine_home.py +95 -0
- package/hook_call.py +132 -0
- package/hook_decision.py +337 -23
- package/hooks/pretool_router.py +36 -29
- package/hooks/turn_end.py +40 -0
- package/index_views.py +5 -0
- package/install.py +90 -36
- package/install_runtime.py +24 -10
- package/lazy_mcp_proxy.py +10 -9
- package/link_check.py +69 -0
- package/local_embedder.py +9 -2
- package/locales/pt-BR.json +72 -4
- package/model_breaker.py +6 -5
- package/model_client.py +1 -1
- package/model_health.py +24 -6
- package/notice_action.py +9 -0
- package/package.json +2 -2
- package/pr_comment.py +94 -0
- package/pr_impact.py +216 -35
- package/process_limits.py +17 -3
- package/project_admission.py +17 -15
- package/project_identity.py +19 -1
- package/project_scan.py +98 -0
- package/removed_callers.py +146 -0
- package/scout_access.py +48 -0
- package/setup_ui.py +33 -4
- package/shell_reads.py +67 -0
- package/smart_tool_daemon.py +149 -39
- package/tray.py +60 -9
- package/update_splash.py +2 -2
- package/venv_launch.py +67 -0
- package/version.py +1 -1
- package/web_adapters/node/engine-home.mjs +42 -0
- package/web_adapters/node/package-lock.json +13 -0
- package/web_adapters/node/package.json +1 -0
- package/web_document_graph.py +12 -1
package/smart_tool_daemon.py
CHANGED
|
@@ -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. 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", "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"},
|
|
@@ -420,6 +424,7 @@ TOOLS = [
|
|
|
420
424
|
"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
425
|
"probe": {"type": "boolean", "default": True, "description": "setup_audit: start/call each MCP server (initialize + tools/list); false reads configs only"},
|
|
422
426
|
"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)"},
|
|
427
|
+
"pr": {"type": "integer", "minimum": 1, "description": "pr_impact_comment: number of the pull request to comment on"},
|
|
423
428
|
"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"},
|
|
424
429
|
"depth": {"type": "integer", "minimum": 1, "maximum": 4, "default": 3, "description": "graph with symbol: call hops searched for tests"},
|
|
425
430
|
"project_root": {"type": "string"}, "project_id": {"type": "string"},
|
|
@@ -1320,8 +1325,29 @@ def _grouped_yaml(profile, blocks, warning):
|
|
|
1320
1325
|
return "\n".join(lines) + "\n"
|
|
1321
1326
|
|
|
1322
1327
|
|
|
1323
|
-
HOME_DOWN_WARNING = ("The embeddings home is not running: index and search are lexical only until it answers
|
|
1324
|
-
"
|
|
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)
|
|
1325
1351
|
RERANK_MISSING_WARNING = {
|
|
1326
1352
|
"gateway": "Rerank not configured: hybrid lexical/vector order, less precise at the top. Configure a rerank_model.",
|
|
1327
1353
|
"home": ("Rerank not configured: hybrid lexical/vector order, less precise at the top. Configure a rerank host in the "
|
|
@@ -1449,7 +1475,7 @@ def _perform_smart_search_isolated(arguments, job_id):
|
|
|
1449
1475
|
source = "index+disk" if overlay else source
|
|
1450
1476
|
warnings.append(notice)
|
|
1451
1477
|
elif model == indexer.LEXICAL_MODEL:
|
|
1452
|
-
warnings.append(
|
|
1478
|
+
warnings.append(_home_down_warning() if config.embedder(cfg) == "home" else LEXICAL_WARNING)
|
|
1453
1479
|
try:
|
|
1454
1480
|
if not arguments.get("_existing_index_only"):
|
|
1455
1481
|
_prepare_project_index(arguments, job_id, cfg, token, model=model)
|
|
@@ -2507,7 +2533,7 @@ def _project_action(arguments):
|
|
|
2507
2533
|
action = arguments.get("action", "list")
|
|
2508
2534
|
if action == "probe":
|
|
2509
2535
|
return _probe_index_models()
|
|
2510
|
-
if action in ('graph','compare','duplicates','duplicates_dismiss','duplicates_restore','docs','layers','affected_tests','pr_impact','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'):
|
|
2511
2537
|
# Análise somente leitura pode demorar; não prende o lock global de ações.
|
|
2512
2538
|
key=arguments.get('project_id')
|
|
2513
2539
|
if not isinstance(key,str) or not re.fullmatch(r'[a-f0-9]{16}',key):
|
|
@@ -2548,14 +2574,21 @@ def _project_action(arguments):
|
|
|
2548
2574
|
if action=='layers':
|
|
2549
2575
|
import layers
|
|
2550
2576
|
return layers.report(project['root'],arguments.get('layers'),arguments.get('confirm',False),arguments.get('view_id'))
|
|
2551
|
-
if action in ('hotspots','dead_code','import_cycles','comments'):
|
|
2577
|
+
if action in ('hotspots','dead_code','import_cycles','comments','credentials','links'):
|
|
2552
2578
|
import code_health
|
|
2579
|
+
import project_scan
|
|
2553
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)
|
|
2554
2583
|
return getattr(code_health,action)(project['root'],arguments.get('view_id'),limit)
|
|
2555
2584
|
if action=='pr_impact':
|
|
2556
2585
|
import pr_impact
|
|
2557
2586
|
limit=_parse_bounded_int(arguments.get('limit'),default=30,min_v=1,max_v=200,field_name='limit')
|
|
2558
2587
|
return pr_impact.report(project['root'],arguments.get('base','HEAD'),limit,arguments.get('view_id'))
|
|
2588
|
+
if action=='pr_impact_comment':
|
|
2589
|
+
import pr_comment
|
|
2590
|
+
limit=_parse_bounded_int(arguments.get('limit'),default=30,min_v=1,max_v=200,field_name='limit')
|
|
2591
|
+
return pr_comment.publish(project['root'],arguments.get('pr'),arguments.get('base'),limit,arguments.get('view_id'))
|
|
2559
2592
|
if action=='affected_tests':
|
|
2560
2593
|
import affected_tests
|
|
2561
2594
|
limit=_parse_bounded_int(arguments.get('limit'),default=30,min_v=1,max_v=200,field_name='limit')
|
|
@@ -2620,7 +2653,7 @@ def _probe_index_models():
|
|
|
2620
2653
|
result[kind] = {"status": "not_configured"}
|
|
2621
2654
|
continue
|
|
2622
2655
|
if kind == "embedding" and home_down:
|
|
2623
|
-
result[kind] = {"status": "error", "error":
|
|
2656
|
+
result[kind] = {"status": "error", "error": _home_down_warning(), "elapsed_s": 0.0}
|
|
2624
2657
|
continue
|
|
2625
2658
|
start = time.monotonic()
|
|
2626
2659
|
try:
|
|
@@ -4496,7 +4529,7 @@ def _posttool_hook(handler):
|
|
|
4496
4529
|
|
|
4497
4530
|
|
|
4498
4531
|
def _pretool_hook(handler):
|
|
4499
|
-
"""PreToolUse decision for the hook (Claude Code
|
|
4532
|
+
"""PreToolUse decision for the hook (Claude Code and Codex, through the thin command). Always 200 with `{}`,
|
|
4500
4533
|
`updatedInput`, `deny`, or `allow` only for the command the hook wrote to print a Smart Tool answer in Codex: a
|
|
4501
4534
|
non-2xx answer would show as a hook error on every tool call, and any other `allow` would skip the user's
|
|
4502
4535
|
permission prompt."""
|
|
@@ -4507,6 +4540,10 @@ def _pretool_hook(handler):
|
|
|
4507
4540
|
_note_edit(payload)
|
|
4508
4541
|
except Exception as exc:
|
|
4509
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}")
|
|
4510
4547
|
output = _decide_within_budget(payload, client or None)
|
|
4511
4548
|
except Exception as exc:
|
|
4512
4549
|
_log(f"PreToolUse hook without a decision: {type(exc).__name__}: {exc}")
|
|
@@ -4522,6 +4559,38 @@ def _pretool_hook(handler):
|
|
|
4522
4559
|
return output
|
|
4523
4560
|
|
|
4524
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
|
+
|
|
4525
4594
|
def _session_audit_hook(handler):
|
|
4526
4595
|
"""SessionStart output of the session-start hook: the update notices both as systemMessage (shown to the user) and
|
|
4527
4596
|
as additionalContext, plus the redirect proposals waiting for a decision as context; `{}` when there is nothing to
|
|
@@ -4806,28 +4875,61 @@ class MCPHandler(BaseHTTPRequestHandler):
|
|
|
4806
4875
|
raise RequestTooLarge(f"Request body over {max_bytes} bytes")
|
|
4807
4876
|
return self.rfile.read(length) if length else b""
|
|
4808
4877
|
|
|
4809
|
-
def
|
|
4810
|
-
|
|
4811
|
-
|
|
4812
|
-
|
|
4813
|
-
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)
|
|
4814
4882
|
self.send_header("Content-Length", "0")
|
|
4815
4883
|
self.end_headers()
|
|
4816
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
|
+
|
|
4817
4913
|
def do_DELETE(self):
|
|
4818
|
-
"""Routes a DELETE: 405 on /mcp, 404 elsewhere."""
|
|
4914
|
+
"""Routes a DELETE: ends a Playwright bridge session, 405 on /mcp, 404 elsewhere."""
|
|
4819
4915
|
if self._reject_foreign_origin():
|
|
4820
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
|
|
4821
4920
|
if self.path == "/mcp":
|
|
4822
4921
|
self._mcp_method_not_allowed()
|
|
4823
4922
|
return
|
|
4824
4923
|
self._write_json(404, {"error": "not found"})
|
|
4825
4924
|
|
|
4826
4925
|
def do_GET(self):
|
|
4827
|
-
"""Routes a GET: 405 on
|
|
4828
|
-
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."""
|
|
4829
4928
|
if self._reject_foreign_origin():
|
|
4830
4929
|
return
|
|
4930
|
+
if self.path == browser_bridge.PATH:
|
|
4931
|
+
self._mcp_method_not_allowed("POST, DELETE")
|
|
4932
|
+
return
|
|
4831
4933
|
if self.path == "/mcp":
|
|
4832
4934
|
self._mcp_method_not_allowed()
|
|
4833
4935
|
return
|
|
@@ -4933,10 +5035,19 @@ class MCPHandler(BaseHTTPRequestHandler):
|
|
|
4933
5035
|
self._write_json(200, result)
|
|
4934
5036
|
|
|
4935
5037
|
def do_POST(self):
|
|
4936
|
-
"""Routes a POST: setup actions, the hook routes (/hooks/pretool, /hooks/posttool,
|
|
4937
|
-
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."""
|
|
4938
5040
|
if self._reject_foreign_origin():
|
|
4939
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
|
|
4940
5051
|
if self.path == "/setup/projects":
|
|
4941
5052
|
try:
|
|
4942
5053
|
setup_ui.require_token(self.headers)
|
|
@@ -4960,6 +5071,12 @@ class MCPHandler(BaseHTTPRequestHandler):
|
|
|
4960
5071
|
if urllib.parse.urlsplit(self.path).path == "/hooks/session-audit":
|
|
4961
5072
|
self._write_json(200, _session_audit_hook(self))
|
|
4962
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
|
|
4963
5080
|
if self.path == "/setup/notices":
|
|
4964
5081
|
try:
|
|
4965
5082
|
self._write_json(200, setup_ui.handle_notices())
|
|
@@ -4973,25 +5090,8 @@ class MCPHandler(BaseHTTPRequestHandler):
|
|
|
4973
5090
|
if self.path != "/mcp":
|
|
4974
5091
|
self._write_json(404, {"error": "not found"})
|
|
4975
5092
|
return
|
|
4976
|
-
|
|
4977
|
-
|
|
4978
|
-
# que algum navegador entregue a requisição sem `Origin`.
|
|
4979
|
-
if "application/json" not in (self.headers.get("Content-Type") or "").lower():
|
|
4980
|
-
self._write_json(415, {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "Content-Type must be application/json"}})
|
|
4981
|
-
return
|
|
4982
|
-
try:
|
|
4983
|
-
raw = self._read_body(MCP_MAX_REQUEST_BYTES)
|
|
4984
|
-
except ValueError as exc:
|
|
4985
|
-
status = 413 if isinstance(exc, RequestTooLarge) else 400
|
|
4986
|
-
self._write_json(status, {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": str(exc)}})
|
|
4987
|
-
return
|
|
4988
|
-
try:
|
|
4989
|
-
request = json.loads(raw or b"{}")
|
|
4990
|
-
except json.JSONDecodeError:
|
|
4991
|
-
self._write_json(400, {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "parse error"}})
|
|
4992
|
-
return
|
|
4993
|
-
if not isinstance(request, dict):
|
|
4994
|
-
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:
|
|
4995
5095
|
return
|
|
4996
5096
|
|
|
4997
5097
|
method = request.get("method")
|
|
@@ -5105,7 +5205,7 @@ def _probe_capabilities():
|
|
|
5105
5205
|
|
|
5106
5206
|
|
|
5107
5207
|
def _heal_browser_control():
|
|
5108
|
-
"""Re-registers the Playwright MCP server when
|
|
5208
|
+
"""Re-registers the Playwright MCP server when its registration no longer works (browser_control.heal)."""
|
|
5109
5209
|
try:
|
|
5110
5210
|
browser_control.heal(_log)
|
|
5111
5211
|
except Exception as exc:
|
|
@@ -5162,15 +5262,19 @@ def main():
|
|
|
5162
5262
|
_log(f"running version not recorded: {type(exc).__name__}: {exc}")
|
|
5163
5263
|
_write_registry(_BOUND_PORT)
|
|
5164
5264
|
atexit.register(_remove_registry)
|
|
5265
|
+
_log(f"daemon started (pid {os.getpid()}, port {_BOUND_PORT})")
|
|
5165
5266
|
try:
|
|
5166
5267
|
for path in endpoint_sync.sync(f"http://127.0.0.1:{_BOUND_PORT}"):
|
|
5167
5268
|
_log(f"port {_BOUND_PORT} written to {path}")
|
|
5168
5269
|
except (OSError, ValueError) as exc:
|
|
5169
5270
|
_log(f"clients not pointed to port {_BOUND_PORT}: {type(exc).__name__}: {exc}")
|
|
5170
5271
|
atexit.register(BROWSER_SERVICE.close)
|
|
5272
|
+
atexit.register(browser_bridge.BRIDGE.stop)
|
|
5171
5273
|
threading.Thread(target=_heal_browser_control, daemon=True).start()
|
|
5274
|
+
threading.Thread(target=_engine_homes_loop, daemon=True).start()
|
|
5172
5275
|
try:
|
|
5173
5276
|
recovered = project_store.recover_interrupted()
|
|
5277
|
+
_log(f"documentation registry: {doc_turn.resume_all()} interrupted function(s) back to pending")
|
|
5174
5278
|
disk_cleanup.sweep([WEB_FETCH_VECTOR_ROOT], _log)
|
|
5175
5279
|
project_store.import_known_legacy(indexer.INDEX_DIR)
|
|
5176
5280
|
_PROJECT_MONITOR = project_monitor.ProjectMonitor(_enqueue_monitored_project)
|
|
@@ -5181,10 +5285,16 @@ def main():
|
|
|
5181
5285
|
_log(f"project monitor unavailable: {_project_error(exc)}")
|
|
5182
5286
|
audit = setup_audit.Scheduler(_audited_roots, _log)
|
|
5183
5287
|
audit.start()
|
|
5288
|
+
reason = "the server loop returned"
|
|
5184
5289
|
try:
|
|
5185
5290
|
server.serve_forever()
|
|
5291
|
+
except BaseException as exc:
|
|
5292
|
+
reason = f"{type(exc).__name__}: {exc}"
|
|
5293
|
+
raise
|
|
5186
5294
|
finally:
|
|
5295
|
+
_log(f"daemon stopping (pid {os.getpid()}): {reason}")
|
|
5187
5296
|
audit.stop()
|
|
5297
|
+
browser_bridge.BRIDGE.stop()
|
|
5188
5298
|
if _PROJECT_MONITOR:
|
|
5189
5299
|
_PROJECT_MONITOR.stop()
|
|
5190
5300
|
with _JOBS_LOCK:
|
package/tray.py
CHANGED
|
@@ -31,11 +31,14 @@ 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
|
|
37
38
|
UPDATE_RETRY_S = 300
|
|
38
39
|
NOTICE_UNREACHABLE_LOG_S = 600
|
|
40
|
+
BALLOON_TEXT_MAX = 255
|
|
41
|
+
BALLOON_TITLE_MAX = 63
|
|
39
42
|
LOG_PATH = os.path.join(paths.DATA_DIR, "tray.log")
|
|
40
43
|
LOG_MAX_BYTES = 256 * 1024
|
|
41
44
|
SETUP_URL = "http://127.0.0.1:8765/setup"
|
|
@@ -89,13 +92,13 @@ def _set_state(health, icon=None):
|
|
|
89
92
|
icon.title = i18n.t(_TITLES[health])
|
|
90
93
|
|
|
91
94
|
|
|
92
|
-
def _notify(icon, text, buttons=(), **values):
|
|
95
|
+
def _notify(icon, text, buttons=(), tag=None, **values):
|
|
93
96
|
"""Windows notification, translated (text is an English catalog key; buttons are (catalog key, protocol link)). A
|
|
94
97
|
toast under Smart Tool's own app id, since the tray balloon is shown as "Python"; when Windows refuses the toast,
|
|
95
|
-
the balloon carries the text and the refusal."""
|
|
98
|
+
the balloon carries the text and the refusal. A toast with a tag replaces the earlier one with the same tag."""
|
|
96
99
|
message = i18n.t(text, **values)
|
|
97
100
|
try:
|
|
98
|
-
toast_notice.show("Smart Tool", [message], [(i18n.t(label), uri) for label, uri in buttons])
|
|
101
|
+
toast_notice.show("Smart Tool", [message], [(i18n.t(label), uri) for label, uri in buttons], tag=tag)
|
|
99
102
|
except Exception as exc:
|
|
100
103
|
icon.notify(f"{message} ({exc})", "Smart Tool")
|
|
101
104
|
|
|
@@ -146,12 +149,46 @@ def _poll_loop(icon):
|
|
|
146
149
|
time.sleep(POLL_INTERVAL_S)
|
|
147
150
|
|
|
148
151
|
|
|
149
|
-
def
|
|
150
|
-
"""
|
|
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
|
+
|
|
181
|
+
def _toast(icon, title, lines, buttons, tag):
|
|
182
|
+
"""One notice: a toast Windows refuses goes to `tray.log` and, cut to what a balloon holds, to the tray balloon; a
|
|
183
|
+
balloon that fails is logged too, and neither keeps the next notices from being shown."""
|
|
151
184
|
try:
|
|
152
185
|
toast_notice.show(title, lines, buttons, tag=tag)
|
|
153
186
|
except Exception as exc:
|
|
154
187
|
_log(f"notice {tag}: {type(exc).__name__}: {exc}")
|
|
188
|
+
try:
|
|
189
|
+
icon.notify(f"{' '.join(lines)} ({exc})"[:BALLOON_TEXT_MAX], title[:BALLOON_TITLE_MAX])
|
|
190
|
+
except Exception as balloon_exc:
|
|
191
|
+
_log(f"notice {tag}: balloon failed: {type(balloon_exc).__name__}: {balloon_exc}")
|
|
155
192
|
|
|
156
193
|
|
|
157
194
|
def _show_notices(icon, notices):
|
|
@@ -160,14 +197,14 @@ def _show_notices(icon, notices):
|
|
|
160
197
|
if offer:
|
|
161
198
|
lines = [f"{role}: {change['current']} -> {change['new']}" for role, change in offer["changes"].items()]
|
|
162
199
|
nonce = offer["nonce"]
|
|
163
|
-
_toast(i18n.t("Smart Tool has new recommended models"), lines, [
|
|
200
|
+
_toast(icon, i18n.t("Smart Tool has new recommended models"), lines, [
|
|
164
201
|
(i18n.t("Apply now"), toast_notice.action_uri("models-apply", n=nonce)),
|
|
165
202
|
(i18n.t("Don't show again"), toast_notice.action_uri("models-decline", n=nonce)),
|
|
166
203
|
], "models-upgrade")
|
|
167
204
|
for row in notices.get("failing") or []:
|
|
168
205
|
last = row.get("last_error") or i18n.t("see the failure log in the settings")
|
|
169
206
|
_toast(
|
|
170
|
-
i18n.t("{model} is failing", model=row["model"]),
|
|
207
|
+
icon, i18n.t("{model} is failing", model=row["model"]),
|
|
171
208
|
[i18n.t("{errors} of {calls} calls failed in 24 h as {role}.", errors=row["errors"], calls=row["calls"],
|
|
172
209
|
role=row["role"]), last[:160]],
|
|
173
210
|
[(i18n.t("Switch model"), toast_notice.action_uri("open-setup", section="models")),
|
|
@@ -238,7 +275,7 @@ def _announce_start(icon):
|
|
|
238
275
|
if failed:
|
|
239
276
|
log = (i18n.N_("View log"), toast_notice.action_uri("open-update-log"))
|
|
240
277
|
_notify(icon, "The update to {target} failed; Smart Tool {version} is still installed. It is tried again in "
|
|
241
|
-
"24 h, or now from this menu.", [log], target=failed, version=version.VERSION)
|
|
278
|
+
"24 h, or now from this menu.", [log], tag="update-failed", target=failed, version=version.VERSION)
|
|
242
279
|
|
|
243
280
|
|
|
244
281
|
def _update_loop(icon):
|
|
@@ -274,8 +311,9 @@ def _update_loop(icon):
|
|
|
274
311
|
_notify(icon, "Updating Smart Tool from {old} to {new}...", old=version.VERSION, new=latest)
|
|
275
312
|
update_check.run_update(latest, automatic=True)
|
|
276
313
|
elif not known:
|
|
314
|
+
update_now = (i18n.N_("Update now"), toast_notice.action_uri("update-now", v=latest))
|
|
277
315
|
_notify(icon, "Smart Tool {version} is available: use \"Update to {version}\" in this menu.",
|
|
278
|
-
version=latest)
|
|
316
|
+
[update_now], version=latest)
|
|
279
317
|
time.sleep(UPDATE_RETRY_S if unreachable else UPDATE_CHECK_INTERVAL_S)
|
|
280
318
|
|
|
281
319
|
|
|
@@ -348,6 +386,17 @@ def _choose_language(lang):
|
|
|
348
386
|
return choose
|
|
349
387
|
|
|
350
388
|
|
|
389
|
+
def _open_log(icon, item):
|
|
390
|
+
"""Menu action: opens `tray.log` with the program Windows associates with it, or says there is none yet."""
|
|
391
|
+
if not os.path.exists(LOG_PATH):
|
|
392
|
+
_notify(icon, "There is no tray log yet.")
|
|
393
|
+
return
|
|
394
|
+
try:
|
|
395
|
+
os.startfile(LOG_PATH)
|
|
396
|
+
except OSError as exc:
|
|
397
|
+
_notify(icon, "Could not open the log: {error}", error=exc)
|
|
398
|
+
|
|
399
|
+
|
|
351
400
|
def _open_setup(icon, item):
|
|
352
401
|
registry = daemon_launcher.read_registry()
|
|
353
402
|
webbrowser.open((registry["url"].rstrip("/") + "/setup") if registry else SETUP_URL)
|
|
@@ -440,6 +489,7 @@ def main():
|
|
|
440
489
|
pystray.MenuItem(lambda item: i18n.t("Projects and indexing…"), _open_projects, default=True),
|
|
441
490
|
pystray.MenuItem(lambda item: i18n.t("Index a folder…"), _add_project),
|
|
442
491
|
pystray.MenuItem(lambda item: i18n.t("Open settings"), _open_setup),
|
|
492
|
+
pystray.MenuItem(lambda item: i18n.t("Open tray log"), _open_log),
|
|
443
493
|
pystray.MenuItem(lambda item: i18n.t("Start with Windows"), _toggle_autostart, checked=_autostart_checked),
|
|
444
494
|
pystray.MenuItem(_update_label, _update_now),
|
|
445
495
|
pystray.MenuItem(lambda item: i18n.t("Update automatically"), _toggle_auto_update,
|
|
@@ -453,6 +503,7 @@ def main():
|
|
|
453
503
|
),
|
|
454
504
|
)
|
|
455
505
|
threading.Thread(target=_poll_loop, args=(icon,), daemon=True).start()
|
|
506
|
+
threading.Thread(target=_supervise_daemon, daemon=True).start()
|
|
456
507
|
threading.Thread(target=_update_loop, args=(icon,), daemon=True).start()
|
|
457
508
|
threading.Thread(target=_notice_loop, args=(icon,), daemon=True).start()
|
|
458
509
|
try:
|
package/update_splash.py
CHANGED
|
@@ -54,12 +54,12 @@ def install_command(target):
|
|
|
54
54
|
the tray announced. `@latest` would let npx reuse an older package from its cache and install that instead;
|
|
55
55
|
--prefer-online makes npm ask the registry for the package's version list, which in the first minutes after a
|
|
56
56
|
publication its cache does not yet have (ETARGET); --expect-version makes the installer refuse a package that is
|
|
57
|
-
not that version."""
|
|
57
|
+
not that version. The installer is asked for English: STEPS and the log are read from its English lines."""
|
|
58
58
|
npx = node_locator.which("npx.cmd")
|
|
59
59
|
if not npx:
|
|
60
60
|
raise RuntimeError(i18n.t("Node.js (npx) was not found; install Node.js and try again."))
|
|
61
61
|
return ["cmd.exe", "/d", "/c", npx, "--yes", "--prefer-online", f"{update_check.PACKAGE}@{target}", "install",
|
|
62
|
-
"--expect-version", target], npx
|
|
62
|
+
"--language", "en", "--expect-version", target], npx
|
|
63
63
|
|
|
64
64
|
|
|
65
65
|
def installed_version(folder=os.path.dirname(os.path.abspath(__file__))):
|
package/venv_launch.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Starts a Python of this installation's venv in one process.
|
|
2
|
+
|
|
3
|
+
On Windows a venv's ``Scripts\\python.exe`` and ``pythonw.exe`` are a redirector that starts the base interpreter as a
|
|
4
|
+
child and waits for it (cpython issue 161511, declined upstream), so every process of the product showed up twice. The
|
|
5
|
+
base interpreter started with ``__PYVENV_LAUNCHER__`` naming the venv's executable runs inside the venv by itself:
|
|
6
|
+
``sys.prefix`` and ``sys.executable`` are the venv's, and Python clears the variable at startup so children do not
|
|
7
|
+
inherit it. It is how ``multiprocessing`` starts its workers from a venv (bpo-35797).
|
|
8
|
+
"""
|
|
9
|
+
import os
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
LAUNCHER_VARIABLE = "__PYVENV_LAUNCHER__"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class VenvLaunchError(RuntimeError):
|
|
16
|
+
"""The venv names a base interpreter that is not on disk."""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def direct(executable):
|
|
20
|
+
"""Interpreter and environment additions that run a venv's executable without its redirector.
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
executable: path of a venv's ``python.exe`` or ``pythonw.exe`` (or of any other interpreter).
|
|
24
|
+
|
|
25
|
+
Returns:
|
|
26
|
+
``(interpreter, additions)``: the base interpreter of the same name, read from the ``home`` line of the venv's
|
|
27
|
+
``pyvenv.cfg``, and ``{LAUNCHER_VARIABLE: executable}``. Outside Windows, or for an interpreter that is not in
|
|
28
|
+
a venv, the executable itself and no additions.
|
|
29
|
+
|
|
30
|
+
Raises:
|
|
31
|
+
VenvLaunchError: the venv's ``pyvenv.cfg`` names no ``home`` or a base interpreter that does not exist.
|
|
32
|
+
"""
|
|
33
|
+
executable = Path(executable)
|
|
34
|
+
config = executable.parent.parent / "pyvenv.cfg"
|
|
35
|
+
if os.name != "nt" or not config.is_file():
|
|
36
|
+
return str(executable), {}
|
|
37
|
+
settings = dict(line.split("=", 1) for line in config.read_text(encoding="utf-8").splitlines() if "=" in line)
|
|
38
|
+
home = next((value.strip() for key, value in settings.items() if key.strip().lower() == "home"), "")
|
|
39
|
+
base = Path(home) / executable.name
|
|
40
|
+
if not home or not base.is_file():
|
|
41
|
+
raise VenvLaunchError(f"The base Python of {config.parent} is missing ({base}); reinstall Smart Tool.")
|
|
42
|
+
return str(base), {LAUNCHER_VARIABLE: str(executable)}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def environment(additions):
|
|
46
|
+
"""The environment for a child that gets ``additions``: the current one plus them, or None (inherit) when empty."""
|
|
47
|
+
return {**os.environ, **additions} if additions else None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def hidden_run_vbs(executable, script, workdir=None):
|
|
51
|
+
"""VBScript that starts ``executable script`` hidden and without waiting, in one process.
|
|
52
|
+
|
|
53
|
+
Args:
|
|
54
|
+
executable: the venv's interpreter to run (see ``direct``).
|
|
55
|
+
script: the Python file to run.
|
|
56
|
+
workdir: working directory of the child, or None to keep the script host's.
|
|
57
|
+
|
|
58
|
+
Returns:
|
|
59
|
+
The script text. WScript.Shell sets the variable in its own process environment, which ``Run`` passes on.
|
|
60
|
+
"""
|
|
61
|
+
interpreter, additions = direct(executable)
|
|
62
|
+
lines = ['Set shell = CreateObject("WScript.Shell")']
|
|
63
|
+
lines += [f'shell.Environment("Process")("{name}") = "{value}"' for name, value in additions.items()]
|
|
64
|
+
if workdir:
|
|
65
|
+
lines.append(f'shell.CurrentDirectory = "{workdir}"')
|
|
66
|
+
lines.append(f'shell.Run Chr(34) & "{interpreter}" & Chr(34) & " " & Chr(34) & "{script}" & Chr(34), 0, False')
|
|
67
|
+
return "\r\n".join(lines) + "\r\n"
|
package/version.py
CHANGED