@allansantos-dev/smart-tool 0.9.56 → 0.9.61

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 CHANGED
@@ -1,5 +1,91 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.9.61 - beta
4
+
5
+ - Old Camoufox builds leave the user's cache. camoufox 0.5.6 installs each build in its own folder and never deletes
6
+ the previous one, so the cache grew by about 2.5 GB per build (8.2 GB on this machine, 2.5 GB of it in use). After
7
+ an update has been verified, the installer runs `web_adapters/browser/prune_camoufox.py`, which deletes the builds
8
+ of the active build's repository older than the active one and logs each removal with its size and the total freed.
9
+ It removes nothing when `pinned` is set in Camoufox's `config.json` or no build is active, and never touches the
10
+ active build, a newer one or another repository's. Each folder is renamed to a hidden name in `browsers/` before it
11
+ is deleted, which Windows refuses while a file inside is open, so a build in use is kept whole and logged; a
12
+ deletion cut short is finished on the next run. A failed pruning is reported and the update stays
13
+ (`tests/test_prune_camoufox.py`, `tests/test_install_legacy.py`). Research:
14
+ `docs/research/2026-11-04-camoufox-cache-pruning.md`.
15
+
16
+ ## 0.9.60 - beta
17
+
18
+ - A new `package-lock.json` reaches every install. `install_runtime.py` ran `npm ci` only when a parser file was
19
+ missing, so an install that already had them kept the old TypeScript, java-parser, Angular compiler and Playwright
20
+ MCP. After `npm ci` succeeds it now records the lock's SHA-256 in `node_modules/.smart-tool-lock.sha256`; a lock
21
+ that differs runs `npm ci` again, and `install_runtime.py --check` reports `node_packages: missing`, so an update
22
+ runs the dependency step for an install whose packages came from another lock, including one installed before this
23
+ version (`tests/test_install_runtime.py`). npm's own `node_modules/.package-lock.json` is not compared, because npm
24
+ ignores it whenever another tool touched the tree.
25
+ - A newer Camoufox browser build for the same library version arrives on every update. Since 0.9.59 an update whose
26
+ dependency files did not change skipped `fetch_camoufox.py`, so a new build reached an install only when one of
27
+ those files changed. When the dependency step is skipped, the installer now runs `fetch_camoufox.py` before stopping
28
+ the service. Camoufox compares the active build with the newest supported release, downloads a newer one into its
29
+ own folder and switches to it only after the SHA-256 check, so the running browser keeps its files and the stop
30
+ window does not grow. A failed download ends the update before anything was stopped or copied
31
+ (`tests/test_install_legacy.py`).
32
+
33
+ ## 0.9.59 - beta
34
+
35
+ - An update keeps open Claude Code sessions connected. The installer ran pip and `install_runtime.py` while the
36
+ service was stopped, about 48 s on a current machine, and Claude Code stops reconnecting after 5 attempts (about
37
+ 15 s), so every open session lost Smart Tool until `/mcp` (33 times in Claude Code's logs from 2026-10-02 to
38
+ 2026-11-04). After a completed update the installer records a SHA-256 of the files that decide the dependencies
39
+ (`requirements.txt`, `install_runtime.py`, `node_locator.py`, the Node `package.json` and `package-lock.json`, the
40
+ browser `requirements.txt`, `fetch_camoufox.py` and `ranged_download.py`) in `.dependencies.sha256`; the next update
41
+ whose files match skips that step and says so. A changed file, a missing record or a missing venv runs it as before,
42
+ and an update rolled back after the step leaves the old record (`tests/test_install_legacy.py`).
43
+ - A restart keeps the port the clients already know. The service tried the default port first, so a restart after
44
+ it had moved to another port went back to the default and cut every session still on the other one; it now tries
45
+ the port in the clients' configuration first, then the default, then any free port (`tests/test_endpoint_sync.py`).
46
+ - A search inside `$(...)` or `` `...` `` is judged in the folder its segment runs in. The redirect hook decided every
47
+ substitution of a command with the folder at its start, so `cd outside; echo $(grep -rn x .)` was redirected as a
48
+ search of the session folder, and a `cd` inside a substitution moved the commands after it; a substitution is now
49
+ decided with the state of its own segment, and its `cd` stays inside it (`tests/test_router.py`).
50
+ - The test files can run in one process (`python -m unittest a b ...`, as the `affected_tests` command suggests).
51
+ Classes replaced functions of shared modules in `setUpClass` without restoring them, and the gateway tests left a
52
+ user adapter folder behind, so 21 tests failed and 8 errored together while each file passed alone; the
53
+ replacements now go through `mock.patch.object` with a class cleanup (`tests/_env.py`, `patch_for_class`).
54
+ - `server/discover`, which Claude Code 2.1.316 sends before `initialize`, keeps its JSON-RPC -32601 answer: the
55
+ daemon speaks protocol 2025-06-18, and a client that gets any error other than -32022 falls back to `initialize`, as
56
+ the protocol revision that defines the method asks (`tests/test_mcp_transport.py`).
57
+
58
+ ## 0.9.58 - beta
59
+
60
+ - Claude Code no longer drops the Smart Tool connection while the service is up. `GET /mcp` and `DELETE /mcp` answer
61
+ 405 with `Allow: POST`, as the MCP Streamable HTTP transport allows for a server with no server-initiated stream and
62
+ no client-ended sessions; they answered 404, which the MCP SDK client treats as a broken connection: Claude Code's
63
+ logs held two `Failed to open SSE stream: Not Found` per connection, 4,838 between 2026-10-02 and 2026-11-04, and the
64
+ connection was later closed "with errors" and reopened. A DELETE elsewhere answers 404 instead of 501
65
+ (`tests/test_mcp_transport.py`).
66
+ - A tool call longer than a minute reaches Claude Code. Claude Code aborts an MCP request whose response has not
67
+ started within 60 s, so a long `web_search`, `web_fetch` or `smart_scout` ended in `The operation timed out.` (202
68
+ times in the same logs). A `tools/call` from a client that accepts `text/event-stream` and still running after 10 s
69
+ is answered as an SSE stream: headers at once, a comment every 15 s, and the result as its only event. A faster call,
70
+ or a client that does not accept SSE, gets the single JSON body as before (`tests/test_mcp_transport.py`; diagnosis
71
+ in `docs/research/2026-11-04-mcp-client-drops.md`).
72
+
73
+ ## 0.9.57 - beta
74
+
75
+ - Codex runs Smart Tool's hooks with no `/hooks` step. Installing or updating the Codex redirect hook or the
76
+ session-start hook also records the approval of the new definition in Codex's `config.toml`, as `/hooks` does: the
77
+ `trusted_hash` Codex computes for that handler, written after a backup with every other line left as it was, and
78
+ read back before the step reports success. The new entry takes the place of the old one, so the other hooks keep
79
+ their index and their approval; turning the session-start hook off carries the approval of an approved hook that
80
+ moves up to its new index. When the installer points the hooks at a new install folder, each Smart Tool hook that
81
+ was approved keeps its approval. A Codex entry that is current but not approved shows as outdated (session-start
82
+ hook: "Not approved in Codex"), and updating records the approval. A `config.toml` that is not valid TOML stops the
83
+ step before `hooks.json` is written (`tests/test_codex_audit_hook.py`, `tests/test_install_legacy.py`).
84
+ - `project_manage action=install_hook_preview` returns the `plan_id` that `action=install_hook` takes, as its
85
+ description says; it returned the identifier under `token`, so an agent could not finish the update.
86
+ - Two hook steps in the same second (updating the redirect hook, then the session-start hook) keep separate backups:
87
+ the second gets a numbered name instead of overwriting the first, which holds the file as it was before both.
88
+
3
89
  ## 0.9.56 - beta
4
90
 
5
91
  - Every command hook Smart Tool writes ends with `--hook-origin=smart-tool`: the Codex redirect hook
package/README.md CHANGED
@@ -17,7 +17,7 @@ registered as the `playwright` server where this machine lets a browser be drive
17
17
  An optional hook routes the agent's native Grep/Glob/Read/Bash/WebSearch/WebFetch calls to these tools when they
18
18
  are cheaper, or just tells the agent what Smart Tool would do.
19
19
 
20
- **Status:** 0.9.56 beta. Windows only. What changed in each version: [CHANGELOG.md](CHANGELOG.md).
20
+ **Status:** 0.9.61 beta. Windows only. What changed in each version: [CHANGELOG.md](CHANGELOG.md).
21
21
 
22
22
  ## How it works
23
23
 
@@ -83,7 +83,7 @@ gateway such as Ollama, nothing about your code leaves the machine.
83
83
  ## Install
84
84
 
85
85
  ```powershell
86
- npx @allansantos-dev/smart-tool@0.9.56 install
86
+ npx @allansantos-dev/smart-tool@0.9.61 install
87
87
  ```
88
88
 
