@allansantos-dev/smart-tool 0.9.55 → 0.9.57

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,31 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.9.57 - beta
4
+
5
+ - Codex runs Smart Tool's hooks with no `/hooks` step. Installing or updating the Codex redirect hook or the
6
+ session-start hook also records the approval of the new definition in Codex's `config.toml`, as `/hooks` does: the
7
+ `trusted_hash` Codex computes for that handler, written after a backup with every other line left as it was, and
8
+ read back before the step reports success. The new entry takes the place of the old one, so the other hooks keep
9
+ their index and their approval; turning the session-start hook off carries the approval of an approved hook that
10
+ moves up to its new index. When the installer points the hooks at a new install folder, each Smart Tool hook that
11
+ was approved keeps its approval. A Codex entry that is current but not approved shows as outdated (session-start
12
+ hook: "Not approved in Codex"), and updating records the approval. A `config.toml` that is not valid TOML stops the
13
+ step before `hooks.json` is written (`tests/test_codex_audit_hook.py`, `tests/test_install_legacy.py`).
14
+ - `project_manage action=install_hook_preview` returns the `plan_id` that `action=install_hook` takes, as its
15
+ description says; it returned the identifier under `token`, so an agent could not finish the update.
16
+ - Two hook steps in the same second (updating the redirect hook, then the session-start hook) keep separate backups:
17
+ the second gets a numbered name instead of overwriting the first, which holds the file as it was before both.
18
+
19
+ ## 0.9.56 - beta
20
+
21
+ - Every command hook Smart Tool writes ends with `--hook-origin=smart-tool`: the Codex redirect hook
22
+ (`hooks/pretool_router.py --client codex`) and the session-start hook (`hooks/session_audit.py`) in Claude Code and
23
+ Codex. The command line then names its owner under the hook origin convention the other local projects follow. An
24
+ entry written by an older version shows as outdated on the setup page, and updating it or turning it off takes out
25
+ the unsigned and the signed form alike, so no second entry is left. In Codex the signed entry waits for approval in
26
+ `/hooks` like any changed hook. Claude Code's redirect hooks are HTTP entries and have no command line to sign
27
+ (`tests/test_codex_audit_hook.py`).
28
+
3
29
  ## 0.9.55 - beta
4
30
 
5
31
  - The agent learns about the problems of the project it works on, and the user is not notified about them. The first
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.55 beta. Windows only. What changed in each version: [CHANGELOG.md](CHANGELOG.md).
20
+ **Status:** 0.9.57 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.55 install
86
+ npx @allansantos-dev/smart-tool@0.9.57 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
@@ -146,7 +146,13 @@ Redirects) and Maintenance (Setup audit, Startup).
146
146
  the usage meter: it is a sidecar on your machine with no price, and its state is the **Local models** section.
147
147
  3. **Agents**: register the MCP server in Claude Code or Codex (runs their official `mcp add` command), install the
148
148
  hook and choose its behavior under **Agent rules**. A hook written by an older Smart Tool shows as outdated, with
149
- what an update changes; updating previews the entry and rewrites only Smart Tool's, after a backup.
149
+ what an update changes; updating previews the entry and rewrites only Smart Tool's, after a backup. Every
150
+ command hook it writes (the Codex redirect hook and the session-start hook) ends with
151
+ `--hook-origin=smart-tool`, so its command line names Smart Tool as its owner; an entry written before that shows
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. 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.
150
156
 
151
157
  **Browser control** comes with the registration, and with every update for clients where smart-tool is registered:
152
158
  the official Playwright MCP (pinned in `web_adapters/node`) is registered as the `playwright` server, driving the
@@ -266,8 +272,9 @@ Redirects) and Maintenance (Setup audit, Startup).
266
272
  when none is stored. Optionally, **Report at session start** on the Setup audit page (Claude Code or Codex) starts
267
273
  every new session with the update notices and the redirect proposals waiting for a decision: it previews the exact
268
274
  SessionStart entry, adds it to `~/.claude/settings.json` or `~/.codex/hooks.json` only after you confirm (backup
269
- first), and **Turn off** removes only that entry. Codex runs a new hook only after you approve it in `/hooks`;
270
- 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
271
278
  (`hooks/session_audit.py`) only asks the running service and prints nothing when the service is down.
