ARTICLE · 1519619
深扒 Claude Code Mods:不学 API、不改源码,普通人也能定制 AI 编程神器
作者:Addy Osmani(Anthropic 技术专家)
译者:倔强青铜三
前言
大家好,我是倔强青铜三。欢迎关注我,微信公众号:倔强青铜三。欢迎点赞、收藏、关注,一键三连!!!
先给一句话版本:Mod 是一个跑在你 Claude Code 会话里的小巧 JavaScript / TypeScript 文件。 它能旁观会话中发生的一切、改写 Claude Code 的行为,甚至亲手绘制自己的 UI——在终端里画,在桌面 App 里也画。你完全不需要先啃 API:运行 claude,用一句话描述你想要的 Mod,在它询问时允许热重载,Claude 这一轮跑完,你的 Mod 就挂上去了。
Claude Code 本身已经给了不少自定义手段:settings、权限规则、斜杠命令、skills、状态栏。而 Mod 走得更远——它们可以改写甚至替换 Claude Code 的行为,还能绘制自定义 UI。 底层来看,Mod 就是打包在插件里的 Hook,每一个都能实时看到你会话中的每一个事件。
这让 Mod 成了一种"把 Claude Code 调教成你顺手的样子"的方式:你可以加一个自己天天想看的读数,给那些让你提心吊胆的命令上一道保险,或者为你喜欢的代码审阅方式专门做一个视图。
本指南会从空文件夹开始,带你亲手写一个 Mod——Token Weather,画在提示符正上方的上下文窗口"实时天气预报",全部代码约 80 行。随后再逛两个更大的 Mod——Blast Radius 和 Replay Theater——看看这套 API 还能玩出什么。
深色终端里三段演示依次登场——Token Weather 的状态带从 18% 的 Clear 一路涨到 81% 的 Storm;Blast Radius 拦下 rm -rf build,列出将被删除的 9 个文件;Replay Theater 逐条回放把 greet 改名为 welcome 的过程。
Token Weather 状态带随上下文窗口变满的全过程:18% Clear → 67% Showers → 81% Storm 画面:一行终端状态带在三种预报间切换——Clear 配黄色太阳、Showers 配蓝色雨伞、Storm 配粉色闪电,各自带 200k 窗口中的 token 占用数,以及最近几回合的小柱状图。
需要 Claude Code 2.1.287 或更高版本。 Mod 默认开启,无需任何设置。API 可能随版本变动。每次 Claude Code 加载 Mod 时,都会把与你当前构建匹配的类型声明写进 Mod 的 .claude-plugin/types/ 文件夹——那才是你这一个版本的权威参考。
Mod 是怎么工作的
一个 Mod,就是一个"行为写在 JavaScript / TypeScript 模块里"的 Claude Code 插件:
文件夹是一个普通插件,带 .claude-plugin/plugin.json清单。hooks/hooks.json在modules里指名一个模块。模块导出 register(on, options)。在其内部,on(event, matcher?, hook)用来注册 Hook。
每个 Hook 都是同一个形状:
on("tool.call", { tool: "Bash" }, async ($, e, next) => {// $ Mods API:ui、session、state、store、fs、process、clock、http、tool、command、model……// e 本次事件的输入,纯数据// next 把 e 传给后续插件,最后交给 Claude Code 自身的默认行为return next(e);});Hook 们连成一条链,像中间件一样:你的先跑,next(e) 把事件交给下一个插件,链的尽头,Claude Code 照常做它本来要做的事。一个 Hook 能做三种动作之一:
示意图:事件先穿过你的 Hook,再穿过其他插件,最后到 Claude Code。每一环都调用 next(e) 往下传,结果再原路返回。直接"接管"的 Hook 则不调用 next 就返回。
| 旁观 Observe | const r = await next(e); /* 看一眼 */ return r | |
| 改写 Rewrite | return next({ ...e, command: safer }) | |
| 接管 Answer | next,直接 return { deny: "…" } |
事件覆盖面很广:工具调用、提交的提示词、回合的开始与结束、会话的启动与退出、斜杠命令,还有 ui.render——界面上每一块被画出来的东西。模块跑在自己的沙箱里,没有 DOM,也没有 Node,所以沙箱之外的一切都通过 $ 来办。
它和 settings 里的 hooks 有什么不同? settings 的 hook 每个事件启动一次 shell 命令,靠 stdin / stdout 传 JSON。而 Mod 只加载一次,常驻会话:它能保存状态,能画随事件实时刷新的 UI,还能反向调用 Claude Code——打开一个面板、跑一个进程、注册一个斜杠命令,或者注册一个可供模型调用的工具。
Claude Code 自己也在用。 Claude Code 的一些自带功能本身就是 Mod 实现的,包括 AGENTS.md 支持和对话旁边的 /diff 面板。它们的源码连同测试一起,公开在 anthropics/claude-code 仓库的 mods/ 目录下——官方团队怎么写 Mod,你可以直接照着看。
动手写第一个 Mod:Token Weather
Token Weather 在每个回合结束后读一次上下文窗口的占用,然后在提示符上方画出一行字:天气图标、百分比、已用 token 数、最近几回合的小图表,以及上一回合新增了多少。
真实会话里长这样。每一回合多读几个文件,状态带就从 ☀ Clear 涨到 ☂ Showers,再涨到 ☇ Storm:
深色终端里,每一回合都让 Claude 多读几个 Python 文件,提示符上方的状态带随之从黄色 Clear 变成蓝色 Showers,再变成粉色 Storm。
捷径:让 Claude 替你写
下面这六步你都可以跳过。Claude Code 自己就会写 Mod——你只要描述想要的,活儿它来干。开一个 claude 会话,把下面这段提示词贴进去:
Make me a Claude Code mod called token-weather: a live forecast of my context window, shown in the band above the prompt.What it should show, on one line:- A weather icon and word for how full the context window is: under 25% ☀ Clear (yellow), 25–49% ☁ Cloudy (cyan), 50–74% ☂ Showers (blue), 75–89% ☇ Storm (magenta), 90% and up ↯ Compact soon (red).- The percentage used, then the tokens used out of the window, like "134.4k / 200k".- A small chart of the last 12 turns, drawn with ▁▂▃▄▅▆▇█.- How much the last turn added, like "▲ +98.3k last turn".It should update after every turn.Claude 会问一次要不要为本会话开启热重载,允许它;这一轮结束时,状态带就出现在提示符上方了。从这以后,每次改动都原地重载,你可以不断提修改意见("让 Storm 从 70% 就开始""结尾加上美元成本"),看着状态带实时变化。这个 Mod 只在当前会话里生效,它的文件夹稍后会被清理——想留下它,把文件夹拷出来,像普通插件那样安装(第 6 步)。
注意,这段提示词只描述了"你想看到什么"。写 Mod 不需要懂 API。 Claude Code 内置的 Mod 编写指南会替你搞定"怎么做":状态存哪里才能在重载后存活、怎么用 claude plugin validate 检查插件、该挂哪些事件。把"What it should show"那几行改成你的需求,它就是你的 Mod,不是我们的。
如果你想先看看它内部是怎么拼起来的,或者想检查 Claude 写的东西靠不靠谱,往下读。
第 1 步:创建文件夹
先确认 Claude Code 够新:
claude --version # 2.1.287 或更高建出这个目录结构:
token-weather/├── .claude-plugin/│ ├── plugin.json│ └── types/ (Claude Code 加载 Mod 时自动写入)├── hooks/│ ├── hooks.json│ └── token-weather.mjs├── types/│ └── index.d.ts (第 3 步添加)└── tests/ └── token-weather.test.ts (第 5 步添加).claude-plugin/plugin.json 是标准的插件清单:
{"name": "token-weather","version": "0.1.0","description": "A live forecast of the context window, drawn above the prompt.","author": { "name": "You" }}hooks/hooks.json 指向模块。一个 Mod 有且只有一个模块:
{"modules": ["./token-weather.mjs"]}第 2 步:先画出点东西
紧贴提示符上方的那条区域是一个叫 AbovePrompt 的组件。Claude Code 自己在那里什么都不画,所以它是绝佳的第一目标。挂住它的 ui.render 事件,返回一棵元素树:
// hooks/token-weather.mjsexport function register(on) {on("ui.render", { component: "AbovePrompt" }, ($, e, next) => {const { Box, Text } = $.ui.resolve(e);return Box({paddingX: 1,children: [Text({ color: "yellow", bold: true, children: "☀ Clear skies" })], }); });}这些元素不是全局变量。$.ui.resolve(e) 返回的是"当前绘制表面"的构造器——因为 Claude Code 画在不同表面上,支持的元素集合略有差异。JSX 也可以用,工厂函数是 h。
带着插件启动会话:
claude --plugin-dir ./token-weather"☀ Clear skies" 出现在提示符上方了。保持会话开着。这个文件夹是被监听的,每次保存都会原地重载模块,不用重启。这种即时反馈循环,正是写 Mod 好玩的地方。
小提示: 摸清了这个形状之后,下一个 Mod 就可以像"捷径"一节那样,直接用嘴描述给 Claude 听。它会把插件写进一个文件夹,在同一个会话里热重载。
第 3 步:读取真实数据,存进 $.state
$.session.usage() 返回的数字和状态栏一致:context.tokens 是上一次响应所基于的输入量,context.window 是模型的窗口大小,context.percent 是两者之比。这个调用是免费的——只有你主动要 breakdown 时才会发一次 token 计数请求。
会话启动时测一次,每个回合结束后再测一次:
on("session.start", async ($, e, next) => {const result = await next(e);await takeReading($);return result;});on("turn.complete", async ($, e, next) => {const result = await next(e);if (!e.agentId) {await takeReading($); // 只统计主循环回合,子代理不算 }return result;});两个 Hook 都先 next(e) 再旁观,谁也不改变事情本来的走向。
读数存哪里? 模块级的 let readings = [] 看着最顺手,但热重载就是一次全新加载:register 重新执行,session.start 重新触发,模块变量全部归零。所以要把历史放进 $.state——它把命名值托管在宿主里,整个会话有效,重载也不丢。
// 由宿主持有,因此这份历史能在本文件热重载后幸存。const readings = { plugin: "token-weather", key: "readings" };async function takeReading($) {const { context } = await $.session.usage();if (!context?.window) return;const tokens = context.tokens ?? 0;const percent = context.percent ?? Math.round((tokens / context.window) * 100);const { value: history = [] } = await $.state.get(readings);await $.state.set(readings, [...history, { tokens, window: context.window, percent }].slice(-HISTORY));}状态值要声明在插件的类型契约里——一个小小的 .d.ts 文件,由清单指路。添加 types/index.d.ts:
export type TokenWeatherReading = { tokens: number; window: number; percent: number };declare module "claude-code" {interface PluginState {"token-weather": { readings: TokenWeatherReading[] }; }}然后在 plugin.json 里加 "types": "./types/index.d.ts"。跳过这一步的话,claude plugin validate 会拦下你,报错信息直接告诉你怎么改:token-weather.readings is not declared: the manifest's types contract must name it in interface PluginState { … }。
作为回报,你会白拿一个能力:自动重绘。 只要 $.state.get 发生在渲染 Hook 执行期间,这次绘制就完成了订阅——之后任何一次 $.state.set 都会重画状态带。你永远不需要手动调用 $.ui.invalidate。
第 4 步:把预报画出来
下面是完整模块:
// Token Weather:画在提示符上方的上下文窗口实时预报。const HISTORY = 12;const BARS = "▁▂▃▄▅▆▇█";const FORECAST = [ { upTo: 25, icon: "☀", word: "Clear", color: "yellow" }, { upTo: 50, icon: "☁", word: "Cloudy", color: "cyan" }, { upTo: 75, icon: "☂", word: "Showers", color: "blue" }, { upTo: 90, icon: "☇", word: "Storm", color: "magenta" }, { upTo: Infinity, icon: "↯", word: "Compact soon", color: "red" },];// 由宿主持有,因此这份历史能在本文件热重载后幸存。const readings = { plugin: "token-weather", key: "readings" };export function register(on) {on("session.start", async ($, e, next) => {const result = await next(e);await takeReading($);return result; });on("turn.complete", async ($, e, next) => {const result = await next(e);if (!e.agentId) {await takeReading($); // 只统计主循环回合,子代理不算 }return result; });on("ui.render", { component: "AbovePrompt" }, async ($, e, next) => {const { value: history = [] } = await $.state.get(readings);if (e.props.hasSurvey || history.length === 0) {return next(e); }const { Box, Text } = $.ui.resolve(e);return band(Box, Text, history, e.props.bodyColumns); });}async function takeReading($) {const { context } = await $.session.usage();if (!context?.window) return;const tokens = context.tokens ?? 0;const percent = context.percent ?? Math.round((tokens / context.window) * 100);const { value: history = [] } = await $.state.get(readings);await $.state.set(readings, [...history, { tokens, window: context.window, percent }].slice(-HISTORY));}function band(Box, Text, history, columns) {const now = history[history.length - 1];const f = FORECAST.find((b) => now.percent < b.upTo);const parts = [Text({ color: f.color, bold: true, children: `${f.icon}${f.word}` }),Text({ children: ` ${now.percent}% of context` }),Text({ dimColor: true, children: ` ${short(now.tokens)} / ${short(now.window)}` }), ];if (columns >= 60) { parts.push(Text({ dimColor: true, children: " last turns " })); parts.push(Text({ color: f.color, children: sparkline(history) }));if (history.length > 1) { parts.push(Text({ dimColor: true, children: trend(history) })); } }return Box({ flexDirection: "row", paddingX: 1, children: parts });}function sparkline(history) {const top = Math.max(...history.map((r) => r.tokens), 1);return history.map((r) => BARS[Math.floor((r.tokens / top) * (BARS.length - 1))]).join("");}function trend(history) {const delta = history[history.length - 1].tokens - history[history.length - 2].tokens;if (delta === 0) return " steady";return delta > 0 ? ` ▲ +${short(delta)} last turn` : ` ▼ ${short(-delta)} last turn`;}function short(n) {if (n >= 1_000_000) return `${+(n / 1_000_000).toFixed(1)}M`;if (n >= 1_000) return `${+(n / 1_000).toFixed(1)}k`;return String(n);}有三个细节值得抄回你自己的 Mod 里:
组件的 props 在 e.props上。hasSurvey告诉你有个调查想要占用状态带,于是 Hook 用next(e)把位置让出去。bodyColumns是状态带的实际宽度——当面板停靠在会话记录旁边时,它比终端更窄,元素树要按它来定尺寸。e的顶层只有e.component、e.surface、e.requestId和e.viewport。没东西可画时就放行。 返回 next(e),把状态带还给 Claude Code 和其他 Mod。用单宽度符号,别用 emoji。 ☀ ☁ ☂ ☇ ↯ 在每一种终端字体里都能对齐。
保存文件,正在跑的会话立刻生效。读几个大文件之后,状态带就会从 Clear 走到 Showers,再走到 Storm——就像本节开头那段录屏一样。
第 5 步:校验和测试
claude plugin validate 会用和 Claude Code 完全一样的方式去读清单和模块源码,然后报告这个模块挂了哪些事件、调用了什么:
$ claude plugin validate ./token-weather > types ./types/index.d.ts declares state: token-weather.readings > ./token-weather.mjs hooks: session.start, turn.complete, ui.render{component=AbovePrompt} > ./token-weather.mjs calls: $.session.usage (via takeReading), $.state.get, $.state.set (via takeReading), $.ui.resolve > ./token-weather.mjs state writes: token-weather.readings > ./token-weather.mjs state reads: token-weather.readings√ Validation passedclaude plugin test 会拿插件里的 *.test.ts 文件,对着真实的 Claude Code 运行时跑。测试里用 on 注册的 Hook 排在链条上 Mod 的后面,替身接管 Claude Code 本应给出的返回值——所以 $.session.usage() 返回什么,完全由你说了算:
// tests/token-weather.test.tsimport { describe, expect, test } from "claude-code/testing";describe("token-weather", () => {test("the band follows the context window", async ($, on) => {// 这里注册的 Hook 排在 Mod 之后,替身接管 Claude Code 本应给出的返回值。let tokens = 36_100;on("session.start", ($, e) => ({ cwd: e.cwd }));on("session.usage", () => ({value: { startedAt: 0, rateLimits: [], context: { tokens, window: 200_000, percent: Math.round(tokens / 2_000) } }, }));on("turn.complete", () => ({ text: "" }));await $.session.start({ surface: "terminal", isInteractive: true, cwd: "/work" } as any);const ui = await $.ui.mount({plugin: "token-weather",surface: "terminal",component: "AbovePrompt",props: { hasSurvey: false, isWorking: false, maxRows: 10, bodyColumns: 120 }, } as any);expect(await ui.find({ type: "Text", text: /Clear/ })).toBeDefined(); tokens = 134_400;await $.turn.complete({ reason: "answer", answer: "ok", durationMs: 1 } as any);expect(await ui.find({ type: "Text", text: /Showers/ })).toBeDefined();expect(await ui.find({ type: "Text", text: /67% of context/ })).toBeDefined();expect(await ui.find({ type: "Text", text: /▲ \+98\.3k last turn/ })).toBeDefined();await ui.unmount(); });});$ claude plugin test ./token-weather(pass) token-weather > the band follows the context window 1 pass 0 fail这个测试顺带验证了第 3 步说的重绘行为:turn.complete 之后状态带自动更新,Mod 从头到尾没请求过一次重绘。
第 6 步:发布它
Mod 就是插件,所以发布方式也一样。把它放进一个 marketplace——可以简单到一个装着 .claude-plugin/marketplace.json 的文件夹:
{"name": "my-mods","owner": { "name": "You" },"plugins": [{ "name": "token-weather", "source": "./token-weather" }]}claude plugin marketplace add ./my-modsclaude plugin install token-weather@my-mods --scope user分享你的 Mod
Mod 是 Claude Code 插件,所以分享方式和所有插件一模一样,没有新东西要学。把 Mod 放进一个带 marketplace 文件的 GitHub 仓库,这个仓库就成了你的 marketplace。谁都能从里面安装,而你更新它只需要一次普通的 push。
在 Claude Code 里安装只要三条命令:
/plugin marketplace add your-org/my-mods/plugin install token-weather@my-mods/reload-plugins重载之后 Mod 就启动了。如果没出现,重启一下 Claude Code。
要注意:Mod 是跑在你机器上、Claude Code 内部的代码,拥有和 Claude Code 相同的访问权限,而且它由发布者编写,不是 Anthropic。所以装 Mod 要像装软件包一样:先读仓库,只装信得过的人的东西。在你亲自执行命令之前,什么都不会被安装。
Claude 目录(Claude Directory)也收录带 Mod 的插件,你可以在 claude.ai/directory/manage 提交自己的作品,让别人不需要你发链接也能找到它。
另外两个 Mod
Token Weather 只旁观、只画图。接下来这两个 Mod 会拦进事件流、打开面板、接收输入。
Blast Radius:危险命令执行之前,先看清它会改掉什么
当 Claude 用 Bash 调用 rm -rf、git reset --hard、git clean、强推或者数据库迁移时,Blast Radius 会按住这次调用。它算出这条命令会动到什么,然后打开一个面板,摆上 Proceed 和 Cancel 两个按钮。按 2,Claude 收到一条带原因的拒绝;按 1,命令原样执行。
深色终端里让 Claude 删除 build 文件夹,黄色边框的 Blast Radius 面板写出命令、列出 build/ 下将被删除的文件,并给出编号的 Proceed / Cancel 选项。第一次按 Cancel 拒绝,第二次按 Proceed 放行。
它用了三个 Hook:Bash 上的 tool.call,以及 Pane 和 AbovePrompt 上的 ui.render。核心正是前面表格里的"接管"动作:
on("tool.call", { tool: "Bash" }, async ($, e, next) => {const risk = classify(String(e.command ?? ""));if (risk === null) return next(e); // 其余命令照常放行const report = await measure($, risk, await $.session.cwd()); // git status、git clean -n、du…… held = { command: e.command, risk, report, decision: null };const opened = await $.ui.open({ id: "blast-radius", title: "Blast Radius", focus: true });if (!opened.isPlaced) held.where = "band"; // 终端太窄放不下面板:改画在提示符上方while (held.decision === null && !next.signal.aborted) {await $.process.run(["sleep", "0.25"]); // 在 $ 调用内部等待的时间不计入 Hook 的时限 }if (held.decision === "proceed") return next(e); // 放行return { deny: `Blast Radius held this command: the user pressed Cancel. It would have: ${report.summary}.` };});它能教你的:
用 $.process.run做干跑。 报告数据来自那些工具自己的命令:git status --porcelain、git clean -n、git log HEAD..origin/main、showmigrations。参数以 argv 数组传入,路径里的任何东西都不会被当成 shell 代码执行。按住一次调用。 每次 dispatch,Hook 有 10 秒自己的时间配额,但等在 $调用内部的时间不算。这个循环靠一次次短暂的sleep进程等待,直到某个按钮的onPress写入决定;当你按下 Esc、next.signal中止时,它就放弃。带快捷键的按钮。 Button({ label: "Proceed", hotkey: "1", onPress })支持点击、Tab + 回车,或直接按数字。退化到状态带。 终端够宽时,面板停靠在会话记录旁边;当 $.ui.open返回isPlaced: false,同样的报告改画在提示符上方:

120 列宽时,Blast Radius 把 git reset --hard 的报告画在提示符上方的状态带里
它是安全网,不是权限系统。它读的是命令文本,所以 $(…)、别名和间接调用 rm 的脚本都能绕过它。要硬拦截,请用权限规则。
Replay Theater:逐条回放上一回合的每次改动
回合进行时,Replay Theater 把每一次 Edit 和 Write 调用都录下来:文件名,加上改动前后的文本。回合一结束,提示符上方出现一条提示。按 r(或输入 /replay),一个面板开始逐条 diff 地走完所有改动,配上编号步骤条和 Prev、Next、Close 按钮。
深色终端里红绿 diff 把 greet 改名为 welcome;提示符上方出现洋红色的 Replay 提示,随后是洋红边框的面板,逐条 diff 走过每次编辑,带 Prev / Next / Close 按钮。
它从不阻塞、从不改动任何编辑,只是旁观:
on("tool.call", async ($, e, next) => {if (EDIT_TOOLS.has(e.tool)) state.pending.push(...(await stepsFor($, e))); // 旧文本/新文本 → diffreturn next(e); // 编辑原样放行});on("turn.start", ($, e, next) => { if (!e.agentId) state.pending = []; return next(e); });on("turn.complete", async ($, e, next) => {const r = await next(e);if (!e.agentId && state.pending.length) state.replay = state.pending; // 每回合只留一份回放return r;});on("session.start", async ($, e, next) => {const r = await next(e);await $.command.register({ name: "replay", description: "Step through the last turn's file edits" });return r;});on("command.run", { command: "replay" }, async ($, e) => ({ text: (await openReplay($)) ? "Replaying" : "No edits" }));它能教你的:
配对事件。 turn.start和turn.complete把编辑圈成每回合一份回放,e.agentId保证子代理的回合不掺进来。注册斜杠命令。 在 session.start里$.command.register,再用command.run应答。读文件。 对 Write 而言, $.fs.read赶在写入落盘前拿到旧内容,所以 diff 是真实的。摆在哪里由表面说了算。 全屏时面板靠右停靠;80 列宽时它内联展开在提示符上方。无论哪种,Mod 画的都是同一棵元素树。

80 列宽时的 Replay Theater,内联画在提示符上方
值得带走的四个习惯
倚仗 Claude Code 替你写的类型。 每次加载你的 Mod,Claude Code 都会把与你构建匹配的声明写进 Mod 的 .claude-plugin/types/文件夹,编辑器和tsc -p不用任何额外配置就能工作。每个事件、$上的每个方法、每个元素的 props,参考都在那里。props 从 e.props读。hasSurvey、bodyColumns它们都住在e.props里,不在e本身上。为热重载做设计。 每次保存都会重新执行 register和session.start,所以数据要放$.state,别放模块变量。画不出来时,去读日志。 跑 claude --debug,找那一行说"某个 Hook 返回的树未通过校验"的日志。
你想 Mod 点什么?
这篇文章里的三个 Mod,各自来自一个朴素的问题:我的上下文还剩多少?、这条命令马上要删什么?、Claude 刚刚改了什么? 你的问题肯定不一样——而这正是重点。几个起手式供参考:
用 $.session.usage()做一个费用或限流仪表盘,借助$.ui.status做成状态栏挂一个 prompt.submit,给每一条提示词自动附上你团队的规范做一个面板,列出 Claude 本会话读过的所有文件——一张它"看过什么"的实时地图 做一个专注计时器,长回合结束时用 $.ui.toast弹一个提醒针对你的技术栈定制一个 tool.call守卫,比如生产环境的 kubectl 上下文、terraform apply















































































