跳到正文
DEV Community· Vildanden·· 4 小時前AI 評分52

用 UserPromptSubmit 為每個 Claude Code 提示詞加入預算提醒

Inject a budget line into every Claude Code prompt with UserPromptSubmit

AI 導讀

Claude Code 的 UserPromptSubmit hook 會在模型讀取每次訊息前執行,可注入精簡的上下文提醒,避免 CLAUDE.md 因持續規則而變得冗長。示例提醒 Claude 優先使用程式碼庫內現有工具、保持改動精簡,遇到需要機密資料或開支的任務先停下詢問。作者建議注入內容只保留幾行;hook 註冊路徑可能因 Claude Code 版本而異,應查閲已安裝版本的文件。

正文

Vildanden

Hooks are not only for blocking bad tool calls. UserPromptSubmit runs when you send a message, before the model sees it — so you can inject a short context block every turn without bloating CLAUDE.md.

Use it for a standing budget reminder: context window, spend ceiling, or “prefer local tools over network.”

Minimal hook

Put this under .claude/hooks/ (exact registration path can vary by Claude Code version — confirm against your installed docs):

#!/usr/bin/env bash
# user-prompt-submit.sh — stdout is appended into the turn context
set -euo pipefail
cat <<'CTX'
[session budget]
- Prefer tools already in the repo; do not install packages unless asked.
- Keep diffs small; one concern per turn.
- If the task needs secrets or spend, stop and ask.
CTX

Wire it so Claude Code runs the script on UserPromptSubmit. Keep the injected text short (a few lines). Long dumps here fight the same context limit you are trying to protect.

Why not put this in CLAUDE.md?

  • CLAUDE.md is loaded once and drifts into a novel. A hook stays one focused reminder.
  • You can change the budget file without rewriting house rules.
  • Pair with a short stack map in CLAUDE.md (under ~80 lines) and put deny/ask policy in .claude/settings.json.

I keep the hooks, settings, and short house-rules file together in Vildanden Agent Config. The free sample is enough to try the pattern.

來源:DEV Community · dev.to