CloudCodeTree LogoCloudCodeTree
AI NewsTutorialsAbout
CloudCodeTree Logo
CloudCodeTree
  • AI News
  • Tutorials
  • About
← Back to AI News
Block or Log a Model Switch Before It Happens: PreModelSwitch and PostModelSwitch Hooks

Block or Log a Model Switch Before It Happens: PreModelSwitch and PostModelSwitch Hooks

Chris Harper

2 min read

Sep 1, 2026 · 12:06 UTC

AI
Workflow
Claude Code
Best Practices

TL;DR: Claude Code v2.1.251 (August 28) adds PreModelSwitch and PostModelSwitch hook events — block unauthorized model switches, log them for audit, or surface re-cache cost before a stale session pays it. SessionStart resume hooks now also receive session staleness and estimated re-cache cost.

When Claude Code decides to switch models mid-session — bumping from Sonnet 5 to Opus 5 for a hard problem — you previously had no visibility or control. v2.1.251 adds two hook points:

  • PreModelSwitch: fires before the switch, letting you block it or prompt for confirmation.
  • PostModelSwitch: fires after the switch, with the new model's name available for logging.

Block unauthorized switches in .claude/settings.json:

{
  "hooks": {
    "PreModelSwitch": [
      {
        "command": "echo 'Model switch blocked by org policy' >&2 && exit 1",
        "description": "Prevent all model switches in this project"
      }
    ]
  }
}

Log switches for cost tracking:

{
  "hooks": {
    "PostModelSwitch": [
      {
        "command": "echo "$(date -u) model switched to $CLAUDE_NEW_MODEL" >> ~/.claude/model-switch.log",
        "description": "Audit log — track which model ran which task"
      }
    ]
  }
}

Session staleness in SessionStart. When a session resumes, the SessionStart hook now receives CLAUDE_SESSION_STALENESS_SECONDS and CLAUDE_ESTIMATED_RECACHE_COST. Use them to warn before paying a large re-cache bill:

#!/usr/bin/env bash
# .claude/hooks/check-staleness.sh
if [[ "${CLAUDE_SESSION_STALENESS_SECONDS:-0}" -gt 3600 ]]; then
  echo "Warning: session is $((CLAUDE_SESSION_STALENESS_SECONDS / 60)) min old." >&2
  echo "Re-caching will cost ~$CLAUDE_ESTIMATED_RECACHE_COST tokens." >&2
fi

Wire it in settings.json:

{
  "hooks": {
    "SessionStart": [
      { "command": "bash .claude/hooks/check-staleness.sh" }
    ]
  }
}

Who this is for: Teams running Claude Code as managed infrastructure — engineering orgs that want to prevent developers from switching to higher-cost models without approval, security teams who need an audit trail of which model ran which task, or budget-conscious shops who want visibility into per-session re-cache costs before they land.

Limits: Hooks run shell commands; complex logic lives in a separate script. The hook environment provides the model name, not the reason for the switch — you can log or block but not inspect Claude's internal decision.

Sources: Claude Code changelog v2.1.251 — code.claude.com · Hooks — Claude Code Docs · Settings reference — Claude Code Docs