89
89
  Updates install themselves, on by default: the tray checks npm when it starts (at logon) and every 24 h, and when there
@@ -150,7 +150,9 @@ Redirects) and Maintenance (Setup audit, Startup).
150
150
  command hook it writes (the Codex redirect hook and the session-start hook) ends with
151
151
  `--hook-origin=smart-tool`, so its command line names Smart Tool as its owner; an entry written before that shows
152
152
  as outdated, and updating replaces it instead of adding a second one. Claude Code's redirect hooks are HTTP
153
- entries with no command line.
153
+ entries with no command line. In Codex, installing or updating a hook replaces Smart Tool's entry in place and
154
+ records its approval in `~/.codex/config.toml`, as `/hooks` would, so Codex runs it with no approval step; the
155
+ other hooks keep theirs.
154
156
 
155
157
  **Browser control** comes with the registration, and with every update for clients where smart-tool is registered:
156
158
  the official Playwright MCP (pinned in `web_adapters/node`) is registered as the `playwright` server, driving the
@@ -270,8 +272,9 @@ Redirects) and Maintenance (Setup audit, Startup).
270
272
  when none is stored. Optionally, **Report at session start** on the Setup audit page (Claude Code or Codex) starts
271
273
  every new session with the update notices and the redirect proposals waiting for a decision: it previews the exact
272
274
  SessionStart entry, adds it to `~/.claude/settings.json` or `~/.codex/hooks.json` only after you confirm (backup
273
- first), and **Turn off** removes only that entry. Codex runs a new hook only after you approve it in `/hooks`;
274
- until then the page shows "waiting for your approval". It is off by default. The hook script
275
+ first), and **Turn off** removes only that entry. In Codex the same step records the approval of the new
276
+ definition in `~/.codex/config.toml`, as `/hooks` would, so no `/hooks` step is left; an entry Codex does not trust
277
+ shows "Not approved in Codex", and **Update** records it. It is off by default. The hook script
275
278
  (`hooks/session_audit.py`) only asks the running service and prints nothing when the service is down.
276
279
  4. **Local models** (optional): if the mcp-memory embedding sidecar is installed on the machine, its local embedder
277
280
  can serve as a fallback (or preferred) embedding model.
package/client_hooks.py CHANGED
@@ -35,7 +35,8 @@ CLIENTS = {
35
35
  "post_matcher": "Grep|Bash|PowerShell|WebFetch|WebSearch"},
