@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/hook_decision.py CHANGED
@@ -12,6 +12,8 @@ consulta legível nunca é negada: é respondida no contexto (`_answer_in_place`
12
12
  não altera permissão.
13
13
  """
14
14
  import os
15
+ import subprocess
16
+ import time
15
17
  import uuid
16
18
 
17
19
  import affected_tests
@@ -23,15 +25,18 @@ import credential_check
23
25
  import dependency_notice
24
26
  import doc_check
25
27
  import doc_scope
28
+ import dossier
26
29
  import duplicates
27
30
  import edit_preview
28
31
  import index_profile
29
32
  import index_scope
30
33
  import layer_check
34
+ import link_check
31
35
  import endpoint_sync
32
36
  import project_admission
33
37
  import project_store
34
38
  import redirect_rule
39
+ import removed_callers
35
40
  import requester
36
41
  import router
37
42
  import tool_redirect
@@ -47,6 +52,13 @@ SINGLE_LANGUAGE_REASON = "redirected native search: its pattern is the only quer
47
52
  EDIT_TOOLS = ("Edit", "MultiEdit", "Write", "apply_patch")
48
53
  MAX_DOC_FINDINGS = 5
49
54
  MAX_DUPLICATE_FINDINGS = 3
55
+ MAX_DECISION_FUNCTIONS = 3
56
+ DECISION_TIMEOUT_MS = 300
57
+ MAX_SHELL_REVIEW_FILES = 20
58
+ MAX_REVIEW_BYTES = 1_000_000
59
+ # FAT keeps two-second timestamps: a file the call wrote can look older than the call.
60
+ MTIME_SLACK_S = 2.0
61
+ SHELL_START_TTL_S = 3600
50
62
  SMART_TOOL_SERVER = "smart-tool"
51
63
  SMART_SEARCH_TOOL = f"mcp__{SMART_TOOL_SERVER}__smart_search"
52
64
  REASON_MAX_CHARS = 200
@@ -292,6 +304,26 @@ def _layer_lines(findings):
292
304
  "if this one is intended, go ahead.")
293
305
 
294
306
 
307
+ def _callers_lines(answers):
308
+ lines = []
309
+ for answer in answers:
310
+ resigned = "changed" in answer
311
+ for item in answer["findings"][:MAX_DOC_FINDINGS]:
312
+ same = f" A function named {item['name'].rpartition('.')[2]} also exists in {', '.join(item['also_defined_in'])}." \
313
+ if item["also_defined_in"] else ""
314
+ sites = removed_callers.sites_text(item)
315
+ lines.append(f"`{item['name']}` ({item['path']}) has a new signature after this edit and is called from {sites} "
316
+ f"outside this file: check that the callers pass what it takes now.{same}" if resigned else
317
+ f"`{item['name']}` ({item['path']}) is gone after this edit but is still called from "
318
+ f"{sites}: update the callers or keep the name.{same}")
319
+ if not answer["findings"]:
320
+ names = ", ".join(f"`{name}`" for name in answer["changed" if resigned else "removed"])
321
+ lines.append(f"no caller of {names}, whose signature changed, was found." if resigned else
322
+ f"no caller of the removed {names} was found.")
323
+ notes = " ".join(dict.fromkeys(answer["note"] for answer in answers if answer["note"]))
324
+ return "Smart Tool callers: " + " ".join(lines) + (f" {notes}" if notes else "")
325
+
326
+
295
327
  def _credential_lines(findings):
296
328
  lines = [f"{rel}:{item['line']} looks like a {item['kind']}" for rel, item in findings[:MAX_DOC_FINDINGS]]
297
329
  if len(findings) > MAX_DOC_FINDINGS:
@@ -300,15 +332,77 @@ def _credential_lines(findings):
300
332
  "variable or a secret store. If it is a fake value for a test, go ahead.")
301
333
 
302
334
 
303
- def _edit_review(payload, doc_mode, duplicate_mode, dependency_mode, comment_mode="off", layer_mode="off"):
335
+ def _link_lines(broken, unchecked):
336
+ """The link notes: the links that point to nothing, and the ones that could not be checked with the reason."""
337
+ parts = []
338
+ if broken:
339
+ lines = [f"{rel}:{item['line']} points to `{item['link']}`, which does not exist" for rel, item in broken[:MAX_DOC_FINDINGS]]
340
+ if len(broken) > MAX_DOC_FINDINGS:
341
+ lines.append(f"{len(broken) - MAX_DOC_FINDINGS} more link(s) in the same situation")
342
+ parts.append("Smart Tool links: " + "; ".join(lines) + ". Fix the path, or create the file if it is coming next.")
343
+ if unchecked:
344
+ lines = [f"{rel}{':' + str(item['line']) if item['line'] else ''}{' `' + item['link'] + '`' if item['link'] else ''} "
345
+ f"({item['why']})" for rel, item in unchecked[:MAX_DOC_FINDINGS]]
346
+ if len(unchecked) > MAX_DOC_FINDINGS:
347
+ lines.append(f"{len(unchecked) - MAX_DOC_FINDINGS} more not checked")
348
+ parts.append("Smart Tool links not checked: " + "; ".join(lines) + ".")
349
+ return parts
350
+
351
+
352
+
353
+
354
+ def _decision_lines(found):
355
+ """The note that names the decisions recorded about the touched functions, each note once.
356
+
357
+ Parameters: found (list of (rel, function name, hits)) the functions with a note and their `dossier.notes_about` hits.
358
+ Returns: str, empty when every note was already said.
359
+ """
360
+ seen, sentences = set(), []
361
+ for rel, name, hits in found:
362
+ fresh = [hit for hit in hits if hit["id"] not in seen]
363
+ seen.update(hit["id"] for hit in fresh)
364
+ if fresh:
365
+ sentences.append(f"`{name}` ({rel}) is named in " + "; ".join(f"`{hit['id']}` {hit['title']}" for hit in fresh))
366
+ return "Smart Tool decision notes: " + ". ".join(sentences) + ". Read them before changing what they record." \
367
+ if sentences else ""
368
+
369
+
370
+ def _decision_findings(root, rel, touched, failures):
371
+ """The recorded decisions about the touched functions of one file, looked up in the project's notes (not its commit
372
+ messages: reading them runs a `git log` the budget cannot cut) within `DECISION_TIMEOUT_MS` each.
373
+
374
+ Parameters: root (str) project folder; rel (str) path of the file relative to it; touched (list) the functions
375
+ `doc_check.written` found touched; failures (list) where a search that fails or is cut adds its line.
376
+ Returns: list of (rel, function name, hits) for the functions that a note or commit message names.
377
+ """
378
+ found = []
379
+ for function in touched:
380
+ try:
381
+ answer = dossier.notes_about(root, rel, function["name"], timeout_ms=DECISION_TIMEOUT_MS, history=False)
382
+ except (OSError, ValueError, RuntimeError) as exc:
383
+ failures.append(f"Smart Tool decision notes check skipped: {exc}")
384
+ break
385
+ line = f"Smart Tool decision notes search cut: {'; '.join(answer['reasons'])}"
386
+ if answer["reasons"] and line not in failures:
387
+ failures.append(line)
388
+ if answer["hits"]:
389
+ found.append((rel, function["name"], answer["hits"]))
390
+ return found
391
+
392
+
393
+ def _edit_review(payload, doc_mode, duplicate_mode, dependency_mode, comment_mode="off", layer_mode="off",
394
+ link_mode="off", decision_mode="off"):
304
395
  """Checks of an edit before it runs. Docstrings follow doc_mode, in code files of registered projects only (tests,
305
396
  docs and files outside a project are left out, as in the docs coverage): missing ones deny the edit in require mode and become a reminder in remind mode; a
