SLOPSHOPPER

moon-band

The moon's phase, its age, a line of poetry and the poet's dynasty above the prompt, with a button that explains the line on demand (cached after the first…

bandcommandtoastmodeltimer
v0.2.2no licenseupdated 2026-10-20zhuobichen/zhaowen-claudemod/moon-band
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · moon-band
› fix the failing auth test and add an audit log call ╭────────────────────────────────────────╮ │ moon-band │ ⏺ Read(src/auth.ts) │ moon-band: data/poems.txt 没读到,先用内置 8 句 │ ⎿ Read 6 lines ╰────────────────────────────────────────╯ ⏺ Update(src/auth.ts) ╭────────────────────────────────────────╮ ⎿ Added 2 lines, removed 1 line │ moon-band │ ⏺ Bash(bun test) │ moon-band: data/poems.txt 没读到,先用内置 8 句 │ ⎿ 3 pass, 1 fail ╰────────────────────────────────────────╯ ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /moon ⎿ moon-band: moon line hidden ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

moon-band

提示行上面一行月光:月相 + 月龄 + 一句古诗 + 朝代,右边一个「详解」按钮。整行压暗。纯装饰,/moon 可以收起来。

🌒 娥眉月 4.6天 · 「今人不见古时月,今月曾经照古人。」李白《把酒问月》  唐  [详解]

点「详解」,下面展开:

唐 · 约 725 年(开元十三年)
诗意:今人看不到古时的月亮,可今晚这轮月,却曾经照过古人。
背景:李白借问月感叹人生短暂、宇宙无穷,是他失意时的自问。

装

/plugin install moon-band --marketplace zhuobichen/zhaowen-claudemod

朝代

语料(46167 句、2461 位作者)里没有朝代字段,所以靠一张「作者 → 朝代」表(hooks/dynasty.ts)。表的取舍按出现频率而不是名气:诗句是从全语料里均匀抽的,作者贡献的行数就等于他出现的概率。表覆盖出现次数前 100 位作者,合计 29,690 句 = 64%。

表外那 36% 是冷门作者,不显示朝代(不猜)。但点过一次「详解」之后,模型会把朝代一起补出来写进缓存,那之后这句诗就认识朝代了。

详解与缓存

怎么打开(按可靠程度排):

方式怎么用备注
/poem直接敲最可靠,不依赖鼠标也不依赖焦点;输出就是那三行,并顺手把缓存暖上
热键 1输入框空着时按 1;或先 ctrl+x tab 把这一带聚焦,再按 1按钮是 plain + hotkey="1",会显示成 1: 详解
点按钮终端支持鼠标上报时直接点多数终端默认不开,所以别指望它

说明:AbovePrompt 这一带里的 Button 是靠 hotkey 触发的——文档原话是 "focuses it (a click, ctrl+x tab): an Input types, a Button arms the hotkeys"。 所以只画按钮、不给热键,在没有鼠标上报的终端里就是个点不动的装饰。

点按钮 → 先查 $.store:

  • 命中 → 立刻展开,不问模型(按钮文案会是「详解(已缓存)」)
  • 未命中 → 按钮变「生成中…」,用 $.model.complete({ model: 'haiku' }) 问一次(走会话自己的客户端与凭据,不用另外配 key),拿回 朝代 / 年份 / 诗意 / 创作背景,写进 store,然后展开

缓存按诗句本身为键,跨会话、重装都有效。store 有 4 MiB 总上限,所以留 300 条(ABOUT_LIMIT),按插入顺序淘汰最早的(aboutEvictionsOf,纯函数,有测试)。

同一句展开着再点就是「收起」;换诗之后旧面板自动不画——因为面板记着自己属于哪一句。

模型不确定的字段优先给 null 而不是编:prompt 里写死了这条,解析时也把 null 原样留下。

月相与月龄是从哪来的(这段重要)

月相名:不是用"平均朔望月"糊出来的。实测:经典的平均公式拿 2026 年 10 月的四个相时刻去对,误差最大到 −0.72 天(近 17 小时);就算把锚点换成 10-10 那次新月、再扫周期参数,最坏误差仍有 0.75 天——因为月亮走得本来就不匀,两参数模型不可能更准。而背错 Meeus 的系数表会得到一个"看着挺准其实全错"的月亮,那更糟。

所以用的是一张相时刻表 + 相邻两时刻线性插值:

  • 数据来源:StarWalk 月相日历、香港天文學會 2026 年月相表(两处一致,差 ±1 分钟),北京时间
  • 覆盖 2026-10-03 → 2026-12-31(13 个时刻,严格四相轮转,间隔 6.7–8.2 天,朔望月 29.63/29.74 天)
  • 表内:准到分钟(相位在两时刻之间按线性推进,所以离边界几小时内的相名可能有几小时的出入)
  • 表外:退回平均朔望月推算,并且行首显示 ≈,告诉你这是个估计,不装成事实

月龄:是距上一次新月的真实天数,不是"相位占比 × 平均月长"。后者会把月龄算小——这个朔望月偏长(新月→上弦 8.0 天),占比算法今天会报 4.2 天,而农历是 4.6 天。农历日期是你能自己核的,所以这个数必须对得上它。

要延长覆盖,就往 hooks/moon.ts 的 INSTANTS 里整段追加相时刻(必须保持四相轮转、不可乱序,新月靠"从第一项起每第四项"定位——有一条测试盯着这个)。表是给 2026-10-03 起的连续四相用的,中间不能跳。

那句诗

每分钟换一句,从一个 46167 句的库(随 mod 一起分发)里挑,一轮不重复。

库在 data/poems.txt:唐诗 3 万句 + 宋词 1.6 万句,每行 诗句<TAB>作者《篇名》,3.18 MiB($.fs.read 的硬上限是 4 MiB)。来源与生成方式见 data/NOTICE.md,复现脚本在仓库根的 tools/build_poems.py。

怎么做到"轮完一遍才回头":用一条满周期线性同余——index = (step * slot + offset) mod N,其中 step 与 N 互质。这是个双射,所以连续 N 个格子会把每一句都取到一次、且只取一次,走完 N 格才重复;step/offset 每个周期重新取,所以下一轮是另一种顺序,不是同一轮重播。

  • 46167 句 / 每分钟一句 → 一轮约 32 天
  • 同一分钟内不变(画面之间跳句没法读)
  • 一个周期内,相邻两分钟不会是同一句(step 与 N 互质且不等于 1)
  • 周期交界处理论上可能与前一句相同(概率 1/N,可忽略)

读数不靠状态:$.store 里只存"要不要显示"这一个开关。

想换库

data/poems.txt 每行 诗句<TAB>来源 即可,缺一半的行、重复的句子会被丢掉。注意 4 MiB 上限(超了 $.fs.read 直接拒绝,mod 会退回内置 8 句并在屏幕上弹一句提示——不会假装在用你的库)。

内置那 8 句只在库读不到时兜底:李白《把酒问月》/《月下独酌》/《静夜思》、张九龄《望月怀远》、张若虚《春江花月夜》、王维《竹里馆》、苏轼《水调歌头》、李商隐《嫦娥》。

图标

用 emoji 月相(🌑🌒🌓🌔🌕🌖🌗🌘,八相一一对应)。渲染不好就换单色字形一族(◐◑◒◓ 那套),改 hooks/moon.ts 的 GLYPHS 一行。

和别的 meter 共存

它挂在 ui.render{component:'AbovePrompt'},和 Context View、deepseek-balance 是同一个位置。所以它 await next(e) 把下层画的树包住再画自己那行——直接返回自己的树会把别人那行吞掉。

开关

/moon 收起/放回,记在 $.store 里,跨会话保留。

文件

.claude-plugin/plugin.json  名字、版本、类型契约的位置
hooks/hooks.json            模块清单
hooks/register.tsx          挂载、/moon、读语料、每 20 秒刷新一次;「详解」按钮与面板
hooks/moon.ts               相时刻表、插值、八相命名、月龄、语料解析与选句、出处拆分(纯函数)
hooks/dynasty.ts            作者 → 朝代表(按出现频率挑的前 100 位)
hooks/about.ts              详解:prompt、模型输出解析、缓存键、淘汰(纯函数)
data/poems.txt              语料本体(46167 行)
data/NOTICE.md              语料来源、许可、转简说明、4 MiB 上限
types/index.d.ts            $.state 里开关与面板的类型契约
tests/moon.test.tsx         23 条:表是不是严格四相轮转、插值是否落在发布时刻上、月龄是否等于距新月的真实天数、
                            表外是否承认自己在估、一个周期是否正好走遍且不重、下一周期换顺序、
                            语料解析(缺一半/重复行要丢)、真的从语料里取句画出来、
                            不吞下面那行、/moon 能收起放回
tests/about.test.tsx        19 条:模型输出解析(围栏/前后废话/缺字段/非 JSON)、
                            朝代表(高频的认得、宋人不会当唐人、不知道就 null)、
                            缓存键与淘汰、出处拆分
Source 5 files
hooks/register.tsx 341 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, Timer } from 'claude-code'
3
4import { ABOUT_LIMIT, aboutEvictionsOf, aboutKeyOf, aboutParse, aboutPromptOf, describeReply } from './about'
5import type { PoemAbout } from './about'
6import { dynastyOf } from './dynasty'
7import { lineOf, poemAt, poemsOf, POEMS, sourceParts } from './moon'
8import type { Poem } from './moon'
9
10// moon-band: the moon's phase and a line of poetry as one dim row above the
11// prompt. Nothing here is load-bearing — it is decoration, and `/moon` takes it
12// away for a while when a screen of prose is wanted instead.
13//
14// 除了装饰,现在还有两件事:
15//   1. **朝代**:那一行末尾补一个「唐」「宋」这样的字。语料没有朝代字段,靠
16//      ./dynasty 里那张按出现频率挑出来的作者表;表外不显示,不猜。
17//   2. **详解按钮**:点一下给出这句诗的意思与创作背景。答案按**诗句**存进插件的
18//      store,同一句第二次点开直接读缓存,不再问模型。
19//
20// It wraps what `next(e)` resolved to rather than drawing the row itself, so
21// whatever else draws at this spot (the context meter, the balance meter) is
22// kept underneath it.
23
24/**
25 * Twenty seconds against a one-minute slot: the line turns over within twenty
26 * seconds of the minute rather than up to a minute late. A redraw is cheap and
27 * the engine folds sooner ones.
28 */
29const REFRESH_MS = 20 * 1000
30const HIDDEN_KEY = 'isHidden'
31const CORPUS_PATH = 'data/poems.txt'
32
33const isHidden = atom({ plugin: 'moon-band', key: 'isHidden' } as const, false)
34
35/** 详解面板。只对「当前这一句」有效——换句之后 render 那边就不会画它了。 */
36type Panel = { line: string; busy: boolean; about: PoemAbout | null }
37
38const panel = atom({ plugin: 'moon-band', key: 'panel' } as const, null as Panel | null)
39
40/** Runs `work`, and answers null when it throws. */
41const quietly = async <T,>(work: () => Promise<T>): Promise<T | null> => {
42  try {
43    return await work()
44  } catch {
45    return null
46  }
47}
48
49let corpus: Poem[] | null = null
50
51/**
52 * The corpus the mod ships, read once. It is the whole point of the thing, so a
53 * read that fails — or comes back with less than the built-ins would have given —
54 * says so out loud and falls back: a quietly smaller corpus would look exactly
55 * like a working one.
56 */
57const loadCorpus = async ($: EngineInterface): Promise<Poem[]> => {
58  if (corpus !== null) return corpus
59
60  const text = await quietly(() => $.fs.read(`${$.plugin.root}/${CORPUS_PATH}`))
61  const read = text === null ? [] : poemsOf(text)
62
63  if (read.length > POEMS.length) {
64    corpus = read
65
66    return corpus
67  }
68
69  try {
70    $.ui.toast(`moon-band: ${CORPUS_PATH} 没读到,先用内置 8 句`)
71  } catch {
72    // the toast is a courtesy; the fallback still holds
73  }
74
75  return POEMS
76}
77
78/** 这一句已经问过模型了吗。 */
79const cachedAboutOf = async ($: EngineInterface, line: string): Promise<PoemAbout | null> => {
80  const raw = await quietly(() => $.store.get(aboutKeyOf(line)))
81
82  if (raw === null || typeof raw !== 'object') return null
83
84  const about = raw as PoemAbout
85
86  return typeof about.meaning === 'string' && typeof about.background === 'string' ? about : null
87}
88
89/**
90 * 记进缓存,并把超出上限的旧条目清掉。
91 *
92 * store 一共 4 MiB、一条详解约 300 字节,留 300 条既够用又离上限很远。
93 * `keys()` 是插入顺序,所以最早的先走。
94 */
95const remember = async ($: EngineInterface, line: string, about: PoemAbout): Promise<void> => {
96  await quietly(() => $.store.set(aboutKeyOf(line), about))
97
98  const keys = (await quietly(() => $.store.keys())) ?? []
99
100  for (const key of aboutEvictionsOf(keys, ABOUT_LIMIT)) {
101    await quietly(() => $.store.delete(key))
102  }
103}
104
105/** 让那一行重画一次。 */
106const redraw = ($: EngineInterface): void => {
107  try {
108    $.ui.invalidate('ui.render')
109  } catch {
110    // the next redraw takes it
111  }
112}
113
114/**
115 * 缓存优先;没有才问一次模型,问到了就写进缓存。
116 *
117 * 按钮和 `/poem` 走同一条路,所以 `/poem` 问过一次之后,按钮就变成"直接看"了。
118 * 失败(模型没答、答得不合用)一律抛,由调用方决定怎么呈现。
119 */
120const ensureAbout = async ($: EngineInterface, poem: Poem): Promise<PoemAbout> => {
121  const cached = await cachedAboutOf($, poem.line)
122
123  if (cached !== null) return cached
124
125  const { system, prompt } = aboutPromptOf(poem.line, poem.from)
126  const ask = async (model: string): Promise<unknown> => $.model.complete({ model, prompt, system, maxTokens: 700 })
127
128  let reply: unknown
129  let about: PoemAbout | null = null
130
131  try {
132    // `haiku` 是引擎的小号模型别名,解析成本会话配置的那个(这里是 DeepSeek-flash)
133    // ——不用自己碰 key,也不用管 base URL。
134    reply = await ask('haiku')
135    about = aboutParse(reply, Date.now())
136  } catch (error) {
137    reply = error instanceof Error ? `throw: ${error.message}` : undefined
138  }
139
140  // 小号模型没给出能用的东西(没答、答得不是 JSON、或者压根不是文本)时,
141  // 换成会话自己的模型再问一次——比直接报错强。
142  if (about === null) {
143    const sessionModel = await quietly(() => $.session.model())
144
145    if (sessionModel !== null && sessionModel !== '' && sessionModel !== 'haiku') {
146      try {
147        reply = await ask(sessionModel)
148        about = aboutParse(reply, Date.now())
149      } catch (error) {
150        reply = error instanceof Error ? `throw: ${error.message}` : reply
151      }
152    }
153  }
154
155  if (about === null) throw new Error(`模型没有给出可用的解读(收到 ${describeReply(reply)})`)
156
157  await remember($, poem.line, about)
158
159  return about
160}
161
162/** 详情面板要画的那三行。 */
163const aboutTextOf = (about: PoemAbout): string => {
164  const head = [about.dynasty, about.year].filter(Boolean).join(' · ')
165
166  return [head, `诗意:${about.meaning}`, `背景:${about.background}`].filter((one) => one !== '').join('\n')
167}
168
169/**
170 * 按钮按下:已展开就收起;缓存里有就直接显示;都没有才问一次模型。
171 *
172 * 全程只改 `panel` 这个 atom —— 画不画、画什么由 render 那边看着 `panel` 和
173 * 「当前是哪一句」决定,所以换句之后旧面板不会赖着不走。
174 */
175const explain = async ($: EngineInterface): Promise<void> => {
176  const lines = await loadCorpus($)
177  const nowMs = (await quietly(() => $.clock.now())) ?? Date.now()
178  const poem = poemAt(nowMs, lines)
179  const current = await read($, panel)
180
181  // 同一句已经展开着 → 收起
182  if (current !== null && current.line === poem.line && current.about !== null) {
183    await update($, panel, () => null)
184    redraw($)
185
186    return
187  }
188
189  const cached = await cachedAboutOf($, poem.line)
190
191  if (cached !== null) {
192    await update($, panel, () => ({ line: poem.line, busy: false, about: cached }))
193    redraw($)
194
195    return
196  }
197
198  await update($, panel, () => ({ line: poem.line, busy: true, about: null }))
199  redraw($)
200
201  try {
202    const about = await ensureAbout($, poem)
203
204    await update($, panel, () => ({ line: poem.line, busy: false, about }))
205  } catch (error) {
206    await update($, panel, () => null)
207
208    try {
209      $.ui.toast(`moon-band: 详解失败 — ${error instanceof Error ? error.message : String(error)}`)
210    } catch {
211      // toast 只是通知,失败也不影响下一拍
212    }
213  } finally {
214    redraw($)
215  }
216}
217
218export const register: Register = on => {
219  let tick: Timer | null = null
220
221  on('session.start', async ($, e, next) => {
222    const result = await next(e)
223
224    await quietly(() => $.command.register({ name: 'moon', description: 'Hide or show the moon line (moon-band)' }))
225    // 按钮要靠热键/焦点才按得动;`/poem` 是那条永远走得通的路
226    await quietly(() =>
227      $.command.register({ name: 'poem', description: '详解这一句:意思与创作背景(moon-band,答案会缓存)' }),
228    )
229    await loadCorpus($)
230
231    const wasHidden = await quietly(() => $.store.get(HIDDEN_KEY))
232
233    if (wasHidden === true) await update($, isHidden, () => true)
234
235    if (tick === null) {
236      try {
237        // keeps a long session's moon and line from going stale
238        tick = $.clock.every(REFRESH_MS, () => {
239          try {
240            $.ui.invalidate('ui.render')
241          } catch {
242            // the next redraw takes it
243          }
244        })
245      } catch {
246        // without the tick the line still redraws on every turn
247      }
248    }
249
250    return result
251  })
252
253  on('command.run', { command: 'moon' }, async ($, e, next) => {
254    const wasHidden = await read($, isHidden)
255
256    await update($, isHidden, () => !wasHidden)
257    await quietly(() => $.store.set(HIDDEN_KEY, !wasHidden))
258
259    return { text: wasHidden ? 'moon line shown' : 'moon line hidden' }
260  })
261
262  // `/poem`:不依赖鼠标、不依赖焦点,直接把这一句的详解当命令输出吐出来。
263  // 顺带把缓存暖上,之后按钮就是"直接看"。
264  on('command.run', { command: 'poem' }, async $ => {
265    const lines = await loadCorpus($)
266    const nowMs = (await quietly(() => $.clock.now())) ?? Date.now()
267    const poem = poemAt(nowMs, lines)
268
269    try {
270      const about = await ensureAbout($, poem)
271
272      redraw($)
273
274      return { text: aboutTextOf(about) }
275    } catch (error) {
276      // 引擎自己会加上 "moon-band:" 前缀,这里别再重复一遍
277      return { text: `详解失败 — ${error instanceof Error ? error.message : String(error)}` }
278    }
279  })
280
281  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
282    if (e.props.hasSurvey) return next(e)
283    if (await read($, isHidden)) return next(e)
284
285    const { Box, Text, Button } = $.ui.resolve(e)
286    const nowMs = (await quietly(() => $.clock.now())) ?? Date.now()
287    const lines = await loadCorpus($)
288    const poem = poemAt(nowMs, lines)
289    const { author } = sourceParts(poem.from)
290    const cached = await cachedAboutOf($, poem.line)
291    // 缓存里的朝代优先:表里没有的作者,问过一次之后就知道了
292    const dynasty = cached?.dynasty ?? dynastyOf(author)
293    const shown = await read($, panel)
294    // 只画「当前这一句」的面板:换句之后旧的自然消失
295    const here = shown !== null && shown.line === poem.line ? shown : null
296    const about = here?.about ?? null
297    const inner = await next(e)
298
299    const label = here?.busy === true ? '生成中…' : about !== null ? '收起' : cached !== null ? '详解(已缓存)' : '详解'
300
301    return (
302      <Box flexDirection="column">
303        {inner}
304        <Box flexDirection="row" flexShrink={0}>
305          <Text dimColor wrap="truncate-end">
306            {lineOf(nowMs, lines)}
307          </Text>
308          {dynasty === null ? null : <Text dimColor>{`  ${dynasty}  `}</Text>}
309          {/* 热键:`AbovePrompt` 这一带被聚焦后(ctrl+x tab,或点一下)按 1 即触发;
310              输入框空着时直接按 1 也行。不给热键的话,这个按钮在有鼠标上报的终端里
311              才点得动,而多数终端并没有。 */}
312          <Button
313            label={label}
314            plain
315            hotkey="1"
316            dimColor
317            onPress={() => {
318              void explain($)
319            }}
320          />
321        </Box>
322        {about === null ? null : (
323          <Box flexDirection="column">
324            {about.dynasty === null && about.year === null ? null : (
325              <Text dimColor wrap="truncate-end">
326                {[about.dynasty, about.year].filter(Boolean).join(' · ')}
327              </Text>
328            )}
329            <Text dimColor wrap="truncate-end">
330              {`诗意:${about.meaning}`}
331            </Text>
332            <Text dimColor wrap="truncate-end">
333              {`背景:${about.background}`}
334            </Text>
335          </Box>
336        )}
337      </Box>
338    )
339  })
340}
341
hooks/about.ts 166 lines
1// 一首诗的「详解」:问一次模型,把答案存进插件的 store,下次遇到同一句直接读。
2//
3// 为什么存在 store 而不是内存:`/plugin` 重装、重启、换会话之后那句诗还会再出现,
4// 那时候不该再花一次模型调用。store 有 **4 MiB 总上限**,所以带一个上限淘汰
5// (见 `ABOUT_LIMIT` 与 `remember`)。
6//
7// 这里只有纯函数:拼 prompt、解析模型输出、排版。真正调用模型的是 register.tsx。
8
9/** 一首诗的详解。 */
10export type PoemAbout = {
11  /** 朝代,如 `唐`;模型拿不准时可为 null。 */
12  dynasty: string | null
13  /** 年份或年代,如 `约 725 年(开元十三年)`。 */
14  year: string | null
15  /** 这一句(这几句)的意思。 */
16  meaning: string
17  /** 作者写这首诗时的处境与缘由。 */
18  background: string
19  /** 写入时间(毫秒)。 */
20  atMs: number
21}
22
23/** store 里每条详解的键前缀。 */
24export const ABOUT_PREFIX = 'about:'
25
26/** store 里保存插入顺序的那个键,用来做过期淘汰。 */
27export const ABOUT_INDEX_KEY = 'aboutIndex'
28
29/** 最多留多少条。按每条 ~300 字节算,300 条约 90 KB,离 4 MiB 很远。 */
30export const ABOUT_LIMIT = 300
31
32/** 一句诗在 store 里的键。 */
33export const aboutKeyOf = (line: string): string => `${ABOUT_PREFIX}${line.trim()}`
34
35/**
36 * 给模型的指令与那句话。
37 *
38 * 好处是它同时钉住了两件事:要**纯 JSON**、以及**不确定就给 null 别编年份**。
39 */
40export const aboutPromptOf = (line: string, from: string): { system: string; prompt: string } => ({
41  system: [
42    '你是一位中国古典诗词学者。针对用户给出的一句诗(可能出自长篇),写简明的解读。',
43    '只输出一个 JSON 对象,不要 Markdown、不要代码围栏、不要多余解释。',
44    '字段:',
45    '  "dynasty": 朝代名,如 "唐"、"宋";确定不了就给 null。',
46    '  "year": 创作年份或年代,尽量具体(如 "约 725 年(开元十三年)");确定不了就给 null。',
47    '  "meaning": 这一句(这几句)在说什么,2–3 句白话。',
48    '  "background": 作者在什么处境下写的这首诗、想表达什么,2–4 句白话。',
49    '不要编造精确年份:宁可给 null 或"约",也不要瞎猜。',
50  ].join('\n'),
51  prompt: `诗句:${line}\n出处:${from}`,
52})
53
54/**
55 * 从模型回复里取出正文。
56 *
57 * 类型上 `$.model.complete` 答应回 `string`,但实测回来过非字符串(于是
58 * `text.trim()` 直接炸)。所以这里把几种可能的形状都认了:
59 * 裸字符串、`{ text }`、`{ content: [{ type:'text', text }] }`。
60 */
61export const replyTextOf = (value: unknown): string => {
62  if (typeof value === 'string') return value
63
64  if (value !== null && typeof value === 'object') {
65    const any = value as any
66
67    if (typeof any.text === 'string') return any.text
68
69    if (Array.isArray(any.content)) {
70      return any.content
71        .map((block: any) => (typeof block?.text === 'string' ? block.text : ''))
72        .join('')
73    }
74  }
75
76  return ''
77}
78
79/** 给报错用的简短描述:收到了什么,而不是只说"失败了"。 */
80export const describeReply = (value: unknown): string => {
81  if (value === undefined) return 'undefined'
82  if (value === null) return 'null'
83
84  const kind = typeof value
85
86  if (kind !== 'object') return `${kind}: ${String(value).slice(0, 60)}`
87
88  try {
89    return `${kind}: ${JSON.stringify(value).slice(0, 120)}`
90  } catch {
91    return kind
92  }
93}
94
95/**
96 * 把模型输出解析成 `PoemAbout`;解析不了返回 null(这次就不写缓存)。
97 *
98 * 模型偶尔会套 ```json 围栏,或者在前后加一句话,所以先剥再取第一个 `{` 到最后一个 `}`。
99 */
100export const aboutParse = (raw: unknown, atMs: number): PoemAbout | null => {
101  const trimmed = replyTextOf(raw)
102    .trim()
103    .replace(/^```(?:json)?\s*/i, '')
104    .replace(/```$/, '')
105    .trim()
106  const start = trimmed.indexOf('{')
107  const end = trimmed.lastIndexOf('}')
108
109  if (start < 0 || end <= start) return null
110
111  let parsed: any
112
113  try {
114    parsed = JSON.parse(trimmed.slice(start, end + 1))
115  } catch {
116    return null
117  }
118
119  const str = (value: unknown): string | null =>
120    typeof value === 'string' && value.trim() !== '' && value.trim() !== 'null' ? value.trim() : null
121
122  const meaning = str(parsed?.meaning)
123  const background = str(parsed?.background)
124
125  // 两个正文都没有,就当这次生成失败(不要把空壳写进缓存)
126  if (meaning === null && background === null) return null
127
128  return {
129    dynasty: str(parsed?.dynasty),
130    year: str(parsed?.year),
131    meaning: meaning ?? '(模型没有给出释义)',
132    background: background ?? '(模型没有给出背景)',
133    atMs,
134  }
135}
136
137/** 详情面板要画的那几行(不含前缀装饰,交给调用方)。 */
138export const aboutLinesOf = (about: PoemAbout): string[] => {
139  const head = [about.dynasty, about.year].filter(Boolean).join(' · ')
140
141  return [
142    ...(head === '' ? [] : [head]),
143    `诗意:${about.meaning}`,
144    `背景:${about.background}`,
145  ]
146}
147
148/** 一句话概括,给不允许换行的地方用。 */
149export const aboutOneLineOf = (about: PoemAbout): string =>
150  `诗意:${about.meaning} 背景:${about.background}`.replace(/\s+/g, ' ')
151
152/**
153 * 淘汰:把插入顺序里最早的那些从 keys 里算出来,返回还需要删掉的键。
154 *
155 * 纯函数,方便测。`keys` 是 store 的 `keys()` 结果(插入顺序)。
156 * @param keys - 全部键。
157 * @param limit - 最多留几条。
158 * @returns 该删掉的 `about:*` 键,按最早优先。
159 */
160export const aboutEvictionsOf = (keys: readonly string[], limit = ABOUT_LIMIT): string[] => {
161  const aboutKeys = keys.filter((key) => key.startsWith(ABOUT_PREFIX))
162  const excess = aboutKeys.length - limit
163
164  return excess <= 0 ? [] : aboutKeys.slice(0, excess)
165}
166
hooks/dynasty.ts 99 lines
1/**
2 * 作者 → 朝代。
3 *
4 * 语料(`data/poems.txt`,46167 句、2461 位作者)里**没有朝代字段**,所以只能靠表。
5 *
6 * 覆盖策略是「按出现频率」而不是「按名气」:诗句是从全语料里均匀抽的,所以一个
7 * 作者贡献的行数就是他被抽到的概率。下面这两张表是出现次数前 100 的作者(合计
8 * 29,690 句,占 64%),其余 36% 落在更冷门的作者身上——那些不显示朝代(不猜),
9 * 等用户点一次「详解」,AI 会把朝代一起补出来并写进缓存,之后就知道了。
10 */
11
12/** 唐代(含五代前的唐人)。 */
13const TANG = `白居易 杜甫 元稹 刘禹锡 李商隐 陆龟蒙 王建 钱起 杜牧 姚合 孟郊 许浑 罗隐 张籍 皮日休 韩愈 贾岛 司空图
14权德舆 张祜 方干 卢纶 温庭筠 薛能 戴叔伦 李群玉 李贺 李端 赵嘏 高适 顾况 皇甫冉 张九龄 李峤 李频 施肩吾 鲍溶
15武元衡 李咸用 宋之问 柳宗元 朱庆余 司空曙 耿𣲗 马戴 张乔 李益 胡曾 韩翃 曹唐 许棠 杨巨源 罗邺 李白 李绅
16李德裕 刘得仁 李嘉祐 雍陶 戎昱 刘商 李涉 王维 张若虚 崔颢 祖咏 裴迪 储光羲 常建 刘长卿 韦应物
17秦韬玉 于武陵 崔涂 崔珏 沈佺期 杜审言 苏味道 王勃 杨炯 卢照邻 骆宾王 陈子昂 张说 贺知章 王之涣
18王翰 王湾 崔护 韩偓 吴融 唐彦谦 郑谷 李中 孟贯 处默 齐己 皎然 贯休 寒山 拾得 灵澈 清江 法照 无可`
19
20/** 宋代。 */
21const SONG = `辛弃疾 苏轼 赵长卿 吴文英 刘辰翁 晏几道 贺铸 张炎 欧阳修 刘克庄 张孝祥 李曾伯 吴潜 韩淲 朱敦儒
22柳永 魏了翁 陈允平 张元干 曹勋 毛滂 向子諲 周邦彦 王之道 史浩 蔡伸 周紫芝 晁补之 张先 杨无咎 赵师侠 晁端礼
23洪适 程垓 晏殊 李清照 陆游 王安石 黄庭坚 秦观 范成大 杨万里 姜夔 文天祥 岳飞 叶梦得 陈与义 朱淑真
24司马光 邵雍 王观 李之仪 李重元 陈亮 刘过 高观国 卢祖皋 史达祖 蒋捷 王沂孙 周密 张辑`
25
26/** 其余朝代的零散作者。 */
27const EXTRA: Record<string, string> = {
28  纳兰性德: '清',
29  袁枚: '清',
30  龚自珍: '清',
31  郑燮: '清',
32  赵翼: '清',
33  曹雪芹: '清',
34  唐寅: '明',
35  杨慎: '明',
36  于谦: '明',
37  戚继光: '明',
38  高启: '明',
39  刘基: '明',
40  马致远: '元',
41  关汉卿: '元',
42  白朴: '元',
43  张养浩: '元',
44  王冕: '元',
45  赵孟頫: '元',
46  陶渊明: '晋',
47  谢灵运: '南朝宋',
48  谢朓: '南朝齐',
49  曹操: '汉',
50  曹丕: '魏',
51  曹植: '魏',
52  王粲: '汉',
53  蔡琰: '汉',
54  卓文君: '汉',
55  项羽: '秦末',
56  荆轲: '战国',
57  屈原: '战国',
58  宋玉: '战国',
59  李煜: '南唐',
60  韦庄: '五代前蜀',
61}
62
63const pairs = (text: string, dynasty: string): [string, string][] =>
64  text
65    .split(/\s+/)
66    .map((name) => name.trim())
67    .filter((name) => name !== '')
68    .map((name) => [name, dynasty] as [string, string])
69
70const MAP = new Map<string, string>([...pairs(TANG, '唐'), ...pairs(SONG, '宋'), ...Object.entries(EXTRA)])
71
72/**
73 * 作者的朝代;表里没有就返回 `null`(调用方自己决定显示什么)。
74 * @param author - 作者名,如 `李白`。
75 */
76export const dynastyOf = (author: string | null | undefined): string | null => {
77  if (author === null || author === undefined) return null
78
79  const name = author.trim()
80
81  if (name === '') return null
82  // 这两个不是人名,说他们的朝代没有意义
83  if (name === '无名氏' || name === '不详') return null
84
85  const hit = MAP.get(name)
86
87  if (hit !== undefined) return hit
88
89  // 太宗皇帝 / 玄宗皇帝 这类:唐代帝王
90  if (/^.+皇帝$/.test(name) && /^(太宗|高宗|中宗|睿宗|玄宗|肃宗|代宗|德宗|顺宗|宪宗|穆宗|敬宗|文宗|武宗|宣宗|懿宗|僖宗|昭宗|哀帝|则天)/.test(name)) {
91    return '唐'
92  }
93
94  return null
95}
96
97/** 表里覆盖了多少个名字(给测试和文档用)。 */
98export const dynastyTableSize = (): number => MAP.size
99
hooks/moon.ts 264 lines
1// The moon and the poem, with no engine calls in them, so a test can hold them
2// to account without a session.
3//
4// The phase name is read off a table of published phase instants rather than
5// from a mean-synodic-month formula, because that formula is not good enough to
6// say a phase name: checked against October 2026's four instants it is out by up
7// to 0.72 days, and no two-parameter fit does better than 0.75 — the Moon's
8// motion is genuinely uneven.
9//
10// The age is not `fraction × mean month` either: it is the days since the last
11// new moon the table knows, which is the number anyone can check against a
12// lunar-calendar date.
13
14/**
15 * The phases, Beijing time (UTC+8), from StarWalk's phase calendar and the Hong
16 * Kong Astronomical Society's 2026 table, which agree to a minute.
17 *
18 * **A strict quarter cycle**: consecutive entries are one quarter apart and the
19 * gaps are 6.7–8.2 days (measured, and a test holds the table to that). Never
20 * add an instant without its neighbours, and never reorder: the interpolation
21 * reads these as evenly spaced quarters, not as dates, and the new moons are
22 * found by counting every fourth entry from the first.
23 */
24const INSTANTS = [
25  1791033900000, // 2026-10-03 21:25 下弦
26  1791647400000, // 2026-10-10 23:50 新月(农历九月初一)
27  1792339920000, // 2026-10-19 00:12 上弦
28  1792987860000, // 2026-10-26 12:11 满月(猎人月)
29  1793564880000, // 2026-11-02 04:28 下弦
30  1794207720000, // 2026-11-09 15:02 新月
31  1794916080000, // 2026-11-17 19:48 上弦
32  1795531980000, // 2026-11-24 22:53 满月(超级海狸月)
33  1796134080000, // 2026-12-01 22:08 下弦
34  1796777520000, // 2026-12-09 08:52 新月
35  1797486180000, // 2026-12-17 13:43 上弦
36  1798075680000, // 2026-12-24 09:28 满月(2026 最后一次超级月亮)
37  1798657140000, // 2026-12-31 02:59 下弦
38]
39
40/** The phase the table starts on: a last quarter, which is 0.75 of the cycle. */
41const FIRST_PHASE = 0.75
42
43/** How long a quarter of the cycle takes on average: the fallback's step. */
44const QUARTER_MS = (29.530588853 / 4) * 86_400_000
45
46const MEAN_MONTH_DAYS = 29.530588853
47const DAY_MS = 86_400_000
48
49/** How long the line stays: a minute, as asked. */
50export const POEM_SLOT_MS = 60_000
51
52export type Moon = {
53  /** Where in the cycle: 0 the new moon, 0.5 the full moon, 1 the next new moon. */
54  fraction: number
55  /** Days since the last new moon — the number a lunar calendar would give. */
56  ageDays: number
57  /** The phase in Chinese. */
58  name: string
59  /** One emoji for the phase; the eight are the whole cycle in order. */
60  glyph: string
61  /** True when the phase is a mean-month estimate: outside the table. */
62  isEstimated: boolean
63}
64
65const NAMES = ['新月', '娥眉月', '上弦月', '盈凸月', '满月', '亏凸月', '下弦月', '残月']
66const GLYPHS = ['🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘']
67
68/** The last new moon the table knows at or before this instant, or null. */
69const newMoonBefore = (nowMs: number): number | null => {
70  let found: number | null = null
71
72  // new moons are every fourth entry, the table opening on a last quarter
73  for (let i = 1; i < INSTANTS.length; i += 4) {
74    if (INSTANTS[i] <= nowMs) found = INSTANTS[i]
75  }
76
77  return found
78}
79
80/** The phase at an instant inside the table, or an estimate outside it. */
81export const moonAt = (nowMs: number): Moon => {
82  const first = INSTANTS[0]
83  const last = INSTANTS[INSTANTS.length - 1]
84
85  let fraction: number
86  let isEstimated = false
87
88  if (nowMs < first) {
89    fraction = FIRST_PHASE - (first - nowMs) / QUARTER_MS / 4
90    isEstimated = true
91  } else if (nowMs > last) {
92    fraction = FIRST_PHASE + (INSTANTS.length - 1) / 4 + (nowMs - last) / QUARTER_MS / 4
93    isEstimated = true
94  } else {
95    let i = 0
96
97    // stop one short: the instant *after* the last pair is the pair's own end,
98    // and asking for it would read past the table
99    while (i < INSTANTS.length - 2 && INSTANTS[i + 1] <= nowMs) i += 1
100
101    const span = INSTANTS[i + 1] - INSTANTS[i]
102    const through = (nowMs - INSTANTS[i]) / span
103
104    fraction = FIRST_PHASE + (i + through) / 4
105  }
106
107  const wrapped = ((fraction % 1) + 1) % 1
108  // the nearest of the eight names; `min` keeps the last band from rounding up
109  // past `残月` into the new moon
110  const octant = Math.min(7, Math.floor(wrapped * 8 + 0.5))
111
112  // Days since the last new moon. The age is the elapsed time, not a share of a
113  // mean month: this lunation runs long, and sharing a mean month understates it
114  // by a third of a day. Past the last new moon the table holds the next one
115  // arrives within a month, so an age older than that is counting on a new moon
116  // nobody told this table about.
117  const newMoon = newMoonBefore(nowMs)
118  const sinceNewMoon = newMoon === null ? null : (nowMs - newMoon) / DAY_MS
119  const isAgeTrue = sinceNewMoon !== null && sinceNewMoon < 30
120
121  return {
122    fraction: wrapped,
123    ageDays: isAgeTrue ? sinceNewMoon : wrapped * MEAN_MONTH_DAYS,
124    name: NAMES[octant],
125    glyph: GLYPHS[octant],
126    isEstimated,
127  }
128}
129
130/** One line and where it comes from. */
131export type Poem = { line: string; from: string }
132
133/**
134 * What the meter draws from until the corpus is read — and if it never is. Eight
135 * famous lines, each carrying its own source; several are one line of a longer
136 * poem, so the title is the poem's, not the line's.
137 */
138export const POEMS: Poem[] = [
139  { line: '今人不见古时月,今月曾经照古人。', from: '李白《把酒问月》' },
140  { line: '举杯邀明月,对影成三人。', from: '李白《月下独酌》' },
141  { line: '海上生明月,天涯共此时。', from: '张九龄《望月怀远》' },
142  { line: '江畔何人初见月?江月何年初照人?', from: '张若虚《春江花月夜》' },
143  { line: '举头望明月,低头思故乡。', from: '李白《静夜思》' },
144  { line: '深林人不知,明月来相照。', from: '王维《竹里馆》' },
145  { line: '人有悲欢离合,月有阴晴圆缺,此事古难全。', from: '苏轼《水调歌头》' },
146  { line: '嫦娥应悔偷灵药,碧海青天夜夜心。', from: '李商隐《嫦娥》' },
147]
148
149/**
150 * The corpus that ships with the mod: one `line<TAB>source` per line. A blank
151 * line, or one without both halves, is dropped rather than drawn as a puzzle.
152 * Duplicates go too — the same line twice would read as a repeat inside a cycle
153 * that promises none.
154 */
155export const poemsOf = (text: string): Poem[] => {
156  const seen = new Set<string>()
157  const poems: Poem[] = []
158
159  for (const raw of text.split('\n')) {
160    const [line, from] = raw.trim().split('\t')
161
162    if (!line || !from) continue
163    if (seen.has(line)) continue
164
165    seen.add(line)
166    poems.push({ line, from })
167  }
168
169  return poems
170}
171
172/** A small non-negative hash of an integer, for seeding a cycle. */
173const hashOf = (value: number): number => {
174  let x = Math.imul(value, 2654435761) >>> 0
175
176  x ^= x >>> 15
177  x = Math.imul(x, 2246822519) >>> 0
178  x ^= x >>> 13
179
180  // back to unsigned: `^` answers a signed 32-bit, and a negative here would
181  // index off the front of the list
182  return x >>> 0
183}
184
185const greatestCommonDivisor = (a: number, b: number): number => {
186  let x = a
187  let y = b
188
189  while (y !== 0) [x, y] = [y, x % y]
190
191  return x
192}
193
194/**
195 * A step that shares no factor with the corpus size, so that walking by it
196 * visits every index exactly once before coming back round. `1` is stepped over:
197 * a step of one is the corpus in file order, which is not a shuffle.
198 */
199const stepFor = (seed: number, count: number): number => {
200  let step = 1 + 2 * (hashOf(seed) % Math.floor(count / 2))
201
202  while (greatestCommonDivisor(step, count) !== 1 || step % count === 1) step += 2
203
204  return step
205}
206
207/**
208 * The index for a slot: **a full cycle of the whole corpus**, no line twice
209 * until every line has been drawn — a linear walk whose step and start are the
210 * only state it keeps.
211 *
212 * `step` is coprime with `count`, so `(step * i + offset) mod count` is a
213 * permutation: the first `count` slots cover every line once, in an order that
214 * looks shuffled. Each cycle re-seeds both, so the next round is a different
215 * order of the same corpus rather than the same round again.
216 */
217export const poemIndexAt = (slot: number, count: number): number => {
218  if (count <= 1) return 0
219
220  const cycle = Math.floor(slot / count)
221  const step = stepFor(cycle + 1, count)
222  const offset = hashOf(cycle) % count
223
224  return (step * ((slot % count) + offset)) % count
225}
226
227/**
228 * The line for this minute: the same one for the whole slot (a line that changed
229 * between frames would be unreadable), never the same as the slot before it
230 * inside a cycle, and one of the corpus's own orderings after that.
231 */
232export const poemAt = (nowMs: number, corpus: Poem[] = POEMS): Poem => {
233  const poems = corpus.length > 0 ? corpus : POEMS
234  const slot = Math.floor(nowMs / POEM_SLOT_MS)
235
236  return poems[poemIndexAt(slot, poems.length)]
237}
238
239/** The one line above the prompt. */
240export const lineOf = (nowMs: number, corpus: Poem[] = POEMS): string => {
241  const moon = moonAt(nowMs)
242  const poem = poemAt(nowMs, corpus)
243
244  return `${moon.isEstimated ? '≈' : ''}${moon.glyph} ${moon.name} ${moon.ageDays.toFixed(1)}天 · 「${poem.line}」${poem.from}`
245}
246
247/** The table, for the test that holds it to being a quarter cycle. */
248export const instantsOf = (): readonly number[] => INSTANTS
249
250/**
251 * `李白《把酒问月》` → `{ author: '李白', title: '把酒问月' }`;没有篇名时 title 为 null。
252 *
253 * 语料里出处一律是这个形状(作者 + 《篇名》),但「出处不详」这类没有书名号,
254 * 那就整串当作者——查朝代时至少还有名字可查。
255 */
256export const sourceParts = (from: string): { author: string; title: string | null } => {
257  const open = from.indexOf('《')
258  const close = from.lastIndexOf('》')
259
260  if (open <= 0 || close <= open) return { author: from.trim(), title: null }
261
262  return { author: from.slice(0, open).trim(), title: from.slice(open + 1, close).trim() }
263}
264
types/index.d.ts 21 lines
1declare module 'claude-code' {
2  interface PluginState {
3    'moon-band': {
4      /** Whether `/moon` has taken the line away. */
5      isHidden: boolean
6      /** 详解面板:只对当前这一句有效(`line` 是它的键)。 */
7      panel: {
8        line: string
9        busy: boolean
10        about: {
11          dynasty: string | null
12          year: string | null
13          meaning: string
14          background: string
15          atMs: number
16        } | null
17      } | null
18    }
19  }
20}
21