36
36
  "codex": {"label": "Codex", "prefix": "codex", "files": [os.path.join(endpoint_sync.codex_dir(), "hooks.json"), os.path.join(endpoint_sync.codex_dir(), "config.toml")],
37
37
  "docs": "https://learn.chatgpt.com/docs/hooks", "event": "PreToolUse", "matcher": "Bash|apply_patch",
38
- "after_install": "Codex only runs new hooks after the user approves the definition in /hooks."},
38
+ "after_install": "Smart Tool recorded the approval of the new definition in Codex's config.toml, as /hooks "
39
+ "would, so Codex runs it from the next session on."},
39
40
  "cursor": {"label": "Cursor", "prefix": "cursor", "files": [os.path.join(HOME, ".cursor", "hooks.json")],
40
41
  "docs": "https://cursor.com/docs/agent/hooks", "event": "preToolUse", "matcher": "Shell|Read|Grep",
41
42
  "blocked": "In Cursor, `allow` approves the tool without the user and empty output blocks: there is no documented neutral "
@@ -86,9 +87,10 @@ def _target(handler):
86
87
  return handler.get("url") or handler.get("command") or ""
87
88
 
88
89
 
89
- def inspect(client):
90
+ def inspect(client, trust=True):
90
91
  """Our hook in the client's config: `current`, `missing`, or `outdated` (an older entry of ours) with `changes`,
91
- plain sentences saying what an update rewrites (tools the old matcher leaves out, an old address or timeout)."""
92
+ plain sentences saying what an update rewrites (tools the old matcher leaves out, an old address or timeout).
93
+ In Codex a current entry that config.toml does not trust is outdated too, unless trust=False."""
92
94
  spec = CLIENTS[client]
93
95
  for path in spec["files"]:
94
96
  try:
@@ -106,6 +108,8 @@ def inspect(client):
106
108
  for event, (matcher, expected) in _entries(client).items():
107
109
  groups = hooks.get(event) if isinstance(hooks, dict) else None
108
110
  changes += _entry_changes(event, matcher, expected, groups)
111
+ if client == "codex" and trust and not changes and not _codex_trusted(event, groups, _our_hook):
112
+ changes.append(f"Codex has not approved its {event} entry; an update records the approval.")
109
113
  return {"state": "outdated" if changes else "current", "changes": changes}
110
114
  return {"state": "missing", "changes": []}
111
115
 
@@ -202,9 +206,20 @@ def _handler(client, route=HTTP_PATH, timeout=HTTP_TIMEOUT_S):
202
206
  return {"type": "command", "command": _command(client), "timeout": timeout}
203
207
 
204
208
 
209
+ def _slot(groups, is_ours):
210
+ """Index, among the groups left once ours are taken out, where our replacement entry goes: the place of our first
211
+ group that holds only our hooks, so the groups after it keep their index (Codex keys an approval by that index);
212
+ the end when there is no such group."""
213
+ for kept, group in enumerate(groups):
214
+ if _ours(group, is_ours) and all(map(is_ours, group["hooks"])):
215
+ return kept
216
+ return len(_without_ours(groups, is_ours))
217
+
218
+
205
219
  def _plan(client_info):
206
220
  """(client, spec, path, data, changes): the client's config with our entries already taken out, and changes
207
- {event: (groups, entry)}, the entry to append to each event's groups."""
221
+ {event: (groups, entry, slot, before)}: the entry to insert at `slot` of each event's groups, and the groups as
222
+ they were before."""
208
223
  client = identify(client_info)
209
224
  if client is None:
210
225
  raise ValueError(f"Unrecognized MCP client ({(client_info or {}).get('name') or 'no clientInfo'}); "
@@ -225,8 +240,9 @@ def _plan(client_info):
225
240
  groups = data["hooks"].setdefault(event, [])
226
241
  if not isinstance(groups, list):
227
242
  raise ValueError(f"{path}: hooks.{event} is not a list; nothing was changed.")
243
+ before, slot = list(groups), _slot(groups, _our_hook)
228
244
  groups[:] = _without_ours(groups)
229
- changes[event] = (groups, {"matcher": matcher, "hooks": [handler]})
245
+ changes[event] = (groups, {"matcher": matcher, "hooks": [handler]}, slot, before)
230
246
  return client, spec, path, data, changes
231
247
 
232
248
 
@@ -239,7 +255,7 @@ def preview(client_info):
239
255
  token = secrets.token_urlsafe(12)
240
256
  _PREVIEWS[token] = {"client": client, "at": time.time()}
241
257
  return {"client": client, "installed": False, "file": path,
242
- "change": {event: entry for event, (_groups, entry) in changes.items()},
258
+ "change": {event: entry for event, (_groups, entry, _slot, _before) in changes.items()},
243
259
  "token": token, "expires_s": PREVIEW_TTL_S, "after_install": spec.get("after_install")}
244
260
 
245
261
 
@@ -252,20 +268,38 @@ def install(client_info, token, confirm):
252
268
  raise ValueError("Installing requires the install_hook_preview token from this session (valid for 10 min) and confirm=true.")
253
269
  if installed(client):
254
270
  return {"client": client, "installed": True, "changed": False, "file": path}
255
- for groups, entry in changes.values():
256
- groups.append(entry)
257
- backup = _write_checked(path, data, lambda: installed(client), "The hook")
271
+ if client == "codex":
272
+ _codex_states()
273
+ for groups, entry, slot, _before in changes.values():
274
+ groups.insert(slot, entry)
275
+ backup = _write_checked(path, data, lambda: inspect(client, trust=False)["state"] == "current", "The hook")
276
+ if client == "codex":
277
+ record_codex_trust({key: value for event, (groups, _entry, _slot, before) in changes.items()
278
+ for key, value in _codex_trust(event, before, groups).items()})
279
+ if not installed(client):
280
+ raise RuntimeError(f"Codex does not trust the hook in {path} after recording its approval.")
258
281
  return {"client": client, "installed": True, "changed": True, "file": path, "backup": backup,
259
282
  "after_install": spec.get("after_install")}
260
283
 
261
284
 
285
+ def backup_file(path):
286
+ """Copies path to a timestamped `.smart-tool-backup-` file beside it and returns that path, None when path does not
287
+ exist. A second backup in the same second gets a numbered name, so it never overwrites the copy of an earlier step."""
288
+ if not os.path.exists(path):
289
+ return None
290
+ stamp = f"{path}.smart-tool-backup-{time.strftime('%Y%m%d-%H%M%S')}"
291
+ backup, number = stamp, 1
292
+ while os.path.exists(backup):
293
+ number += 1
294
+ backup = f"{stamp}-{number}"
295
+ shutil.copy2(path, backup)
296
+ return backup
297
+
298
+
262
299
  def _write_checked(path, data, verify, what):
263
300
  """Writes data as JSON to path through a temp file after a timestamped backup; when verify() fails on the written
264
301
  file, restores the backup (or removes the new file) and raises. Returns the backup path (None for a new file)."""
265
- backup = None
266
- if os.path.exists(path):
267
- backup = f"{path}.smart-tool-backup-{time.strftime('%Y%m%d-%H%M%S')}"
268
- shutil.copy2(path, backup)
302
+ backup = backup_file(path)
269
303
  os.makedirs(os.path.dirname(path), exist_ok=True)
270
304
  temporary = path + ".smart-tool-tmp"
271
305
  with open(temporary, "w", encoding="utf-8") as stream:
@@ -300,7 +334,8 @@ def _audit_client(client):
300
334
 
301
335
 
302
336
  def _audit_plan(client="claude"):
303
- """(path, data, groups) of the client's hooks file with our SessionStart entry already removed from groups."""
337
+ """(path, data, groups, slot, before) of the client's hooks file: groups with our SessionStart entry already
338
+ removed, the slot where a replacement goes and the groups as they were before."""
304
339
  path = os.path.realpath(_audit_client(client)["files"][0])
305
340
  try:
306
341
  with open(path, encoding="utf-8") as stream:
@@ -312,8 +347,9 @@ def _audit_plan(client="claude"):
312
347
  groups = data["hooks"].setdefault("SessionStart", [])
313
348
  if not isinstance(groups, list):
314
349
  raise ValueError(f"{path}: hooks.SessionStart is not a list; nothing was changed.")
350
+ before, slot = list(groups), _slot(groups, _audit_hook)
315
351
  groups[:] = _without_ours(groups, _audit_hook)
316
- return path, data, groups
352
+ return path, data, groups, slot, before
317
353
 
318
354
 
319
355
  def _codex_hash(event, group, index=0):
@@ -331,35 +367,173 @@ def _codex_hash(event, group, index=0):
331
367
  return "sha256:" + hashlib.sha256(text.encode("utf-8")).hexdigest()
332
368
 
333
369
 
334
- def _codex_approved(groups):
335
- """Our SessionStart handler is trusted in Codex's config.toml: the entry keyed by hooks.json path, event, group
336
- and handler index holds the hash of the definition as it is now (a missing or different hash means /hooks has not
337
- approved it, so Codex does not run it). An unreadable config.toml raises ValueError."""
338
- spec = CLIENTS["codex"]
370
+ def _codex_event(event):
371
+ """Codex's snake_case name of a hooks.json event (`PreToolUse` -> `pre_tool_use`), as in its state keys."""
372
+ return "".join(f"_{char.lower()}" if char.isupper() else char for char in event).lstrip("_")
373
+
374
+
375
+ def _codex_key(event, group_index, handler_index, hooks=None):
376
+ """Codex's `hooks.state` key of one handler of `hooks` (default: Codex's hooks.json): file path, event, group
377
+ index, handler index."""
378
+ return f"{hooks or CLIENTS['codex']['files'][0]}:{_codex_event(event)}:{group_index}:{handler_index}"
379
+
380
+
381
+ def _codex_states(path=None):
382
+ """The `hooks.state` table of Codex's config.toml at `path` (default: Codex's), {} when the file or the table is
383
+ missing; a config.toml that is not valid TOML raises ValueError."""
384
+ path = path or CLIENTS["codex"]["files"][1]
339
385
  try:
340
- with open(spec["files"][1], encoding="utf-8") as stream:
386
+ with open(path, encoding="utf-8") as stream:
341
387
  hooks = tomllib.loads(stream.read()).get("hooks")
342
- states = hooks.get("state") if isinstance(hooks, dict) else None
343
- states = states if isinstance(states, dict) else {}
344
388
  except FileNotFoundError:
345
- return False
389
+ return {}
346
390
  except tomllib.TOMLDecodeError as exc:
347
- raise ValueError(f"{spec['files'][1]} is not valid TOML: {exc}")
348
- paths = {spec["files"][0], os.path.realpath(spec["files"][0])}
391
+ raise ValueError(f"{path} is not valid TOML: {exc}")
392
+ states = hooks.get("state") if isinstance(hooks, dict) else None
393
+ return states if isinstance(states, dict) else {}
394
+
395
+
396
+ def _codex_trusted(event, groups, is_ours):
397
+ """Our handler under `event` is trusted in Codex's config.toml: the entry keyed by hooks.json path, event, group
398
+ and handler index holds the hash of the definition as it is now (a missing or different hash means Codex does not
399
+ run it). An unreadable config.toml raises ValueError."""
400
+ states = _codex_states()
401
+ name = _codex_event(event)
402
+ path = CLIENTS["codex"]["files"][0]
349
403
  for group_index, group in enumerate(groups):
350
- if not _ours(group, _audit_hook):
404
+ if not _ours(group, is_ours):
351
405
  continue
352
- handler_index = next(i for i, hook in enumerate(group["hooks"]) if _audit_hook(hook))
353
- for path in paths:
354
- trusted = (states.get(f"{path}:session_start:{group_index}:{handler_index}") or {}).get("trusted_hash")
355
- if trusted == _codex_hash("session_start", group, handler_index):
406
+ handler_index = next(i for i, hook in enumerate(group["hooks"]) if is_ours(hook))
407
+ for prefix in {path, os.path.realpath(path)}:
408
+ trusted = (states.get(f"{prefix}:{name}:{group_index}:{handler_index}") or {}).get("trusted_hash")
409
+ if trusted == _codex_hash(name, group, handler_index):
356
410
  return True
357
411
  return False
358
412
 
359
413
 
414
+ def _command_handlers(groups):
415
+ """(group index, handler index, group, handler) of every command handler in an event's groups."""
416
+ return [(group_index, handler_index, group, hook) for group_index, group in enumerate(groups)
417
+ if isinstance(group, dict) and isinstance(group.get("hooks"), list)
418
+ for handler_index, hook in enumerate(group["hooks"])
419
+ if isinstance(hook, dict) and hook.get("type") == "command" and "command" in hook]
420
+
421
+
422
+ def _codex_trust(event, before, after):
423
+ """{state key: trusted hash} Codex needs once Smart Tool rewrote one event's groups from `before` to `after`: our
424
+ handlers, which the user approved by confirming the change, and every other command handler that moved to a new
425
+ index while config.toml trusts its definition at the old one."""
426
+ states = _codex_states()
427
+ name = _codex_event(event)
428
+ old = {id(hook): (group_index, handler_index, group)
429
+ for group_index, handler_index, group, hook in _command_handlers(before)}
430
+ wanted = {}
431
+ for group_index, handler_index, group, hook in _command_handlers(after):
432
+ key = _codex_key(event, group_index, handler_index)
433
+ if _our_hook(hook) or _audit_hook(hook):
434
+ wanted[key] = _codex_hash(name, group, handler_index)
435
+ continue
436
+ found = old.get(id(hook))
437
+ if found and found[:2] != (group_index, handler_index):
438
+ trusted = (states.get(_codex_key(event, *found[:2])) or {}).get("trusted_hash")
439
+ if trusted == _codex_hash(name, found[2], found[1]):
440
+ wanted[key] = _codex_hash(name, group, handler_index)
441
+ return wanted
442
+
443
+
444
+ def _toml_table(line):
445
+ """Key path of a `[table]` header line (`[hooks.state.'x']` -> ("hooks", "state", "x")), None for any other line."""
446
+ stripped = line.strip()
447
+ if not stripped.startswith("[") or stripped.startswith("[["):
448
+ return None
449
+ try:
450
+ table = tomllib.loads(stripped)
451
+ except tomllib.TOMLDecodeError:
452
+ return None
453
+ path = []
454
+ while isinstance(table, dict) and len(table) == 1:
455
+ key = next(iter(table))
456
+ path.append(key)
457
+ table = table[key]
458
+ return tuple(path)
459
+
460
+
461
+ def _with_trusted_hash(lines, key, value, newline):
462
+ """config.toml lines with `trusted_hash = "<value>"` under `[hooks.state.<key>]`: replaced or added inside the
463
+ table when its header exists, else a new table at the end."""
464
+ line = f'trusted_hash = "{value}"{newline}'
465
+ header = next((i for i, text in enumerate(lines) if _toml_table(text) == ("hooks", "state", key)), None)
466
+ if header is None:
467
+ if lines and not lines[-1].endswith("\n"):
468
+ lines[-1] += newline
469
+ quoted = f"'{key}'" if "'" not in key else json.dumps(key)
470
+ return lines + [newline, f"[hooks.state.{quoted}]{newline}", line]
471
+ end = next((i for i in range(header + 1, len(lines)) if lines[i].lstrip().startswith("[")), len(lines))
472
+ for i in range(header + 1, end):
473
+ if lines[i].split("=")[0].strip() == "trusted_hash":
474
+ lines[i] = line
475
+ return lines
476
+ lines.insert(header + 1, line)
477
+ return lines
478
+
479
+
480
+ def repoint_trust(hooks_path, before_text, after_text):
481
+ """{state key: hash} for Codex's hooks.json at hooks_path once the installer rewrote it from before_text to
482
+ after_text to point at a new install folder: each handler of ours whose old definition config.toml trusted at the
483
+ same index gets the hash of its new one, so the move does not stop it. An unreadable config.toml raises ValueError."""
484
+ states = _codex_states(os.path.join(os.path.dirname(hooks_path), "config.toml"))
485
+ before = json.loads(before_text).get("hooks") or {}
486
+ wanted = {}
487
+ for event, groups in (json.loads(after_text).get("hooks") or {}).items():
488
+ old = {position[:2]: position for position in _command_handlers(before.get(event) or [])}
489
+ for group_index, handler_index, group, hook in _command_handlers(groups):
490
+ key = _codex_key(event, group_index, handler_index, hooks_path)
491
+ was = old.get((group_index, handler_index))
492
+ if (_our_hook(hook) or _audit_hook(hook)) and was and (states.get(key) or {}).get("trusted_hash") == \
493
+ _codex_hash(_codex_event(event), was[2], handler_index):
494
+ wanted[key] = _codex_hash(_codex_event(event), group, handler_index)
495
+ return wanted
496
+
497
+
498
+ def record_codex_trust(wanted, path=None):
499
+ """Records Codex's approval of each {state key: hash} in its config.toml at `path` (default: Codex's), as /hooks
500
+ does, after a timestamped backup; every other line keeps its text. A file that does not read back with these hashes
501
+ is restored and raises. Returns the backup path, None when there was nothing to record or no file before."""
502
+ if not wanted:
503
+ return None
504
+ path = path or CLIENTS["codex"]["files"][1]
505
+ try:
506
+ with open(path, encoding="utf-8", newline="") as stream:
507
+ text = stream.read()
508
+ except FileNotFoundError:
509
+ text = ""
510
+ newline = "\r\n" if "\r\n" in text else "\n"
511
+ lines = text.splitlines(keepends=True)
512
+ for key, value in wanted.items():
513
+ lines = _with_trusted_hash(lines, key, value, newline)
514
+ backup = backup_file(path)
515
+ os.makedirs(os.path.dirname(path), exist_ok=True)
516
+ temporary = path + ".smart-tool-tmp"
517
+ with open(temporary, "w", encoding="utf-8", newline="") as stream:
518
+ stream.write("".join(lines))
519
+ os.replace(temporary, path)
520
+ try:
521
+ states = _codex_states(path)
522
+ recorded = all((states.get(key) or {}).get("trusted_hash") == value for key, value in wanted.items())
523
+ except ValueError:
524
+ recorded = False
525
+ if not recorded:
526
+ if backup:
527
+ shutil.copy2(backup, path)
528
+ else:
529
+ os.remove(path)
530
+ raise RuntimeError(f"The hook approval does not read back from {path} after writing; the file was restored.")
531
+ return backup
532
+
533
+
360
534
  def audit_state(client="claude"):
361
535
  """The SessionStart audit hook in the client's hooks file: `current` (our entry equals this version's and, in
362
- Codex, was approved in /hooks), `waiting_approval` (Codex only: written but not approved, so it does not run yet),
536
+ Codex, config.toml trusts it), `waiting_approval` (Codex only: written but not trusted, so it does not run yet),
363
537
  `outdated` (an entry of ours that differs) or `missing`."""
364
538
  path = _audit_client(client)["files"][0]
365
539
  try:
@@ -373,11 +547,11 @@ def audit_state(client="claude"):
373
547
  return "missing"
374
548
  if _audit_entry() not in found:
375
549
  return "outdated"
376
- return "current" if client != "codex" or _codex_approved(groups) else AUDIT_WAITING
550
+ return "current" if client != "codex" or _codex_trusted("SessionStart", groups, _audit_hook) else AUDIT_WAITING
377
551
 
378
552
 
379
553
  def audit_hook_installed(client):
380
- """The session-start hook is on and running (Codex: approved in /hooks), so a search need not repeat the redirect
554
+ """The session-start hook is on and running (Codex: trusted in config.toml), so a search need not repeat the redirect
381
555
  proposals it already carries.
382
556
  An unreadable config file counts as off here; `audit_state` raises for it on the setup screen."""
383
557
  if client not in AUDIT_CLIENTS:
@@ -389,16 +563,16 @@ def audit_hook_installed(client):
389
563
 
390
564
 
391
565
  def _audit_after(client):
392
- """{after_install: ...} for a client whose new hooks need the user's approval, else nothing."""
566
+ """{after_install: ...} for a client whose new hooks run only once approved, else nothing."""
393
567
  note = CLIENTS[client].get("after_install")
394
568
  return {"after_install": note} if note else {}
395
569
 
396
570
 
397
571
  def audit_preview(client="claude"):
398
572
  """The change that turns the SessionStart audit report on in the client, with a token for `audit_install`."""
399
- path, _data, _groups = _audit_plan(client)
573
+ path = _audit_plan(client)[0]
400
574
  entry = _audit_entry()
401
- if audit_state(client) in (AUDIT_ON, AUDIT_WAITING):
575
+ if audit_state(client) == AUDIT_ON:
402
576
  return {"installed": True, "file": path, "change": None}
403
577
  token = secrets.token_urlsafe(12)
404
578
  _PREVIEWS[token] = {"client": f"audit:{client}", "at": time.time()}
@@ -408,25 +582,34 @@ def audit_preview(client="claude"):
408
582
 
409
583
  def audit_install(token, confirm, client="claude"):
410
584
  """Writes the SessionStart audit entry into the client's hooks file with a backup; needs the `audit_preview` token
411
- (10 min) and confirm=True. Returns {installed, changed, file, backup}, plus `after_install` in Codex: the hook
412
- runs only after the user approves it in /hooks."""
585
+ (10 min) and confirm=True; in Codex it also records the approval in config.toml. Returns {installed, changed, file,
586
+ backup}, plus `after_install` in Codex."""
413
587
  planned = _PREVIEWS.pop(token or "", None)
414
588
  if confirm is not True or not planned or planned["client"] != f"audit:{client}" or time.time() - planned["at"] > PREVIEW_TTL_S:
415
589
  raise ValueError("Turning the audit report on requires the preview token (valid for 10 min) and confirm=true.")
416
- path, data, groups = _audit_plan(client)
417
- if audit_state(client) in (AUDIT_ON, AUDIT_WAITING):
590
+ path, data, groups, slot, before = _audit_plan(client)
591
+ if audit_state(client) == AUDIT_ON:
418
592
  return {"installed": True, "changed": False, "file": path}
419
- groups.append(_audit_entry())
593
+ if client == "codex":
594
+ _codex_states()
595
+ groups.insert(slot, _audit_entry())
420
596
  backup = _write_checked(path, data, lambda: audit_state(client) in (AUDIT_ON, AUDIT_WAITING), "The audit hook")
597
+ if client == "codex":
598
+ record_codex_trust(_codex_trust("SessionStart", before, groups))
599
+ if audit_state(client) != AUDIT_ON:
600
+ raise RuntimeError(f"Codex does not trust the audit hook in {path} after recording its approval.")
421
601
  return {"installed": True, "changed": True, "file": path, "backup": backup, **_audit_after(client)}
422
602
 
423
603
 
424
604
  def audit_remove(client="claude"):
425
- """Takes only our SessionStart entry out of the client's hooks file (after a backup); nothing else is touched."""
426
- path, data, groups = _audit_plan(client)
605
+ """Takes only our SessionStart entry out of the client's hooks file (after a backup); in Codex the hooks after it
606
+ keep their approval at their new index. Nothing else is touched."""
607
+ path, data, groups, _slot_at, before = _audit_plan(client)
427
608
  if audit_state(client) == "missing":
428
609
  return {"installed": False, "changed": False, "file": path}
429
610
  if not groups:
430
611
  del data["hooks"]["SessionStart"]
431
612
  backup = _write_checked(path, data, lambda: audit_state(client) == "missing", "The removal")
613
+ if client == "codex":
614
+ record_codex_trust(_codex_trust("SessionStart", before, groups))
432
615
  return {"installed": False, "changed": True, "file": path, "backup": backup}
package/install.py CHANGED
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env python3
2
2
  import argparse
3
3
  import filecmp
4
+ import hashlib
4
5
  import json
5
6
  import os
6
7
  import re
@@ -12,6 +13,7 @@ import urllib.request
12
13
  import venv
13
14
  from pathlib import Path
14
15
 
16
+ import client_hooks
15
17
  import paths
16
18
  import version
17
19
 
@@ -23,6 +25,10 @@ HOOK_SCRIPTS = ("pretool_router.py", "session_audit.py")
23
25
  STARTUP_SCRIPT = Path(os.environ.get("APPDATA", str(Path.home() / "AppData" / "Roaming"))) / "Microsoft" / "Windows" / \
24
26
  "Start Menu" / "Programs" / "Startup" / "SmartTool-Tray.vbs"
25
27
  MANIFEST = ".install-manifest.json"
28
+ DEPENDENCY_INPUTS = ("requirements.txt", "install_runtime.py", "node_locator.py", "web_adapters/node/package.json",
29
+ "web_adapters/node/package-lock.json", "web_adapters/browser/requirements.txt",
30
+ "web_adapters/browser/fetch_camoufox.py", "web_adapters/browser/ranged_download.py")
31
+ DEPENDENCY_STAMP = ".dependencies.sha256"
26
32
  REGISTRY = Path(paths.DATA_DIR) / "daemon.json"
27
33
  BLOCKED = {"__pycache__", ".token-guard", ".git", ".pytest_cache", ".data", ".artifacts", ".claude", ".vscode",
28
34
  ".impeccable", "tests", "sessions", "results", "dist", "node_modules", ".node-runtime", ".venv",
@@ -129,8 +135,9 @@ def _daemon_up():
129
135
 
130
136
 
131
137
  def hook_files():
138
+ """Claude Code's settings.json and Codex's hooks.json (CLAUDE_CONFIG_DIR and CODEX_HOME when set)."""
132
139
  claude = Path(os.environ.get("CLAUDE_CONFIG_DIR") or Path.home() / ".claude")
133
- return claude / "settings.json", Path.home() / ".codex" / "hooks.json"
140
+ return claude / "settings.json", Path(os.environ.get("CODEX_HOME") or Path.home() / ".codex") / "hooks.json"
134
141
 
135
142
 
136
143
  def _script_paths(text):
@@ -179,10 +186,11 @@ def _repointed(text, folder, target):
179
186
 
180
187
 
181
188
  def remove_other_installs(target):
182
- """An older installation in another folder keeps the port and the hooks: stop it, point the hooks at target and
183
- delete its program folder. Its state folders are left alone."""
189
+ """An older installation in another folder keeps the port and the hooks: stop it, point the hooks at target (in
190
+ Codex, with the approval of each trusted hook of ours carried to its new command) and delete its program folder.
191
+ Its state folders are left alone."""
184
192
  removed = []
185
- stamp = time.strftime("%Y%m%d-%H%M%S")
193
+ codex = hook_files()[1]
186
194
  for folder in other_installs(target):
187
195
  print(f"Older Smart Tool installation found at {folder}; removing it.")
188
196
  stop_processes(folder)
@@ -190,8 +198,10 @@ def remove_other_installs(target):
190
198
  original = path.read_text(encoding="utf-8") if path.is_file() else ""
191
199
  text = _repointed(original, folder, target)
192
200
  if text != original:
193
- shutil.copy2(path, path.with_name(f"{path.name}.smart-tool-backup-{stamp}"))
201
+ trust = client_hooks.repoint_trust(str(path), original, text) if path == codex else {}
202
+ client_hooks.backup_file(str(path))
194
203
  path.write_text(text, encoding="utf-8")
204
+ client_hooks.record_codex_trust(trust, str(path.with_name("config.toml")))
195
205
  print(f"Hooks in {path} now point to {target}.")
196
206
  startup = STARTUP_SCRIPT.read_text(encoding="utf-8", errors="replace") if STARTUP_SCRIPT.is_file() else ""
197
207
  if any(_same_folder(_script_folder(script), folder) for script in _script_paths(startup)):
@@ -275,6 +285,50 @@ def restore_packages(python, frozen, backup):
275
285
  str(backup / "requirements.frozen.txt")], check=True)
