@allansantos-dev/smart-tool 0.9.56 → 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,21 @@
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
+
3
19
  ## 0.9.56 - beta
4
20
 
5
21
  - 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.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.56 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
@@ -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
@@ -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.56",
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"))
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.57"
5
5
  _CONTACT_RE = re.compile(r"^(?:[^\s@()<>;]+@[^\s@()<>;]+\.[^\s@()<>;]+|https?://[^\s()<>;]+)$")
6
6
 
7
7