306
397
  documented function whose signature changed always gets a reminder. Comments the edit adds in the wrong place
307
398
  (see comment_check) follow comment_mode in the same files: require denies, remind adds context. Copies of indexed
308
399
  functions follow duplicate_mode and only add context, never deny. An edit of a package.json, requirements*.txt or go.mod follows dependency_mode: advisories
309
- of the added or changed dependencies are added as context, never a denial."""
400
+ of the added or changed dependencies are added as context, never a denial. Local links an edit of an HTML or Markdown
401
+ file adds or changes follow link_mode: missing targets and links that cannot be checked are added as context. The notes
402
+ and commit messages that name a touched function follow decision_mode and only add context."""
310
403
  with code_graph.pending_scope():
311
- return _edit_review_scoped(payload, doc_mode, duplicate_mode, dependency_mode, comment_mode, layer_mode)
404
+ return _edit_review_scoped(payload, doc_mode, duplicate_mode, dependency_mode, comment_mode, layer_mode, link_mode,
405
+ decision_mode)
312
406
 
313
407
 
314
408
  def _dependency_part(before, after, ecosystem):
@@ -324,19 +418,29 @@ def _dependency_part(before, after, ecosystem):
324
418
  return f"{dependency_notice.PREFIX}dependency check skipped: {exc}"
325
419
 
326
420
 
327
- def _review_changes(changes, doc_mode, duplicate_mode, dependency_mode, comment_mode, layer_mode="off"):
328
- """The checks of an edit over (path, before, after) triples: docstrings, comments, documentation anchors, copies and
329
- dependency advisories, each following its mode.
421
+ def _review_changes(changes, doc_mode, duplicate_mode, dependency_mode, comment_mode, layer_mode="off", link_mode="off",
422
+ decision_mode="off"):
423
+ """The checks of an edit over (path, before, after) triples: docstrings, comments, documentation anchors, copies,
424
+ dependency advisories, local links, layers and the decisions recorded about the touched functions, each following its mode.
330
425
 
331
- Parameters: changes (iterable of (absolute path, text before or None, text after)); the four modes (`off` skips a check).
426
+ Parameters: changes (iterable of (absolute path, text before or None, text after)); the modes (`off` skips a check).
332
427
  Returns: tuple (message parts, doc findings, comment findings); the parts are empty when nothing is worth saying.