276
286
 
277
287
 
288
+ def dependency_digest(root):
289
+ """SHA-256 over the DEPENDENCY_INPUTS under root: the files that decide what pip and install_runtime.py install."""
290
+ digest = hashlib.sha256()
291
+ for rel in DEPENDENCY_INPUTS:
292
+ digest.update(rel.encode("utf-8") + b"\0" + (root / rel).read_bytes() + b"\0")
293
+ return digest.hexdigest()
294
+
295
+
296
+ def runtime_complete(target, python):
297
+ """`install_runtime.py --check` of target: Node, parsers, browser packages and browsers all present. It only
298
+ reads, so it runs while the daemon is still up."""
299
+ return subprocess.run([str(python), str(target / "install_runtime.py"), "--check"], cwd=target,
300
+ capture_output=True, text=True, timeout=120).returncode == 0
301
+
302
+
303
+ def dependencies_current(target, python):
304
+ """True when the last update that completed in target ran the dependency step with the inputs this package
305
+ ships and the web runtime is still complete, so pip and install_runtime.py would change nothing. Running them
306
+ anyway keeps the daemon down for about 48 s, longer than an MCP client keeps reconnecting (Claude Code gives up
307
+ after 5 attempts, about 15 s)."""
308
+ stamp = target / DEPENDENCY_STAMP
309
+ return (python.is_file() and stamp.is_file()
310
+ and stamp.read_text(encoding="utf-8").strip() == dependency_digest(SOURCE)
311
+ and runtime_complete(target, python))
312
+
313
+
314
+ def refresh_camoufox(target):
315
+ """Runs target's `fetch_camoufox.py` while the daemon is still up, so a newer browser build for the same library
316
+ version arrives on every update. Camoufox installs each build in its own folder and switches the active one only
317
+ after the download checks out, so the running browser keeps its files; with no newer build it only looks up the
318
+ releases."""
319
+ browser = target / "web_adapters" / "browser"
320
+ subprocess.run([str(browser / ".venv" / "Scripts" / "python.exe"), str(browser / "fetch_camoufox.py")], check=True)
321
+
322
+
323
+ def prune_camoufox(target):
324
+ """Runs target's `prune_camoufox.py` after a verified update, so the Camoufox builds older than the active one leave
325
+ the user's cache. The update is already complete, so a failure is reported, not rolled back."""
326
+ browser = target / "web_adapters" / "browser"
327
+ result = subprocess.run([str(browser / ".venv" / "Scripts" / "python.exe"), str(browser / "prune_camoufox.py")])
328
+ if result.returncode:
329
+ print(f"Old Camoufox builds not pruned: prune_camoufox.py exited {result.returncode}.", file=sys.stderr)
330
+
331
+
278
332
  def install_dependencies(target, python):
