@allansantos-dev/smart-tool 0.9.80 → 0.9.81
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 +65 -0
- package/README.md +21 -4
- package/client_hooks.py +10 -8
- package/code_health.py +5 -3
- package/code_impact.py +1 -1
- package/config.py +35 -0
- package/dossier.py +40 -5
- package/hook_decision.py +240 -20
- package/hooks/pretool_router.py +5 -4
- package/install.py +66 -27
- package/install_runtime.py +24 -10
- package/link_check.py +69 -0
- package/local_embedder.py +1 -1
- package/locales/pt-BR.json +71 -2
- package/model_client.py +1 -1
- package/model_health.py +24 -6
- package/notice_action.py +9 -0
- package/package.json +1 -1
- package/pr_comment.py +94 -0
- package/pr_impact.py +216 -35
- package/project_admission.py +17 -15
- package/removed_callers.py +146 -0
- package/setup_ui.py +33 -4
- package/smart_tool_daemon.py +8 -3
- package/tray.py +29 -9
- package/update_splash.py +2 -2
- package/version.py +1 -1
- package/web_document_graph.py +12 -1
package/install_runtime.py
CHANGED
|
@@ -21,6 +21,7 @@ import venv
|
|
|
21
21
|
import zipfile
|
|
22
22
|
from pathlib import Path
|
|
23
23
|
|
|
24
|
+
import i18n
|
|
24
25
|
import node_locator
|
|
25
26
|
|
|
26
27
|
|
|
@@ -43,6 +44,12 @@ MOLI_URL = f"https://github.com/lexmount/moli/releases/download/v{MOLI_VERSION}/
|
|
|
43
44
|
MOLI_SHA256 = "64c00ce02d6db8e1c22c55e88fbcaaf3e7517e930f24c25ff46a457b421040c8"
|
|
44
45
|
MOLI_DIR = BROWSER_DIR / "moli"
|
|
45
46
|
MOLI_EXE = MOLI_DIR / "moli.exe"
|
|
47
|
+
LANGUAGE = "en"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def t(text, **values):
|
|
51
|
+
"""text (an English catalog key) in LANGUAGE, with its {placeholders} filled from values."""
|
|
52
|
+
return i18n.t(text, lang=LANGUAGE, **values)
|
|
46
53
|
|
|
47
54
|
|
|
48
55
|
def _node_supported(node):
|
|
@@ -119,7 +126,7 @@ def _replace_folder(unpacked, final, temp_dir):
|
|
|
119
126
|
|
|
120
127
|
def _install_node():
|
|
121
128
|
"""Baixa o Node LTS oficial e confere SHA-256 antes de extrair."""
|
|
122
|
-
print("Downloading Node LTS for the Smart Tool web runtime...", flush=True)
|
|
129
|
+
print(t("Downloading Node LTS for the Smart Tool web runtime..."), flush=True)
|
|
123
130
|
with urllib.request.urlopen("https://nodejs.org/dist/index.json", timeout=30) as response:
|
|
124
131
|
releases = json.load(response)
|
|
125
132
|
release = next((row for row in releases if row.get("lts") and
|
|
@@ -144,7 +151,7 @@ def _install_node():
|
|
|
144
151
|
if not (unpacked / "node.exe").is_file() or not (unpacked / "npm.cmd").is_file():
|
|
145
152
|
raise RuntimeError("Node package does not contain the expected executables.")
|
|
146
153
|
_replace_folder(unpacked, NODE_RUNTIME, temp_dir)
|
|
147
|
-
print(
|
|
154
|
+
print(t("Node {version} installed inside Smart Tool.", version=version))
|
|
148
155
|
|
|
149
156
|
|
|
150
157
|
def _moli_ready():
|
|
@@ -156,7 +163,7 @@ def _moli_ready():
|
|
|
156
163
|
|
|
157
164
|
def _install_moli():
|
|
158
165
|
"""Downloads the pinned Moli release from GitHub, checks its SHA-256 and unpacks it into web_adapters/browser."""
|
|
159
|
-
print(
|
|
166
|
+
print(t("Downloading Moli {version} (structured-first headless browser, 43 MB)...", version=MOLI_VERSION), flush=True)
|
|
160
167
|
BROWSER_DIR.mkdir(parents=True, exist_ok=True)
|
|
161
168
|
with tempfile.TemporaryDirectory(prefix="moli-setup-", dir=BROWSER_DIR) as temp:
|
|
162
169
|
temp_dir = Path(temp)
|
|
@@ -167,7 +174,7 @@ def _install_moli():
|
|
|
167
174
|
if not (unpacked / "moli.exe").is_file():
|
|
168
175
|
raise RuntimeError("The Moli package does not contain moli.exe.")
|
|
169
176
|
_replace_folder(unpacked, MOLI_DIR, temp_dir)
|
|
170
|
-
print(
|
|
177
|
+
print(t("Moli {version} installed inside Smart Tool.", version=MOLI_VERSION))
|
|
171
178
|
|
|
172
179
|
|
|
173
180
|
def _run(args, *, cwd=None, label="Web dependency", idle_s=600, stream=False, attempts=1):
|
|
@@ -179,15 +186,19 @@ def _run(args, *, cwd=None, label="Web dependency", idle_s=600, stream=False, at
|
|
|
179
186
|
env.setdefault("NODE_USE_SYSTEM_CA", "1")
|
|
180
187
|
flags = (subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.CREATE_NO_WINDOW) if os.name == "nt" else 0
|
|
181
188
|
for attempt in range(1, attempts + 1):
|
|
182
|
-
|
|
189
|
+
if attempt > 1:
|
|
190
|
+
print(t("{label}: starting (attempt {attempt} of {attempts})...", label=label, attempt=attempt,
|
|
191
|
+
attempts=attempts), flush=True)
|
|
192
|
+
else:
|
|
193
|
+
print(t("{label}: starting...", label=label), flush=True)
|
|
183
194
|
try:
|
|
184
195
|
_run_once(args, cwd, env, flags, label, idle_s, stream)
|
|
185
|
-
print(
|
|
196
|
+
print(t("{label}: done.", label=label), flush=True)
|
|
186
197
|
return
|
|
187
198
|
except RuntimeError as exc:
|
|
188
199
|
if attempt == attempts:
|
|
189
200
|
raise
|
|
190
|
-
print(
|
|
201
|
+
print(t("{error}; trying again.", error=exc), flush=True)
|
|
191
202
|
|
|
192
203
|
|
|
193
204
|
def _run_once(args, cwd, env, flags, label, idle_s, stream):
|
|
@@ -229,7 +240,7 @@ def _run_once(args, cwd, env, flags, label, idle_s, stream):
|
|
|
229
240
|
raise RuntimeError(f"{label} stopped: no output for {idle_s}s; last output: {tail[-1] if tail else 'none'}")
|
|
230
241
|
if not stream and now - noted >= 30:
|
|
231
242
|
noted = now
|
|
232
|
-
print(
|
|
243
|
+
print(t("{label}: waiting for {seconds}s...", label=label, seconds=int(now - started)), flush=True)
|
|
233
244
|
time.sleep(0.5)
|
|
234
245
|
reader.join(timeout=10)
|
|
235
246
|
if process.returncode:
|
|
@@ -374,7 +385,7 @@ def install(reuse_browser_runtime=None):
|
|
|
374
385
|
status = _check()
|
|
375
386
|
if not all(status.values()):
|
|
376
387
|
raise RuntimeError(f"Incomplete web runtime: {status}")
|
|
377
|
-
print("Smart Tool runtime installed: Node, open-websearch, TypeScript, Java, Angular, Playwright MCP, Camoufox, Crawl4AI and Moli.")
|
|
388
|
+
print(t("Smart Tool runtime installed: Node, open-websearch, TypeScript, Java, Angular, Playwright MCP, Camoufox, Crawl4AI and Moli."))
|
|
378
389
|
|
|
379
390
|
|
|
380
391
|
def main():
|
|
@@ -382,7 +393,10 @@ def main():
|
|
|
382
393
|
parser.add_argument("--check", action="store_true", help="Show the status without installing")
|
|
383
394
|
parser.add_argument("--reuse-browser-runtime", metavar="FOLDER",
|
|
384
395
|
help="Reuse an existing venv without duplicating files (useful when disk is low)")
|
|
396
|
+
parser.add_argument("--language", choices=i18n.config.LANGUAGES, default="en", help="language of the messages")
|
|
385
397
|
args = parser.parse_args()
|
|
398
|
+
global LANGUAGE
|
|
399
|
+
LANGUAGE = args.language
|
|
386
400
|
if args.check:
|
|
387
401
|
status = _check()
|
|
388
402
|
for name, ready in status.items():
|
|
@@ -391,7 +405,7 @@ def main():
|
|
|
391
405
|
try:
|
|
392
406
|
install(args.reuse_browser_runtime)
|
|
393
407
|
except (OSError, RuntimeError, subprocess.SubprocessError) as exc:
|
|
394
|
-
print(
|
|
408
|
+
print(t("Web runtime installation failed: {error}", error=exc), file=sys.stderr)
|
|
395
409
|
return 1
|
|
396
410
|
return 0
|
|
397
411
|
|
package/link_check.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Local links an edit of an HTML or Markdown file adds or changes, checked against the files on disk, for the edit hook.
|
|
2
|
+
Links come from `web_document_graph.analyze` (the same reader the code graph uses). A link counts only when its text is
|
|
3
|
+
new in the file (a link that was already broken is not the edit's), and only relative paths are looked up: http(s),
|
|
4
|
+
mailto, tel, data and #anchors are skipped. What cannot be decided is returned as unchecked with the reason instead of
|
|
5
|
+
being dropped: a root-relative path (the web root is not known), a template expression, a page with a <base> element,
|
|
6
|
+
a file that cannot be read, HTML that did not parse."""
|
|
7
|
+
import collections
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
10
|
+
|
|
11
|
+
import web_document_graph
|
|
12
|
+
|
|
13
|
+
EXTENSIONS = (".html", ".htm", ".md", ".markdown")
|
|
14
|
+
_TEMPLATE = re.compile(r"\{\{|\{%|<%|<\?|\$\{")
|
|
15
|
+
_BASE = re.compile(r"<base[\s>]", re.I)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _links(origin, text):
|
|
19
|
+
"""The local links of text (their specifiers and lines) and the parser diagnostics, in document order."""
|
|
20
|
+
found = web_document_graph.analyze({origin: text}, ())
|
|
21
|
+
return [item for item in found["dependencies"] if item["resolution"] == "unresolved"], found["diagnostics"]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _missing(target):
|
|
25
|
+
"""Whether target does not exist; any other failure to look it up raises OSError."""
|
|
26
|
+
try:
|
|
27
|
+
os.stat(target)
|
|
28
|
+
except (FileNotFoundError, NotADirectoryError):
|
|
29
|
+
return True
|
|
30
|
+
return False
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def review(path, before, after):
|
|
34
|
+
"""The local links the edit introduced that point to nothing, and the ones that could not be checked.
|
|
35
|
+
|
|
36
|
+
Parameters: path (str) absolute path of the edited file; before (str or None) text before the edit; after (str) text
|
|
37
|
+
after it.
|
|
38
|
+
Returns: dict with `broken` (list of {line, link}) and `unchecked` (list of {line, link, why}; line and link are None
|
|
39
|
+
for a parse failure of the whole file); both empty for a file that is not HTML or Markdown.
|
|
40
|
+
"""
|
|
41
|
+
result = {"broken": [], "unchecked": []}
|
|
42
|
+
if os.path.splitext(path)[1].lower() not in EXTENSIONS:
|
|
43
|
+
return result
|
|
44
|
+
origin = os.path.abspath(path).replace(os.sep, "/")
|
|
45
|
+
known = collections.Counter(item["specifier"] for item in _links(origin, before)[0]) if before else collections.Counter()
|
|
46
|
+
links, diagnostics = _links(origin, after)
|
|
47
|
+
result["unchecked"] += [{"line": None, "link": None, "why": item["reason"]} for item in diagnostics]
|
|
48
|
+
has_base = bool(_BASE.search(after)) and origin.lower().endswith((".html", ".htm"))
|
|
49
|
+
for item in links:
|
|
50
|
+
link = item["specifier"]
|
|
51
|
+
if known[link] > 0:
|
|
52
|
+
known[link] -= 1
|
|
53
|
+
continue
|
|
54
|
+
why = None
|
|
55
|
+
if has_base:
|
|
56
|
+
why = "the page has a <base> element, which changes where relative links lead"
|
|
57
|
+
elif _TEMPLATE.search(link):
|
|
58
|
+
why = "it is a template expression, not a path"
|
|
59
|
+
elif link.startswith("/"):
|
|
60
|
+
why = "it is relative to the root of a site or repository, which is not known here"
|
|
61
|
+
else:
|
|
62
|
+
try:
|
|
63
|
+
if _missing(web_document_graph.local_target(origin, link)):
|
|
64
|
+
result["broken"].append({"line": item["line"], "link": link})
|
|
65
|
+
except (OSError, ValueError) as exc:
|
|
66
|
+
why = f"it could not be looked up: {exc}"
|
|
67
|
+
if why:
|
|
68
|
+
result["unchecked"].append({"line": item["line"], "link": link, "why": why})
|
|
69
|
+
return result
|
package/local_embedder.py
CHANGED
|
@@ -211,7 +211,7 @@ def embed(model, texts, deadline=None, cancel_check=None, on_retry=None):
|
|
|
211
211
|
for attempt in range(1, MAX_ATTEMPTS + 1):
|
|
212
212
|
if cancel_check:
|
|
213
213
|
cancel_check()
|
|
214
|
-
|
|
214
|
+
model_health.guard("/v1/embeddings", model)
|
|
215
215
|
conn.timeout = _left(deadline)
|
|
216
216
|
try:
|
|
217
217
|
with model_breaker.slot(model):
|
package/locales/pt-BR.json
CHANGED
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
"Keep mine, don't ask again": "Manter os meus, não perguntar de novo",
|
|
38
38
|
"Switch back to my previous models": "Voltar aos meus modelos anteriores",
|
|
39
39
|
"Model failures (last 24 h)": "Falhas de modelos (últimas 24 h)",
|
|
40
|
-
"Failed calls to a gateway model, grouped by type (429, 503, timeout, ...) and role, with the latest lines of each group. A model that fails half of its calls (5 or more) also raises a Windows notification.": "Chamadas com falha a um modelo do gateway, agrupadas por tipo (429, 503, tempo esgotado, ...) e função, com as linhas mais recentes de cada grupo. Um modelo que falha em metade das chamadas (5 ou mais) também gera uma notificação do Windows.",
|
|
40
|
+
"Failed calls to a gateway model, grouped by type (429, 503, timeout, ...) and role, with the latest lines of each group. A model that fails half of its calls (5 or more) also raises a Windows notification. Calls refused while a model is paused show as Circuit open and do not count toward that limit.": "Chamadas com falha a um modelo do gateway, agrupadas por tipo (429, 503, tempo esgotado, ...) e função, com as linhas mais recentes de cada grupo. Um modelo que falha em metade das chamadas (5 ou mais) também gera uma notificação do Windows. Chamadas recusadas enquanto um modelo está pausado aparecem como Circuito aberto e não contam para esse limite.",
|
|
41
41
|
"Any model id your gateway accepts. The gateway's catalog shows up as suggestions while you type.": "Qualquer id de modelo que o seu gateway aceite. O catálogo do gateway aparece como sugestões enquanto você digita.",
|
|
42
42
|
"<strong>Connect the gateway first.</strong> The catalog and the model choice open once the gateway answers.": "<strong>Conecte o gateway primeiro.</strong> O catálogo e a escolha do modelo abrem quando o gateway responde.",
|
|
43
43
|
"Connect the gateway first.": "Conecte o gateway primeiro.",
|
|
@@ -187,6 +187,7 @@
|
|
|
187
187
|
"Other 5xx": "Outro 5xx",
|
|
188
188
|
"Timeout": "Tempo esgotado",
|
|
189
189
|
"Connection": "Conexão",
|
|
190
|
+
"Circuit open": "Circuito aberto",
|
|
190
191
|
"Other": "Outro",
|
|
191
192
|
"Indexing": "Indexação",
|
|
192
193
|
"Query": "Consulta",
|
|
@@ -887,6 +888,10 @@
|
|
|
887
888
|
"{0} {1} (~{2} tokens)": "{0} {1} (~{2} tokens)",
|
|
888
889
|
"Checking the browsers…": "Verificando os navegadores…",
|
|
889
890
|
"View log": "Ver o log",
|
|
891
|
+
"Update now": "Atualizar agora",
|
|
892
|
+
"Open tray log": "Abrir o log da bandeja",
|
|
893
|
+
"There is no tray log yet.": "Ainda não há log da bandeja.",
|
|
894
|
+
"Could not open the log: {error}": "Não foi possível abrir o log: {error}",
|
|
890
895
|
"What changed": "O que mudou",
|
|
891
896
|
"Tip only, does not block": "Só dica, não bloqueia",
|
|
892
897
|
"Blocks": "Bloqueia",
|
|
@@ -940,12 +945,76 @@
|
|
|
940
945
|
"When the project has confirmed layers (.smart-tool/layers.json), warns about a call an edit adds from a lower layer to a function of a higher one. A project without layers is never checked. It never blocks.": "Quando o projeto tem camadas confirmadas (.smart-tool/layers.json), avisa sobre uma chamada que a edição adiciona de uma camada inferior para uma função de uma superior. Projeto sem camadas nunca é verificado. Nunca bloqueia.",
|
|
941
946
|
"The edit runs; the agent is told which new calls go up the layers.": "A edição roda; o agente é avisado de quais chamadas novas sobem as camadas.",
|
|
942
947
|
"No layer checks.": "Sem verificação de camadas.",
|
|
948
|
+
"Broken local links on edit": "Links locais quebrados na edição",
|
|
949
|
+
"Checks the relative links (href, src, Markdown link targets) an edit of an HTML or Markdown file adds or changes against the files on disk, and says which ones it could not check. Links that were already broken are left alone. It never blocks.": "Confere os links relativos (href, src, destinos de link do Markdown) que a edição de um arquivo HTML ou Markdown adiciona ou altera com os arquivos do disco, e diz quais não conseguiu conferir. Links que já estavam quebrados são deixados em paz. Nunca bloqueia.",
|
|
950
|
+
"The edit runs; the agent is told which new links point to a file that does not exist.": "A edição roda; o agente é avisado de quais links novos apontam para um arquivo que não existe.",
|
|
951
|
+
"No link checks.": "Sem verificação de links.",
|
|
952
|
+
"Recorded decisions on edit": "Decisões registradas na edição",
|
|
953
|
+
"Looks up the notes of the project (docs/research, the backlog, CLAUDE.md and AGENTS.md) and its commit messages for the functions an edit touches, and names the ones that record a decision about them. A single-word function name counts only when a note qualifies it with its module or class. It never blocks.": "Procura nas notas do projeto (docs/research, o backlog, CLAUDE.md e AGENTS.md) e nas mensagens de commit as funções que a edição toca, e cita as que registram uma decisão sobre elas. Um nome de função de uma palavra só conta quando uma nota o qualifica com o módulo ou a classe. Nunca bloqueia.",
|
|
954
|
+
"The edit runs; the agent is told which notes and commits record a decision about a touched function.": "A edição roda; o agente é avisado de quais notas e commits registram uma decisão sobre uma função tocada.",
|
|
955
|
+
"No decision lookup.": "Sem busca de decisões.",
|
|
943
956
|
"{0} volume alert": "{0} alerta de volume",
|
|
944
957
|
"{0} volume alerts": "{0} alertas de volume",
|
|
945
958
|
"In {0}, move each listed package to a version past its advisories; project_manage action=deps lists every advisory ID.": "Em {0}, mova cada pacote listado para uma versão além dos seus avisos; project_manage action=deps lista cada ID de aviso.",
|
|
946
959
|
"dependency advisories": "avisos de dependências",
|
|
947
960
|
"Fix the cause named in the detail (OSV unreachable, or the advisory cache file), then run the audit again.": "Corrija a causa indicada no detalhe (OSV inacessível ou o arquivo de cache de avisos) e rode a auditoria de novo.",
|
|
948
|
-
"; {0} more": "; mais {0}"
|
|
961
|
+
"; {0} more": "; mais {0}",
|
|
962
|
+
"Impact report as a pull request comment": "Relatório de impacto como comentário de pull request",
|
|
963
|
+
"Applies on the next request of an agent.": "Vale no próximo pedido de um agente.",
|
|
964
|
+
"Lets Smart Tool post the impact report as a comment on a pull request through the gh CLI, with your own gh login. This writes to GitHub: nothing is ever posted while this is off, and each post is one agent request (project_manage action=pr_impact_comment). A rerun replaces the previous Smart Tool comment instead of adding another.": "Permite que o Smart Tool poste o relatório de impacto como comentário de um pull request pela CLI gh, com o seu próprio login do gh. Isto escreve no GitHub: nada é postado enquanto estiver desligado, e cada postagem é um pedido de um agente (project_manage action=pr_impact_comment). Repetir o pedido substitui o comentário anterior do Smart Tool em vez de acrescentar outro.",
|
|
965
|
+
"Nothing is posted to GitHub.": "Nada é postado no GitHub.",
|
|
966
|
+
"Agents may post the impact report as a comment on a pull request through the gh CLI.": "Os agentes podem postar o relatório de impacto como comentário de um pull request pela CLI gh.",
|
|
967
|
+
"Could not close the running Smart Tool ({count} process(es) still active).": "Não foi possível encerrar o Smart Tool em execução ({count} processo(s) ainda ativo(s)).",
|
|
968
|
+
"Another Smart Tool daemon is still active on the registered port; close it before updating.": "Outro daemon do Smart Tool ainda está ativo na porta registrada; encerre-o antes de atualizar.",
|
|
969
|
+
"Older Smart Tool installation found at {folder}; removing it.": "Instalação mais antiga do Smart Tool encontrada em {folder}; removendo.",
|
|
970
|
+
"Hooks in {path} now point to {target}.": "Os hooks em {path} agora apontam para {target}.",
|
|
971
|
+
"Old Camoufox builds not pruned: prune_camoufox.py exited {code}.": "Versões antigas do Camoufox não foram removidas: prune_camoufox.py terminou com o código {code}.",
|
|
972
|
+
"no output": "sem saída",
|
|
973
|
+
"Daemon did not respond: {detail}": "O daemon não respondeu: {detail}",
|
|
974
|
+
"Missing MCP tools: {tools}": "Ferramentas MCP ausentes: {tools}",
|
|
975
|
+
"The daemon runs version {running}, not the {expected} being installed": "O daemon executa a versão {running}, e não a {expected} que está sendo instalada",
|
|
976
|
+
"The active daemon (pid {pid}) does not belong to this installation: {command}": "O daemon ativo (pid {pid}) não pertence a esta instalação: {command}",
|
|
977
|
+
"Browser control not set up: {detail}": "Controle do navegador não configurado: {detail}",
|
|
978
|
+
"Browser control in {client}: {state}": "Controle do navegador em {client}: {state}",
|
|
979
|
+
"Could not read the Smart Tool settings, so the Windows language is used instead: {problem}": "Não foi possível ler as configurações do Smart Tool; o idioma do Windows será usado: {problem}",
|
|
980
|
+
"This package is Smart Tool {version}, not the {requested} requested; nothing was changed.": "Este pacote é o Smart Tool {version}, e não o {requested} pedido; nada foi alterado.",
|
|
981
|
+
"The target cannot be the source folder itself.": "A pasta de destino não pode ser a própria pasta de origem.",
|
|
982
|
+
"Tests skipped by --skip-tests.": "Testes ignorados por --skip-tests.",
|
|
983
|
+
"No test suite in {source}; a packaged install runs with --skip-tests (npx @allansantos-dev/smart-tool@{version} install).": "Não há suíte de testes em {source}; uma instalação a partir do pacote roda com --skip-tests (npx @allansantos-dev/smart-tool@{version} install).",
|
|
984
|
+
"Tests failed; installation aborted without touching the installed version.": "Os testes falharam; a instalação foi interrompida sem alterar a versão instalada.",
|
|
985
|
+
"Updating Smart Tool at {target} ({count} files from {source})": "Atualizando o Smart Tool em {target} ({count} arquivos de {source})",
|
|
986
|
+
"Installing Smart Tool at {target} ({count} files from {source})": "Instalando o Smart Tool em {target} ({count} arquivos de {source})",
|
|
987
|
+
"Removed the old copy {folder}.": "Cópia antiga {folder} removida.",
|
|
988
|
+
"Smart Tool ready.": "Smart Tool pronto.",
|
|
989
|
+
"Files installed; daemon not restarted (--no-start).": "Arquivos instalados; daemon não reiniciado (--no-start).",
|
|
990
|
+
"Could not remove the old copy {folder}: {error}": "Não foi possível remover a cópia antiga {folder}: {error}",
|
|
991
|
+
"Files changed: {changed}; removed as obsolete: {removed}": "Arquivos alterados: {changed}; removidos por obsolescência: {removed}",
|
|
992
|
+
"Dependencies unchanged since the last update; pip and install_runtime.py skipped.": "Dependências iguais às da última atualização; pip e install_runtime.py ignorados.",
|
|
993
|
+
"Failed: {error}. Restoring the previous version.": "Falhou: {error}. Restaurando a versão anterior.",
|
|
994
|
+
"Incomplete rollback; backup kept at {backup}: {problems}": "Restauração incompleta; cópia de segurança mantida em {backup}: {problems}",
|
|
995
|
+
"Downloading Node LTS for the Smart Tool web runtime...": "Baixando o Node LTS para o runtime web do Smart Tool...",
|
|
996
|
+
"Node {version} installed inside Smart Tool.": "Node {version} instalado dentro do Smart Tool.",
|
|
997
|
+
"Downloading Moli {version} (structured-first headless browser, 43 MB)...": "Baixando o Moli {version} (navegador headless que prioriza dados estruturados, 43 MB)...",
|
|
998
|
+
"Moli {version} installed inside Smart Tool.": "Moli {version} instalado dentro do Smart Tool.",
|
|
999
|
+
"{label}: starting (attempt {attempt} of {attempts})...": "{label}: iniciando (tentativa {attempt} de {attempts})...",
|
|
1000
|
+
"{label}: starting...": "{label}: iniciando...",
|
|
1001
|
+
"{label}: done.": "{label}: concluído.",
|
|
1002
|
+
"{error}; trying again.": "{error}; tentando de novo.",
|
|
1003
|
+
"{label}: waiting for {seconds}s...": "{label}: aguardando há {seconds}s...",
|
|
1004
|
+
"Smart Tool runtime installed: Node, open-websearch, TypeScript, Java, Angular, Playwright MCP, Camoufox, Crawl4AI and Moli.": "Runtime do Smart Tool instalado: Node, open-websearch, TypeScript, Java, Angular, Playwright MCP, Camoufox, Crawl4AI e Moli.",
|
|
1005
|
+
"Web runtime installation failed: {error}": "A instalação do runtime web falhou: {error}",
|
|
1006
|
+
"Not indexing {root}: it is {reason}. A project is the folder where the session started; pass that folder as project_root.": "Não estou indexando {root}: a pasta é {reason}. Um projeto é a pasta onde a sessão começou; passe essa pasta como project_root.",
|
|
1007
|
+
"Not indexing {root}: the session started in {home}, which is {home_reason}, not a project. Start the session inside the project folder.": "Não estou indexando {root}: a sessão começou em {home}, que não serve como projeto, pois é {home_reason}. Inicie a sessão dentro da pasta do projeto.",
|
|
1008
|
+
"Not indexing {root}: the session started in the project {home}, and a new project is indexed only from the session that started in it.": "Não estou indexando {root}: a sessão começou no projeto {home}, e um projeto novo só é indexado pela sessão que começou nele.",
|
|
1009
|
+
"a drive or filesystem root": "uma raiz de unidade ou do sistema de arquivos",
|
|
1010
|
+
"a personal folder, not a project": "uma pasta pessoal, não um projeto",
|
|
1011
|
+
"the temporary folder": "a pasta temporária",
|
|
1012
|
+
"inside a tool's hidden folder in the home folder": "uma pasta dentro da pasta oculta de uma ferramenta, na pasta do usuário",
|
|
1013
|
+
"a system or application folder": "uma pasta do sistema ou de aplicativos",
|
|
1014
|
+
"application data": "uma pasta de dados de aplicativo",
|
|
1015
|
+
"a build or dependency folder ({folder})": "uma pasta de build ou de dependências ({folder})",
|
|
1016
|
+
"a Java home": "uma pasta de instalação do Java",
|
|
1017
|
+
"inside the system temporary folder": "uma pasta dentro da pasta temporária do sistema"
|
|
949
1018
|
},
|
|
950
1019
|
"ignore": [
|
|
951
1020
|
"and {0} more",
|
package/model_client.py
CHANGED
|
@@ -32,7 +32,7 @@ def fetch(path, token, method="GET", body=None, timeout=15):
|
|
|
32
32
|
if OFFLINE.get():
|
|
33
33
|
raise RuntimeError(OFFLINE.get())
|
|
34
34
|
model=body.get("model") if isinstance(body,dict) else None
|
|
35
|
-
|
|
35
|
+
model_health.guard(path,model)
|
|
36
36
|
with model_breaker.slot(model):
|
|
37
37
|
started=time.monotonic();result=None;headers=None;failure=None
|
|
38
38
|
try:
|
package/model_health.py
CHANGED
|
@@ -14,6 +14,7 @@ import sqlite3
|
|
|
14
14
|
import time
|
|
15
15
|
|
|
16
16
|
import config
|
|
17
|
+
import model_breaker
|
|
17
18
|
import project_store
|
|
18
19
|
import usage_meter
|
|
19
20
|
|
|
@@ -34,6 +35,7 @@ _PURPOSE_ROLE = {"scope": "scope_model", "scout": "scout_model", "docs": "docs_m
|
|
|
34
35
|
_TOOL = contextvars.ContextVar("model_health_tool", default=None)
|
|
35
36
|
_COLLECTED = contextvars.ContextVar("model_health_collected", default=None)
|
|
36
37
|
_SCHEMA = set()
|
|
38
|
+
_CIRCUIT_OPEN = model_breaker.CircuitOpen.__name__ + ":"
|
|
37
39
|
_STATUS = re.compile(r"HTTP(?: Error)? (\d{3})")
|
|
38
40
|
_TIMEOUT = re.compile(r"timed out|timeout|WinError 10060|Errno 110\b", re.I)
|
|
39
41
|
_CONNECTION = re.compile(r"URLError|ConnectionError|ConnectionRefused|ConnectionReset|refused|reset|getaddrinfo|"
|
|
@@ -68,8 +70,11 @@ def _tables(db):
|
|
|
68
70
|
|
|
69
71
|
|
|
70
72
|
def classify(error):
|
|
71
|
-
"""Failure type of a stored error text: '
|
|
72
|
-
'connection' or 'other'. An HTTP status in the text wins over words in the
|
|
73
|
+
"""Failure type of a stored error text: 'circuit_open' (refused while the model is paused), '429', '503', '5xx' (any
|
|
74
|
+
other 5xx), 'auth' (401/403), 'timeout', 'connection' or 'other'. An HTTP status in the text wins over words in the
|
|
75
|
+
response body, except that the pause text names the 429/503 that opened it."""
|
|
76
|
+
if (error or "").startswith(_CIRCUIT_OPEN):
|
|
77
|
+
return "circuit_open"
|
|
73
78
|
status = _STATUS.search(error or "")
|
|
74
79
|
if status:
|
|
75
80
|
code = int(status.group(1))
|
|
@@ -107,8 +112,19 @@ def error_text(exc):
|
|
|
107
112
|
return " ".join(text.split())[:ERROR_CHARS]
|
|
108
113
|
|
|
109
114
|
|
|
115
|
+
def guard(path, model):
|
|
116
|
+
"""`model_breaker.guard` that also logs the refusal, then re-raises it."""
|
|
117
|
+
try:
|
|
118
|
+
model_breaker.guard(model)
|
|
119
|
+
except model_breaker.CircuitOpen as refusal:
|
|
120
|
+
record(path, {"model": model}, refusal)
|
|
121
|
+
raise
|
|
122
|
+
|
|
123
|
+
|
|
110
124
|
def record(path, body, failure=None):
|
|
111
|
-
"""Counts one model call and, when it failed, logs it.
|
|
125
|
+
"""Counts one model call and, when it failed, logs it. A `CircuitOpen` refusal sent nothing: it is logged in the
|
|
126
|
+
failure table only, so it is neither a call nor an error of the rate and never reaches the tool answer's warning
|
|
127
|
+
(the search already says the model is paused). Never raises: the log must not change the call's result."""
|
|
112
128
|
if path not in _PATHS:
|
|
113
129
|
return
|
|
114
130
|
try:
|
|
@@ -116,17 +132,19 @@ def record(path, body, failure=None):
|
|
|
116
132
|
role = role_of(model, purpose=usage_meter.purpose())
|
|
117
133
|
now = time.time()
|
|
118
134
|
text = error_text(failure) if failure is not None else None
|
|
135
|
+
refused = isinstance(failure, model_breaker.CircuitOpen)
|
|
119
136
|
with project_store._LOCK, _db() as db:
|
|
120
137
|
_tables(db)
|
|
121
|
-
|
|
122
|
-
|
|
138
|
+
if not refused:
|
|
139
|
+
db.execute("INSERT INTO model_calls VALUES(?,?,?,1,?) ON CONFLICT(hour,model,role) DO UPDATE SET "
|
|
140
|
+
"calls=calls+1,errors=errors+excluded.errors", (int(now // 3600), model, role, int(text is not None)))
|
|
123
141
|
if text is not None:
|
|
124
142
|
db.execute("INSERT INTO model_failures VALUES(?,?,?,?,?,?)", (now, model, role, _TOOL.get() or "", path, text))
|
|
125
143
|
db.execute("DELETE FROM model_failures WHERE at<? OR rowid NOT IN "
|
|
126
144
|
"(SELECT rowid FROM model_failures ORDER BY at DESC LIMIT ?)", (now - KEEP_S, KEEP_FAILURES))
|
|
127
145
|
db.execute("DELETE FROM model_calls WHERE hour<?", (int((now - KEEP_S) // 3600),))
|
|
128
146
|
collected = _COLLECTED.get()
|
|
129
|
-
if text is not None and collected is not None:
|
|
147
|
+
if text is not None and collected is not None and not refused:
|
|
130
148
|
collected.append({"model": model, "role": role, "error": text})
|
|
131
149
|
except Exception:
|
|
132
150
|
pass
|
package/notice_action.py
CHANGED
|
@@ -5,6 +5,7 @@ Started by Windows through the protocol registered in `toast_notice.register`, w
|
|
|
5
5
|
refused) is appended to `notice-actions.log` in the data folder, because nothing else can show an error here.
|
|
6
6
|
"""
|
|
7
7
|
import os
|
|
8
|
+
import re
|
|
8
9
|
import sys
|
|
9
10
|
import time
|
|
10
11
|
import urllib.parse
|
|
@@ -18,6 +19,7 @@ import toast_notice
|
|
|
18
19
|
|
|
19
20
|
LOG_PATH = os.path.join(paths.DATA_DIR, "notice-actions.log")
|
|
20
21
|
LOG_MAX_BYTES = 256 * 1024
|
|
22
|
+
NPM_VERSION = re.compile(r"\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?")
|
|
21
23
|
|
|
22
24
|
|
|
23
25
|
def run(uri):
|
|
@@ -43,6 +45,13 @@ def run(uri):
|
|
|
43
45
|
import update_check
|
|
44
46
|
webbrowser.open(update_check.SITE_URL)
|
|
45
47
|
return "changes opened"
|
|
48
|
+
if action == "update-now":
|
|
49
|
+
import update_check
|
|
50
|
+
target = params.get("v", "")
|
|
51
|
+
if not NPM_VERSION.fullmatch(target):
|
|
52
|
+
raise ValueError(f"Not an npm version: {target[:40]!r}")
|
|
53
|
+
update_check.run_update(target, automatic=False)
|
|
54
|
+
return f"update to {target} started"
|
|
46
55
|
if action == "mute-model":
|
|
47
56
|
import model_health
|
|
48
57
|
return model_health.mute(params.get("model", ""))
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@allansantos-dev/smart-tool",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.81",
|
|
4
4
|
"description": "Local MCP server that gives coding agents (Claude Code, Codex) cheaper, sharper tools than their built-in search. Windows.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Smart Tool contributors",
|
package/pr_comment.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""Posts the `pr_impact` report as a comment on a pull request through the gh CLI.
|
|
2
|
+
|
|
3
|
+
This writes to GitHub with the user's own gh login, so it runs only while the setup screen's `pr_comment` consent is on.
|
|
4
|
+
The comment carries a hidden marker: a rerun edits the last comment that has it instead of stacking a new one.
|
|
5
|
+
"""
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import shutil
|
|
10
|
+
import subprocess
|
|
11
|
+
import tempfile
|
|
12
|
+
|
|
13
|
+
import config
|
|
14
|
+
import pr_impact
|
|
15
|
+
|
|
16
|
+
MARKER = "<!-- smart-tool:pr-impact -->"
|
|
17
|
+
GH_TIMEOUT_S = 60
|
|
18
|
+
COMMENT_ID = re.compile(r"#issuecomment-(\d+)$")
|
|
19
|
+
USER_FOLDER = re.compile(r"(?<![\w.\-/\\])(?:[A-Za-z]:)?[\\/](?:Users|home)[\\/][^\s`'\"|)\]]+")
|
|
20
|
+
DRIVE_PATH = re.compile(r"\b[A-Za-z]:[\\/][^\s`'\"|)\]]*")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _gh(gh, root, *args):
|
|
24
|
+
"""Runs gh from the project folder and returns its stdout; a failure says what gh answered."""
|
|
25
|
+
try:
|
|
26
|
+
done = subprocess.run([gh, *args], cwd=root, stdin=subprocess.DEVNULL, capture_output=True, text=True,
|
|
27
|
+
encoding="utf-8", errors="replace", timeout=GH_TIMEOUT_S,
|
|
28
|
+
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
|
|
29
|
+
except (OSError, subprocess.TimeoutExpired) as exc:
|
|
30
|
+
raise RuntimeError(f"gh {' '.join(args[:2])} could not run: {exc}")
|
|
31
|
+
if done.returncode:
|
|
32
|
+
raise RuntimeError(f"gh {' '.join(args[:2])} failed: {(done.stderr or done.stdout).strip()[:300]}")
|
|
33
|
+
return done.stdout
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _relativize(text, root):
|
|
37
|
+
"""Drops the project folder from every path in text and replaces any other user-folder or drive path, so the
|
|
38
|
+
comment shows no location on the user's machine."""
|
|
39
|
+
absolute = os.path.abspath(root)
|
|
40
|
+
parts = [re.escape(part) for part in re.split(r"[\\/]+", absolute) if part]
|
|
41
|
+
folder = (r"[\\/]" if absolute[:1] in "/\\" else "") + r"[\\/]+".join(parts)
|
|
42
|
+
text = re.sub(folder + r"[\\/]+", "", text, flags=re.I)
|
|
43
|
+
text = re.sub(folder + r"(?![\w.\-])", ".", text, flags=re.I)
|
|
44
|
+
return DRIVE_PATH.sub("<local path>", USER_FOLDER.sub("<local path>", text))
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _previous_comment_id(gh, root, pr):
|
|
48
|
+
"""The id of the last comment on the pull request that carries the marker, or None."""
|
|
49
|
+
comments = json.loads(_gh(gh, root, "pr", "view", str(pr), "--json", "comments"))["comments"]
|
|
50
|
+
for comment in reversed(comments):
|
|
51
|
+
found = COMMENT_ID.search(comment.get("url", ""))
|
|
52
|
+
if MARKER in comment.get("body", "") and found:
|
|
53
|
+
return found.group(1)
|
|
54
|
+
return None
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def publish(root, pr, base, limit=30, view_id=None):
|
|
58
|
+
"""Posts the impact report of the change against base on pull request pr, or replaces the previous Smart Tool comment.
|
|
59
|
+
|
|
60
|
+
Parameters: root (str) project folder, where gh finds the repository; pr (int) pull request number; base (str) git
|
|
61
|
+
revision the report compares with; limit (int) rows per list; view_id (str or None).
|
|
62
|
+
Returns: dict with the comment 'url', whether it was 'updated' and the 'pr'.
|
|
63
|
+
Raises: RuntimeError when the consent is off, gh is missing or not logged in, or gh fails; ValueError for a bad pr or base.
|
|
64
|
+
"""
|
|
65
|
+
if config.pr_comment() != "on":
|
|
66
|
+
raise RuntimeError("pr_comment is off: nothing is posted to GitHub. The user turns it on in the Smart Tool setup "
|
|
67
|
+
"screen (Agent rules, Impact report as a pull request comment).")
|
|
68
|
+
if type(pr) is not int or pr < 1:
|
|
69
|
+
raise ValueError("pr must be the number of the pull request, a positive integer.")
|
|
70
|
+
if not isinstance(base, str) or not base:
|
|
71
|
+
raise ValueError("base is required: the git revision the pull request is compared with, such as origin/main.")
|
|
72
|
+
gh = shutil.which("gh")
|
|
73
|
+
if not gh:
|
|
74
|
+
raise RuntimeError("The gh CLI is not installed or not on PATH: install it from https://cli.github.com and run gh auth login.")
|
|
75
|
+
try:
|
|
76
|
+
_gh(gh, root, "auth", "status")
|
|
77
|
+
except RuntimeError as exc:
|
|
78
|
+
raise RuntimeError(f"gh is not logged in ({exc}); run gh auth login.")
|
|
79
|
+
body = _relativize(pr_impact.report(root, base, limit, view_id)["markdown"], root) + "\n" + MARKER + "\n"
|
|
80
|
+
previous = _previous_comment_id(gh, root, pr)
|
|
81
|
+
with tempfile.TemporaryDirectory() as folder:
|
|
82
|
+
path = os.path.join(folder, "comment.md")
|
|
83
|
+
with open(path, "w", encoding="utf-8", newline="\n") as stream:
|
|
84
|
+
stream.write(body)
|
|
85
|
+
if previous:
|
|
86
|
+
answer = json.loads(_gh(gh, root, "api", "--method", "PATCH",
|
|
87
|
+
f"repos/{{owner}}/{{repo}}/issues/comments/{previous}", "-F", f"body=@{path}"))
|
|
88
|
+
url = answer.get("html_url", "")
|
|
89
|
+
else:
|
|
90
|
+
lines = _gh(gh, root, "pr", "comment", str(pr), "--body-file", path).strip().splitlines()
|
|
91
|
+
url = lines[-1] if lines else ""
|
|
92
|
+
if not url.startswith("https://"):
|
|
93
|
+
raise RuntimeError("gh did not return the comment URL, so the post is not confirmed; look at the pull request.")
|
|
94
|
+
return {"url": url, "updated": bool(previous), "pr": pr}
|