333
428
  """
334
429
  doc_findings, scope_findings, duplicate_findings, failures, dependency_parts = [], [], [], [], []
335
- comment_findings, layer_findings, credential_findings = [], [], []
430
+ comment_findings, layer_findings, credential_findings, caller_answers = [], [], [], []
431
+ broken_links, unchecked_links = [], []
432
+ decision_findings, decisions_asked = [], 0
336
433
  for path, before, after in changes:
337
434
  root = _project_of(path)
338
435
  rel = os.path.relpath(os.path.realpath(path), os.path.realpath(root)).replace(os.sep, "/") if root else os.path.basename(path)
339
436
  credential_findings += [(rel, item) for item in credential_check.review(before, after)]
437
+ if link_mode != "off":
438
+ try:
439
+ found = link_check.review(path, before, after)
440
+ broken_links += [(rel, item) for item in found["broken"]]
441
+ unchecked_links += [(rel, item) for item in found["unchecked"]]
442
+ except (ValueError, RuntimeError, OSError) as exc:
443
+ failures.append(f"Smart Tool links check skipped: {exc}")
340
444
  ecosystem = dependency_notice.ecosystem_of(path)
341
445
  if dependency_mode != "off" and ecosystem:
342
446
  dependency_parts += [part for part in (_dependency_part(before, after, ecosystem),) if part]
@@ -364,12 +468,27 @@ def _review_changes(changes, doc_mode, duplicate_mode, dependency_mode, comment_
364
468
  layer_findings += [(rel, item) for item in layer_check.review(root, rel, before, after, edited)]
365
469
  except (ValueError, RuntimeError, OSError) as exc:
366
470
  failures.append(f"Smart Tool layers check skipped: {exc}")
471
+ if decision_mode != "off" and root and index_profile.kind(rel, profile) == "code":
472
+ asked = edited["touched"][:MAX_DECISION_FUNCTIONS - decisions_asked]
473
+ decisions_asked += len(asked)
474
+ decision_findings += _decision_findings(root, rel, asked, failures)
475
+ if root:
476
+ try:
477
+ for review, key in ((removed_callers.review, "removed"), (removed_callers.signature_review, "changed")):
478
+ answer = review(root, rel, before, after)
479
+ if answer["findings"] or answer[key] and answer["note"]:
480
+ caller_answers.append(answer)
481
+ except (ValueError, RuntimeError, OSError) as exc:
482
+ failures.append(f"Smart Tool callers check skipped: {exc}")
367
483
  parts = ([_doc_lines(doc_findings)] if doc_findings else []) + \
368
484
  ([_comment_lines(comment_findings)] if comment_findings else []) + \
369
485
  ([_scope_lines(scope_findings)] if scope_findings else []) + \
370
486
  ([_duplicate_lines(duplicate_findings)] if duplicate_findings else []) + \
371
487
  ([_layer_lines(layer_findings)] if layer_findings else []) + \
372
- ([_credential_lines(credential_findings)] if credential_findings else []) + failures + dependency_parts
488
+ ([_decision_lines(decision_findings)] if decision_findings else []) + \
489
+ ([_callers_lines(caller_answers)] if caller_answers else []) + \
490
+ ([_credential_lines(credential_findings)] if credential_findings else []) + \
491
+ _link_lines(broken_links, unchecked_links) + failures + dependency_parts
373
492
  return parts, doc_findings, comment_findings
374
493
 
375
494
 
@@ -380,16 +499,115 @@ def review_diff(changes, cfg):
380
499
  Returns: str, the hook's message for the whole set; empty when every check is quiet or off.
381
500
  """
382
501
  modes = (config.doc_mode(cfg), config.duplicate_mode(cfg), config.dependency_mode(cfg), config.comment_mode(cfg),
383
- config.layer_mode(cfg))
502
+ config.layer_mode(cfg), config.link_mode(cfg), config.decision_mode(cfg))
384
503
  with code_graph.pending_scope():
385
504
  return " ".join(_review_changes(changes, *modes)[0])
386
505
 
387
506
 