279
333
  if not python.exists():
280
334
  venv.create(python.parent.parent, with_pip=True)
@@ -406,6 +460,9 @@ def prune_backups(target):
406
460
 
407
461
  def _update(args, target, files, existed, python, pythonw):
408
462
  """Replaces the installed files, dependencies and daemon, restoring the previous version on any failure."""
463
+ run_deps = not args.skip_deps and not dependencies_current(target, python)
464
+ if not args.skip_deps and not run_deps:
465
+ refresh_camoufox(target)
409
466
  stop_processes(target)
410
467
  if not args.no_start:
411
468
  wait_port_free(target)
@@ -416,10 +473,12 @@ def _update(args, target, files, existed, python, pythonw):
416
473
  copy_files(target, files, backup, changed, removed)
417
474
  clear_bytecode(target)
418
475
  print(f"Files changed: {len(changed)}; removed as obsolete: {len(removed)}")
419
- if not args.skip_deps:
476
+ if run_deps:
420
477
  frozen = freeze(python)
421
478
  deps_touched = True
422
479
  install_dependencies(target, python)
480
+ elif not args.skip_deps:
481
+ print("Dependencies unchanged since the last update; pip and install_runtime.py skipped.")
423
482
  if not args.no_start:
424
483
  mark_updating(False)
425
484
  start(target, python, pythonw)
@@ -443,7 +502,11 @@ def _update(args, target, files, existed, python, pythonw):
443
502
  raise SystemExit(1)
444
503
  shutil.rmtree(backup, ignore_errors=True)
445
504
  raise SystemExit(1)
505
+ if run_deps:
506
+ (target / DEPENDENCY_STAMP).write_text(dependency_digest(SOURCE), encoding="utf-8")
446
507
  shutil.rmtree(backup)
508
+ if not args.skip_deps and not args.no_start:
509
+ prune_camoufox(target)
447
510
 
448
511
 
449
512
  if __name__ == "__main__":
@@ -239,10 +239,39 @@ def _run_once(args, cwd, env, flags, label, idle_s, stream):
239
239
  raise RuntimeError(f"{label} failed (exit {process.returncode}): {tail[-1] if tail else 'no output'}")
240
240
 
241
241
 
