跳到正文
AI寒武纪 · 微信公众号·· 2026-10-02精选AI 评分76

Claude Code 开放 Mod 系统,可用提示词生成扩展并热加载

刚刚,Claude Code 开放魔改!动嘴就能换界面改行为,DeepSeek Harness被偷家

AI 导读

Claude Code 开放 Mod 机制,用户可像游戏打补丁一样修改其界面、操作逻辑和底层功能,甚至输入一段 Prompt 让 Claude 现场生成 Mod 并热加载。

推荐理由

官方 Mod 机制支持用 TypeScript 或一句话让 Claude 生成扩展并热加载,文章还给出从零手写 Token Weather 的完整步骤。

正文

原创 你说的完全正确 2026-10-02 08:31 江苏

↑阅读之前记得关注+星标⭐️,😄,每天才能第一时间接收到更新

Claude Code现在支持装Mod了,和deepseek harness 一样,deepseek叫插件,cc叫mod,你可以像给游戏打补丁一样,彻底魔改它的界面、操作逻辑甚至底层功能。

你可以自己写几行 TypeScript,也可以直接打字让 Claude 现场把 Mod 写出来并热加载生效。

现在不管是拦截危险命令、在终端画出各种实时图表,还是逐行回放代码修改记录,都可以通过 Mod 轻松搞定。

就连 Claude Code 自带的 /diff 和 AGENTS.md 支持,官方现在都已经改成了 Mod 实现。

Claude Code 之父 Boris Cherny 发推表示:现在只需要输入 Prompt,就能让 Claude 按照你想要的方式工作和展现。每个人的工作流都不同,没有理由让所有人都面对一模一样的 Claude。

DeepSeek Harness 之父 Tianyi Cui 第一时间围观并点赞,哈哈哈🤣

官方演示:三个Mod展示无限可能

官方首先展示了三个极具代表性的 Mod,覆盖了监控、安全防护和交互审查三大场景。

1. Token Weather(上下文天气预报)

在输入框上方实时显示当前上下文窗口的占用情况,并画出过去 12 轮交互的柱状图。

占用低于 25% 显示为晴天(Clear)
达到 67% 显示为阵雨(Showers)
超过 81% 显示为暴风雨(Storm)

2. Blast Radius(爆炸半径拦截器)

防手抖神器。当 Claude 试图执行 rm -rf、git reset --hard 或强制推送等高危命令时,系统会自动暂停执行,并在侧边栏或者提示栏列出该命令到底会影响哪些文件,等待你按键确认。

3. Replay Theater(修改回放影院)

记录 Claude 在一轮对话中做出的所有文件修改。输入 /replay 或者按下快捷键,就能在侧边面板中像放幻灯片一样,一步一步查看每处代码的 Diff。

Mods 的工作原理

Mod 本质上是一个 TypeScript 或 JavaScript 模块,它运行在你的会话中,监听 Claude Code 产生的各种事件。

每个事件发生时,所有 Mod 会像中间件一样串联起来:

一个 Mod 钩子函数通常具备三种能力:

1.Observe(观察):静默记录数据,例如统计文件修改、计算 Token 消耗。

2.Rewrite(重写):在数据传递给下一个环节前进行篡改,比如在 Prompt 发送给模型前追加规范,或者脱敏工具输出中的敏感信息。

3.Answer(拦截并接管):直接返回结果,不再往下执行,比如直接拒绝执行某个高危命令。

on("tool.call", { tool: "Bash" }, async ($, e, next) => {
  // $    代表 Mods API:包含 ui, session, state, fs, process 等模块
  // e    当前事件的输入数据
  // next 将事件继续传递给下一个插件以及 Claude Code 自身
  return next(e);
});

Mod 拥有和 Claude Code 本身完全相同的系统权限,没有沙箱隔离。官方强调,只安装来自可信来源的 Mod。

对于企业和团队用户,官方提供了管理员控制策略。系统内置了一个名为 sec-default 的安全底线 Mod,默认最先加载,防止普通用户安装的 Mod 绕过团队设置的权限拒绝规则。

动手写你的第一个 Mod:Token Weather

下面带你从零构建 Token Weather,代码量只有 80 行左右。

运行环境要求:Claude Code 2.1.287 或更高版本。

快捷方式:直接让 Claude 帮你写

在终端中启动 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.

允许开启热重载后,输入框上方会立即出现状态栏。后续任何需求变动,只要继续跟它提要求即可实时生效。