388
- def _edit_review_scoped(payload, doc_mode, duplicate_mode, dependency_mode, comment_mode="off", layer_mode="off"):
507
+ def file_changes(root, base, rels):
508
+ """The (path, text before, text after) triples `review_diff` takes, for the text files among `rels`.
509
+
510
+ Parameters: root (str) folder the paths are relative to; base (str) git revision holding the text before; rels (iterable
511
+ of str) forward-slash paths relative to root.
512
+ Returns: list of (absolute path, text at base or None for a file new since base, current text); a file that cannot be
513
+ read as UTF-8, is over MAX_REVIEW_BYTES or is gone is left out.
514
+ """
515
+ triples = []
516
+ for rel in rels:
517
+ full = os.path.join(root, *rel.split("/"))
518
+ try:
519
+ if os.path.getsize(full) > MAX_REVIEW_BYTES:
520
+ continue
521
+ with open(full, encoding="utf-8") as stream:
522
+ after = stream.read()
523
+ except (OSError, UnicodeDecodeError):
524
+ continue
525
+ try:
526
+ before = affected_tests._git(root, "show", f"{base}:./{rel}")
527
+ except ValueError:
528
+ before = None
529
+ triples.append((full, before, after))
530
+ return triples
531
+
532
+
533
+ _SHELL_STARTS = {}
534
+
535
+
536
+ def note_shell_start(payload):
537
+ """Records when a shell call (Bash, PowerShell) starts, by its tool_use_id: the PostToolUse payload carries no start
538
+ time and no snapshot, so this is what tells the files the call wrote from the ones that were already changed."""
539
+ if not isinstance(payload, dict) or payload.get("tool_name") not in tool_redirect.NO_OP or not payload.get("tool_use_id"):
540
+ return
541
+ now = time.time()
542
+ for old in [key for key, at in _SHELL_STARTS.items() if now - at > SHELL_START_TTL_S]:
543
+ _SHELL_STARTS.pop(old, None)
544
+ _SHELL_STARTS[payload["tool_use_id"]] = now
545
+
546
+
547
+ def _in_git_repository(folder):
548
+ """Whether folder or one of its parents holds a `.git` entry (a folder, or a file for a worktree or submodule)."""
549
+ folder = os.path.abspath(folder)
550
+ while True:
551
+ if os.path.exists(os.path.join(folder, ".git")):
552
+ return True
553
+ parent = os.path.dirname(folder)
554
+ if parent == folder:
555
+ return False
556
+ folder = parent
557
+
558
+
559
+ def _shell_review(payload):
560
+ """PostToolUse notes for the files a shell call wrote (`sed -i`, a redirection, `npm install`): the files git shows
561
+ changed since HEAD, tracked or not, whose modification time is not older than the call's start (see
562
+ `note_shell_start`), through the same checks as `review_diff`. A file the user or another tool changed before the
563
+ call is left out. Anything that stops the review, a git failure included, comes back as a note.
564
+
565
+ Parameters: payload (dict) the PostToolUse payload of the call.
566
+ Returns: the hook output, `{}` when there is nothing to say.
567
+ """
568
+ started = _SHELL_STARTS.pop(payload["tool_use_id"], None)
569
+ cwd = payload.get("cwd")
570
+ cfg = config.load_config()
571
+ modes = (config.doc_mode(cfg), config.duplicate_mode(cfg), config.dependency_mode(cfg), config.comment_mode(cfg),
572
+ config.layer_mode(cfg), config.link_mode(cfg), config.decision_mode(cfg))
573
+ if set(modes) == {"off"}:
574
+ return {}
575
+ if not isinstance(cwd, str) or not os.path.isdir(cwd) or not _in_git_repository(cwd):
576
+ return {}
577
+ if started is None:
578
+ return _shell_note("the start of this call was not recorded, so the files it wrote cannot be told apart")
579
+ try:
580
+ changed = affected_tests._changes(cwd, "HEAD")
581
+ written = sorted(rel for rel, found in changed.items() if found["status"] != "deleted"
582
+ and _written_since(os.path.join(cwd, *rel.split("/")), started - MTIME_SLACK_S))
583
+ notes = review_diff(file_changes(cwd, "HEAD", written[:MAX_SHELL_REVIEW_FILES]), cfg)
584
+ except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as exc:
585
+ return _shell_note(str(exc))
586
+ if len(written) > MAX_SHELL_REVIEW_FILES:
587
+ notes += f" {len(written) - MAX_SHELL_REVIEW_FILES} more changed file(s) were not reviewed."
588
+ notes = notes.strip()
589
+ return {"hookSpecificOutput": {"hookEventName": "PostToolUse", "additionalContext": notes}} if notes else {}
590
+
591
+
592
+ def _written_since(path, moment):
593
+ """Whether path was modified at or after moment (seconds since the epoch); a file that cannot be read was not."""
594
+ try:
595
+ return os.stat(path).st_mtime >= moment
596
+ except OSError:
597
+ return False
598
+
599
+
600
+ def _shell_note(reason):
601
+ return {"hookSpecificOutput": {"hookEventName": "PostToolUse",
602
+ "additionalContext": f"Smart Tool shell review skipped: {reason}"}}
603
+
604
+
605
+ def _edit_review_scoped(payload, doc_mode, duplicate_mode, dependency_mode, comment_mode="off", layer_mode="off",
606
+ link_mode="off", decision_mode="off"):
389
607
  """`_edit_review` inside one `code_graph.pending_scope`, so the pending-changes scan runs once per review."""
390
608
  parts, doc_findings, comment_findings = _review_changes(
391
609
  edit_preview.preview(payload.get("tool_name"), payload.get("tool_input"), payload.get("cwd")),
392
- doc_mode, duplicate_mode, dependency_mode, comment_mode, layer_mode)
610
+ doc_mode, duplicate_mode, dependency_mode, comment_mode, layer_mode, link_mode, decision_mode)
393
611
  if not parts:
394
612
  return {}
395
613
  message = " ".join(parts)