242
+ def _lock_digest():
243
+ return hashlib.sha256((NODE_DIR / "package-lock.json").read_bytes()).hexdigest()
244
+
245
+
246
+ def _lock_stamp():
247
+ """Written after `npm ci` succeeds; `npm ci` deletes node_modules first, so a failed run leaves no stamp."""
248
+ return NODE_DIR / "node_modules" / ".smart-tool-lock.sha256"
249
+
250
+
251
+ def _node_packages_current():
252
+ """node_modules was installed from the package-lock.json shipped now and still holds every entry point. npm's own
253
+ hidden lockfile is not compared because npm ignores it whenever another tool touched the tree."""
254
+ try:
255
+ stamped = _lock_stamp().read_text(encoding="utf-8").strip()
256
+ except OSError:
257
+ return False
258
+ return stamped == _lock_digest() and all(path.is_file() for path in (
259
+ OPEN_WEBSEARCH_CLI, TYPESCRIPT_PARSER, JAVA_PARSER, ANGULAR_PARSER, PLAYWRIGHT_MCP_CLI))
260
+
261
+
262
+ def _install_node_packages(npm):
263
+ if _node_packages_current():
264
+ return
265
+ _run([npm, "ci", "--omit=dev", "--no-audit", "--no-fund"], cwd=NODE_DIR,
266
+ label="Web adapters and code parser via npm", idle_s=300)
267
+ _lock_stamp().write_text(_lock_digest(), encoding="utf-8")
268
+
269
+
242
270
  def _check():
243
271
  node, _npm = _node_commands()
