@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/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",
|
|
@@ -844,7 +845,6 @@
|
|
|
844
845
|
"Its {0} entry does not cover {1}.": "A entrada {0} dele não cobre {1}.",
|
|
845
846
|
"It calls {0} instead of {1}.": "Ele chama {0} em vez de {1}.",
|
|
846
847
|
"Its tool list is ordered or written differently from the current one.": "A lista de ferramentas dele está em outra ordem ou escrita de outro jeito que a atual.",
|
|
847
|
-
"The daemon announcement ({0}) is outside the home folder; the hook cannot name it as its port file.": "O anúncio do daemon ({0}) está fora da pasta do usuário; o hook não consegue nomeá-lo como seu arquivo de porta.",
|
|
848
848
|
"Path contains a space and has no 8.3 short name ({0}); the hook was not installed.": "O caminho tem um espaço e não tem nome curto 8.3 ({0}); o hook não foi instalado.",
|
|
849
849
|
"{0} does not have the expected format (object with 'hooks'); nothing was changed.": "{0} não tem o formato esperado (objeto com 'hooks'); nada foi alterado.",
|
|
850
850
|
"{0} does not appear in {1} after writing; the file was restored.": "{0} não aparece em {1} depois de gravar; o arquivo foi restaurado.",
|
|
@@ -854,7 +854,6 @@
|
|
|
854
854
|
"Codex does not trust the hook in {0} after recording its approval.": "O Codex não confia no hook em {0} depois de gravar a aprovação.",
|
|
855
855
|
"Codex does not trust the audit hook in {0} after recording its approval.": "O Codex não confia no hook de auditoria em {0} depois de gravar a aprovação.",
|
|
856
856
|
"The hook approval does not read back from {0} after writing; the file was restored.": "A aprovação do hook não é lida de volta em {0} depois de gravar; o arquivo foi restaurado.",
|
|
857
|
-
"Smart Tool daemon has no registered URL; start the daemon before installing the hook.": "O serviço do Smart Tool não tem URL registrada; inicie o serviço antes de instalar o hook.",
|
|
858
857
|
"{0}: hooks.{1} is not a list; nothing was changed.": "{0}: hooks.{1} não é uma lista; nada foi alterado.",
|
|
859
858
|
"Smart Tool updated from {old} to {new}.": "Smart Tool atualizado da versão {old} para a {new}.",
|
|
860
859
|
"The update to {target} failed; Smart Tool {version} is still installed. It is tried again in 24 h, or now from this menu.": "A atualização para a versão {target} falhou; o Smart Tool {version} continua instalado. Ela será tentada de novo em 24 h, ou agora por este menu.",
|
|
@@ -887,6 +886,10 @@
|
|
|
887
886
|
"{0} {1} (~{2} tokens)": "{0} {1} (~{2} tokens)",
|
|
888
887
|
"Checking the browsers…": "Verificando os navegadores…",
|
|
889
888
|
"View log": "Ver o log",
|
|
889
|
+
"Update now": "Atualizar agora",
|
|
890
|
+
"Open tray log": "Abrir o log da bandeja",
|
|
891
|
+
"There is no tray log yet.": "Ainda não há log da bandeja.",
|
|
892
|
+
"Could not open the log: {error}": "Não foi possível abrir o log: {error}",
|
|
890
893
|
"What changed": "O que mudou",
|
|
891
894
|
"Tip only, does not block": "Só dica, não bloqueia",
|
|
892
895
|
"Blocks": "Bloqueia",
|
|
@@ -940,15 +943,80 @@
|
|
|
940
943
|
"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
944
|
"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
945
|
"No layer checks.": "Sem verificação de camadas.",
|
|
946
|
+
"Broken local links on edit": "Links locais quebrados na edição",
|
|
947
|
+
"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.",
|
|
948
|
+
"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.",
|
|
949
|
+
"No link checks.": "Sem verificação de links.",
|
|
950
|
+
"Recorded decisions on edit": "Decisões registradas na edição",
|
|
951
|
+
"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.",
|
|
952
|
+
"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.",
|
|
953
|
+
"No decision lookup.": "Sem busca de decisões.",
|
|
943
954
|
"{0} volume alert": "{0} alerta de volume",
|
|
944
955
|
"{0} volume alerts": "{0} alertas de volume",
|
|
945
956
|
"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
957
|
"dependency advisories": "avisos de dependências",
|
|
947
958
|
"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}"
|
|
959
|
+
"; {0} more": "; mais {0}",
|
|
960
|
+
"Impact report as a pull request comment": "Relatório de impacto como comentário de pull request",
|
|
961
|
+
"Applies on the next request of an agent.": "Vale no próximo pedido de um agente.",
|
|
962
|
+
"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.",
|
|
963
|
+
"Nothing is posted to GitHub.": "Nada é postado no GitHub.",
|
|
964
|
+
"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.",
|
|
965
|
+
"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)).",
|
|
966
|
+
"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.",
|
|
967
|
+
"Older Smart Tool installation found at {folder}; removing it.": "Instalação mais antiga do Smart Tool encontrada em {folder}; removendo.",
|
|
968
|
+
"Hooks in {path} now point to {target}.": "Os hooks em {path} agora apontam para {target}.",
|
|
969
|
+
"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}.",
|
|
970
|
+
"no output": "sem saída",
|
|
971
|
+
"Daemon did not respond: {detail}": "O daemon não respondeu: {detail}",
|
|
972
|
+
"Missing MCP tools: {tools}": "Ferramentas MCP ausentes: {tools}",
|
|
973
|
+
"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",
|
|
974
|
+
"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}",
|
|
975
|
+
"Browser control not set up: {detail}": "Controle do navegador não configurado: {detail}",
|
|
976
|
+
"Browser control in {client}: {state}": "Controle do navegador em {client}: {state}",
|
|
977
|
+
"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}",
|
|
978
|
+
"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.",
|
|
979
|
+
"The target cannot be the source folder itself.": "A pasta de destino não pode ser a própria pasta de origem.",
|
|
980
|
+
"Tests skipped by --skip-tests.": "Testes ignorados por --skip-tests.",
|
|
981
|
+
"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).",
|
|
982
|
+
"Tests failed; installation aborted without touching the installed version.": "Os testes falharam; a instalação foi interrompida sem alterar a versão instalada.",
|
|
983
|
+
"Updating Smart Tool at {target} ({count} files from {source})": "Atualizando o Smart Tool em {target} ({count} arquivos de {source})",
|
|
984
|
+
"Installing Smart Tool at {target} ({count} files from {source})": "Instalando o Smart Tool em {target} ({count} arquivos de {source})",
|
|
985
|
+
"Removed the old copy {folder}.": "Cópia antiga {folder} removida.",
|
|
986
|
+
"Smart Tool ready.": "Smart Tool pronto.",
|
|
987
|
+
"Files installed; daemon not restarted (--no-start).": "Arquivos instalados; daemon não reiniciado (--no-start).",
|
|
988
|
+
"Could not remove the old copy {folder}: {error}": "Não foi possível remover a cópia antiga {folder}: {error}",
|
|
989
|
+
"Files changed: {changed}; removed as obsolete: {removed}": "Arquivos alterados: {changed}; removidos por obsolescência: {removed}",
|
|
990
|
+
"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.",
|
|
991
|
+
"Failed: {error}. Restoring the previous version.": "Falhou: {error}. Restaurando a versão anterior.",
|
|
992
|
+
"Incomplete rollback; backup kept at {backup}: {problems}": "Restauração incompleta; cópia de segurança mantida em {backup}: {problems}",
|
|
993
|
+
"Downloading Node LTS for the Smart Tool web runtime...": "Baixando o Node LTS para o runtime web do Smart Tool...",
|
|
994
|
+
"Node {version} installed inside Smart Tool.": "Node {version} instalado dentro do Smart Tool.",
|
|
995
|
+
"Downloading Moli {version} (structured-first headless browser, 43 MB)...": "Baixando o Moli {version} (navegador headless que prioriza dados estruturados, 43 MB)...",
|
|
996
|
+
"Moli {version} installed inside Smart Tool.": "Moli {version} instalado dentro do Smart Tool.",
|
|
997
|
+
"{label}: starting (attempt {attempt} of {attempts})...": "{label}: iniciando (tentativa {attempt} de {attempts})...",
|
|
998
|
+
"{label}: starting...": "{label}: iniciando...",
|
|
999
|
+
"{label}: done.": "{label}: concluído.",
|
|
1000
|
+
"{error}; trying again.": "{error}; tentando de novo.",
|
|
1001
|
+
"{label}: waiting for {seconds}s...": "{label}: aguardando há {seconds}s...",
|
|
1002
|
+
"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.",
|
|
1003
|
+
"Web runtime installation failed: {error}": "A instalação do runtime web falhou: {error}",
|
|
1004
|
+
"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.",
|
|
1005
|
+
"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.",
|
|
1006
|
+
"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.",
|
|
1007
|
+
"a drive or filesystem root": "uma raiz de unidade ou do sistema de arquivos",
|
|
1008
|
+
"a personal folder, not a project": "uma pasta pessoal, não um projeto",
|
|
1009
|
+
"the temporary folder": "a pasta temporária",
|
|
1010
|
+
"inside a tool's hidden folder in the home folder": "uma pasta dentro da pasta oculta de uma ferramenta, na pasta do usuário",
|
|
1011
|
+
"a system or application folder": "uma pasta do sistema ou de aplicativos",
|
|
1012
|
+
"application data": "uma pasta de dados de aplicativo",
|
|
1013
|
+
"a build or dependency folder ({folder})": "uma pasta de build ou de dependências ({folder})",
|
|
1014
|
+
"a Java home": "uma pasta de instalação do Java",
|
|
1015
|
+
"inside the system temporary folder": "uma pasta dentro da pasta temporária do sistema"
|
|
949
1016
|
},
|
|
950
1017
|
"ignore": [
|
|
951
1018
|
"and {0} more",
|
|
1019
|
+
"Stop",
|
|
952
1020
|
"saved msg",
|
|
953
1021
|
"more row-more",
|
|
954
1022
|
"callout info",
|
package/model_breaker.py
CHANGED
|
@@ -13,7 +13,7 @@ import urllib.error
|
|
|
13
13
|
FAILURES_TO_OPEN = 3
|
|
14
14
|
PAUSE_S = 30
|
|
15
15
|
MAX_IN_FLIGHT = 6
|
|
16
|
-
|
|
16
|
+
BUSY_CODES = (429, 503)
|
|
17
17
|
_lock = threading.Lock()
|
|
18
18
|
_failures = {}
|
|
19
19
|
_open_until = {}
|
|
@@ -35,12 +35,13 @@ def guard(model):
|
|
|
35
35
|
"HTTP 429/503 answers from the gateway; no request was sent.")
|
|
36
36
|
|
|
37
37
|
|
|
38
|
-
def note(model, failure=None):
|
|
39
|
-
"""Records the outcome of a request: a success closes the circuit,
|
|
40
|
-
failure changes nothing. After the pause the first failure opens it again.
|
|
38
|
+
def note(model, failure=None, codes=BUSY_CODES):
|
|
39
|
+
"""Records the outcome of a request: a success closes the circuit, an HTTP status in `codes` counts toward opening
|
|
40
|
+
it, any other failure changes nothing. After the pause the first failure opens it again. `codes` is the gateway's
|
|
41
|
+
busy answers by default; the embeddings home adds its 500, an inference that fails until the home recovers."""
|
|
41
42
|
if not model:
|
|
42
43
|
return
|
|
43
|
-
busy = isinstance(failure, urllib.error.HTTPError) and failure.code in
|
|
44
|
+
busy = isinstance(failure, urllib.error.HTTPError) and failure.code in codes
|
|
44
45
|
with _lock:
|
|
45
46
|
if failure is None:
|
|
46
47
|
_failures[model] = 0
|
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,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@allansantos-dev/smart-tool",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.82",
|
|
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
|
-
"author": "
|
|
6
|
+
"author": "Allan Santos",
|
|
7
7
|
"homepage": "https://allansantos-dv.github.io/smart-tool/",
|
|
8
8
|
"repository": {
|
|
9
9
|
"type": "git",
|
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}
|