@@ -404,20 +622,22 @@ def _edit_review_scoped(payload, doc_mode, duplicate_mode, dependency_mode, comm
404
622
 
405
623
  def decide(payload, client, web_route, jobs):
406
624
  """Hook output for one PreToolUse payload: edits follow doc_mode (require | remind | off) and duplicate_mode
407
- (warn | off) and dependency_mode (warn | off), and every edit review also notes credentials the edit writes, the other tools follow hook_mode (redirect | advise | off). In redirect mode the Smart Tool call that
625
+ (warn | off) and dependency_mode (warn | off) and decision_mode (warn | off), and every edit review also notes credentials the edit writes, the other tools follow hook_mode (redirect | advise | off). In redirect mode the Smart Tool call that
408
626
  replaces a redirected one starts in `jobs` under the call's tool_use_id (see `_redirect`); only a search whose
409
627
  query cannot be built, or a client that sends no tool_use_id, is denied with the exact call to make, and never in a
410
628
  subagent whose tool list has no Smart Tool MCP tool: it has nothing to switch to."""
411
629
  cfg = config.load_config()
630
+ note_shell_start(payload)
412
631
  if isinstance(payload, dict):
413
632
  requester.note_origin(payload.get("session_id"), payload.get("cwd"))
414
633
  if isinstance(payload, dict) and payload.get("tool_name") in EDIT_TOOLS:
415
- doc_mode, duplicate_mode, dependency_mode, comment_mode, layer_mode = (
634
+ doc_mode, duplicate_mode, dependency_mode, comment_mode, layer_mode, link_mode, decision_mode = (
416
635
  config.doc_mode(cfg), config.duplicate_mode(cfg), config.dependency_mode(cfg), config.comment_mode(cfg),
417
- config.layer_mode(cfg))
418
- if "off" == doc_mode == duplicate_mode == dependency_mode == comment_mode == layer_mode:
636
+ config.layer_mode(cfg), config.link_mode(cfg), config.decision_mode(cfg))
637
+ if "off" == doc_mode == duplicate_mode == dependency_mode == comment_mode == layer_mode == link_mode == decision_mode:
419
638
  return {}
420
- return _edit_review(payload, doc_mode, duplicate_mode, dependency_mode, comment_mode, layer_mode)
639
+ return _edit_review(payload, doc_mode, duplicate_mode, dependency_mode, comment_mode, layer_mode, link_mode,
640
+ decision_mode)
421
641
  if isinstance(payload, dict) and str(payload.get("tool_name")).startswith(f"mcp__{SMART_TOOL_SERVER}__"):
422
642
  if payload["tool_name"] == SMART_SEARCH_TOOL:
423
643
  router.CLIENT.set(client)
@@ -523,8 +743,8 @@ def _log_served(client, payload):
523
743
 
524
744
  def after(payload, client, jobs):
525
745
  """PostToolUse output: the call's own response with the Smart Tool answer started for its tool_use_id in the field
526
- the model reads (`updatedToolOutput`), or `{}` when there is none, it did not come in time or the response has an
527
- unknown shape (the native output stays)."""
746
+ the model reads (`updatedToolOutput`); for a shell call with no such answer, the notes of `_shell_review` on the files
747
+ it wrote; else `{}` (the native output stays)."""
528
748
  if not isinstance(payload, dict) or not payload.get("tool_use_id"):
529
749
  return {}
530
750
  key, tool_name = payload["tool_use_id"], payload.get("tool_name")
@@ -532,7 +752,7 @@ def after(payload, client, jobs):
532
752
  jobs.forget(key)
533
753
  output = tool_redirect.output_for(tool_name, payload.get("tool_response"), text) if text else None
534
754
  if output is None:
535
- return {}
755
+ return _shell_review(payload) if tool_name in tool_redirect.NO_OP else {}
536
756
  _log_served(client, payload)
537
757
  return {"hookSpecificOutput": {"hookEventName": "PostToolUse", "updatedToolOutput": output}}
538
758
 
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env python3
2
- """Hook PreToolUse de comando (Codex): cliente fino que repassa o payload ao daemon do Smart Tool (POST
3
- /hooks/pretool), onde a decisão roda já aquecida (`hook_decision.py`). O Claude Code chama a mesma rota direto, como
4
- hook `type: "http"`. Falha aberto: daemon fora do ar ou erro = saída neutra `{}`, nunca `allow`.
2
+ """Hook de comando (Codex): cliente fino que repassa o payload ao daemon do Smart Tool (POST /hooks/pretool, ou
3
+ /hooks/posttool com `--post`), onde a decisão roda já aquecida (`hook_decision.py`). O Claude Code chama as mesmas rotas
4
+ direto, como hook `type: "http"`. Falha aberto: daemon fora do ar ou erro = saída neutra `{}`, nunca `allow`.
5
5
  """
6
6
  import json
7
7
  import os
@@ -32,7 +32,8 @@ def main():
32
32
  print(json.dumps({"systemMessage": "Smart Tool: daemon subindo, roteamento pulado nesta chamada."},
33
33
  ensure_ascii=False))
34
34
  return
35
- request = urllib.request.Request(f"{base}/hooks/pretool?{urllib.parse.urlencode({'client': _client()})}",
35
+ route = "posttool" if "--post" in sys.argv[1:] else "pretool"
36
+ request = urllib.request.Request(f"{base}/hooks/{route}?{urllib.parse.urlencode({'client': _client()})}",
36
37
  data=raw, headers={"Content-Type": "application/json"}, method="POST")
37
38
  with urllib.request.urlopen(request, timeout=TIMEOUT_S) as response:
38
39
  output = json.loads(response.read() or b"{}")
package/install.py CHANGED
@@ -15,6 +15,8 @@ from pathlib import Path
15
15
 
16
16
  import atomic_io
17
17
  import client_hooks
18
+ import config
19
+ import i18n
18
20
  import paths
19
21
  import version
20
22
 
@@ -36,7 +38,32 @@ BLOCKED = {"__pycache__", ".token-guard", ".git", ".pytest_cache", ".data", ".ar
36
38
  ".scratch", ".memory", "docs", "reports", "site", "design", "release", "npm", ".github", "AGENTS.md", "CLAUDE.md", "DESIGN.md", "PRODUCT.md", "install.py", "uninstall.py", ".gitignore", ".gitattributes", MANIFEST}
37
39
  PACKAGE_ONLY = {"bin", "package.json", ".npmignore"}
38
40
  REQUIRED_TOOLS = {"smart_search", "smart_search_result", "web_search", "project_manage"}
41
+ LANGUAGE = "en"
39
42
  _OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))