244
272
  status = {
245
273
  "node": bool(node),
274
+ "node_packages": bool(node and _node_packages_current()),
246
275
  "open_websearch": bool(node and OPEN_WEBSEARCH_CLI.is_file()),
247
276
  "typescript_parser": bool(node and TYPESCRIPT_PARSER.is_file()),
248
277
  "java_parser":bool(node and JAVA_PARSER.is_file()),
@@ -318,10 +347,7 @@ def install(reuse_browser_runtime=None):
318
347
  if not node or not npm:
319
348
  _install_node()
320
349
  node, npm = _node_commands()
321
- if not all(path.is_file() for path in (OPEN_WEBSEARCH_CLI, TYPESCRIPT_PARSER, JAVA_PARSER, ANGULAR_PARSER,
322
- PLAYWRIGHT_MCP_CLI)):
323
- _run([npm, "ci", "--omit=dev", "--no-audit", "--no-fund"], cwd=NODE_DIR,
324
- label="Web adapters and code parser via npm", idle_s=300)
350
+ _install_node_packages(npm)
325
351
  if reuse_browser_runtime:
326
352
  existing = Path(reuse_browser_runtime).expanduser().resolve()
327
353
  if not (existing / "Scripts" / "python.exe").is_file():
@@ -78,7 +78,7 @@
78
78
  "Claude Code": "Claude Code",
79
79
  "Codex": "Codex",
80
80
  "Off by default. When on, every new session starts with the Smart Tool update notices (also shown to you) and the redirect proposals waiting for a decision. It adds a SessionStart entry to": "Desligado por padrão. Quando ligado, cada nova sessão começa com os avisos de atualização do Smart Tool (mostrados também a você) e as propostas de redirecionamento que esperam uma decisão. Ela adiciona uma entrada SessionStart em",
81
- ", written after a backup, and turning it off removes only that entry. Codex runs a new hook only after you approve it in /hooks. Either way, the agent learns about a project's setup audit on its first Smart Tool call there, once per session.": ", gravada depois de um backup; ao desligar, só essa entrada é removida. O Codex só executa um hook novo depois que você o aprova em /hooks. Com ou sem ele, o agente fica sabendo da auditoria de um projeto na primeira chamada ao Smart Tool ali, uma vez por sessão.",
81
+ ", written after a backup, and turning it off removes only that entry. In Codex the same step records the approval in config.toml, as /hooks would. Either way, the agent learns about a project's setup audit on its first Smart Tool call there, once per session.": ", gravada depois de um backup; ao desligar, só essa entrada é removida. No Codex, o mesmo passo grava a aprovação no config.toml, como o /hooks faria. Com ou sem ele, o agente fica sabendo da auditoria de um projeto na primeira chamada ao Smart Tool ali, uma vez por sessão.",
82
82
  "Turn on": "Ligar",
83
83
  "Turn off": "Desligar",
84
84
  "Write it": "Gravar",
@@ -371,7 +371,7 @@
371
371
  "Runs on its own every": "Roda sozinha a cada",
372
372
  "Register a project on the Projects page to audit it.": "Registre um projeto na página Projetos para auditá-lo.",
373
373
  "Setup audit unavailable:": "Auditoria da configuração indisponível:",
374
- "Waiting for approval in /hooks": "Aguardando aprovação em /hooks",
374
+ "Not approved in Codex": "Sem aprovação no Codex",
375
375
  "Update": "Atualizar",
376
376
  "Session-start report state unavailable:": "Estado do relatório de início de sessão indisponível:",
377
377
  "Adds this entry under": "Adiciona esta entrada em",
@@ -666,7 +666,7 @@
666
666
  "Paste the provider API key before saving.": "Cole a chave de API do provedor antes de salvar.",
667
667
  "Invalid action: use save or remove.": "Ação inválida: use save ou remove.",
668
668
  "Invalid {0} model id: {1} (no spaces, up to 200 characters).": "Id de modelo {0} inválido: {1} (sem espaços, até 200 caracteres).",
669
- "installed, waiting for your approval in /hooks": "instalado, aguardando a sua aprovação em /hooks",
669
+ "installed, but Codex does not trust this definition; Update records the approval": "instalado, mas o Codex não confia nesta definição; Atualizar grava a aprovação",
670
670
  "{0} rejected the key ({1}). Check that you copied the whole key from your account.": "{0} rejeitou a chave ({1}). Confira se você copiou a chave inteira da sua conta.",
671
671
  "{0} returned a rate limit while testing the key; try again in a few minutes.": "{0} devolveu um limite de requisições ao testar a chave; tente de novo em alguns minutos.",
672
672
  "Invalid action: use apply, decline or revert.": "Ação inválida: use apply, decline ou revert.",
@@ -826,7 +826,7 @@
826
826
  "Remove the views in this preview: {0}? The project files will be kept.": "Remover as visões desta prévia: {0}? Os arquivos do projeto serão mantidos.",
827
827
  "{0} · Maps · Smart Tool": "{0} · Mapas · Smart Tool",
828
828
  "{0} Open the manager to check the project.": "{0} Abra o gerenciador para conferir o projeto.",
829
- "Codex only runs new hooks after the user approves the definition in /hooks.": "O Codex só roda hooks novos depois que você aprova a definição em /hooks.",
829
+ "Smart Tool recorded the approval of the new definition in Codex's config.toml, as /hooks would, so Codex runs it from the next session on.": "O Smart Tool gravou a aprovação da nova definição no config.toml do Codex, como o /hooks faria, então o Codex a executa a partir da próxima sessão.",
830
830
  "Cursor": "Cursor",
831
831
  "In Cursor, `allow` approves the tool without the user and empty output blocks: there is no documented neutral response, so the hook is not installed automatically.": "No Cursor, `allow` aprova a ferramenta sem você e uma saída vazia bloqueia: não há resposta neutra documentada, então o hook não é instalado automaticamente.",
832
832
  "The hook": "O hook",
@@ -841,6 +841,10 @@
841
841
  "{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.",
842
842
  "{0}: hooks.SessionStart is not a list; nothing was changed.": "{0}: hooks.SessionStart não é uma lista; nada foi alterado.",
843
843
  "Its timeout or type is older than the current one.": "O tempo limite ou o tipo dele é mais antigo que o atual.",
844
+ "Codex has not approved its {0} entry; an update records the approval.": "O Codex não aprovou a entrada {0} dele; atualizar grava a aprovação.",
845
+ "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.",
846
+ "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.",
847
+ "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.",
844
848
  "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.",
845
849
  "{0}: hooks.{1} is not a list; nothing was changed.": "{0}: hooks.{1} não é uma lista; nada foi alterado.",
846
850
  "Smart Tool updated from {old} to {new}.": "Smart Tool atualizado da versão {old} para a {new}.",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@allansantos-dev/smart-tool",
3
- "version": "0.9.56",
3
+ "version": "0.9.61",
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": "Allan Santos",
package/redirect_rule.py CHANGED
@@ -404,16 +404,20 @@ def _bash(command, cwd, powershell=False):
404
404
 
405
405
 
406
406
  def _shell(command, cwd, state, powershell, depth):
407
- """(decision, target, reason) of one shell script; substitutions and `bash -c`/`powershell -Command` scripts are
408
- decided with the same state (folder, variables, loop variables)."""
407
+ """(decision, target, reason) of one shell script; `bash -c`/`powershell -Command` scripts are decided with the
408
+ same state (folder, variables, loop variables), and each substitution with the state of the segment it sits in,
409
+ as a subshell whose `cd` does not leak out."""
409
410
  verdict = ("allow", None, "No content search over a folder.")
410
411
  text, inner = _substitutions(_strip_heredocs(command), powershell)
411
- for script in inner if depth < MAX_NESTING else ():
412
- found = _shell(script, cwd, state, powershell, depth + 1)
413
- if found[0] == "redirect":
414
- return found
412
+ pending = inner if depth < MAX_NESTING else []
415
413
  variables, lists, listing = state["variables"], state["lists"], None
416
414
  for segment, after_pipe in segments(text):
415
+ count = segment.count(LISTING) + segment.count(SUBSTITUTION)
416
+ for script in pending[:count]:
417
+ found = _shell(script, cwd, {**state}, powershell, depth + 1)
418
+ if found[0] == "redirect":
419
+ return found
420
+ pending = pending[count:]
417
421
  words = _split(segment, powershell)
418
422
  if words[:2] == ["while", "read"]:
419
423
  name = next((t for t in words[2:] if not t.startswith("-")), None)
package/setup_ui.py CHANGED
@@ -327,7 +327,8 @@ def handle_audit(body):
327
327
  """Setup audit panel: `index` lists the registered projects with their last audit summary; `report` returns the
328
328
  last stored report of one of them; `run` audits it now (MCP servers contacted unless probe is false). Only
329
329
  registered project folders are accepted. The opt-in session-start report in Claude Code or Codex (`client`, default
330
- claude; Codex runs it only after /hooks approval, state `waiting_approval`): `hook_state`,
330
+ claude; in Codex the install also records the approval in config.toml, and `waiting_approval` means Codex does not
331
+ trust the written entry): `hook_state`,
331
332
  `hook_preview` (the exact entry and a token), `hook_install` (with that token, after a backup) and `hook_remove`
332
333
  (only Smart Tool's entry, after a backup)."""
333
334
  if not isinstance(body, dict):
@@ -337,7 +338,7 @@ def handle_audit(body):
337
338
  client = body.get("client", "claude")
338
339
  if body.get("action") == "hook_state":
339
340
  state = client_hooks.audit_state(client)
340
- detail = {"detail": "installed, waiting for your approval in /hooks"} if state == client_hooks.AUDIT_WAITING else {}
341
+ detail = {"detail": "installed, but Codex does not trust this definition; Update records the approval"} if state == client_hooks.AUDIT_WAITING else {}
341
342
  return {"state": state, "file": client_hooks.CLIENTS[client]["files"][0], **detail}
342
343
  if body.get("action") == "hook_preview":
343
344
  return client_hooks.audit_preview(client)
@@ -827,7 +828,7 @@ __I18N__
827
828
  <div class="card">
828
829
  <div class="card-head"><h3>Report at session start</h3><span class="pill" id="audit-hook-pill" data-tone="busy">Checking</span></div>
829
830
  <div class="field"><label for="sel-audit-hook-client">Client</label><select id="sel-audit-hook-client"><option value="claude">Claude Code</option><option value="codex">Codex</option></select></div>
830
- <p class="lede">Off by default. When on, every new session starts with the Smart Tool update notices (also shown to you) and the redirect proposals waiting for a decision. It adds a SessionStart entry to <span class="mono" id="audit-hook-file"></span>, written after a backup, and turning it off removes only that entry. Codex runs a new hook only after you approve it in /hooks. Either way, the agent learns about a project's setup audit on its first Smart Tool call there, once per session.</p>
831
+ <p class="lede">Off by default. When on, every new session starts with the Smart Tool update notices (also shown to you) and the redirect proposals waiting for a decision. It adds a SessionStart entry to <span class="mono" id="audit-hook-file"></span>, written after a backup, and turning it off removes only that entry. In Codex the same step records the approval in config.toml, as /hooks would. Either way, the agent learns about a project's setup audit on its first Smart Tool call there, once per session.</p>
831
832
  <div class="actions"><button type="button" class="primary" id="btn-audit-hook-on" hidden>Turn on</button><button type="button" id="btn-audit-hook-off" hidden>Turn off</button></div>
832
833
  <div id="audit-hook-confirm" hidden>
833
834
  <p class="hint" id="audit-hook-where"></p>
@@ -1911,13 +1912,14 @@ async function loadAuditHook() {
1911
1912
  try {
1912
1913
  const hook = await post("/setup/audit", { action: "hook_state", client: auditHookClient() });
1913
1914
  $("audit-hook-file").textContent = hook.file;
1914
- const on = hook.state === "current" || hook.state === "waiting_approval";
1915
+ const on = hook.state === "current";
1916
+ const stale = hook.state === "outdated" || hook.state === "waiting_approval";
1915
1917
  const pillEl = $("audit-hook-pill");
1916
- pillEl.textContent = hook.state === "waiting_approval" ? "Waiting for approval in /hooks" : on ? "On" : hook.state === "outdated" ? "Outdated" : "Off";
1917
- pillEl.dataset.tone = hook.state === "waiting_approval" || hook.state === "outdated" ? "warn" : on ? "ok" : "idle";
1918
+ pillEl.textContent = hook.state === "waiting_approval" ? "Not approved in Codex" : on ? "On" : hook.state === "outdated" ? "Outdated" : "Off";
1919
+ pillEl.dataset.tone = stale ? "warn" : on ? "ok" : "idle";
1918
1920
  if (hook.detail) setMsg("audit-hook-msg", "", hook.detail + ".");
1919
1921
  $("btn-audit-hook-on").hidden = on;
1920
- $("btn-audit-hook-on").textContent = hook.state === "outdated" ? "Update" : "Turn on";
1922
+ $("btn-audit-hook-on").textContent = stale ? "Update" : "Turn on";
1921
1923
  $("btn-audit-hook-off").hidden = hook.state === "missing";
1922
1924
  } catch (error) {
1923
1925
  setMsg("audit-hook-msg", "error", "Session-start report state unavailable: " + error.message);
@@ -88,6 +88,10 @@ REGISTRY_PATH = os.path.join(RUN_DIR, "daemon.json")
88
88
  DEFAULT_PORT = int(os.environ.get("SMART_TOOL_PORT", "8765"))
89
89
  PROTOCOL_VERSION = "2025-06-18"
90
90
  MCP_MAX_REQUEST_BYTES = 10 * 1024 * 1024
91
+ # Claude Code aborts an MCP POST whose response has not started within 60 s; a tool call still running after
92
+ # MCP_STREAM_AFTER_S is answered as an SSE stream instead, with a comment every MCP_KEEPALIVE_S.
93
+ MCP_STREAM_AFTER_S = 10
94
+ MCP_KEEPALIVE_S = 15
91
95
  _BOUND_PORT = DEFAULT_PORT
92
96
 
93
97
  DDG_SEARCH_SCRIPT = web_search_adapters.DDG_SEARCH_SCRIPT
@@ -2225,7 +2229,10 @@ def _project_action_locked(arguments):
2225
2229
  return {"current_client": client_hooks.status(client), **integration_metrics.summary(arguments.get("days", 7))}
2226
2230
  if action == "install_hook_preview":
2227
2231
  _session, client = _session_client()
2228
- return client_hooks.preview(client)
2232
+ plan = client_hooks.preview(client)
2233
+ if "token" in plan:
2234
+ plan["plan_id"] = plan.pop("token")
2235
+ return plan
2229
2236
  if action == "install_hook":
2230
2237
  _session, client = _session_client()
2231
2238
  result = client_hooks.install(client, arguments.get("plan_id"), arguments.get("confirm"))
@@ -4208,6 +4215,16 @@ def _dispatch(method, params, session_id):
4208
4215
  raise KeyError(method)
4209
4216
 
4210
4217
 
4218
+ def _rpc_reply(method, params, session_id, req_id):
4219
+ """JSON-RPC response to one request: its result, or the error the client should see."""
4220
+ try:
4221
+ return {"jsonrpc": "2.0", "id": req_id, "result": _dispatch(method, params, session_id)}
4222
+ except KeyError:
4223
+ return {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32601, "message": f"method not supported: {method}"}}
4224
+ except Exception as exc:
4225
+ return {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32000, "message": _sanitize_text(str(exc))}}
4226
+
4227
+
4211
4228
  _LOOPBACK_HOSTNAMES = frozenset({"127.0.0.1", "localhost", "::1"})
4212
4229
 
4213
4230
 
@@ -4347,9 +4364,31 @@ class MCPHandler(BaseHTTPRequestHandler):
4347
4364
  raise RequestTooLarge(f"Request body over {max_bytes} bytes")
4348
4365
  return self.rfile.read(length) if length else b""
4349
4366
 
4367
+ def _mcp_method_not_allowed(self):
4368
+ """405 for GET and DELETE on /mcp: no server-initiated stream and no client-ended sessions. The spec's answer for
4369
+ both; the MCP SDK client treats any other status, 404 included, as a broken connection."""
4370
+ self.send_response(405)
4371
+ self.send_header("Allow", "POST")
4372
+ self.send_header("Content-Length", "0")
4373
+ self.end_headers()
4374
+
4375
+ def do_DELETE(self):
4376
+ """Routes a DELETE: 405 on /mcp, 404 elsewhere."""
4377
+ if self._reject_foreign_origin():
4378
+ return
4379
+ if self.path == "/mcp":
4380
+ self._mcp_method_not_allowed()
4381
+ return
4382
+ self._write_json(404, {"error": "not found"})
4383
+
4350
4384
  def do_GET(self):
4385
+ """Routes a GET: 405 on /mcp, the health and status probes, the setup and project pages and their data; 404
4386
+ elsewhere."""
4351
4387
  if self._reject_foreign_origin():
4352
4388
  return
4389
+ if self.path == "/mcp":
4390
+ self._mcp_method_not_allowed()
4391
+ return
4353
4392
  if self.path == "/health":
4354
4393
  self._write_json(200, {"status": "ok", "version": version.VERSION})
4355
4394
  return
@@ -4505,17 +4544,42 @@ class MCPHandler(BaseHTTPRequestHandler):
4505
4544
  self.end_headers()
4506
4545
  return
4507
4546
 
4508
- try:
4509
- result = _dispatch(method, params, session_id)
4510
- except KeyError:
4511
- self._write_json(200, {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32601, "message": f"method not supported: {method}"}})
4547
+ if method == "tools/call" and "text/event-stream" in (self.headers.get("Accept") or ""):
4548
+ self._answer_tool_call(params, session_id, req_id)
4512
4549
  return