272
279
  4. **Local models** (optional): if the mcp-memory embedding sidecar is installed on the machine, its local embedder
273
280
  can serve as a fallback (or preferred) embedding model.
package/client_hooks.py CHANGED
@@ -14,6 +14,8 @@ HOOK_SCRIPT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "hooks",
14
14
  MARKER = "pretool_router.py"
15
15
  AUDIT_SCRIPT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "hooks", "session_audit.py")
16
16
  AUDIT_MARKER = "session_audit.py"
17
+ # Hook origin convention shared by every project that installs hooks: a failed command hook names its owner.
18
+ HOOK_ORIGIN = "--hook-origin=smart-tool"
17
19
  AUDIT_MATCHER = "startup|resume|clear|compact|fork"
18
20
  AUDIT_TIMEOUT_S = 10
19
21
  AUDIT_CLIENTS = ("claude", "codex")
@@ -33,7 +35,8 @@ CLIENTS = {
33
35
  "post_matcher": "Grep|Bash|PowerShell|WebFetch|WebSearch"},
34
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")],
35
37
  "docs": "https://learn.chatgpt.com/docs/hooks", "event": "PreToolUse", "matcher": "Bash|apply_patch",
36
- "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."},
37
40
  "cursor": {"label": "Cursor", "prefix": "cursor", "files": [os.path.join(HOME, ".cursor", "hooks.json")],
38
41
  "docs": "https://cursor.com/docs/agent/hooks", "event": "preToolUse", "matcher": "Shell|Read|Grep",
39
42
  "blocked": "In Cursor, `allow` approves the tool without the user and empty output blocks: there is no documented neutral "
@@ -84,9 +87,10 @@ def _target(handler):
84
87
  return handler.get("url") or handler.get("command") or ""
85
88
 
86
89
 
87
- def inspect(client):
90
+ def inspect(client, trust=True):
88
91
  """Our hook in the client's config: `current`, `missing`, or `outdated` (an older entry of ours) with `changes`,
89
- 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."""
90
94
  spec = CLIENTS[client]
91
95
  for path in spec["files"]:
92
96
  try:
@@ -104,6 +108,8 @@ def inspect(client):
104
108
  for event, (matcher, expected) in _entries(client).items():
105
109
  groups = hooks.get(event) if isinstance(hooks, dict) else None
106
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.")
107
113
  return {"state": "outdated" if changes else "current", "changes": changes}
108
114
  return {"state": "missing", "changes": []}
109
115
 
@@ -185,7 +191,8 @@ def _shell_safe(path):
185
191
 
186
192
 
187
193
  def _command(client):
188
- return f"{_shell_safe(sys.executable)} {_shell_safe(HOOK_SCRIPT)} --client {client}"
194
+ """The PreToolUse command of a client without HTTP hooks, signed with HOOK_ORIGIN at the end."""
195
+ return f"{_shell_safe(sys.executable)} {_shell_safe(HOOK_SCRIPT)} --client {client} {HOOK_ORIGIN}"
189
196
 
190
197
 
191
198
  def _handler(client, route=HTTP_PATH, timeout=HTTP_TIMEOUT_S):
@@ -199,9 +206,20 @@ def _handler(client, route=HTTP_PATH, timeout=HTTP_TIMEOUT_S):
199
206
  return {"type": "command", "command": _command(client), "timeout": timeout}
200
207
 
201
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
+
202
219
  def _plan(client_info):
203
220
  """(client, spec, path, data, changes): the client's config with our entries already taken out, and changes
204
- {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."""
205
223
  client = identify(client_info)
206
224
  if client is None:
207
225
  raise ValueError(f"Unrecognized MCP client ({(client_info or {}).get('name') or 'no clientInfo'}); "
@@ -222,8 +240,9 @@ def _plan(client_info):
222
240
  groups = data["hooks"].setdefault(event, [])
223
241
  if not isinstance(groups, list):
224
242
  raise ValueError(f"{path}: hooks.{event} is not a list; nothing was changed.")
243
+ before, slot = list(groups), _slot(groups, _our_hook)
225
244
  groups[:] = _without_ours(groups)
226
- changes[event] = (groups, {"matcher": matcher, "hooks": [handler]})
245
+ changes[event] = (groups, {"matcher": matcher, "hooks": [handler]}, slot, before)
227
246
  return client, spec, path, data, changes
228
247
 
229
248
 
@@ -236,7 +255,7 @@ def preview(client_info):
236
255
  token = secrets.token_urlsafe(12)
237
256
  _PREVIEWS[token] = {"client": client, "at": time.time()}
238
257
  return {"client": client, "installed": False, "file": path,
239
- "change": {event: entry for event, (_groups, entry) in changes.items()},
258
+ "change": {event: entry for event, (_groups, entry, _slot, _before) in changes.items()},
240
259
  "token": token, "expires_s": PREVIEW_TTL_S, "after_install": spec.get("after_install")}
241
260
 
242
261
 
@@ -249,20 +268,38 @@ def install(client_info, token, confirm):
249
268
  raise ValueError("Installing requires the install_hook_preview token from this session (valid for 10 min) and confirm=true.")
250
269
  if installed(client):
251
270
  return {"client": client, "installed": True, "changed": False, "file": path}
252
- for groups, entry in changes.values():
253
- groups.append(entry)
254
- 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.")
255
281
  return {"client": client, "installed": True, "changed": True, "file": path, "backup": backup,
256
282
  "after_install": spec.get("after_install")}
257
283
 
258
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
+
259
299
  def _write_checked(path, data, verify, what):
260
300
  """Writes data as JSON to path through a temp file after a timestamped backup; when verify() fails on the written
261
301
  file, restores the backup (or removes the new file) and raises. Returns the backup path (None for a new file)."""
262
- backup = None
263
- if os.path.exists(path):
264
- backup = f"{path}.smart-tool-backup-{time.strftime('%Y%m%d-%H%M%S')}"
265
- shutil.copy2(path, backup)
302
+ backup = backup_file(path)
266
303
  os.makedirs(os.path.dirname(path), exist_ok=True)
267
304
  temporary = path + ".smart-tool-tmp"
268
305
  with open(temporary, "w", encoding="utf-8") as stream:
@@ -282,8 +319,10 @@ def _audit_hook(hook):
282
319
 
283
320
 
284
321
  def _audit_entry():
322
+ """The SessionStart group of the session-start hook, its command signed with HOOK_ORIGIN at the end."""
285
323
  return {"matcher": AUDIT_MATCHER,
286
- "hooks": [{"type": "command", "command": f"{_shell_safe(sys.executable)} {_shell_safe(AUDIT_SCRIPT)}",
324
+ "hooks": [{"type": "command",
325
+ "command": f"{_shell_safe(sys.executable)} {_shell_safe(AUDIT_SCRIPT)} {HOOK_ORIGIN}",
287
326
  "timeout": AUDIT_TIMEOUT_S}]}
288
327
 
289
328
 
@@ -295,7 +334,8 @@ def _audit_client(client):
295
334
 
296
335
 
297
336
  def _audit_plan(client="claude"):
298
- """(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."""
299
339
  path = os.path.realpath(_audit_client(client)["files"][0])
300
340
  try:
301
341
  with open(path, encoding="utf-8") as stream:
@@ -307,8 +347,9 @@ def _audit_plan(client="claude"):
307
347
  groups = data["hooks"].setdefault("SessionStart", [])
308
348
  if not isinstance(groups, list):
309
349
  raise ValueError(f"{path}: hooks.SessionStart is not a list; nothing was changed.")
350
+ before, slot = list(groups), _slot(groups, _audit_hook)
310
351
  groups[:] = _without_ours(groups, _audit_hook)
311
- return path, data, groups
352
+ return path, data, groups, slot, before
312
353
 
313
354
 
314
355
  def _codex_hash(event, group, index=0):
@@ -326,35 +367,173 @@ def _codex_hash(event, group, index=0):
326
367
  return "sha256:" + hashlib.sha256(text.encode("utf-8")).hexdigest()
327
368
 
328
369
 
329
- def _codex_approved(groups):
330
- """Our SessionStart handler is trusted in Codex's config.toml: the entry keyed by hooks.json path, event, group
331
- and handler index holds the hash of the definition as it is now (a missing or different hash means /hooks has not
332
- approved it, so Codex does not run it). An unreadable config.toml raises ValueError."""
333
- 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]
334
385
  try:
335
- with open(spec["files"][1], encoding="utf-8") as stream:
386
+ with open(path, encoding="utf-8") as stream:
336
387
  hooks = tomllib.loads(stream.read()).get("hooks")
337
- states = hooks.get("state") if isinstance(hooks, dict) else None
338
- states = states if isinstance(states, dict) else {}
339
388
  except FileNotFoundError:
340
- return False
389
+ return {}
341
390
  except tomllib.TOMLDecodeError as exc:
342
- raise ValueError(f"{spec['files'][1]} is not valid TOML: {exc}")
343
- 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]
344
403
  for group_index, group in enumerate(groups):
345
- if not _ours(group, _audit_hook):
404
+ if not _ours(group, is_ours):
346
405
  continue
347
- handler_index = next(i for i, hook in enumerate(group["hooks"]) if _audit_hook(hook))
348
- for path in paths:
349
- trusted = (states.get(f"{path}:session_start:{group_index}:{handler_index}") or {}).get("trusted_hash")
350
- 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):
351
410
  return True
352
411
  return False
353
412
 
354
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
+
355
534
  def audit_state(client="claude"):
356
535
  """The SessionStart audit hook in the client's hooks file: `current` (our entry equals this version's and, in
357
- 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),
358
537
  `outdated` (an entry of ours that differs) or `missing`."""
359
538
  path = _audit_client(client)["files"][0]
360
539
  try:
@@ -368,11 +547,11 @@ def audit_state(client="claude"):
368
547
  return "missing"
369
548
  if _audit_entry() not in found:
370
549
  return "outdated"
371
- 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
372
551
 
373
552
 
374
553
  def audit_hook_installed(client):
375
- """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
376
555
  proposals it already carries.
377
556
  An unreadable config file counts as off here; `audit_state` raises for it on the setup screen."""
378
557
  if client not in AUDIT_CLIENTS:
@@ -384,16 +563,16 @@ def audit_hook_installed(client):
384
563
 
385
564
 
386
565
  def _audit_after(client):
387
- """{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."""
388
567
  note = CLIENTS[client].get("after_install")
389
568
  return {"after_install": note} if note else {}
390
569
 
391
570
 
392
571
  def audit_preview(client="claude"):
393
572
  """The change that turns the SessionStart audit report on in the client, with a token for `audit_install`."""
394
- path, _data, _groups = _audit_plan(client)
573
+ path = _audit_plan(client)[0]
395
574
  entry = _audit_entry()
396
- if audit_state(client) in (AUDIT_ON, AUDIT_WAITING):
575
+ if audit_state(client) == AUDIT_ON:
397
576
  return {"installed": True, "file": path, "change": None}
398
577
  token = secrets.token_urlsafe(12)
399
578
  _PREVIEWS[token] = {"client": f"audit:{client}", "at": time.time()}
@@ -403,25 +582,34 @@ def audit_preview(client="claude"):
403
582
 
404
583
  def audit_install(token, confirm, client="claude"):
405
584
  """Writes the SessionStart audit entry into the client's hooks file with a backup; needs the `audit_preview` token
406
- (10 min) and confirm=True. Returns {installed, changed, file, backup}, plus `after_install` in Codex: the hook
407
- 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."""
408
587
  planned = _PREVIEWS.pop(token or "", None)
409
588
  if confirm is not True or not planned or planned["client"] != f"audit:{client}" or time.time() - planned["at"] > PREVIEW_TTL_S:
410
589
  raise ValueError("Turning the audit report on requires the preview token (valid for 10 min) and confirm=true.")
411
- path, data, groups = _audit_plan(client)
412
- 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:
413
592
  return {"installed": True, "changed": False, "file": path}
414
- groups.append(_audit_entry())
593
+ if client == "codex":
594
+ _codex_states()
595
+ groups.insert(slot, _audit_entry())
415
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.")
416
601
  return {"installed": True, "changed": True, "file": path, "backup": backup, **_audit_after(client)}
417
602
 
418
603
 
419
604
  def audit_remove(client="claude"):
420
- """Takes only our SessionStart entry out of the client's hooks file (after a backup); nothing else is touched."""
421
- 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)
422
608
  if audit_state(client) == "missing":