43
+ def installer_language(requested=None):
44
+ """The language of the installer's messages: requested (--language), else the one picked in the settings, else the
45
+ Windows display language. Settings that cannot be read, or that hold an unknown language, are reported on stderr
46
+ and the Windows language is used."""
47
+ if requested:
48
+ return requested
49
+ problem, chosen = config.corrupted_reason(), ""
50
+ if not problem:
51
+ try:
52
+ chosen = config.language()
53
+ except (ValueError, config.ConfigCorruptedError) as exc:
54
+ problem = str(exc)
55
+ fallback = i18n.system_language()
56
+ if problem:
57
+ print(i18n.t("Could not read the Smart Tool settings, so the Windows language is used instead: {problem}",
58
+ lang=fallback, problem=problem), file=sys.stderr)
59
+ return chosen or fallback
60
+
61
+
62
+ def t(text, **values):
63
+ """text (an English catalog key) in LANGUAGE, with its {placeholders} filled from values."""
64
+ return i18n.t(text, lang=LANGUAGE, **values)
65
+
66
+
40
67
  def ships(rel):
41
68
  parts = Path(rel).parts
42
69
  *folders, name = parts
@@ -98,7 +125,7 @@ def stop_processes(target):
98
125
  if not left:
99
126
  return
100
127
  if time.monotonic() > deadline:
101
- raise RuntimeError(f"Could not close the running Smart Tool ({len(left)} process(es) still active).")
128
+ raise RuntimeError(t("Could not close the running Smart Tool ({count} process(es) still active).", count=len(left)))
102
129
  time.sleep(0.5)
103
130
 
104
131
 
@@ -123,7 +150,7 @@ def wait_port_free(target):
123
150
  stop_processes(target)
124
151
  time.sleep(0.5)
125
152
  if _daemon_up():
126
- raise RuntimeError("Another Smart Tool daemon is still active on the registered port; close it before updating.")
153
+ raise RuntimeError(t("Another Smart Tool daemon is still active on the registered port; close it before updating."))
127
154
 
128
155
 
129
156
  def _daemon_up():
@@ -193,7 +220,7 @@ def remove_other_installs(target):
193
220
  removed = []
194
221
  codex = hook_files()[1]
195
222
  for folder in other_installs(target):
196
- print(f"Older Smart Tool installation found at {folder}; removing it.")
223
+ print(t("Older Smart Tool installation found at {folder}; removing it.", folder=folder))
197
224
  stop_processes(folder)
198
225
  for path in hook_files():
199
226
  original = path.read_text(encoding="utf-8") if path.is_file() else ""
@@ -203,7 +230,7 @@ def remove_other_installs(target):
203
230
  atomic_io.backup_file(str(path))
204
231
  path.write_text(text, encoding="utf-8")
205
232
  client_hooks.record_codex_trust(trust, str(path.with_name("config.toml")))
206
- print(f"Hooks in {path} now point to {target}.")
233
+ print(t("Hooks in {path} now point to {target}.", path=path, target=target))
207
234
  startup = STARTUP_SCRIPT.read_text(encoding="utf-8", errors="replace") if STARTUP_SCRIPT.is_file() else ""
208
235
  if any(_same_folder(_script_folder(script), folder) for script in _script_paths(startup)):
209
236
  STARTUP_SCRIPT.unlink()
@@ -327,7 +354,7 @@ def prune_camoufox(target):
327
354
  browser = target / "web_adapters" / "browser"
328
355
  result = subprocess.run([str(browser / ".venv" / "Scripts" / "python.exe"), str(browser / "prune_camoufox.py")])
329
356
  if result.returncode:
330
- print(f"Old Camoufox builds not pruned: prune_camoufox.py exited {result.returncode}.", file=sys.stderr)
357
+ print(t("Old Camoufox builds not pruned: prune_camoufox.py exited {code}.", code=result.returncode), file=sys.stderr)
331
358
 
332
359
 
333
360
  def install_dependencies(target, python):
@@ -335,7 +362,7 @@ def install_dependencies(target, python):
335
362
  venv.create(python.parent.parent, with_pip=True)
336
363
  subprocess.run([str(python), "-m", "pip", "install", "--disable-pip-version-check", "-q", "-r",
337
364
  str(target / "requirements.txt")], check=True)
338
- subprocess.run([str(python), str(target / "install_runtime.py")], check=True)
365
+ subprocess.run([str(python), str(target / "install_runtime.py"), "--language", LANGUAGE], check=True)
339
366
 
340
367
 
341
368
  def start(target, python, pythonw):
@@ -357,17 +384,20 @@ def verify(target, python):
357
384
  "print(json.dumps({'version':running,'tools':sorted(r['name'] for r in json.load(opener.open(req,timeout=10))['result']['tools'])}))")
358
385
  result = subprocess.run([str(python), "-c", script], cwd=target, capture_output=True, text=True, timeout=60)
359
386
  if result.returncode:
360
- raise RuntimeError("Daemon did not respond: " + ((result.stderr or result.stdout).strip().splitlines() or ["no output"])[-1])
387
+ detail = ((result.stderr or result.stdout).strip().splitlines() or [t("no output")])[-1]
388
+ raise RuntimeError(t("Daemon did not respond: {detail}", detail=detail))
361
389
  served = json.loads(result.stdout.strip().splitlines()[-1])
362
390
  missing = REQUIRED_TOOLS - set(served["tools"])
363
391
  if missing:
364
- raise RuntimeError("Missing MCP tools: " + ", ".join(sorted(missing)))
392
+ raise RuntimeError(t("Missing MCP tools: {tools}", tools=", ".join(sorted(missing))))
365
393
  if served["version"] != version.VERSION:
366
- raise RuntimeError(f"The daemon runs version {served['version']}, not the {version.VERSION} being installed")
394
+ raise RuntimeError(t("The daemon runs version {running}, not the {expected} being installed",
395
+ running=served["version"], expected=version.VERSION))
367
396
  pid = json.loads(REGISTRY.read_text(encoding="utf-8"))["pid"]
368
397
  command = powershell(f"(Get-CimInstance Win32_Process -Filter 'ProcessId = {int(pid)}').CommandLine").stdout
369
398
  if str(target / "smart_tool_daemon.py").lower() not in command.lower():
370
- raise RuntimeError(f"The active daemon (pid {pid}) does not belong to this installation: {command.strip()[:200]}")
399
+ raise RuntimeError(t("The active daemon (pid {pid}) does not belong to this installation: {command}",
400
+ pid=pid, command=command.strip()[:200]))
371
401
 
372
402
 
373
403
  def enable_browser_control(target, python):
@@ -382,11 +412,12 @@ def enable_browser_control(target, python):
382
412
  except (OSError, subprocess.TimeoutExpired, ValueError, IndexError) as exc:
383
413
  result, outcome = None, f"{type(exc).__name__}: {exc}"
384
414
  if not isinstance(outcome, dict):
385
- detail = outcome or ((result.stderr or result.stdout).strip().splitlines() or ["no output"])[-1]
386
- print(f"Browser control not set up: {detail}")
415
+ detail = outcome or ((result.stderr or result.stdout).strip().splitlines() or [t("no output")])[-1]
416
+ print(t("Browser control not set up: {detail}", detail=detail))
387
417
  return
388
418
  for client, state in outcome.items():
389
- print(f"Browser control in {client}: {state['state']}" + (f" ({state['reason']})" if state.get("reason") else ""))
419
+ print(t("Browser control in {client}: {state}", client=client, state=state["state"])
420
+ + (f" ({state['reason']})" if state.get("reason") else ""))
390
421
 
391
422
 
392
423
  MIN_PYTHON = (3, 11)
@@ -404,18 +435,23 @@ def main():
404
435
  help="install without running tests/run.py (npm package, whose tests ran in CI; emergency only otherwise)")
405
436
  parser.add_argument("--expect-version",
406
437
  help="refuse to install unless this package is that version (the update screen passes the one it announced)")
438
+ parser.add_argument("--language", choices=config.LANGUAGES,
439
+ help="language of the messages (default: the setting, else the Windows display language)")
407
440
  args = parser.parse_args()
441
+ global LANGUAGE
442
+ LANGUAGE = installer_language(args.language)
408
443
  if args.expect_version and args.expect_version != version.VERSION:
409
- raise SystemExit(f"This package is Smart Tool {version.VERSION}, not the {args.expect_version} requested; "
410
- "nothing was changed.")
444
+ raise SystemExit(t("This package is Smart Tool {version}, not the {requested} requested; nothing was changed.",
445
+ version=version.VERSION, requested=args.expect_version))
411
446
  paths.refuse_overridden_folders("install")
412
447
  target = args.target.resolve()
413
448
  if target == SOURCE:
414
- raise SystemExit("The target cannot be the source folder itself.")
449
+ raise SystemExit(t("The target cannot be the source folder itself."))
415
450
  if args.skip_tests:
416
- print("Tests skipped by --skip-tests.")
451
+ print(t("Tests skipped by --skip-tests."))
417
452
  elif not (SOURCE / "tests" / "run.py").is_file():
418
- raise SystemExit(f"No test suite in {SOURCE}; a packaged install runs with --skip-tests (npx @allansantos-dev/smart-tool@{version.VERSION} install).")
453
+ raise SystemExit(t("No test suite in {source}; a packaged install runs with --skip-tests "
454
+ "(npx @allansantos-dev/smart-tool@{version} install).", source=SOURCE, version=version.VERSION))
419
455
  else:
420
456
  interpreter = python_paths(target)[0] if python_paths(target)[0].is_file() else Path(sys.executable)
421
457
  tests = subprocess.run([str(interpreter), str(SOURCE / "tests" / "run.py")], capture_output=True, text=True,
@@ -424,11 +460,13 @@ def main():
424
460
  if tests.stderr.strip():
425
461
  print(tests.stderr.rstrip()[-3000:], file=sys.stderr)
426
462
  if tests.returncode:
427
- raise SystemExit("Tests failed; installation aborted without touching the installed version.")
463
+ raise SystemExit(t("Tests failed; installation aborted without touching the installed version."))
428
464
  python, pythonw = python_paths(target)
429
465
  files = source_files()
430
466
  existed = (target / "smart_tool_daemon.py").is_file()
431
- print(("Updating" if existed else "Installing") + f" Smart Tool at {target} ({len(files)} files from {SOURCE})")
467
+ where = {"target": target, "count": len(files), "source": SOURCE}
468
+ print(t("Updating Smart Tool at {target} ({count} files from {source})", **where) if existed
469
+ else t("Installing Smart Tool at {target} ({count} files from {source})", **where))
432
470
  target.mkdir(parents=True, exist_ok=True)
433
471
  remove_other_installs(target)
434
472
  mark_updating(True)
@@ -439,8 +477,8 @@ def main():
439
477
  if not args.no_start:
440
478
  enable_browser_control(target, python)
441
479
  for folder in prune_backups(target):
442
- print(f"Removed the old copy {folder}.")
443
- print("Smart Tool ready." if not args.no_start else "Files installed; daemon not restarted (--no-start).")
480
+ print(t("Removed the old copy {folder}.", folder=folder))
481
+ print(t("Smart Tool ready.") if not args.no_start else t("Files installed; daemon not restarted (--no-start)."))
444
482
 
445
483
 
446
484
  def prune_backups(target):
@@ -456,7 +494,7 @@ def prune_backups(target):
456
494
  shutil.rmtree(folder)
457
495
  removed.append(str(folder))
458
496
  except OSError as exc:
459
- print(f"Could not remove the old copy {folder}: {exc}", file=sys.stderr)
497
+ print(t("Could not remove the old copy {folder}: {error}", folder=folder, error=exc), file=sys.stderr)
460
498
  return removed
461
499
 
462
500
 
@@ -474,19 +512,19 @@ def _update(args, target, files, existed, python, pythonw):
474
512
  try:
475
513
  copy_files(target, files, backup, changed, removed)
476
514
  clear_bytecode(target)
477
- print(f"Files changed: {len(changed)}; removed as obsolete: {len(removed)}")
515
+ print(t("Files changed: {changed}; removed as obsolete: {removed}", changed=len(changed), removed=len(removed)))
478
516
  if run_deps:
479
517
  frozen = freeze(python)
480
518
  deps_touched = True
481
519
  install_dependencies(target, python)
482
520
  elif not args.skip_deps:
483
- print("Dependencies unchanged since the last update; pip and install_runtime.py skipped.")
521
+ print(t("Dependencies unchanged since the last update; pip and install_runtime.py skipped."))
484
522
  if not args.no_start:
485
523
  mark_updating(False)
486
524
  start(target, python, pythonw)
487
525
  verify(target, python)
488
526
  except BaseException as exc:
489
- print(f"Failed: {exc}. Restoring the previous version.", file=sys.stderr)
527
+ print(t("Failed: {error}. Restoring the previous version.", error=exc), file=sys.stderr)
490
528
  problems = []
491
529
  steps = [lambda: mark_updating(True), lambda: stop_processes(target),
492
530
  lambda: restore(target, backup, changed, removed)]
@@ -500,7 +538,8 @@ def _update(args, target, files, existed, python, pythonw):
500
538
  except Exception as error:
501
539
  problems.append(str(error))
502
540
  if problems:
503
- print(f"Incomplete rollback; backup kept at {backup}: " + " | ".join(problems), file=sys.stderr)
541
+ print(t("Incomplete rollback; backup kept at {backup}: {problems}", backup=backup, problems=" | ".join(problems)),
542
+ file=sys.stderr)
504
543
  raise SystemExit(1)
505
544
  shutil.rmtree(backup, ignore_errors=True)
506
545
  raise SystemExit(1)