详细说说这个tooken天气预报是怎么手动做出的

手动开发步骤拆解

第一步:创建文件目录

token-weather/
├── .claude-plugin/
│   ├── plugin.json
│   └── types/            (加载时自动生成)
├── hooks/
│   ├── hooks.json
│   └── token-weather.mjs
├── types/
│   └── index.d.ts
└── tests/
    └── token-weather.test.ts

配置 .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 指定模块入口:

{
  "modules"
: ["./token-weather.mjs"]
}

第二步:绘制基础 UI

在 hooks/token-weather.mjs 中监听 ui.render 事件,目标组件为 AbovePrompt:

export 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" })],
    });
  });
}

启动会话并加载插件:

claude --plugin-dir ./token-weather

输入框上方会立即出现黄色字样的晴天状态。

第三步:读取数据并持久化到 $.state

每次热重载都会重新执行模块,普通的 JS 全局变量会被重置。数据必须保存在 $.state 里面才能在热重载后留存。

在 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"。

通过 $.session.usage() 获取上下文数据:

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(-12));
}

在 session.start 和 turn.complete 事件中触发数据记录:

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;
});

第四步:完整代码拼接

把数据渲染成终端字符画,完整代码如下:

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);
}

第五步:验证与测试

运行校验命令检查配置与调用关系:

claude plugin validate ./token-weather

编写测试用例 tests/token-weather.test.ts:

import { describe, expect, test } from "claude-code/testing";
describe
("token-weather", () => {
  test
("the band follows the context window", async ($, on) => {
    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();
    await
 ui.unmount();
  });
});

运行自动化测试:

claude plugin test ./token-weather

第六步:分发与安装

Mod 本身就是插件。你可以创建一个 marketplace.json 并推送到 GitHub:

{
  "name"
: "my-mods",
  "owner"
: { "name": "You" },
  "plugins"
: [{ "name": "token-weather", "source": "./token-weather" }]
}

用户只需三条命令就能安装:

/plugin marketplace add your-org/my-mods
/plugin install token-weather@my-mods
/reload-plugins

也可以直接提交到官方的 Claude 插件市场:

claude.ai/directory/manage。


进阶:如何拦截危险命令与构建交互面板

看懂了 Token Weather,再来看另外两个进阶 Mod 是如何做交互的。

1. Blast Radius 的命令拦截机制

它不仅监听了 tool.call,还实现了无感知干预:

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());
  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"]);
  }
  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 进行预检,防止 Shell 代码注入。

挂起等待:Mod 的钩子有 10 秒超时限制,但在 $ 内部方法(如 sleep 进程)里的等待时间不会计入超时。

响应式 UI:终端窗口足够宽时在侧边开面板,宽度变窄时(例如 120 列)自动降级到输入框上方渲染。

2. Replay Theater 的改动追踪机制

它完全不修改任何执行结果,只做旁路监听:

on("tool.call", async ($, e, next) => {
  if
 (EDIT_TOOLS.has(e.tool)) state.pending.push(...(await stepsFor($, e)));
  return
 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 归拢同一轮对话中的多次写入。

真实 Diff:写入文件前先用 $.fs.read 抓取原内容,精准算出前后变化。

注册指令:通过 $.command.register 在会话启动时注册自定义斜杠命令。


开发习惯与避坑指南

官方团队在构建内置 Mod 时总结了四条经验:

1.善用自动生成的类型声明:每次加载 Mod,系统都会在 .claude-plugin/types/ 生成当前版本的最新类型定义,直接跟着 TypeScript 提示写。

2.组件参数在 e.props 里面:hasSurvey、bodyColumns 等参数都在 e.props 下,不要直接去 e 顶层获取。

3.状态存进 $.state:为热重载做好准备,绝对不要用模块内部的闭包变量存历史数据。

4.遇事不决查日志:如果 UI 没按预期画出来,运行 claude --debug,查看是否有组件校验失败的报错。

从今天开始,你不再需要苦等官方更新功能。想要什么工作流,自己写一个 Mod,或者直接让 Claude 给你搓一个。

官方详细指南看这里:

https://claude.dev/blog/getting-started-with-claude-code-mods/

--end--

最后记得⭐️我,每天都在更新:如果觉得文章还不错的话可以点赞转发推荐评论

/...@作者:你说的完全正确(YAR师)

跳转微信打开

来源:AI寒武纪 · 微信公众号 · mp.weixin.qq.com