423
609
  return {"installed": False, "changed": False, "file": path}
424
610
  if not groups:
425
611
  del data["hooks"]["SessionStart"]
426
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))
427
615
  return {"installed": False, "changed": True, "file": path, "backup": backup}
package/install.py CHANGED
@@ -12,6 +12,7 @@ import urllib.request
12
12
  import venv
13
13
  from pathlib import Path
14
14
 
15
+ import client_hooks
15
16
  import paths
16
17
  import version
17
18
 
@@ -129,8 +130,9 @@ def _daemon_up():
129
130
 
130
131
 
131
132
  def hook_files():
133
+ """Claude Code's settings.json and Codex's hooks.json (CLAUDE_CONFIG_DIR and CODEX_HOME when set)."""
132
134
  claude = Path(os.environ.get("CLAUDE_CONFIG_DIR") or Path.home() / ".claude")
133
- return claude / "settings.json", Path.home() / ".codex" / "hooks.json"
135
+ return claude / "settings.json", Path(os.environ.get("CODEX_HOME") or Path.home() / ".codex") / "hooks.json"
134
136
 
135
137
 
136
138
  def _script_paths(text):
@@ -179,10 +181,11 @@ def _repointed(text, folder, target):
179
181
 
180
182
 
181
183
  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."""
184
+ """An older installation in another folder keeps the port and the hooks: stop it, point the hooks at target (in
185
+ Codex, with the approval of each trusted hook of ours carried to its new command) and delete its program folder.
186
+ Its state folders are left alone."""
184
187
  removed = []
185
- stamp = time.strftime("%Y%m%d-%H%M%S")
188
+ codex = hook_files()[1]
186
189
  for folder in other_installs(target):
187
190
  print(f"Older Smart Tool installation found at {folder}; removing it.")
188
191
  stop_processes(folder)
@@ -190,8 +193,10 @@ def remove_other_installs(target):
190
193
  original = path.read_text(encoding="utf-8") if path.is_file() else ""
191
194
  text = _repointed(original, folder, target)
192
195
  if text != original:
193
- shutil.copy2(path, path.with_name(f"{path.name}.smart-tool-backup-{stamp}"))
196
+ trust = client_hooks.repoint_trust(str(path), original, text) if path == codex else {}
197
+ client_hooks.backup_file(str(path))
194
198
  path.write_text(text, encoding="utf-8")
199
+ client_hooks.record_codex_trust(trust, str(path.with_name("config.toml")))
195
200
  print(f"Hooks in {path} now point to {target}.")
196
201
  startup = STARTUP_SCRIPT.read_text(encoding="utf-8", errors="replace") if STARTUP_SCRIPT.is_file() else ""
197
202
  if any(_same_folder(_script_folder(script), folder) for script in _script_paths(startup)):
@@ -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.55",
3
+ "version": "0.9.57",
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/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);
@@ -2225,7 +2225,10 @@ def _project_action_locked(arguments):
2225
2225
  return {"current_client": client_hooks.status(client), **integration_metrics.summary(arguments.get("days", 7))}
2226
2226
  if action == "install_hook_preview":
2227
2227
  _session, client = _session_client()
2228
- return client_hooks.preview(client)
2228
+ plan = client_hooks.preview(client)
2229
+ if "token" in plan:
2230
+ plan["plan_id"] = plan.pop("token")
2231
+ return plan
2229
2232
  if action == "install_hook":
2230
2233
  _session, client = _session_client()
2231
2234
  result = client_hooks.install(client, arguments.get("plan_id"), arguments.get("confirm"))
@@ -4088,7 +4091,7 @@ def _session_audit_hook(handler):
4088
4091
  handler._read_body(HOOK_MAX_BODY_BYTES)
4089
4092
  except ValueError as exc:
4090
4093
  _log(f"SessionStart hook body refused: {exc}")
4091
- updates =" ".join(notice for _key, notice in _update_notices())
4094
+ updates = " ".join(notice for _key, notice in _update_notices())
4092
4095
  context = "\n".join(part for part in (updates, _proposals_notice()) if part)
4093
4096
  if not context:
4094
4097
  return {}
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.55"
4
+ VERSION = "0.9.57"
5
5
  _CONTACT_RE = re.compile(r"^(?:[^\s@()<>;]+@[^\s@()<>;]+\.[^\s@()<>;]+|https?://[^\s()<>;]+)$")
6
6
 
7
7