4513
- except Exception as exc:
4514
- self._write_json(200, {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32000, "message": _sanitize_text(str(exc))}})
4550
+ reply = _rpc_reply(method, params, session_id, req_id)
4551
+ headers = {"Mcp-Session-Id": session_id} if method == "initialize" and "result" in reply else {}
4552
+ self._write_json(200, reply, headers)
4553
+
4554
+ def _answer_tool_call(self, params, session_id, req_id):
4555
+ """Answers a tools/call from a client that accepts SSE: one JSON body when the call ends within
4556
+ MCP_STREAM_AFTER_S, else an SSE stream started at once, a comment every MCP_KEEPALIVE_S and the reply as its
4557
+ only event. A client gone before the end leaves the call to finish unanswered, as a closed JSON request does."""
4558
+ box = {}
4559
+ worker = threading.Thread(target=lambda: box.update(reply=_rpc_reply("tools/call", params, session_id, req_id)),
4560
+ daemon=True)
4561
+ worker.start()
4562
+ worker.join(MCP_STREAM_AFTER_S)
4563
+ if not worker.is_alive():
4564
+ self._write_json(200, box["reply"])
4515
4565
  return
4516
-
4517
- headers = {"Mcp-Session-Id": session_id} if method == "initialize" else {}
4518
- self._write_json(200, {"jsonrpc": "2.0", "id": req_id, "result": result}, headers)
4566
+ try:
4567
+ self.send_response(200)
4568
+ self.send_header("Content-Type", "text/event-stream")
4569
+ self.send_header("Cache-Control", "no-store")
4570
+ self.send_header("X-Content-Type-Options", "nosniff")
4571
+ self.end_headers()
4572
+ self.wfile.flush()
4573
+ worker.join(MCP_KEEPALIVE_S)
4574
+ while worker.is_alive():
4575
+ self.wfile.write(b": keepalive\n\n")
4576
+ self.wfile.flush()
4577
+ worker.join(MCP_KEEPALIVE_S)
4578
+ event = json.dumps(box["reply"], ensure_ascii=False)
4579
+ self.wfile.write(f"event: message\ndata: {event}\n\n".encode("utf-8"))
4580
+ self.wfile.flush()
4581
+ except (ConnectionError, BrokenPipeError):
4582
+ pass
4519
4583
 
4520
4584
 
4521
4585
  def _write_registry(port):
@@ -4548,9 +4612,11 @@ def _smart_tool_answers(port):
4548
4612
 
4549
4613
 
4550
4614
  def _bind_server():
4551
- """Default port, then the port clients already know, then any free port (announced in daemon.json and synced to
4552
- the clients by endpoint_sync). A port held by another live Smart Tool stops this start instead of duplicating it."""
4553
- for port in dict.fromkeys(p for p in (DEFAULT_PORT, endpoint_sync.known_port(), 0) if p is not None):
4615
+ """The port clients already know, then the default port, then any free port (announced in daemon.json and synced
4616
+ to the clients by endpoint_sync). A connected session keeps the URL it started with, so a restart that moved
4617
+ back to the default would cut every session on the known port. A port held by another live Smart Tool stops this
4618
+ start instead of duplicating it."""
4619
+ for port in dict.fromkeys(p for p in (endpoint_sync.known_port(), DEFAULT_PORT, 0) if p is not None):
4554
4620
  try:
4555
4621
  return _ExclusiveThreadingHTTPServer(("127.0.0.1", port), MCPHandler)
4556
4622
  except OSError:
package/version.py CHANGED
@@ -1,7 +1,7 @@
1
1
  """Single source of the Smart Tool version and of the User-Agent sent to public APIs."""
2
2
  import re
3
3
 
4
- VERSION = "0.9.56"
4
+ VERSION = "0.9.61"
5
5
  _CONTACT_RE = re.compile(r"^(?:[^\s@()<>;]+@[^\s@()<>;]+\.[^\s@()<>;]+|https?://[^\s()<>;]+)$")
6
6
 
7
7
 
@@ -0,0 +1,66 @@
1
+ """Removes the Camoufox builds older than the active one after a verified update. camoufox 0.5.6 installs each build in
2
+ its own folder under `browsers/<repo>/` and never deletes the previous ones, so the cache grows by about 2.5 GB per
3
+ build. Nothing is removed while the user pinned a build (`camoufox set` writes `pinned` in config.json), and only the
4
+ active build's own repository is pruned: the active build and any newer one stay. Each folder is first renamed to a
5
+ hidden name, which Windows refuses while any file inside is open, so a build in use is skipped whole instead of left
6
+ half removed; a hidden folder left by an interrupted deletion is removed on the next run."""
7
+ import os
8
+ import shutil
9
+ import time
10
+
11
+ REMOVING_PREFIX = ".removing-"
12
+
13
+
14
+ def folder_size(path):
15
+ """Bytes of the files under path."""
16
+ return sum(os.path.getsize(os.path.join(root, name)) for root, _dirs, names in os.walk(path) for name in names)
17
+
18
+
19
+ def _delete(build, browsers_dir):
20
+ """Renames the build's folder to a hidden one in browsers_dir and deletes it; the size freed, or None when the
21
+ rename was refused because a file inside is in use."""
22
+ name = f"{build.repo_name}/{build.path.name}"
23
+ size = folder_size(build.path)
24
+ hidden = browsers_dir / f"{REMOVING_PREFIX}{build.repo_name}-{build.path.name}-{time.time_ns()}"
25
+ try:
26
+ os.rename(build.path, hidden)
27
+ except PermissionError as exc:
28
+ print(f"Kept Camoufox build {name}: in use ({exc.strerror})", flush=True)
29
+ return None
30
+ shutil.rmtree(hidden)
31
+ print(f"Removed old Camoufox build {name} ({size / 2**20:.0f} MB)", flush=True)
32
+ return size
33
+
34
+
35
+ def prune(installed, config, browsers_dir):
36
+ """Deletes the builds in installed (camoufox `InstalledVersion`s) of the active build's repository whose version is
37
+ older than the active one, unless config pins a build, and returns the bytes freed."""
38
+ if config.get("pinned"):
39
+ print(f"Camoufox build pinned to {config['pinned']}: old builds kept", flush=True)
40
+ return 0
41
+ freed = 0
42
+ for leftover in browsers_dir.glob(f"{REMOVING_PREFIX}*"):
43
+ size = folder_size(leftover)
44
+ shutil.rmtree(leftover)
45
+ freed += size
46
+ print(f"Removed an interrupted deletion: {leftover.name} ({size / 2**20:.0f} MB)", flush=True)
47
+ active = next((build for build in installed if build.is_active), None)
48
+ if active is None:
49
+ print("No active Camoufox build: old builds kept", flush=True)
50
+ return freed
51
+ for build in installed:
52
+ if build.repo_name == active.repo_name and build.version < active.version:
53
+ freed += _delete(build, browsers_dir) or 0
54
+ print(f"Old Camoufox builds pruned: {freed / 2**30:.2f} GB freed; active build "
55
+ f"{active.repo_name}/{active.path.name} kept", flush=True)
56
+ return freed
57
+
58
+
59
+ def main():
60
+ """Prunes the user's real Camoufox cache, read through camoufox's own multiversion manager."""
61
+ from camoufox import multiversion
62
+ prune(multiversion.list_installed(), multiversion.load_config(), multiversion.BROWSERS_DIR)
63
+
64
+
65
+ if __name__ == "__main__":
66
+ main()