SLOPSHOPPER

hud

claude-hud 0.10.0 as a mod: model, project, git, context, usage, tools, agents and todos, plus alerts, budget, history, a task summary, a detail pane and…

panebandspinnerguardcommandtoast
★ 7v0.12.3MITupdated 2026-10-26hoobnn/hoobnn-agent-mods/claude-code/hud
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · hud
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /hud ⎿ hud: claude-hud band hidden ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts HUD ⟨Claude Code's own drawing⟩
README

hud

Claude Code 状态栏 HUD。

简体中文 · English

把 claude-hud 0.10.0 改成了 Claude Code mod:模型、项目、git、上下文、用量、正在跑的工具、子代理和待办,都集中在输入框旁边。可以放在输入框上方,也可以放在下方原来状态栏的位置。在 claude-hud 的基础上,还加了额度预警、用量耗尽预测、每日预算、一行任务摘要、详情面板,以及 12 套随时切换的主题。

hud:neon 主题

功能

  • claude-hud 原有的信息都在:模型和推理强度、项目和 git 分支及改动、上下文和用量进度条、正在跑的工具、子代理和待办。
  • 提前预警:上下文或额度到你设定的百分比时弹提示;按当前速度估算额度何时用完(5 小时额度按最近一小时的速度算);Fable 这类按模型单独计的周额度也显示出来,同样预警和预测;距自动压缩还剩多少 token;提示缓存过期后,提醒下一条消息要重新写入多少 token;某一轮让上下文涨得特别多时,显示涨了多少和最近几轮的迷你柱状图(如 上一轮 +98k ▂▁█),一眼看出是哪一轮把上下文撑大的;未提交的改动或未推送的提交太多时提醒。
  • 花费:今天的花费对比每日预算,近 7 天花费的迷你折线图。
  • 一行任务摘要,以及 /hud detail 详情面板:每个工具的调用次数和耗时、最近几轮的用时、花费和上下文增长、子代理、待办、今天和本周的花费。
  • 12 套主题:科技霓虹、彩虹渐变、emoji、带颜文字看板娘的动漫风(樱花、猫咪、机甲、热血)、Tokyo Night、黑客帝国、Nerd Font 和 powerline。
  • 长任务结束提醒(macOS 可加提示音),以及远程控制的连接状态。

安装

claude plugin marketplace add hoobnn/hoobnn-agent-mods
claude plugin install hud@hoobnn-agent-mods

它读取 claude-hud 自己的配置文件(~/.claude/plugins/claude-hud/config.json 和 ~/.claude/claude-hud.json),已有的 claude-hud 设置可以直接沿用,/claude-hud:configure 也照常可用。

主题

用 /hud theme <名字> 立即切换;只输入 /hud theme 会弹窗选择(列出接下来的四套,其他主题可在 Other 里输入;关掉弹窗或在 -p 模式下,会列出全部主题和示例);/hud theme next 换下一套,/hud theme reset 回到 classic。选择会写回 /config 的 theme 选项,以后的会话也会沿用。

主题风格
classicclaude-hud 原样
neon赛博朋克:霓虹真彩色,⬢ ◆ ◈ ⚡,▰▱ 进度条, ❯ 分隔
rainbow每个元素一种颜色,进度条和模型名是彩虹渐变
emoji🤖 📂 🌿 🧠 ⚡ 📅 ⏳ ✅
sakura樱花粉,🌸 🎀 🍡 💗,✿ 进度条,颜文字看板娘 (◕‿◕)♡
kawaii马卡龙色,「Opus」,●○ 进度条,猫咪看板娘 ฅ^•ω•^ฅ
mecha紫、绿、橙,UNIT·Opus◤,SYNC / PWR 仪表,机器人看板娘 [•_•]
shonen红橙金,🔥 ⭐ 🍥 💥,渐变进度条,热血看板娘 (ง •̀_•́)ง
tokyo-nightTokyo Night 配色,图标克制
matrix黑底绿字,▮▯ 进度条, ┊ 分隔
nerdNerd Font 图标(需要 Nerd Font)
powerlineNerd Font 图标加 powerline 色块(需要 Nerd Font)

同一个示例会话在 12 套主题下的样子:assets/themes/gallery.png;每套主题的单图在 assets/themes/<主题>.png。

动漫风主题的看板娘会跟着状态变脸:平时很淡定,跑工具时忙碌,上下文到 70%(或额度到 90%)开始担心,85% 慌张,用量耗尽时直接晕倒。showMascot 可以关掉它。

  • 配色:主题的颜色覆盖在 claude-hud 的 colors 之上;在 claude-hud 自己的配置里改过(不是默认值)的颜色保持不变。
  • 宽度:图标由 claude-hud 绘制,换行时会计入它们的宽度;分隔符都不宽于 │ ;powerline 每行多占 2 列,从 claude-hud 和附加行可用的列数里扣除。emoji 只用默认即显示为 emoji 的字符(不带 U+FE0F)。
  • 已知限制:claude-hud 靠开头的 [ 把 [模型 | 提供方] 标记(Bedrock、Vertex)保持在一行;去掉方括号的主题失去这个保护,终端较窄时这类标记可能在 | 处折行。

命令

  • /hud:显示或隐藏 HUD;/hud off、/hud on 直接设定(输入框底栏的 「HUD」按钮也一样)。
  • /hud theme [名字|next|reset]:切换主题。
  • /hud detail:打开或关闭详情面板。Claude 工作时也能用。

选项

在 /config 里修改,或写在 ~/.claude/settings.json 的 pluginConfigs 里:

选项作用默认
visible显示 HUD开
footerButton在输入框底栏显示 「HUD」开关按钮开
positionabove 放在输入框上方,below 放在下方原状态栏的位置(Claude Desktop 没有这个位置,那里总在输入框上方)above
theme主题classic
showMascot动漫风主题显示颜文字看板娘开
contextAlerts上下文到这些百分比时提醒,逗号分隔,如 80,90;留空关闭空
usageAlerts5 小时或 7 天额度到这些百分比时提醒;留空关闭空
showForecast按当前速度会在重置前用完时,显示预计用完的时间开
compactWarnPercent上下文到达自动压缩阈值的这个百分比后,显示还剩多少 token;0 关闭60
coldCacheTokens提示缓存过期后,上下文至少有这么多 token 时,提醒下一条消息要重新写入多少;0 关闭20000
turnGrowthTokens一轮让上下文涨了至少这么多 token 时,显示涨幅和最近几轮的迷你柱状图;0 关闭20000
dailyBudgetUsd每日预算(美元),显示今天的花费对比;0 关闭0
showHistory显示近 7 天花费折线和连续使用天数关
summaryEveryTurns第一轮后和每隔几轮生成一行任务摘要(复用提示词缓存);0 关闭5
notifyAfterSeconds一轮跑了这么多秒以上才在结束时提醒(toast 加系统通知);0 关闭0
notifySound结束提醒带提示音(macOS)开
gitDirtyWarn未提交的改动达到这么多个路径时提醒;0 关闭20
gitAheadWarn未推送的提交达到这么多个时提醒;0 关闭5
showAgents显示 claude-hud 的子代理行(Claude Code 自己已经会列出,默认关)关
extraCmdclaude-hud 的 --extra-cmd:一条 shell 命令,输出作为一个标签(需要 CLAUDE_HUD_ALLOW_EXTRA_CMD=1)空
debug注册 mcp__hud__hud_debug 调试工具关

语言跟随 claude-hud 配置文件里的 language(en、zh-Hans、zh-Hant、ja、ko、es、fr、de、pt-BR、ru),mod 新加的预警、面板、/hud 回复和任务摘要也一起跟随。

同系列 mod

hoobnn-agent-mods 里还有任务进度条(todo-bar)、回合回执(receipt)、运行动画和宠物(spinner)、Tailscale 节点状态(ts-band)和一言(hitokoto),可以搭配使用。

开发

自行推算的字段

Claude Code 的状态栏 stdin 里有这些字段,mod API 没有,所以由 mod 自己推算:

  • prompt_cache:计时从主线程最后一次请求开始(取自 turn.step,没有时取 transcript 里主线程最后一条响应),时长按最后一次写缓存用的 TTL(写的是 1 小时档时为 1h,否则 5m)。hit_ratio 是整个会话里主线程输入中读缓存的部分所占的比例。
  • model_scoped(按模型单独计的周额度,如 Fable 的):mod API 和状态栏都不提供,所以从 Claude Code 自己缓存的用量接口结果读取,即 .claude.json 里的 cachedUsageUtilization(文件变化时才重读,超过一小时的数据不用,与 Claude Code 自己的读取方式一致)。不发任何请求。claude-hud 把它们和 5 小时、7 天额度画在一起,附带消耗速度。
  • session_name:transcript 里 /rename 起的标题,没有时用自动生成的标题,再没有时用 slug。
  • workspace.repo:从 $.session.repo() 的远程 URL 解析。
  • output_style:设置里的 outputStyle。
  • 会话第一次请求模型之前,current_usage 用引擎给出的上下文总量(按未缓存计),推理强度用设置里的 effortLevel;两者都在第一个 turn.step 到达后更新,并保存在会话状态里,重新加载后仍在。
  • total_api_duration_ms 只统计这个会话里 mod 启用之后看到的请求。

新增部分的细节

  • 远程控制:会话开启远程控制时,第一行末尾显示 │ ⇄ 远程控制,链接到 claude.ai 上的这个会话,后面按端列出已连接的客户端(已连接 手机 · 网页/桌面×2)。Claude App 和 claude.ai 不会触发 session.attach,所以通过远程控制发来的消息或命令会把状态标为 已连接,直到桥接变化。引擎把桥接记在 ~/.claude/sessions/<pid>.json 的 bridgeSessionId 里(按会话 id 查找),mod API 不提供,所以每 3 秒读一次这个文件,有变化时重画 HUD;客户端和所在的端取自 session.attach / session.detach。
  • 附加行:宽度够时接在 claude-hud 最后一行后面,不够时单独占一行放在下面;放不下的部分依次让出,先是主题的看板娘,然后是 7 天折线,最后是 ⚠ git 提醒。每一部分只在有内容时显示:
  • ✎ 一行任务摘要:第一轮之后以及每隔 summaryEveryTurns 轮,用 $.model.fork 分叉当前对话生成(命中提示词缓存)。transcript 里有未完成的任务清单时跳过(清单已经说明模型在做什么),旧的摘要这期间也先让开。
  • 用量预测(showForecast):5 小时、7 天或按模型计的周额度在重置前会用完时,显示预计用完的时间:5 小时额度在会话有 10 分钟读数后按最近一小时的速度算,周额度按本周期开始以来的速度算。
  • 距自动压缩还剩的 token(距自动压缩 42k):上下文到达阈值的 compactWarnPercent 后显示。阈值取自 Claude Code 自己($.session.usage({ breakdown: 'summary' })),上下文窗口变化时重新读取。
  • 提示缓存过期(缓存已过期,下条消息重写 120k):会话用过的缓存过期后,如果下一条消息要重新写入的上下文不少于 coldCacheTokens,显示这个量。
  • 上下文涨幅(上一轮 +98k ▂▁█):上一轮让上下文至少涨了 turnGrowthTokens 时,显示涨了多少,后面是最近 8 轮涨幅的迷你柱状图(压缩那一轮按 0 计)。灵感来自 token-weather 的逐轮图表。
  • 今天所有会话的花费对比 dailyBudgetUsd,数据来自 claude-hud 的每日花费账本;到 80% 变黄,超出变红。
  • 近 7 天花费的迷你折线和连续使用天数(showHistory);无论是否显示,花费都会在 mod 的存储里保留 60 天。
  • ⚠ 未提交的路径数达到 gitDirtyWarn、未推送的提交数达到 gitAheadWarn 时提醒。
  • 预警:上下文用量到达 contextAlerts 里的每个百分比、5 小时、7 天或按模型计的周额度到达 usageAlerts 里的每个百分比时弹 toast;每个阈值只提醒一次,读数回落到阈值以下 5 个百分点(如 /compact 或额度重置)后才会再次提醒。
  • 结束提醒:主线程的一轮跑了 notifyAfterSeconds 秒或更久时,结束时弹 toast,同时通过你在 Claude Code 里设置的通知渠道发一条系统通知,开启 notifySound 时再响一声(macOS)。
  • Claude Desktop 等用自身字体绘制的端(桌面版、手机、编辑器):HUD 不套用终端的行,改为一行行小号的读数,自动换行,按主题配色显示警告:额度及重置时间、缓存到期、会话时长,以及摘要、预测、未提交改动等附加信息,不画进度条和折线。桌面版的底栏和侧栏已经显示模型、推理强度、项目、分支和上下文,对话里也有工具调用,所以这几项都不再显示。
  • /hud detail 面板:本会话每个工具的调用次数、总耗时、平均耗时和失败数;最近 8 轮的用时、花费和上下文增长;子代理;待办;今天和本周的花费。
  • 及时重画:压缩完成后立即重画;/model 之后也会重画(在新模型第一次请求之前就显示它)。
  • 相对 claude-hud 的显示调整: │ 和 | 分隔符调暗;正在跑的工具涉及的文件显示为相对会话目录的路径(◐ Read src/a.ts);会话时长显示为 ⏱ 12m,提示缓存显示为 缓存 至 14:05,不用占两列宽的 ⏱️。

没有移植的部分

  • OSC 8 file:// 链接(项目路径):Link 只接受 https,所以保留文字、去掉链接。https 链接(GitHub 分支)仍可点击。
  • worktree(--worktree 会话的名称、路径和分支):mod API 不提供。

目录结构

  • hooks/register.tsx:钩子,以及所有调用 $ 的代码(引擎只在这个文件内追踪 $):会话开始、回合事件、/hud、刷新循环、预警、花费和摘要,以及渲染钩子。其他模块拿到的是包住 $ 的闭包(Io、SessionApi)。
  • hooks/config.ts:mod 的选项,一次性读成类型化的 Config。
  • hooks/stdin.ts:根据会话(用量、设置、仓库、回合步骤)和 transcript 拼出 claude-hud 需要的状态栏 stdin;以及 claude-hud 读取的宿主信息(环境变量、平台、内存)。
  • hooks/render.ts:一次渲染:claude-hud 的各行、远程控制标签、今天的花费;git 提醒用到的计数。
  • hooks/remote.ts:远程控制的桥接(取自 sessions/<pid>.json)和它的标签。
  • hooks/summary.ts:任务摘要的回复,整理成一行。
  • hooks/draw.tsx:根据渲染钩子解析出的元素绘制各行(输入框上方或下方)和 /hud detail 面板。
  • hooks/live.ts:模块在两次渲染之间、$.state 以外保存的东西(重新加载后还能找回的缓存、横条宽度、调试工具最近一次的结果)和当前主题。
  • hooks/kit/:claude-code/kit 的副本(选项读取、写回 /config);改源文件后运行 scripts/sync-kit.sh。
  • hooks/transcript-feed.ts:为整个 mod 统一读取 transcript,只读一次、之后增量读取(只读新追加的行,按文件大小判断)。每一行都交给 claude-hud 自己的 Parser,也交给一个小读取器,用来补上 $ 不提供的 stdin 字段:session_name 和 prompt_cache。
  • hooks/hud/:claude-hud 的 src/(MIT,见 LICENSE.claude-hud),尽量贴近上游。本地改动:
  • index.ts:main(source) 从 mod 接收 stdin;错误和配置提示交给渲染输出;去掉了作为脚本运行的代码块。
  • render/index.ts:各行输出到 sink(setRenderSink、emitLine),不再用 console.log。
  • i18n/:在 types.ts、index.ts 和新文件里多了七种语言(ja、ko、es、fr、de、pt-BR、ru,另有别名 pt);导出 getCanonicalLanguage;isCjkLanguage 也把 ja 和 ko 算进去。config.ts 的 LANGUAGES 列出了它们。
  • config.ts:setConfigPatch 把 mod 的选项叠加到已读取的配置上(除非 mod 的 showAgents 选项打开,否则 showAgents 关闭)。
  • render/parts.ts:countLabel 允许某种语言把数量写成 Regeln: 3({n} 模板),避免 3 Regeln 这种需要复数变化的写法。
  • transcript.ts:导出 Parser,并通过 setTranscriptProvider 让 mod 接管 parseTranscript。
  • git-runner.ts:git 通过 $.process.run 运行;去掉了 Windows worker。
  • config.ts:限长读取配置改为一次 readFileSync;O_NOFOLLOW 改为 lstat 检查。
  • render/theme.ts(新增):claude-hud 输出的符号([ ]、git:(、◐ ✓ ▸、⚠ ▲、⏱、↑↓、⎇)以及 Context、Usage、Weekly、缓存和花费标签前的图标,在 parts.ts、vcs.ts、activity.ts、usage.ts、lines.ts、labels.ts 和 colors.ts 里通过 glyph() / iconLabel() 读取。默认值与上游一致,不调用 setGlyphs 时输出不变。
  • claude-config-dir.ts:getHudCacheDir(plugins/claude-hud-mod),供 speed.ts 和 daily-cost.ts 使用,缓存不会和状态栏版的 claude-hud 冲突。
  • hooks/shims/:claude-hud 引用的 Node API,基于 $ 实现。同步读取直接用渲染前取好的数据回答;没取到的先去取,再重跑这次渲染(host.ts)。写入先暂存,渲染完成后一次写出。
  • hooks/ansi.ts:把 SGR 转义序列转成带样式的片段。
  • hooks/i18n.ts:mod 自己的文案,覆盖 claude-hud 支持的所有语言,复数形式、金额和百分比按各语言习惯书写。
  • hooks/themes.ts:各主题(配色、图标、分隔符、附加行颜色、powerline、渐变、看板娘),以及应用它们的片段效果。
  • hooks/extras.ts:mod 新增内容的纯函数:阈值、用量预测、花费历史、git 计数、附加行和提示音。

从上游同步

把新的 src/ 覆盖到 hooks/hud/(不要 windows-git-worker.ts),把 node:* 的 import 改指向 ../shims/*.js(node:fs/promises 指向 fs_promises.js),重新应用上面列出的改动(新出现的硬编码符号也改走 render/theme.ts),然后在仓库根目录运行 scripts/check.sh claude-code/hud。要和上游对比,把 mcp__hud__hud_debug 报告的 stdin 喂给 node <claude-hud>/dist/index.js。

Source 85 files
hooks/register.tsx 715 lines
1// claude-hud as a mod. claude-hud's own source (hooks/hud, MIT, see
2// LICENSE.claude-hud) renders the lines; this module wires the engine's
3// events to it and draws its output above or below the prompt. The work sits
4// beside it: stdin.ts builds the statusline's stdin, render.ts runs a pass,
5// remote.ts follows Remote Control, draw.tsx draws. Whatever calls `$` stays
6// in this file (the engine follows `$` only within the hooks module's own
7// file); the other modules get closures over it (`Io`, `SessionApi`).
8import './shims/globals.js'
9
10import { atom, derive, read, update } from 'claude-code'
11import type { EngineInterface, Register } from 'claude-code'
12
13import type { Desk, DockPet, Fired, HudLine, Remote, StepInfo, ToolStats, TurnCost } from '../types'
14import { readConfig } from './config.js'
15import { drawDesk, drawPane, drawRows } from './draw.js'
16import { getContextUsage } from './hud/stdin.js'
17import { addSample, appendExtras, chimeWav, crossThresholds, deskOf, exhaustAt, extrasLine, formatDuration, growthOf, lastDays, localDay, paceAt, pruneHistory, streak } from './extras.js'
18import type { ExtrasInput, Samples } from './extras.js'
19import { loadConfig, setConfigPatch } from './hud/config.js'
20import { setLanguage } from './hud/i18n/index.js'
21import { setTranscriptProvider } from './hud/transcript.js'
22import type { StdinData } from './hud/types.js'
23import { FIVE_HOUR_WINDOW_MS, SEVEN_DAY_WINDOW_MS } from './hud/usage-pace.js'
24import { m, summaryPrompt } from './i18n.js'
25import { isPickerOpen } from './kit/band.js'
26import { cellWidth, dockFits, drawPet } from './kit/pet.js'
27import { keptRows, migrateStore, persist, switchArg } from './kit/prefs.js'
28import type { Prefs } from './kit/prefs.js'
29import { fitColumns, live, useTheme } from './live.js'
30import { BRIDGE, remoteControl } from './remote.js'
31import { gitCounts, renderHud } from './render.js'
32import { factsSummary, type Io, runWithFacts, setIo } from './shims/host.js'
33import { loadHostFacts, type SessionApi } from './stdin.js'
34import { cleanSummary } from './summary.js'
35import { applyPalette, applyTheme, findTheme, moodOf, THEMES } from './themes.js'
36import type { Theme } from './themes.js'
37import { transcriptData } from './transcript-feed.js'
38
39const lines = atom({ plugin: 'hud', key: 'lines' } as const, [] as HudLine[])
40// The same readings for a surface that draws in its own type (see deskOf).
41const desk = atom({ plugin: 'hud', key: 'desk' } as const, { gauges: [], notes: [] } as Desk)
42// Set this session by `/hud` or session.start; null in a session resumed or
43// cleared, which gets no session.start: `isHidden` is the `visible` row's then.
44const hiddenSet = atom({ plugin: 'hud', key: 'isHidden' } as const, null as boolean | null)
45// The `visible` row's, set in register.
46let isRowHidden = false
47const isHidden = derive([hiddenSet], set => set ?? isRowHidden)
48// Session state, so a reload keeps what earlier requests reported.
49const steps = atom({ plugin: 'hud', key: 'step' } as const, {
50  model: null,
51  effort: null,
52  apiDurationMs: 0,
53  currentUsage: null,
54  lastRequestAt: null,
55} as StepInfo)
56// Remote clients attached to the session (a phone, the web), with their surface.
57const remotes = atom({ plugin: 'hud', key: 'remotes' } as const, [] as Remote[])
58const summary = atom({ plugin: 'hud', key: 'summary' } as const, null as string | null)
59const turns = atom({ plugin: 'hud', key: 'turns' } as const, 0)
60const fired = atom({ plugin: 'hud', key: 'fired' } as const, { context: [], fiveHour: [], sevenDay: [] } as Fired)
61const history = atom({ plugin: 'hud', key: 'history' } as const, {} as Record<string, number>)
62const tools = atom({ plugin: 'hud', key: 'tools' } as const, {} as ToolStats)
63const turnLog = atom({ plugin: 'hud', key: 'turnLog' } as const, [] as TurnCost[])
64const turnStart = atom({ plugin: 'hud', key: 'turnStart' } as const, null as { usd: number | null; tokens: number | null } | null)
65/** Turns `/hud detail` lists. */
66const TURN_LOG_SIZE = 8
67// spinner's pet, and whether it stands beside the HUD's rows (below the prompt only).
68const petDock = atom({ plugin: 'spinner', key: 'dock' } as const, null as DockPet | null)
69const isPetDocked = atom({ plugin: 'hud', key: 'dock' } as const, false)
70const petPats = atom({ plugin: 'hud', key: 'petPats' } as const, 0)
71// True while a picker is open above the band (see kit/band.tsx).
72const isPicking = atom({ plugin: 'hud', key: 'isPicking' } as const, false)
73
74const PANE = 'hud-detail'
75// Days of spend the store keeps; the HUD draws the last 7.
76const HISTORY_DAYS = 60
77
78setTranscriptProvider(async path => transcriptData(path))
79
80// Events (tool calls, model requests, turn ends) drive the live updates; the
81// tick only keeps minute-grained clocks (duration, resets, cache) current.
82const TICK_MS = 15_000
83const DEBOUNCE_MS = 250
84const RC_POLL_MS = 3_000
85
86/** The kit's hold on this mod's store and `/config` rows. */
87function prefsOf($: EngineInterface): Prefs {
88  return {
89    kept: key => $.store.get(key),
90    forget: key => $.store.delete(key),
91    write: (field, value) => $.config.set({ key: `hud.${field}`, value }),
92  }
93}
94
95/** Marks the message-only client present when `origin` came over the bridge; true if that is news. */
96async function sawBridge($: EngineInterface, origin: { kind: string }): Promise<boolean> {
97  if (origin.kind !== 'bridge') return false
98  if ((await read($, remotes)).some(r => r.surface === BRIDGE)) return false
99  await update($, remotes, rs => [...rs.filter(r => r.surface !== BRIDGE), { id: BRIDGE, surface: BRIDGE }])
100  return true
101}
102
103type Gauges = { context?: number; fiveHour?: number; sevenDay?: number }
104
105/** Toasts once per threshold a gauge crosses; re-armed once it drops back. */
106async function alert($: EngineInterface, gauges: Gauges, contextAlerts: number[], usageAlerts: number[]): Promise<void> {
107  const was = await read($, fired)
108  const context = crossThresholds(gauges.context, contextAlerts, was.context)
109  const fiveHour = crossThresholds(gauges.fiveHour, usageAlerts, was.fiveHour)
110  const sevenDay = crossThresholds(gauges.sevenDay, usageAlerts, was.sevenDay)
111  if (context.alert !== null) $.ui.toast(m('alert.context', { p: context.alert }))
112  if (fiveHour.alert !== null) $.ui.toast(m('alert.fiveHour', { p: fiveHour.alert }))
113  if (sevenDay.alert !== null) $.ui.toast(m('alert.sevenDay', { p: sevenDay.alert }))
114  const now = { ...was, context: context.fired, fiveHour: fiveHour.fired, sevenDay: sevenDay.fired }
115  if (JSON.stringify(now) !== JSON.stringify(was)) await update($, fired, () => now)
116}
117
118/** The same for the model-scoped weekly windows (Fable's), which `session.measure` does not carry. */
119async function alertScoped($: EngineInterface, windows: readonly { name: string; percent: number }[], usageAlerts: number[]): Promise<void> {
120  if (usageAlerts.length === 0 || windows.length === 0) return
121  const was = await read($, fired)
122  const scoped = { ...was.scoped }
123  for (const { name, percent } of windows) {
124    const crossed = crossThresholds(percent, usageAlerts, scoped[name] ?? [])
125    if (crossed.alert !== null) $.ui.toast(m('alert.scoped', { name, p: crossed.alert }))
126    scoped[name] = crossed.fired
127  }
128  if (JSON.stringify(scoped) !== JSON.stringify(was.scoped ?? {})) await update($, fired, f => ({ ...f, scoped }))
129}
130
131/** The gauges a usage reading carries (`$.session.usage()`, or a pushed `session.measure`). */
132function gaugesOf(usage: { context: { percent?: number }; rateLimits: readonly { kind: string; percentUsed: number }[] }): Gauges {
133  const percent = (kind: string) => usage.rateLimits.find(r => r.kind === kind)?.percentUsed
134  return { context: usage.context.percent, fiveHour: percent('five_hour'), sevenDay: percent('seven_day') }
135}
136
137/** The context the next message re-caches, once a cache this session used has expired and holds at least `min` tokens. */
138function coldCacheOf(stdin: StdinData, min: number): number | null {
139  const cache = stdin.prompt_cache
140  const tokens = stdin.context_window?.total_input_tokens ?? 0
141  return min > 0 && cache?.caching_observed && !cache.warm && tokens >= min ? tokens : null
142}
143
144/** Draws `picked` (the redraw scheduled) and writes the theme row. */
145async function setTheme($: EngineInterface, picked: Theme, schedule: () => void): Promise<{ text: string }> {
146  useTheme(picked)
147  schedule()
148  await persist(prefsOf($), 'theme', picked.name)
149  return { text: m('theme.set', { name: `${picked.name} ${picked.sample}` }) }
150}
151
152/** `/hud [off|on]`: the HUD hidden or shown (no verb toggles), its row written when it changed. */
153async function setHidden($: EngineInterface, verb: string, schedule: () => void): Promise<boolean> {
154  const was = await read($, isHidden)
155  const hidden = switchArg(verb, was)
156  await update($, hiddenSet, () => hidden)
157  if (hidden !== was) await persist(prefsOf($), 'visible', !hidden)
158  schedule()
159  return hidden
160}
161
162// Before 0.8 a theme picked with `/hud theme` was kept in the store; it is the `theme` row now.
163const STORE_MOVES = { theme: (kept: unknown) => (findTheme(kept) ? (['theme', findTheme(kept)!.name] as const) : null) }
164
165export const register: Register = (on, options) => {
166  const config = readConfig(options)
167  isRowHidden = !config.isVisible
168  useTheme(config.theme)
169  // A session the desktop app hosts: no terminal, the desktop attached. Its side panel
170  // draws the context, so the desktop's HUD leaves it out.
171  let isHeadless = false
172  let isDesktop = false
173  setConfigPatch(hud => {
174    const themed = applyPalette(hud, live.theme)
175    // Claude Code lists running subagents itself, with their time and tokens; claude-hud's
176    // agent lines would repeat them, so they show only when asked for.
177    return config.hasAgents ? themed : { ...themed, display: { ...themed.display, showAgents: false } }
178  })
179  let isSummarizing = false
180  // Set in session.start: everything that outlives one dispatch calls the
181  // engine through these closures.
182  let refresh: () => Promise<void> = async () => {}
183  let after: (ms: number, fn: () => void) => void = () => {}
184  let isRunning = false
185  let isQueued = false
186  let isScheduled = false
187  let isStarted = false
188  // Where auto-compaction runs (null: off), for the window it was read for: it
189  // moves only with the window, so a model switch reads it again.
190  let compactAt: { window: number; at: number | null } | null = null
191  // The 5-hour window's readings this session: its forecast follows the last hour's pace.
192  let fiveHour: Samples | undefined
193
194  const schedule = () => {
195    // A draw can come before session.start: nothing to schedule on yet, and
196    // session.start refreshes anyway.
197    if (isScheduled || !isStarted) return
198    isScheduled = true
199    after(DEBOUNCE_MS, () => {
200      isScheduled = false
201      void refresh()
202    })
203  }
204
205  on('session.start', async ($, e, next) => {
206    isHeadless = !e.isInteractive
207    // After a reload the desktop is attached already and says so again to nobody.
208    isDesktop = isHeadless && (await $.session.surfaces()).includes('desktop')
209    const io: Io = {
210      stat: path => $.fs.stat(path, { resolve: true }),
211      read: path => $.fs.read(path),
212      list: path => $.fs.list(path),
213      write: (path, text) => $.fs.write(path, text),
214      run: (argv, init) => $.process.run(argv, init),
215    }
216    const session: SessionApi = {
217      info: async () => {
218        const [id, cwd, root, model, usage, version, settings, step, repo] = await Promise.all([
219          $.session.id(),
220          $.session.cwd(),
221          $.session.root(),
222          $.session.model(),
223          $.session.usage(),
224          $.session.version(),
225          $.settings.read().catch(() => ({})),
226          read($, steps),
227          $.session.repo().catch(() => null),
228        ])
229        return { id, cwd, root, model, usage, version, settings: settings as Record<string, unknown>, step, repo }
230      },
231      // A value from before 0.4.3 (bare ids) is dropped rather than misread.
232      remotes: async () => (await read($, remotes)).filter(r => typeof r === 'object' && r !== null),
233      exists: path => $.fs.exists(path),
234    }
235    setIo(io)
236    after = (ms, fn) => void $.clock.after(ms, fn)
237    isStarted = true
238    refresh = async () => {
239      if (isRunning) {
240        isQueued = true
241        return
242      }
243      isRunning = true
244      const started = Date.now()
245      try {
246        const { rows, stdin, todayUsd } = await renderHud(io, session)
247        const window = stdin.context_window?.context_window_size ?? 0
248        if (config.compactWarnPercent > 0 && window > 0 && compactAt?.window !== window) {
249          const breakdown = (await $.session.usage({ breakdown: 'summary' }).catch(() => null))?.context.breakdown
250          compactAt = { window, at: breakdown?.isAutoCompactEnabled ? (breakdown.autoCompactThreshold ?? null) : null }
251        }
252        const tokens = stdin.context_window?.total_input_tokens ?? 0
253        const compactLeft =
254          compactAt?.at && tokens >= (compactAt.at * config.compactWarnPercent) / 100 ? compactAt.at - tokens : null
255        const pet = config.position === 'below' ? await read($, petDock) : null
256        const now = await $.clock.now()
257        if (todayUsd !== null) await recordSpend(now, todayUsd)
258        const days = await read($, history)
259        const today = localDay(now)
260        const limits = stdin.rate_limits
261        const five = limits?.five_hour
262        if (five && typeof five.used_percentage === 'number' && five.resets_at) {
263          fiveHour = addSample(fiveHour, five.used_percentage, five.resets_at, now)
264        }
265        const scoped = (stdin.model_scoped ?? []).flatMap(w =>
266          w.display_name && typeof w.utilization === 'number'
267            ? [{ name: w.display_name, percent: w.utilization, resetsAt: w.resets_at ? Math.floor(Date.parse(w.resets_at) / 1000) : null }]
268            : [],
269        )
270        await alertScoped($, scoped, config.usageAlerts)
271        // The 7-day window keeps the pace since it began: an hour of work says little about a week.
272        const exhaust = config.hasForecast
273          ? [
274              { label: m('limit.fiveHour'), at: paceAt(fiveHour, five?.used_percentage, five?.resets_at, FIVE_HOUR_WINDOW_MS, now) },
275              { label: m('limit.sevenDay'), at: exhaustAt(limits?.seven_day?.used_percentage, limits?.seven_day?.resets_at, SEVEN_DAY_WINDOW_MS, now) },
276              ...scoped.map(w => ({ label: m('limit.scoped', { name: w.name }), at: exhaustAt(w.percent, w.resetsAt, SEVEN_DAY_WINDOW_MS, now) })),
277            ].flatMap(({ label, at }) => (at === null ? [] : [{ label, at }]))
278          : []
279        const extrasInput: ExtrasInput = {
280          summary: await read($, summary),
281          exhaust,
282          todayUsd,
283          budgetUsd: config.budgetUsd,
284          week: config.hasHistory ? { values: lastDays(days, today, 7), streak: streak(days, today) } : null,
285          compactLeft,
286          coldCache: coldCacheOf(stdin, config.coldCacheTokens),
287          growth: growthOf(await read($, turnLog), config.turnGrowthTokens),
288          git: config.gitDirtyWarn > 0 || config.gitAheadWarn > 0 ? await gitCounts(io, stdin.cwd ?? '') : null,
289          gitDirtyWarn: config.gitDirtyWarn,
290          gitAheadWarn: config.gitAheadWarn,
291          columns: fitColumns(),
292          style: live.theme.extras,
293          // spinner's pet stands in for the theme's mascot below the prompt.
294          mascot: config.hasMascot && live.theme.mascot && !pet ? live.theme.mascot[mood(stdin)] : null,
295        }
296        const extra = extrasLine(extrasInput)
297        const all = applyTheme(appendExtras(rows, extra, fitColumns()), live.theme)
298        // The pet moves in beside the rows when it fits, and out when it does not.
299        const widest = Math.max(0, ...all.map(row => row.reduce((sum, span) => sum + cellWidth(span.text), 0)))
300        const wasDocked = await read($, isPetDocked)
301        const isDocked = pet !== null && !(await read($, isHidden)) && live.columns !== undefined && dockFits(widest, live.columns, pet.width, wasDocked)
302        if (isDocked !== wasDocked) await update($, isPetDocked, () => isDocked)
303        live.lastLines = all.map(row => row.map(span => span.text).join(''))
304        live.lastError = null
305        await update($, lines, () => all)
306        const cache = stdin.prompt_cache
307        const ttlSeconds = cache?.ttl === '1h' ? 3600 : 300
308        // claude-hud's own reading: Claude Code's percent, else the request's tokens.
309        const used = getContextUsage(stdin)
310        await update($, desk, () =>
311          deskOf({
312            ...extrasInput,
313            context: !isDesktop && used.size > 0 && used.tokens > 0 ? used : null,
314            limits: [
315              ...(typeof five?.used_percentage === 'number' ? [{ label: '5h', percent: five.used_percentage, resetsAt: five.resets_at ? five.resets_at * 1000 : null }] : []),
316              ...(typeof limits?.seven_day?.used_percentage === 'number'
317                ? [{ label: '7d', percent: limits.seven_day.used_percentage, resetsAt: limits.seven_day.resets_at ? limits.seven_day.resets_at * 1000 : null }]
318                : []),
319              ...scoped.map(w => ({ label: w.name, percent: w.percent, resetsAt: w.resetsAt === null ? null : w.resetsAt * 1000 })),
320            ],
321            cache: cache?.warm && typeof cache.expires_at === 'number' ? { until: cache.expires_at * 1000, warnMs: Math.max(60, ttlSeconds / 5) * 1000 } : null,
322            durationMs: stdin.cost?.total_duration_ms ?? null,
323            now,
324          }),
325        )
326      } catch (err) {
327        live.lastError = err instanceof Error ? `${err.message}\n${err.stack ?? ''}` : String(err)
328      } finally {
329        live.refreshMs = Date.now() - started
330        isRunning = false
331      }
332      if (isQueued) {
333        isQueued = false
334        void refresh()
335      }
336    }
337
338    // The mascot's mood: the quota, the context, whether a tool is running.
339    const mood = (stdin: StdinData) => {
340      const limits = stdin.rate_limits
341      const usage = Math.max(limits?.five_hour?.used_percentage ?? 0, limits?.seven_day?.used_percentage ?? 0)
342      const tools = live.transcriptPath ? transcriptData(live.transcriptPath)?.tools ?? [] : []
343      return moodOf(stdin.context_window?.used_percentage, usage, tools.some(t => t.status === 'running'))
344    }
345    // Today's spend into the history, and the store, which other sessions share.
346    const recordSpend = async (now: number, todayUsd: number) => {
347      const today = localDay(now)
348      const usd = Math.round(todayUsd * 100) / 100
349      if ((await read($, history))[today] === usd) return
350      const stored = ((await $.store.get('history')) ?? {}) as Record<string, number>
351      const merged = pruneHistory({ ...stored, [today]: usd }, today, HISTORY_DAYS)
352      await $.store.set('history', merged)
353      await update($, history, () => merged)
354    }
355
356    const kept = await $.store.get('history')
357    if (kept && typeof kept === 'object') {
358      const today = localDay(await $.clock.now())
359      await update($, history, () => pruneHistory(kept as Record<string, number>, today, HISTORY_DAYS))
360    }
361
362    const keptTheme = findTheme((await keptRows(prefsOf($), STORE_MOVES)).theme)
363    if (keptTheme) useTheme(keptTheme)
364    await update($, hiddenSet, () => !config.isVisible)
365
366    await loadHostFacts(io, config.extraCmd)
367    // claude-hud sets its language in each pass; the command's description is read before the first.
368    await runWithFacts(async () => setLanguage((await loadConfig()).language))
369    await $.command.register({ name: 'hud', description: m('cmd.description'), argumentHint: '[off|on | detail | theme [name|next|reset]]', immediate: true })
370    if (config.isDebug) {
371      await $.tool.register({
372        name: 'hud_debug',
373        description: 'claude-hud mod diagnostics: the stdin it built, its last error and refresh time.',
374        inputSchema: { type: 'object', properties: {} },
375      })
376    }
377    // Usage the session already had (a resumed one): alerts now, not after the first measurement.
378    const usage = await $.session.usage().catch(() => null)
379    if (usage) {
380      await alert($, gaugesOf(usage), config.contextAlerts, config.usageAlerts)
381    }
382    $.clock.every(TICK_MS, () => void refresh())
383    void refresh()
384    // Remote Control turns on and off outside the turn's events (`/remote-control`,
385    // `--remote-control` connecting): a cheap read of the session file, a redraw on a change.
386    $.clock.every(RC_POLL_MS, async () => {
387      const bridge = await remoteControl(io, await $.session.id()).catch(() => live.bridgeSessionId)
388      if (bridge !== live.bridgeSessionId) {
389        // A new bridge, or none: whoever wrote over the old one is not known to be there.
390        await update($, remotes, all => all.filter(r => r.surface !== BRIDGE))
391        schedule()
392      }
393    })
394
395    const result = await next(e)
396    await migrateStore(prefsOf($), STORE_MOVES)
397    return result
398  })
399
400  on('command.run', { command: 'hud' }, async ($, e) => {
401    const [verb = '', arg = ''] = e.args.trim().toLowerCase().split(/\s+/)
402    if (verb === 'theme') {
403      const list = THEMES.map(t => `${t.name}${t.isNerdFont ? '*' : ''} ${t.sample}`).join(' · ')
404      const names = THEMES.map(t => t.name).join(', ')
405      const at = THEMES.indexOf(live.theme)
406      if (!arg) {
407        // The engine's dialog offers the next four; "Other" takes any name. Dismissed, or no one to ask (-p): the list.
408        const offered = [1, 2, 3, 4].map(i => THEMES[(at + i) % THEMES.length]!.name)
409        const answer = await $.ui.ask(m('theme.ask', { name: live.theme.name, list: names }), { options: offered, header: 'HUD theme' }).catch(() => null)
410        if (answer === null) return { text: m('theme.list', { name: live.theme.name, list }) }
411        const asked = findTheme(answer.trim().split(/\s+/)[0]?.toLowerCase())
412        if (!asked) return { text: m('theme.unknown', { name: answer.trim(), list: names }) }
413        return setTheme($, asked, schedule)
414      }
415      // `reset`: the option's default, claude-hud's own look.
416      const picked = arg === 'next' ? THEMES[(at + 1) % THEMES.length] : arg === 'reset' ? THEMES[0] : findTheme(arg)
417      if (!picked) return { text: m('theme.unknown', { name: arg, list: names }) }
418      return setTheme($, picked, schedule)
419    }
420    if (verb === 'detail') {
421      if ((await $.ui.panes()).some(p => p.id === PANE)) {
422        await $.ui.close({ id: PANE })
423        return { text: m('pane.closed') }
424      }
425      await $.ui.open({ id: PANE, title: m('pane.title') })
426      return { text: m('pane.opened') }
427    }
428    const hidden = await setHidden($, verb, schedule)
429
430    return { text: m(hidden ? 'cmd.hidden' : 'cmd.shown') }
431  })
432
433  // A button in the prompt footer: what `/hud` alone does. Mode labels other plugins add stay beside it.
434  if (config.hasFooterButton) {
435    on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
436      const hidden = await read($, isHidden)
437      const below = await next(e)
438      const { Box, Button } = $.ui.resolve(e)
439      return (
440        <Box flexDirection="row" alignItems="center" gap={1}>
441          <Button key="hud-toggle" plain dimColor={hidden} label="HUD" onPress={() => setHidden($, '', schedule)} />
442          {below}
443        </Box>
444      )
445    })
446  }
447
448  on('session.attach', async ($, e, next) => {
449    if (e.surface === 'desktop' && isHeadless) isDesktop = true
450    if (e.surface !== 'terminal') {
451      await update($, remotes, all => [...all.filter(r => r.id !== e.clientId), { id: e.clientId, surface: e.surface }])
452    }
453    schedule()
454
455    return next(e)
456  })
457
458  // Remote Control's clients are seen by what they send.
459  on('prompt.submit', async ($, e, next) => {
460    if (await read($, isPicking)) await update($, isPicking, () => false)
461    if (await sawBridge($, e.origin)) schedule()
462    return next(e)
463  })
464  on('command.run', async ($, e, next) => {
465    if (await sawBridge($, e.origin)) schedule()
466    if (e.command !== 'model') return next(e)
467    // /model: the last step's model is the old one; the session's is shown until the next step.
468    const result = await next(e)
469    await update($, steps, step => ({ ...step, model: null }))
470    schedule()
471    return result
472  })
473
474  // Remote Control's prompts reach the session as deliveries before they are a prompt.
475  on('session.receive', async ($, e, next) => {
476    if (await sawBridge($, e.origin)) schedule()
477    return next(e)
478  })
479
480  // Usage pushed by the engine: the alerts at once, and the gauges redrawn.
481  on('session.measure', async ($, e, next) => {
482    await alert($, gaugesOf(e), config.contextAlerts, config.usageAlerts)
483    schedule()
484    return next(e)
485  })
486
487  // A compaction empties the context: the gauge drops now, not at the next tick.
488  on('session.compact', async ($, e, next) => {
489    const result = await next(e)
490    if (e.agentId === undefined) schedule()
491    return result
492  })
493
494  // spinner's pet came, went or changed: whether it fits is decided again.
495  on('state.set', { plugin: 'spinner', key: 'dock' }, async ($, e, next) => {
496    const result = await next(e)
497    schedule()
498    return result
499  })
500
501  // A click on the pet drawn here: spinner counts it as a pat.
502  on('ui.message', async ($, e, next) => {
503    if ((e.data as { pat?: unknown } | null)?.pat === true) await update($, petPats, n => n + 1)
504    return next(e)
505  })
506
507  on('session.detach', async ($, e, next) => {
508    await update($, remotes, all => all.filter(r => r.id !== e.clientId))
509    schedule()
510
511    return next(e)
512  })
513
514  on('tool.call', { tool: /^mcp__hud__hud_debug$/ }, async () => {
515    const text = JSON.stringify(
516      { lines: live.lastLines, stdin: live.lastStdin, bridgeSessionId: live.bridgeSessionId, sessionFile: live.sessionFile, error: live.lastError, refreshMs: live.refreshMs, columns: live.columns, facts: factsSummary() },
517      null,
518      2,
519    )
520
521    return { result: text, text }
522  })
523
524  on('tool.call', async ($, e, next) => {
525    schedule()
526    const started = Date.now()
527    const ran = await next(e)
528    const ms = Date.now() - started
529    const failed = 'deny' in ran ? ran.deny !== undefined : ran.isError === true
530    await update($, tools, all => {
531      const was = all[e.tool] ?? { count: 0, totalMs: 0, errors: 0 }
532      return { ...all, [e.tool]: { count: was.count + 1, totalMs: was.totalMs + ms, errors: was.errors + (failed ? 1 : 0) } }
533    })
534    schedule()
535
536    return ran
537  })
538
539  on('turn.step', async function* ($, e, next) {
540    const started = Date.now()
541    const result = yield* next(e)
542    const elapsed = Date.now() - started
543    const usage = result.usage
544    await update($, steps, step =>
545      e.agentId
546        ? { ...step, apiDurationMs: step.apiDurationMs + elapsed }
547        : {
548            model: e.model,
549            effort: e.effort === undefined ? step.effort : String(e.effort),
550            apiDurationMs: step.apiDurationMs + elapsed,
551            currentUsage: usage
552              ? {
553                  input_tokens: usage.input_tokens,
554                  output_tokens: usage.output_tokens,
555                  cache_creation_input_tokens: usage.cache_creation_input_tokens,
556                  cache_read_input_tokens: usage.cache_read_input_tokens,
557                }
558              : step.currentUsage,
559            // The request's start is when the main thread's prompt cache was last used.
560            lastRequestAt: started,
561          },
562    )
563    schedule()
564
565    return result
566  })
567
568  // What the turn about to run starts from, for its row in `/hud detail`.
569  on('turn.start', async ($, e, next) => {
570    const usage = await $.session.usage().catch(() => null)
571    await update($, turnStart, () => ({ usd: usage?.cost?.usd ?? null, tokens: usage?.context.tokens ?? null }))
572    return next(e)
573  })
574
575  on('turn.complete', async ($, e, next) => {
576    schedule()
577    if (e.agentId !== undefined) return next(e)
578    const start = await read($, turnStart)
579    if (start) {
580      const usage = await $.session.usage().catch(() => null)
581      const usd = usage?.cost?.usd
582      const tokens = usage?.context.tokens
583      await update($, turnStart, () => null)
584      await update($, turnLog, log => [
585        ...log.slice(-(TURN_LOG_SIZE - 1)),
586        {
587          n: (log[log.length - 1]?.n ?? 0) + 1,
588          durationMs: e.durationMs,
589          usd: usd !== undefined && start.usd !== null ? usd - start.usd : null,
590          tokens: tokens !== undefined && start.tokens !== null ? tokens - start.tokens : null,
591        },
592      ])
593    }
594    if (e.isAborted) return next(e)
595
596    if (config.notifyMs > 0 && e.durationMs >= config.notifyMs && e.reason === 'answer') {
597      $.ui.toast(m('turn.done', { d: formatDuration(e.durationMs) }))
598      // And by the person's own notification channel, for when they have looked away.
599      void $.ui.notify(m('turn.done', { d: formatDuration(e.durationMs) }), { title: 'Claude Code' }).catch(() => {})
600      if (config.hasChime) void $.audio.play({ base64: chimeWav(), mime: 'audio/wav' }).catch(() => {})
601    }
602    const count = await update($, turns, n => n + 1)
603    // While the model keeps a task list with work left, the list already says what it is doing
604    // (Claude Code draws it, and so do todo-bar and the todos line): no fork, and an older line steps aside.
605    const todos = live.transcriptPath ? transcriptData(live.transcriptPath)?.todos ?? [] : []
606    const hasPlan = todos.some(t => t.status !== 'completed')
607    if (hasPlan && (await read($, summary)) !== null) {
608      await update($, summary, () => null)
609      schedule()
610    }
611    if (config.summaryEvery > 0 && !hasPlan && !isSummarizing && (count === 1 || count % config.summaryEvery === 0)) {
612      isSummarizing = true
613      // Not awaited: the fork reads the conversation from the prompt cache while the person reads the answer.
614      void $.model
615        .fork({ prompt: summaryPrompt() })
616        .then(async reply => {
617          const line = reply.isAnswered ? cleanSummary(reply.text) : null
618          if (line) {
619            await update($, summary, () => line)
620            schedule()
621          }
622        })
623        .catch(() => {})
624        .finally(() => {
625          isSummarizing = false
626        })
627    }
628
629    return next(e)
630  })
631
632  const trackWidth = (columns: number | undefined) => {
633    if (columns && columns !== live.columns) {
634      live.columns = columns
635      schedule()
636    }
637  }
638
639  // A picker (`/` commands, `@` files) opens above the band: the band steps aside meanwhile.
640  on('prompt.edit', async ($, e, next) => {
641    const box = await next(e)
642    const isOpen = isPickerOpen(box.text, box.cursor)
643    if ((await read($, isPicking)) !== isOpen) await update($, isPicking, () => isOpen)
644    return box
645  })
646  // A change no key made (a history recall, a clear, a fill) opens or closes one too.
647  on('prompt.change', async ($, e, next) => {
648    const isOpen = isPickerOpen(e.text, e.cursor)
649    if ((await read($, isPicking)) !== isOpen) await update($, isPicking, () => isOpen)
650    return next(e)
651  })
652
653  // Above the prompt; on a remote surface too when the HUD sits below it, as the desktop
654  // app raises no PromptHint (nor does the phone or the editor).
655  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
656    if (config.position !== 'above' && e.surface === 'terminal') return next(e)
657    // Two cells in, as the engine indents the lines under the prompt. Below a terminal's
658    // prompt the terminal's width is the one the rows are fitted to.
659    if (config.position === 'above' || isHeadless) trackWidth(e.props.bodyColumns - 2)
660    if (e.props.hasSurvey || (await read($, isHidden)) || (await read($, isPicking))) return next(e)
661    // A remote surface draws in its own type: the readings as words, not the terminal's rows.
662    if (e.surface !== 'terminal') {
663      const shown = await read($, desk)
664      if (shown.gauges.length === 0 && shown.notes.length === 0) return next(e)
665      return drawDesk($.ui.resolve(e), shown, await next(e))
666    }
667    const rows = await read($, lines)
668    if (rows.length === 0) return next(e)
669
670    return drawRows($.ui.resolve(e), rows, await next(e), 2)
671  })
672
673  if (config.position === 'below') {
674    // Under the prompt, where the statusline sat: the HUD, then the engine's hint line.
675    on('ui.render', { component: 'PromptHint' }, async ($, e, next) => {
676      if (e.surface !== 'terminal') return next(e)
677      trackWidth(e.viewport?.columns)
678      const rows = await read($, lines)
679      if (rows.length === 0 || (await read($, isHidden))) {
680        return next(e)
681      }
682      const ui = $.ui.resolve(e)
683      const pet = (await read($, isPetDocked)) ? await read($, petDock) : null
684      if (!pet || !('Client' in ui)) return drawRows(ui, rows, await next(e))
685
686      const { Box } = ui
687      return (
688        <Box flexDirection="row">
689          <Box flexDirection="column" flexGrow={1} flexShrink={0}>
690            {drawRows(ui, rows, await next(e))}
691          </Box>
692          {drawPet(ui, pet, 'pet')}
693        </Box>
694      )
695    })
696  }
697
698  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
699    // Read so the pane redraws with the HUD: the transcript's agents and todos change with it.
700    await read($, lines)
701    const transcript = live.transcriptPath ? transcriptData(live.transcriptPath) : null
702    const now = await $.clock.now()
703    return drawPane($.ui.resolve(e), {
704      tools: await read($, tools),
705      turns: await read($, turnLog),
706      agents: transcript?.agents ?? [],
707      todos: transcript?.todos ?? [],
708      history: await read($, history),
709      today: localDay(now),
710      budgetUsd: config.budgetUsd,
711      now: Date.now(),
712    })
713  })
714}
715
hooks/shims/globals.ts 54 lines
1// The two Node globals claude-hud reaches for: `process` and `Buffer`.
2// Filled from the session at start (see register.tsx).
3export const processShim = {
4  env: {} as Record<string, string | undefined>,
5  platform: 'darwin',
6  pid: 0,
7  argv: ['node', 'claude-hud'] as string[],
8  execPath: '',
9  stdout: { columns: undefined as number | undefined, isTTY: false },
10  stderr: { columns: undefined as number | undefined, isTTY: false },
11  stdin: undefined,
12  cwdPath: '/',
13  cwd(): string {
14    return processShim.cwdPath
15  },
16}
17
18type ByteString = Uint8Array & { toString(encoding?: string): string }
19
20function withText(bytes: Uint8Array): ByteString {
21  const out = bytes as ByteString
22  out.toString = () => new TextDecoder().decode(bytes)
23  return out
24}
25
26const BufferShim = {
27  from(value: string | ArrayLike<number>): ByteString {
28    return withText(typeof value === 'string' ? new TextEncoder().encode(value) : Uint8Array.from(value))
29  },
30  alloc(size: number): ByteString {
31    return withText(new Uint8Array(size))
32  },
33  byteLength(value: string): number {
34    return new TextEncoder().encode(value).length
35  },
36  concat(list: Uint8Array[]): ByteString {
37    const out = new Uint8Array(list.reduce((n, c) => n + c.length, 0))
38    let at = 0
39    for (const c of list) {
40      out.set(c, at)
41      at += c.length
42    }
43    return withText(out)
44  },
45}
46
47const g = globalThis as Record<string, unknown>
48g.process = processShim
49g.Buffer = BufferShim
50if (typeof g.console === 'undefined') {
51  const quiet = () => {}
52  g.console = { log: quiet, error: quiet, warn: quiet, info: quiet, debug: quiet }
53}
54
hooks/config.ts 66 lines
1// hud's options (plugin.json `userConfig`), read once into a typed config.
2// The HUD's language and layout stay claude-hud's own config file's.
3import type { PluginOptions } from 'claude-code'
4
5import { parseThresholds } from './extras.js'
6import { count, flag, oneOf, text } from './kit/options.js'
7import { findTheme, THEMES, type Theme } from './themes.js'
8
9export type Config = {
10  isVisible: boolean
11  /** A HUD button in the prompt footer. */
12  hasFooterButton: boolean
13  position: 'above' | 'below'
14  theme: Theme
15  hasMascot: boolean
16  /** claude-hud's `--extra-cmd`. */
17  extraCmd: string
18  /** Registers `mcp__hud__hud_debug`. */
19  isDebug: boolean
20  /** A turn at least this long toasts when it ends; 0 is off. */
21  notifyMs: number
22  hasChime: boolean
23  contextAlerts: number[]
24  usageAlerts: number[]
25  hasForecast: boolean
26  budgetUsd: number
27  hasHistory: boolean
28  /** Summarize after the first turn and every this many; 0 is off. */
29  summaryEvery: number
30  /** Show the tokens left before auto-compaction from this percent of the way there; 0 is off. */
31  compactWarnPercent: number
32  /** Once the prompt cache has expired, show what the next message re-caches from this many context tokens; 0 is off. */
33  coldCacheTokens: number
34  /** Show the last turn's context growth once it reaches this many tokens; 0 off. */
35  turnGrowthTokens: number
36  gitDirtyWarn: number
37  gitAheadWarn: number
38  hasAgents: boolean
39}
40
41export function readConfig(options: PluginOptions): Config {
42  return {
43    isVisible: flag(options.visible, true),
44    hasFooterButton: flag(options.footerButton, true),
45    position: oneOf(options.position, ['above', 'below'], 'above'),
46    theme: findTheme(options.theme) ?? THEMES[0]!,
47    hasMascot: flag(options.showMascot, true),
48    extraCmd: text(options.extraCmd),
49    isDebug: flag(options.debug, false),
50    notifyMs: count(options.notifyAfterSeconds, 0, { min: 0 }) * 1000,
51    hasChime: flag(options.notifySound, true),
52    contextAlerts: parseThresholds(text(options.contextAlerts)),
53    usageAlerts: parseThresholds(text(options.usageAlerts)),
54    hasForecast: flag(options.showForecast, true),
55    budgetUsd: count(options.dailyBudgetUsd, 0, { min: 0 }),
56    hasHistory: flag(options.showHistory, false),
57    summaryEvery: count(options.summaryEveryTurns, 5, { min: 0, isInteger: true }),
58    compactWarnPercent: count(options.compactWarnPercent, 60, { min: 0 }),
59    coldCacheTokens: count(options.coldCacheTokens, 20_000, { min: 0, isInteger: true }),
60    turnGrowthTokens: count(options.turnGrowthTokens, 20_000, { min: 0, isInteger: true }),
61    gitDirtyWarn: count(options.gitDirtyWarn, 20, { min: 0 }),
62    gitAheadWarn: count(options.gitAheadWarn, 5, { min: 0 }),
63    hasAgents: flag(options.showAgents, false),
64  }
65}
66
hooks/draw.tsx 171 lines
1// The HUD's drawings, over the elements a render hook resolved: its rows
2// (above or below the prompt) and the `/hud detail` pane.
3import type { Elements, RenderElement } from 'claude-code'
4
5import type { Desk, DeskItem, HudLine, ToolStats, TurnCost } from '../types'
6import { formatDuration, lastDays, sparkline, streak } from './extras.js'
7import type { AgentEntry, TodoItem } from './hud/types.js'
8import { formatTokens } from './hud/utils/format.js'
9import { m, money } from './i18n.js'
10
11type Ui = Pick<Elements['terminal'], 'Box' | 'Text' | 'Link'>
12
13/** The HUD's rows over whatever the engine (or another mod) draws in the same place. */
14export function drawRows(ui: Ui, rows: HudLine[], rest: RenderElement, indent = 0): RenderElement {
15  const { Box, Text, Link } = ui
16
17  return (
18    <Box flexDirection="column">
19      {rows.map((row, i) => (
20        // A row of sibling Texts, not nested ones: a nested Text drops dimColor.
21        // claude-hud fits its own rows; the extras row wraps when it runs long.
22        <Box key={`l${i}`} flexDirection="row" flexWrap="wrap" paddingLeft={indent}>
23          {row.map((span, j) => {
24            const text = (
25              <Text
26                key={`s${j}`}
27                color={span.color}
28                backgroundColor={span.backgroundColor}
29                bold={span.bold}
30                dimColor={span.dimColor}
31                italic={span.italic}
32                underline={span.underline}
33                strikethrough={span.strikethrough}
34                inverse={span.inverse}
35              >
36                {span.text}
37              </Text>
38            )
39            // claude-hud's https links (a GitHub branch) stay clickable.
40            return span.href ? (
41              <Link key={`s${j}`} href={span.href}>
42                {text}
43              </Link>
44            ) : (
45              text
46            )
47          })}
48        </Box>
49      ))}
50      {rest}
51    </Box>
52  )
53}
54
55/**
56 * The HUD on a surface with a type of its own (the desktop app, a phone, an editor):
57 * small readings that wrap, a dim label before each value, the theme's warning colors.
58 */
59export function drawDesk(ui: Pick<Elements['terminal'], 'Box' | 'Text'>, desk: Desk, rest: RenderElement): RenderElement {
60  const { Box, Text } = ui
61  const item = (it: DeskItem, key: string) => (
62    <Box key={key} flexDirection="row" columnGap={1}>
63      {it.label ? <Text size="footnote" dimColor>{it.label}</Text> : null}
64      <Text
65        size="footnote"
66        tabular
67        weight={it.tone === undefined || it.isMuted ? 'regular' : 'medium'}
68        color={it.tone === 'bad' ? 'error' : it.tone === 'warn' ? 'warning' : undefined}
69        dimColor={it.isMuted === true && it.tone === undefined}
70      >
71        {it.value}
72      </Text>
73      {it.hint ? <Text size="footnote" dimColor>{it.hint}</Text> : null}
74    </Box>
75  )
76  const row = (items: DeskItem[], name: string) =>
77    items.length === 0 ? null : (
78      <Box key={name} flexDirection="row" flexWrap="wrap" columnGap="lg">
79        {items.map((it, i) => item(it, `${name}${i}`))}
80      </Box>
81    )
82  return (
83    <Box flexDirection="column">
84      {row(desk.gauges, 'g')}
85      {row(desk.notes, 'n')}
86      {rest}
87    </Box>
88  )
89}
90
91export type PaneData = {
92  tools: ToolStats
93  /** The last finished turns, oldest first. */
94  turns: readonly TurnCost[]
95  agents: readonly AgentEntry[]
96  todos: readonly TodoItem[]
97  /** Spend per day, `YYYY-MM-DD` → USD. */
98  history: Record<string, number>
99  today: string
100  budgetUsd: number
101  now: number
102}
103
104/** `/hud detail`: each tool's calls and time, the last turns, subagents, todos, and the spend. */
105export function drawPane(ui: Pick<Elements['terminal'], 'Box' | 'Text'>, data: PaneData): RenderElement {
106  const { Box, Text } = ui
107  const stats = Object.entries(data.tools).sort((a, b) => b[1].totalMs - a[1].totalMs)
108  const agents = data.agents.slice(-8)
109  const week = lastDays(data.history, data.today, 7)
110  const heading = (text: string) => <Text bold color="cyan">{text}</Text>
111  const todaySpent = money(data.history[data.today] ?? 0) + (data.budgetUsd > 0 ? `/${money(data.budgetUsd)}` : '')
112  const days7 = streak(data.history, data.today)
113  const spendLine = [
114    m('spend.today', { spent: todaySpent }),
115    `${m('spend.week', { spent: money(week.reduce((a, b) => a + b, 0)) })} ${sparkline(week)}`,
116    ...(days7 > 1 ? [m('streak', { n: days7 })] : []),
117  ].join(' · ')
118
119  return (
120    <Box flexDirection="column">
121      {heading(m('pane.tools'))}
122      {stats.length === 0 && <Text dimColor>{m('pane.noTools')}</Text>}
123      {stats.slice(0, 12).map(([name, s]) => (
124        <Box key={`t-${name}`} flexDirection="row" columnGap={1}>
125          <Text>{name}</Text>
126          <Text dimColor>
127            {m('pane.toolStats', { count: s.count, total: formatDuration(s.totalMs), avg: formatDuration(s.totalMs / s.count) })}
128          </Text>
129          {s.errors > 0 ? <Text color="red">{m('pane.failed', { n: s.errors })}</Text> : null}
130        </Box>
131      ))}
132      <Text> </Text>
133      {heading(m('pane.turns'))}
134      {data.turns.length === 0 && <Text dimColor>{m('pane.none')}</Text>}
135      {[...data.turns].reverse().map(t => (
136        <Text key={`turn-${t.n}`} dimColor>
137          {m('pane.turnRow', {
138            n: t.n,
139            time: formatDuration(t.durationMs),
140            cost: t.usd === null ? '—' : money(t.usd),
141            tokens: t.tokens === null ? '—' : `${t.tokens < 0 ? '−' : '+'}${formatTokens(Math.abs(t.tokens))}`,
142          })}
143        </Text>
144      ))}
145      <Text> </Text>
146      {heading(m('pane.agents'))}
147      {agents.length === 0 && <Text dimColor>{m('pane.none')}</Text>}
148      {agents.map(a => (
149        <Box key={`a-${a.id}`} flexDirection="row" columnGap={1}>
150          <Text color={a.status === 'running' ? 'yellow' : 'green'}>{a.status === 'running' ? '◐' : '✓'}</Text>
151          <Text>{a.type}</Text>
152          <Text dimColor wrap="truncate-end">
153            {a.description ?? ''} {formatDuration((a.endTime?.getTime() ?? data.now) - a.startTime.getTime())}
154          </Text>
155        </Box>
156      ))}
157      <Text> </Text>
158      {heading(m('pane.todos'))}
159      {data.todos.length === 0 && <Text dimColor>{m('pane.none')}</Text>}
160      {data.todos.map((t, i) => (
161        <Text key={`d-${i}`} dimColor={t.status === 'completed'} color={t.status === 'in_progress' ? 'yellow' : undefined}>
162          {t.status === 'completed' ? '☑' : t.status === 'in_progress' ? '◐' : '☐'} {t.content}
163        </Text>
164      ))}
165      <Text> </Text>
166      {heading(m('pane.spend'))}
167      <Text>{spendLine}</Text>
168    </Box>
169  )
170}
171
hooks/hud/stdin.ts 213 lines
1import type { StdinData, UsageData, TranscriptData } from './types.js';
2import type { ModelFormatMode } from './config.js';
3import { parseScopedWindows } from './external-usage.js';
4import { sanitizeTranscriptModel } from './model-source.js';
5import { sanitizeDisplayText } from './utils/sanitize.js';
6
7const NO_DATA_TIMEOUT_MS = 250;
8const MAX_STDIN_BYTES = 256 * 1024;
9
10type StdinStream = Pick<NodeJS.ReadStream, 'setEncoding' | 'on' | 'pause'> & { isTTY?: boolean };
11
12// Returns null for a TTY (setup's manual run), no input, oversized input, or invalid JSON.
13// Resolves as soon as the buffered text parses, in case the writer leaves stdin open.
14export function readStdin(stream: StdinStream = process.stdin): Promise<StdinData | null> {
15  if (stream.isTTY) {
16    return Promise.resolve(null);
17  }
18
19  return new Promise((resolve) => {
20    let raw = '';
21    let done = false;
22    const finish = (value: StdinData | null): void => {
23      if (done) return;
24      done = true;
25      clearTimeout(noDataTimer);
26      stream.pause();
27      resolve(value);
28    };
29    const parse = (): StdinData | null => {
30      try {
31        const value: unknown = JSON.parse(raw);
32        return value !== null && typeof value === 'object' ? value as StdinData : null;
33      } catch {
34        return null;
35      }
36    };
37    const noDataTimer = setTimeout(() => {
38      if (!raw) finish(null);
39    }, NO_DATA_TIMEOUT_MS);
40
41    stream.setEncoding('utf8');
42    stream.on('data', (chunk: string) => {
43      raw += chunk;
44      if (raw.length > MAX_STDIN_BYTES) {
45        finish(null);
46        return;
47      }
48      const parsed = parse();
49      if (parsed) finish(parsed);
50    });
51    stream.on('end', () => finish(parse()));
52    stream.on('error', () => finish(null));
53  });
54}
55
56export function getTotalTokens(stdin: StdinData): number {
57  const usage = stdin.context_window?.current_usage;
58  return (usage?.input_tokens ?? 0)
59    + (usage?.cache_creation_input_tokens ?? 0)
60    + (usage?.cache_read_input_tokens ?? 0);
61}
62
63export interface ContextUsage {
64  percent: number;
65  tokens: number;
66  size: number;
67}
68
69const toPercent = (value: number): number => Math.min(100, Math.max(0, Math.round(value)));
70
71// Claude Code's used_percentage when it reports one. It reads 0 or null before the
72// first response and after /compact, so fall back to current_usage, then to the
73// transcript's last known context size.
74export function getContextUsage(
75  stdin: StdinData,
76  autoCompactWindow?: number | null,
77  transcriptTokens?: number,
78): ContextUsage {
79  const live = getTotalTokens(stdin);
80  const tokens = live > 0 ? live : transcriptTokens ?? 0;
81  const window = stdin.context_window;
82  if (typeof autoCompactWindow === 'number' && autoCompactWindow > 0) {
83    return { percent: toPercent((tokens / autoCompactWindow) * 100), tokens, size: autoCompactWindow };
84  }
85
86  const size = window?.context_window_size ?? 0;
87  const native = window?.used_percentage;
88  if (typeof native === 'number' && Number.isFinite(native) && native > 0) {
89    return { percent: toPercent(native), tokens, size };
90  }
91  return { percent: size > 0 ? toPercent((tokens / size) * 100) : 0, tokens, size };
92}
93
94export function isContextUnreported(stdin: StdinData): boolean {
95  const native = stdin.context_window?.used_percentage;
96  return !(typeof native === 'number' && native > 0) && getTotalTokens(stdin) === 0;
97}
98
99export function getModelName(stdin: StdinData): string {
100  return stdin.model?.display_name?.trim() || stdin.model?.id?.trim() || 'Unknown';
101}
102
103function isClaudeModel(model: string): boolean {
104  const lower = model.toLowerCase();
105  return lower.startsWith('claude-') || lower.startsWith('anthropic.');
106}
107
108// display.modelSource: "stdin" shows what Claude Code requested, "transcript" what the
109// API served, and "auto" switches to the served model only when a proxy swapped in a
110// non-Claude model.
111export function resolveModelName(
112  stdin: StdinData,
113  transcript: TranscriptData | undefined,
114  modelSource: 'auto' | 'stdin' | 'transcript' = 'stdin',
115): string {
116  const stdinModel = getModelName(stdin);
117  const servedModel = sanitizeTranscriptModel(transcript?.lastAssistantModel);
118  if (modelSource === 'stdin' || !servedModel) {
119    return stdinModel;
120  }
121  if (modelSource === 'transcript') {
122    return servedModel;
123  }
124  return isClaudeModel(servedModel) ? stdinModel : servedModel;
125}
126
127export function isBedrockModelId(modelId?: string): boolean {
128  return modelId?.toLowerCase().includes('anthropic.claude-') ?? false;
129}
130
131// Vertex AI model IDs use '@' as the version separator (e.g. claude-3-5-sonnet@20241022).
132export function isVertexModelId(modelId?: string): boolean {
133  return modelId?.includes('@') ?? false;
134}
135
136const ENTERPRISE_MODEL_IDS = new Set(['opusplan', 'sonnetplan', 'haikuplan']);
137
138const MINIMAX_ANTHROPIC_ENDPOINTS = new Set([
139  'https://api.minimax.io/anthropic',
140  'https://api.minimaxi.com/anthropic',
141]);
142
143function isMiniMaxAnthropicEndpoint(env: NodeJS.ProcessEnv): boolean {
144  const baseUrl = env.ANTHROPIC_BASE_URL?.trim() || env.ANTHROPIC_API_BASE_URL?.trim();
145  if (!baseUrl) {
146    return false;
147  }
148  try {
149    const url = new URL(baseUrl);
150    return MINIMAX_ANTHROPIC_ENDPOINTS.has(`${url.origin}${url.pathname.replace(/\/+$/, '')}`);
151  } catch {
152    return false;
153  }
154}
155
156export function getProviderLabel(stdin: StdinData, env: NodeJS.ProcessEnv = process.env): string | null {
157  if (env.CLAUDE_CODE_USE_BEDROCK === '1') return 'Bedrock';
158  if (env.CLAUDE_CODE_USE_VERTEX === '1') return 'Vertex';
159  if (isMiniMaxAnthropicEndpoint(env)) return 'MiniMax';
160  if (ENTERPRISE_MODEL_IDS.has(stdin.model?.id?.toLowerCase() ?? '')) return 'Enterprise';
161  return null;
162}
163
164function parsePercent(value: unknown): number | null {
165  return typeof value === 'number' && Number.isFinite(value) ? toPercent(value) : null;
166}
167
168function parseResetAt(value: unknown): Date | null {
169  return typeof value === 'number' && Number.isFinite(value) && value > 0 ? new Date(value * 1000) : null;
170}
171
172export function getUsageFromStdin(stdin: StdinData): UsageData | null {
173  const limits = stdin.rate_limits;
174  const fiveHour = parsePercent(limits?.five_hour?.used_percentage);
175  const sevenDay = parsePercent(limits?.seven_day?.used_percentage);
176  if (fiveHour === null && sevenDay === null) {
177    return null;
178  }
179  // hud mod: the model-scoped windows come in with the stdin.
180  const scopedWindows = parseScopedWindows(stdin.model_scoped);
181  return {
182    fiveHour,
183    sevenDay,
184    fiveHourResetAt: parseResetAt(limits?.five_hour?.resets_at),
185    sevenDayResetAt: parseResetAt(limits?.seven_day?.resets_at),
186    ...(scopedWindows.length > 0 && { scopedWindows }),
187  };
188}
189
190// Free text from stdin (session names, output styles, versions) is shown in the terminal.
191export function stdinText(value: unknown, maxLength = 80): string | undefined {
192  if (typeof value !== 'string') {
193    return undefined;
194  }
195  return sanitizeDisplayText(value).trim().slice(0, maxLength) || undefined;
196}
197
198// Drops the "(1M context)" style suffix; the context bar already shows the window.
199export function stripContextSuffix(name: string): string {
200  return name.replace(/\s*\([^)]*\bcontext\b[^)]*\)/i, '').trim();
201}
202
203export function formatModelName(name: string, format?: ModelFormatMode, override?: string): string {
204  if (override) {
205    return override;
206  }
207  if (!format || format === 'full') {
208    return name;
209  }
210  const compact = stripContextSuffix(name);
211  return format === 'short' ? compact.replace(/^Claude\s+/i, '') : compact;
212}
213
hooks/extras.ts 426 lines
1// What the mod adds to claude-hud's lines: alerts, a usage forecast, today's
2// spend against a budget, the spend history, a git nag and the task summary.
3// Pure helpers; register.tsx feeds them from `$` and draws the row.
4import type { Desk, DeskItem, HudLine, TurnCost } from '../types'
5import { textWidth } from './hud/render/ansi.js'
6import { formatTokens } from './hud/utils/format.js'
7import { m, money } from './i18n.js'
8
9/** "80, 90" → [80, 90]: whole percents in 1-100, ascending; empty turns alerts off. */
10export function parseThresholds(spec: string): number[] {
11  const values = spec
12    .split(/[\s,]+/)
13    .map(s => Number.parseInt(s, 10))
14    .filter(n => Number.isFinite(n) && n >= 1 && n <= 100)
15  return [...new Set(values)].sort((a, b) => a - b)
16}
17
18// A threshold fires again only once the percent has dropped this far below it
19// (a /compact, a window reset), so the tick does not repeat a toast.
20const REARM_BELOW = 5
21
22/**
23 * The thresholds `percent` stands at or past, given those already fired; `alert`
24 * is the highest newly crossed one (null when none). Fired ones the percent
25 * dropped well below are re-armed.
26 */
27export function crossThresholds(
28  percent: number | null | undefined,
29  thresholds: number[],
30  fired: number[],
31): { alert: number | null; fired: number[] } {
32  if (percent === null || percent === undefined || !Number.isFinite(percent)) return { alert: null, fired }
33  const kept = fired.filter(t => percent >= t - REARM_BELOW)
34  const fresh = thresholds.filter(t => percent >= t && !kept.includes(t))
35  return { alert: fresh.length > 0 ? fresh[fresh.length - 1]! : null, fired: [...kept, ...fresh].sort((a, b) => a - b) }
36}
37
38// Below this much usage a linear projection is noise; claude-hud's pace uses the same floor.
39const MIN_USED_PERCENT = 10
40
41/**
42 * When a rate-limit window runs out at the rate used so far (ms), or null when
43 * it lasts until its reset (or the data cannot say).
44 */
45export function exhaustAt(
46  percent: number | null | undefined,
47  resetsAtSec: number | null | undefined,
48  windowMs: number,
49  now: number,
50): number | null {
51  if (percent === null || percent === undefined || !resetsAtSec || percent < MIN_USED_PERCENT) return null
52  if (percent >= 100) return now
53  const resetsAt = resetsAtSec * 1000
54  const elapsed = windowMs - (resetsAt - now)
55  if (elapsed <= 0 || resetsAt <= now) return null
56  const at = now + ((100 - percent) / percent) * elapsed
57  return at < resetsAt ? at : null
58}
59
60/** Readings of one rate-limit window: `[ms, percent]`, oldest first, for the window that resets at `resetsAt`. */
61export type Samples = { resetsAt: number; points: [number, number][] }
62
63/** How far back the recent pace looks, and the least span it needs to mean anything. */
64const PACE_LOOKBACK_MS = 60 * 60_000
65const PACE_MIN_SPAN_MS = 10 * 60_000
66
67/** `samples` with a reading at `now` added: a new window starts over, readings past the lookback leave. */
68export function addSample(samples: Samples | undefined, percent: number, resetsAtSec: number, now: number): Samples {
69  const resetsAt = resetsAtSec * 1000
70  const kept = samples && samples.resetsAt === resetsAt ? samples.points.filter(([t]) => now - t <= PACE_LOOKBACK_MS) : []
71  return { resetsAt, points: [...kept, [now, percent]] }
72}
73
74/**
75 * When a window runs out at the pace of the last hour (ms), or null when that
76 * pace lasts until the reset. With under ten minutes of readings, the pace
77 * since the window began (exhaustAt) stands in.
78 */
79export function paceAt(samples: Samples | undefined, percent: number | null | undefined, resetsAtSec: number | null | undefined, windowMs: number, now: number): number | null {
80  const first = samples?.points[0]
81  if (!samples || !first || !resetsAtSec || samples.resetsAt !== resetsAtSec * 1000 || now - first[0] < PACE_MIN_SPAN_MS) {
82    return exhaustAt(percent, resetsAtSec, windowMs, now)
83  }
84  if (percent === null || percent === undefined || percent < MIN_USED_PERCENT) return null
85  if (percent >= 100) return now
86  const rate = (percent - first[1]) / (now - first[0])
87  if (rate <= 0) return null
88  const at = now + (100 - percent) / rate
89  return at < samples.resetsAt ? at : null
90}
91
92const pad = (n: number) => String(n).padStart(2, '0')
93
94/** "14:05" in the machine's time zone. */
95export function clockTime(ms: number): string {
96  const d = new Date(ms)
97  return `${pad(d.getHours())}:${pad(d.getMinutes())}`
98}
99
100/** "2026-10-02" in the machine's time zone. */
101export function localDay(ms: number): string {
102  const d = new Date(ms)
103  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
104}
105
106/** The day `n` days after `day` (negative: before). */
107export function addDays(day: string, n: number): string {
108  const [y, m, d] = day.split('-').map(Number)
109  return localDay(new Date(y!, m! - 1, d! + n, 12).getTime())
110}
111
112/** "45s", "2m05s", "1h03m". */
113export function formatDuration(ms: number): string {
114  const s = Math.max(0, Math.round(ms / 1000))
115  if (s < 60) return `${s}s`
116  if (s < 3600) return `${Math.floor(s / 60)}m${pad(s % 60)}s`
117  return `${Math.floor(s / 3600)}h${pad(Math.floor((s % 3600) / 60))}m`
118}
119
120const BLOCKS = '▁▂▃▄▅▆▇█'
121
122/** One block per value, scaled to the largest; a zero is the lowest block. */
123export function sparkline(values: number[]): string {
124  const max = Math.max(0, ...values)
125  return values
126    .map(v => (max <= 0 || v <= 0 ? BLOCKS[0] : BLOCKS[Math.min(7, Math.max(1, Math.round((v / max) * 7)))]))
127    .join('')
128}
129
130/** The last turn's context growth and the recent turns', once the last grew it by at least `min` tokens. */
131export function growthOf(log: readonly TurnCost[], min: number): { last: number; recent: number[] } | null {
132  const last = log[log.length - 1]?.tokens ?? null
133  if (min <= 0 || last === null || last < min) return null
134  return { last, recent: log.map(t => Math.max(0, t.tokens ?? 0)) }
135}
136
137/** Spend per day, `YYYY-MM-DD` → USD. */
138export type History = Record<string, number>
139
140/** The last `days` days' spend, oldest first, ending today. */
141export function lastDays(history: History, today: string, days: number): number[] {
142  return Array.from({ length: days }, (_, i) => history[addDays(today, i - days + 1)] ?? 0)
143}
144
145/** Consecutive days with spend, ending today (or yesterday, before today's first spend). */
146export function streak(history: History, today: string): number {
147  let day = (history[today] ?? 0) > 0 ? today : addDays(today, -1)
148  let count = 0
149  while ((history[day] ?? 0) > 0) {
150    count++
151    day = addDays(day, -1)
152  }
153  return count
154}
155
156/** Days older than `keepDays` before today leave the history. */
157export function pruneHistory(history: History, today: string, keepDays: number): History {
158  const oldest = addDays(today, -keepDays)
159  return Object.fromEntries(Object.entries(history).filter(([day]) => day > oldest))
160}
161
162/**
163 * `git status --porcelain=v2 --branch` (lines, or `-z` records) → changed paths
164 * and commits ahead of upstream.
165 */
166export function parseGitStatus(stdout: string): { dirty: number; ahead: number } {
167  const isZ = stdout.includes('\0')
168  const records = stdout.split(isZ ? '\0' : '\n')
169  let dirty = 0
170  let ahead = 0
171  for (let i = 0; i < records.length; i++) {
172    const record = records[i]!
173    if (!record) continue
174    if (record.startsWith('#')) {
175      const ab = /^# branch\.ab \+(\d+) -\d+/.exec(record)
176      if (ab) ahead = Number(ab[1])
177    } else {
178      dirty++
179      // Under -z a rename or copy is followed by its original path, a record of its own.
180      if (isZ && record.startsWith('2 ')) i++
181    }
182  }
183  return { dirty, ahead }
184}
185
186/** "Today $3.20/$10.00 ▓▓▓░░░░░", red once past the budget, yellow from 80%. */
187export function budgetSpans(todayUsd: number, budgetUsd: number, width = 8): HudLine {
188  const ratio = budgetUsd > 0 ? todayUsd / budgetUsd : 0
189  const filled = Math.min(width, Math.round(ratio * width))
190  const color = ratio >= 1 ? 'red' : ratio >= 0.8 ? 'yellow' : 'green'
191  const spans: HudLine = [{ text: `${m('spend.today', { spent: `${money(todayUsd)}/${money(budgetUsd)}` })} `, dimColor: ratio < 0.8 }]
192  if (filled > 0) spans.push({ text: '▓'.repeat(filled), color })
193  if (filled < width) spans.push({ text: '░'.repeat(width - filled), dimColor: true })
194  return spans
195}
196
197export type ExtrasInput = {
198  summary: string | null
199  /** Rate-limit windows that run out before they reset: label and when. */
200  exhaust: { label: string; at: number }[]
201  todayUsd: number | null
202  budgetUsd: number
203  /** The last 7 days' spend, oldest first, and the streak; null hides the history. */
204  week: { values: number[]; streak: number } | null
205  git: { dirty: number; ahead: number } | null
206  /** Tokens left before auto-compaction runs, once the context is far enough in; null hides it. */
207  compactLeft?: number | null
208  /** The context tokens the next message writes to the cache again, once it has expired; null hides it. */
209  coldCache?: number | null
210  /** How far the last turn grew the context, and the recent turns' growth, oldest first; null hides it. */
211  growth?: { last: number; recent: number[] } | null
212  gitDirtyWarn: number
213  gitAheadWarn: number
214  /** The row's width; parts that do not fit leave it, least important first. */
215  columns?: number
216  /** The theme's glyphs and colors for the row; claude-hud's look when absent. */
217  style?: ExtrasStyle
218  /** The theme mascot's face, first in the row. */
219  mascot?: string | null
220}
221
222export type ExtrasStyle = {
223  summary?: string
224  warning?: string
225  summaryColor?: string
226  forecastColor?: string
227  weekColor?: string
228  warningColor?: string
229  mascotColor?: string
230}
231
232const SEPARATOR = ' │ '
233
234const lineWidth = (spans: HudLine) => spans.reduce((sum, span) => sum + textWidth(span.text), 0)
235
236/** The row under claude-hud's lines; empty when there is nothing to say. */
237export function extrasLine(x: ExtrasInput): HudLine {
238  // Kept in display order; `rank` is what goes last when the row is too wide.
239  const parts: { spans: HudLine; rank: number }[] = []
240  const style = x.style ?? {}
241  if (x.mascot) parts.push({ spans: [{ text: x.mascot, color: style.mascotColor ?? style.summaryColor ?? 'cyan', bold: true }], rank: -1 })
242  if (x.summary) parts.push({ spans: [{ text: `${style.summary ?? '✎'} ${x.summary}`, color: style.summaryColor ?? 'cyan' }], rank: 3 })
243  for (const { label, at } of x.exhaust) {
244    parts.push({ spans: [{ text: m('forecast', { label, time: clockTime(at) }), color: style.forecastColor ?? 'magenta' }], rank: 2 })
245  }
246  if (typeof x.compactLeft === 'number') {
247    parts.push({ spans: [{ text: m('compact.left', { tokens: formatTokens(Math.max(0, x.compactLeft)) }), color: style.forecastColor ?? 'magenta' }], rank: 2 })
248  }
249  if (typeof x.coldCache === 'number') {
250    parts.push({ spans: [{ text: m('cache.cold', { tokens: formatTokens(x.coldCache) }), color: style.warningColor ?? 'yellow' }], rank: 2 })
251  }
252  if (x.growth) {
253    const color = style.forecastColor ?? 'magenta'
254    parts.push({
255      spans: [
256        { text: `${m('turn.growth', { tokens: formatTokens(x.growth.last) })} `, color },
257        { text: sparkline(x.growth.recent), color },
258      ],
259      rank: 1,
260    })
261  }
262  if (x.budgetUsd > 0 && x.todayUsd !== null) parts.push({ spans: budgetSpans(x.todayUsd, x.budgetUsd), rank: 1 })
263  if (x.week && x.week.values.some(v => v > 0)) {
264    parts.push({
265      spans: [
266        { text: `${m('week')} `, dimColor: true },
267        { text: sparkline(x.week.values), color: style.weekColor ?? 'blue' },
268        ...(x.week.streak > 1 ? [{ text: ` ${m('streak', { n: x.week.streak })}`, dimColor: true }] : []),
269      ],
270      rank: 0,
271    })
272  }
273  const nags: string[] = []
274  if (x.git && x.gitDirtyWarn > 0 && x.git.dirty >= x.gitDirtyWarn) nags.push(m('git.dirty', { n: x.git.dirty }))
275  if (x.git && x.gitAheadWarn > 0 && x.git.ahead >= x.gitAheadWarn) nags.push(m('git.ahead', { n: x.git.ahead }))
276  if (nags.length > 0) parts.push({ spans: [{ text: `${style.warning ?? '⚠'} ${nags.join(' · ')}`, color: style.warningColor ?? 'yellow' }], rank: 4 })
277
278  const join = (kept: typeof parts) =>
279    kept.flatMap((part, i) => (i === 0 ? part.spans : [{ text: SEPARATOR, dimColor: true }, ...part.spans]))
280  const kept = [...parts]
281  while (x.columns && kept.length > 1 && lineWidth(join(kept)) > x.columns) {
282    const lowest = Math.min(...kept.map(p => p.rank))
283    kept.splice(kept.findIndex(p => p.rank === lowest), 1)
284  }
285  return join(kept)
286}
287
288/** claude-hud's ` │ ` and ` | ` between elements, dimmed like the extras row's. */
289export function dimSeparators(row: HudLine): HudLine {
290  return row.flatMap(span => {
291    if (span.dimColor || !/ [│|] /.test(span.text)) return [span]
292    return span.text
293      .split(/( [│|] )/)
294      .flatMap((text, i) => (!text ? [] : i % 2 === 1 ? [{ text, dimColor: true }] : [{ ...span, text }]))
295  })
296}
297
298/**
299 * claude-hud's short rows packed side by side where they fit in `columns`: it merges
300 * only its merge groups, and those with the usage bars, so a terminal of 100 columns
301 * got the context, the limits and the cache a row each. The first row stays alone.
302 */
303export function packRows(rows: HudLine[], columns: number | undefined): HudLine[] {
304  if (!columns) return rows
305  const packed: HudLine[] = []
306  for (const [i, row] of rows.entries()) {
307    const last = packed[packed.length - 1]
308    if (i > 1 && last && lineWidth(last) + textWidth(SEPARATOR) + lineWidth(row) <= columns) {
309      packed[packed.length - 1] = [...last, { text: SEPARATOR, dimColor: true }, ...row]
310    } else {
311      packed.push(row)
312    }
313  }
314  return packed
315}
316
317/** The extras row joins claude-hud's last row when both fit in `columns`, else goes under it. */
318export function appendExtras(rows: HudLine[], extra: HudLine, columns: number | undefined): HudLine[] {
319  if (extra.length === 0) return rows
320  const last = rows[rows.length - 1]
321  if (last && columns && lineWidth(last) + textWidth(SEPARATOR) + lineWidth(extra) <= columns) {
322    return [...rows.slice(0, -1), [...last, { text: SEPARATOR, dimColor: true }, ...extra]]
323  }
324  return [...rows, extra]
325}
326
327const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
328
329function base64(bytes: Uint8Array): string {
330  let out = ''
331  for (let i = 0; i < bytes.length; i += 3) {
332    const [a, b = 0, c = 0] = [bytes[i]!, bytes[i + 1], bytes[i + 2]]
333    const n = (a << 16) | (b << 8) | c
334    out += B64[(n >> 18) & 63]! + B64[(n >> 12) & 63]!
335    out += i + 1 < bytes.length ? B64[(n >> 6) & 63]! : '='
336    out += i + 2 < bytes.length ? B64[n & 63]! : '='
337  }
338  return out
339}
340
341let chime: string | null = null
342
343/** A short two-note chime, as a base64 16-bit mono WAV: the turn-done sound. */
344export function chimeWav(): string {
345  if (chime) return chime
346  const rate = 22_050
347  const notes = [
348    { hz: 880, ms: 110 },
349    { hz: 1320, ms: 170 },
350  ]
351  const samples = notes.flatMap(({ hz, ms }) => {
352    const count = Math.round((rate * ms) / 1000)
353    return Array.from({ length: count }, (_, i) => {
354      const fade = Math.min(1, i / 200, (count - i) / 600)
355      return Math.round(Math.sin((2 * Math.PI * hz * i) / rate) * fade * 0.35 * 32767)
356    })
357  })
358  const data = samples.length * 2
359  const buf = new DataView(new ArrayBuffer(44 + data))
360  const text = (at: number, s: string) => [...s].forEach((ch, i) => buf.setUint8(at + i, ch.charCodeAt(0)))
361  text(0, 'RIFF')
362  buf.setUint32(4, 36 + data, true)
363  text(8, 'WAVE')
364  text(12, 'fmt ')
365  buf.setUint32(16, 16, true)
366  buf.setUint16(20, 1, true)
367  buf.setUint16(22, 1, true)
368  buf.setUint32(24, rate, true)
369  buf.setUint32(28, rate * 2, true)
370  buf.setUint16(32, 2, true)
371  buf.setUint16(34, 16, true)
372  text(36, 'data')
373  buf.setUint32(40, data, true)
374  samples.forEach((s, i) => buf.setInt16(44 + i * 2, s, true))
375  chime = base64(new Uint8Array(buf.buffer))
376  return chime
377}
378
379export type DeskInput = ExtrasInput & {
380  /** The context's size and use; null leaves it to the surface (the desktop's side panel). */
381  context: { tokens: number; size: number; percent: number } | null
382  /** Each usage window: its label, how much is used, when it resets (ms). */
383  limits: { label: string; percent: number; resetsAt: number | null }[]
384  /** When the warm prompt cache expires (ms), and how early to warn; null when cold or unknown. */
385  cache: { until: number; warnMs: number } | null
386  durationMs: number | null
387  now: number
388}
389
390const toneOf = (percent: number): DeskItem['tone'] => (percent >= 90 ? 'bad' : percent >= 75 ? 'warn' : undefined)
391
392/**
393 * The HUD for a surface that draws in a proportional face (the desktop app, a
394 * phone, an editor): readings as words, no bars, sparklines or padded columns,
395 * and nothing the desktop already shows (model, effort, project, branch, tools).
396 */
397export function deskOf(x: DeskInput): Desk {
398  const gauges: DeskItem[] = []
399  if (x.context) {
400    const { tokens, size, percent } = x.context
401    gauges.push({ label: m('desk.context'), value: `${formatTokens(tokens)}/${formatTokens(size)}`, hint: `${Math.round(percent)}%`, tone: toneOf(percent) })
402  }
403  for (const w of x.limits) {
404    const left = w.resetsAt !== null && w.resetsAt > x.now ? m('desk.resets', { d: formatDuration(w.resetsAt - x.now) }) : undefined
405    gauges.push({ label: w.label, value: `${Math.round(w.percent)}%`, hint: left, tone: toneOf(w.percent) })
406  }
407  if (x.cache && x.cache.until > x.now) {
408    gauges.push({ value: m('desk.cache', { time: clockTime(x.cache.until) }), tone: x.cache.until - x.now <= x.cache.warnMs ? 'warn' : undefined, isMuted: true })
409  }
410  if (x.durationMs !== null && x.durationMs > 0) gauges.push({ value: `⏱ ${formatDuration(x.durationMs)}`, isMuted: true })
411
412  const notes: DeskItem[] = []
413  if (x.summary) notes.push({ value: `✎ ${x.summary}`, isMuted: true })
414  for (const { label, at } of x.exhaust) notes.push({ value: m('forecast', { label, time: clockTime(at) }), tone: 'warn' })
415  if (typeof x.compactLeft === 'number') notes.push({ value: m('compact.left', { tokens: formatTokens(Math.max(0, x.compactLeft)) }), tone: 'warn' })
416  if (typeof x.coldCache === 'number') notes.push({ value: m('cache.cold', { tokens: formatTokens(x.coldCache) }), tone: 'warn' })
417  if (x.growth) notes.push({ value: m('turn.growth', { tokens: formatTokens(x.growth.last) }), isMuted: true })
418  if (x.budgetUsd > 0 && x.todayUsd !== null) {
419    const ratio = x.todayUsd / x.budgetUsd
420    notes.push({ value: m('spend.today', { spent: `${money(x.todayUsd)}/${money(x.budgetUsd)}` }), tone: ratio >= 1 ? 'bad' : ratio >= 0.8 ? 'warn' : undefined, isMuted: ratio < 0.8 })
421  }
422  if (x.git && x.gitDirtyWarn > 0 && x.git.dirty >= x.gitDirtyWarn) notes.push({ value: `⚠ ${m('git.dirty', { n: x.git.dirty })}`, tone: 'warn' })
423  if (x.git && x.gitAheadWarn > 0 && x.git.ahead >= x.gitAheadWarn) notes.push({ value: `⚠ ${m('git.ahead', { n: x.git.ahead })}`, tone: 'warn' })
424  return { gauges, notes }
425}
426
hooks/hud/config.ts 546 lines
1import * as fs from '../shims/fs.js';
2import * as path from '../shims/path.js';
3import * as os from '../shims/os.js';
4import { expandHomeDirPrefix, getClaudeConfigDir, getHudPluginDir } from './claude-config-dir.js';
5import { createDebug } from './debug.js';
6import type { Language } from './i18n/types.js';
7import { MAX_TERMINAL_WIDTH } from './utils/terminal.js';
8import { sanitizeDisplayText } from './utils/sanitize.js';
9
10const debug = createDebug('config');
11const MAX_CONFIG_FILE_BYTES = 64 * 1024;
12const MAX_CONFIG_NESTING_DEPTH = 8;
13const UNSAFE_CONFIG_KEYS = new Set(['__proto__', 'prototype', 'constructor']);
14
15const LANGUAGES = ['en', 'zh', 'zh-Hans', 'zh-Hant', 'zh-TW', 'ja', 'ko', 'es', 'fr', 'de', 'pt', 'pt-BR', 'ru'] as const satisfies readonly Language[];
16const LINE_LAYOUTS = ['compact', 'expanded'] as const;
17const PATH_LEVELS = [1, 2, 3, 'full'] as const;
18const CONTEXT_VALUE_MODES = ['percent', 'tokens', 'remaining', 'both'] as const;
19const USAGE_VALUE_MODES = ['percent', 'remaining'] as const;
20const GIT_BRANCH_OVERFLOW_MODES = ['truncate', 'wrap'] as const;
21// full: display name as-is; compact: drop the context-window suffix; short: also drop "Claude ".
22const MODEL_FORMATS = ['full', 'compact', 'short'] as const;
23const MODEL_SOURCES = ['auto', 'stdin', 'transcript'] as const;
24const EFFORT_FORMATS = ['full', 'symbol', 'text'] as const;
25const TIME_FORMATS = ['relative', 'absolute', 'both', 'elapsed', 'elapsedAndAbsolute'] as const;
26const HOUR_CYCLES = ['auto', 'h11', 'h12', 'h23', 'h24'] as const;
27const CUSTOM_LINE_POSITIONS = ['first', 'last'] as const;
28const ADDED_DIRS_LAYOUTS = ['inline', 'line'] as const;
29const COLOR_NAMES = ['dim', 'red', 'green', 'yellow', 'magenta', 'cyan', 'brightBlue', 'brightMagenta'] as const;
30
31const ELEMENTS = [
32  'project',
33  'addedDirs',
34  'context',
35  'usage',
36  'promptCache',
37  'cacheHitRate',
38  'memory',
39  'environment',
40  'tools',
41  'skills',
42  'mcp',
43  'agents',
44  'todos',
45  'sessionTime',
46] as const;
47
48// Orderable segments of the first line, shared by the expanded and compact layouts.
49const FIRST_LINE_SEGMENTS = [
50  'model',
51  'project',
52  'advisor',
53  'sessionName',
54  'version',
55  'extra',
56  'duration',
57  'cost',
58  'speed',
59  'auth',
60] as const;
61
62export type LineLayoutType = typeof LINE_LAYOUTS[number];
63export type PathLevels = typeof PATH_LEVELS[number];
64export type ContextValueMode = typeof CONTEXT_VALUE_MODES[number];
65export type UsageValueMode = typeof USAGE_VALUE_MODES[number];
66export type GitBranchOverflowMode = typeof GIT_BRANCH_OVERFLOW_MODES[number];
67export type ModelFormatMode = typeof MODEL_FORMATS[number];
68export type EffortFormatMode = typeof EFFORT_FORMATS[number];
69export type TimeFormatMode = typeof TIME_FORMATS[number];
70export type HourCycleMode = typeof HOUR_CYCLES[number];
71export type CustomLinePosition = typeof CUSTOM_LINE_POSITIONS[number];
72export type AddedDirsLayout = typeof ADDED_DIRS_LAYOUTS[number];
73export type HudColorName = typeof COLOR_NAMES[number];
74export type HudElement = typeof ELEMENTS[number];
75export type FirstLineSegment = typeof FIRST_LINE_SEGMENTS[number];
76
77/** A named preset, a 256-color index (0-255), or a #rrggbb hex string. */
78export type HudColorValue = HudColorName | number | string;
79
80export interface HudColorOverrides {
81  context: HudColorValue;
82  usage: HudColorValue;
83  warning: HudColorValue;
84  usageWarning: HudColorValue;
85  critical: HudColorValue;
86  model: HudColorValue;
87  project: HudColorValue;
88  git: HudColorValue;
89  gitBranch: HudColorValue;
90  label: HudColorValue;
91  custom: HudColorValue;
92  barFilled: string;
93  barEmpty: string;
94}
95
96export const DEFAULT_ELEMENT_ORDER: HudElement[] = [...ELEMENTS];
97export const DEFAULT_MERGE_GROUPS: HudElement[][] = [['context', 'usage']];
98// Empty keeps each renderer's native order until the user moves a segment.
99export const DEFAULT_PROJECT_LINE_ORDER: FirstLineSegment[] = [];
100
101export interface HudConfig {
102  language: Language;
103  lineLayout: LineLayoutType;
104  showSeparators: boolean;
105  pathLevels: PathLevels;
106  maxWidth: number | null;
107  forceMaxWidth: boolean;
108  elementOrder: HudElement[];
109  projectLineOrder: FirstLineSegment[];
110  gitStatus: {
111    enabled: boolean;
112    showDirty: boolean;
113    showAheadBehind: boolean;
114    showFileStats: boolean;
115    showWorktree: boolean;
116    branchOverflow: GitBranchOverflowMode;
117    pushWarningThreshold: number;
118    pushCriticalThreshold: number;
119  };
120  jjStatus: {
121    enabled: boolean;
122    showDirty: boolean;
123    showConflicts: boolean;
124  };
125  display: {
126    showModel: boolean;
127    showProject: boolean;
128    showAddedDirs: boolean;
129    addedDirsLayout: AddedDirsLayout;
130    showContextBar: boolean;
131    contextValue: ContextValueMode;
132    showConfigCounts: boolean;
133    showCost: boolean;
134    // Also show cost for routed providers (Bedrock/Vertex), which showCost hides.
135    showRoutedCost: boolean;
136    showDailyCost: boolean;
137    showWeeklyCost: boolean;
138    showDuration: boolean;
139    showSpeed: boolean;
140    showTokenBreakdown: boolean;
141    showUsage: boolean;
142    usageValue: UsageValueMode;
143    usageBarEnabled: boolean;
144    showResetLabel: boolean;
145    usageCompact: boolean;
146    showModelScopedUsage: boolean;
147    usagePace: boolean;
148    showTools: boolean;
149    showSkills: boolean;
150    showMcp: boolean;
151    toolNameMaxLength: number;
152    toolsMaxVisible: number;
153    skillsMaxVisible: number;
154    showAgents: boolean;
155    showTodos: boolean;
156    showSessionName: boolean;
157    showAuth: boolean;
158    showAuthUser: boolean;
159    // Max characters of the account name (0 = full).
160    authUserLength: number;
161    showClaudeCodeVersion: boolean;
162    showEffortLevel: boolean;
163    effortFormat: EffortFormatMode;
164    showMemoryUsage: boolean;
165    showPromptCache: boolean;
166    showCacheHitRate: boolean;
167    showSessionTokens: boolean;
168    showOutputStyle: boolean;
169    showSessionStartDate: boolean;
170    showLastResponseAt: boolean;
171    showCompactions: boolean;
172    mergeGroups: HudElement[][];
173    // Elements pushed to the right edge of a merged line, when it fits and the width is known.
174    rightAlign: HudElement[];
175    contextWarningThreshold: number;
176    contextCriticalThreshold: number;
177    usageThreshold: number;
178    sevenDayThreshold: number;
179    environmentThreshold: number;
180    externalUsagePath: string;
181    externalUsageWritePath: string;
182    externalUsageFreshnessMs: number;
183    modelFormat: ModelFormatMode;
184    modelOverride: string;
185    // auto: transcript model for non-Claude (proxied) models; stdin/transcript: always that source.
186    modelSource: typeof MODEL_SOURCES[number];
187    showProvider: boolean;
188    providerName: string;
189    customLine: string;
190    customLinePosition: CustomLinePosition;
191    timeFormat: TimeFormatMode;
192    hourCycle: HourCycleMode;
193    showClockSeconds: boolean;
194    showAdvisor: boolean;
195    advisorOverride: string;
196    autoCompactWindow: number | null;
197  };
198  colors: HudColorOverrides;
199}
200
201export const DEFAULT_CONFIG: HudConfig = {
202  language: 'en',
203  lineLayout: 'expanded',
204  showSeparators: false,
205  pathLevels: 1,
206  maxWidth: null,
207  forceMaxWidth: false,
208  elementOrder: [...DEFAULT_ELEMENT_ORDER],
209  projectLineOrder: [...DEFAULT_PROJECT_LINE_ORDER],
210  gitStatus: {
211    enabled: true,
212    showDirty: true,
213    showAheadBehind: false,
214    showFileStats: false,
215    showWorktree: false,
216    branchOverflow: 'truncate',
217    pushWarningThreshold: 0,
218    pushCriticalThreshold: 0,
219  },
220  jjStatus: {
221    enabled: false,
222    showDirty: true,
223    showConflicts: true,
224  },
225  display: {
226    showModel: true,
227    showProject: true,
228    showAddedDirs: true,
229    addedDirsLayout: 'inline',
230    showContextBar: true,
231    contextValue: 'percent',
232    showConfigCounts: false,
233    showCost: false,
234    showRoutedCost: false,
235    showDailyCost: false,
236    showWeeklyCost: false,
237    showDuration: false,
238    showSpeed: false,
239    showTokenBreakdown: true,
240    showUsage: true,
241    usageValue: 'percent',
242    usageBarEnabled: true,
243    showResetLabel: true,
244    usageCompact: false,
245    showModelScopedUsage: true,
246    usagePace: false,
247    showTools: false,
248    showSkills: false,
249    showMcp: false,
250    toolNameMaxLength: 0,
251    toolsMaxVisible: 4,
252    skillsMaxVisible: 4,
253    showAgents: false,
254    showTodos: false,
255    showSessionName: false,
256    showAuth: false,
257    showAuthUser: false,
258    authUserLength: 8,
259    showClaudeCodeVersion: false,
260    showEffortLevel: false,
261    effortFormat: 'full',
262    showMemoryUsage: false,
263    showPromptCache: false,
264    showCacheHitRate: false,
265    showSessionTokens: false,
266    showOutputStyle: false,
267    showSessionStartDate: false,
268    showLastResponseAt: false,
269    showCompactions: false,
270    mergeGroups: DEFAULT_MERGE_GROUPS.map(group => [...group]),
271    rightAlign: [],
272    contextWarningThreshold: 70,
273    contextCriticalThreshold: 85,
274    usageThreshold: 0,
275    sevenDayThreshold: 80,
276    environmentThreshold: 0,
277    externalUsagePath: '',
278    externalUsageWritePath: '',
279    externalUsageFreshnessMs: 300000,
280    modelFormat: 'full',
281    modelOverride: '',
282    modelSource: 'stdin',
283    showProvider: false,
284    providerName: '',
285    customLine: '',
286    customLinePosition: 'last',
287    timeFormat: 'relative',
288    hourCycle: 'auto',
289    showClockSeconds: false,
290    showAdvisor: false,
291    advisorOverride: '',
292    autoCompactWindow: null,
293  },
294  colors: {
295    context: 'green',
296    usage: 'brightBlue',
297    warning: 'yellow',
298    usageWarning: 'brightMagenta',
299    critical: 'red',
300    model: 'cyan',
301    project: 'yellow',
302    git: 'magenta',
303    gitBranch: 'cyan',
304    label: 'dim',
305    custom: 208,
306    barFilled: '█',
307    barEmpty: '░',
308  },
309};
310
311export function getConfigPath(): string {
312  return path.join(getHudPluginDir(os.homedir()), 'config.json');
313}
314
315// Lives outside plugins/, which users often symlink across several CLAUDE_CONFIG_DIRs,
316// so it stays per-directory and can override the shared config.
317export function getConfigOverridePath(): string {
318  return path.join(getClaudeConfigDir(os.homedir()), 'claude-hud.json');
319}
320
321// A rule maps a raw user value to a valid one, or to the fallback (the default).
322type Rule = (value: unknown, fallback: any) => unknown;
323
324const isNumber = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value);
325
326const oneOf = (allowed: readonly unknown[]): Rule => (value, fallback) => (
327  allowed.includes(value) ? value : fallback
328);
329const clamp = (min: number, max: number): Rule => (value, fallback) => (
330  isNumber(value) ? Math.max(min, Math.min(max, value)) : fallback
331);
332const floorAtLeastZero: Rule = (value, fallback) => (isNumber(value) ? Math.max(0, Math.floor(value)) : fallback);
333const count: Rule = (value, fallback) => (Number.isInteger(value) && (value as number) >= 0 ? value : fallback);
334const text = (maxLength: number): Rule => (value, fallback) => (
335  typeof value === 'string' ? sanitizeDisplayText(value).slice(0, maxLength) : fallback
336);
337
338// Keeps known names once each, in order. An empty result falls back only when `nonEmpty`.
339const names = (known: readonly unknown[], nonEmpty: boolean): Rule => (value, fallback) => {
340  if (!Array.isArray(value)) return fallback;
341  const kept = [...new Set(value.filter(item => known.includes(item)))];
342  return kept.length > 0 || !nonEmpty ? kept : fallback;
343};
344
345// Groups need two or more known elements, and an element joins at most one group.
346const mergeGroups: Rule = (value, fallback) => {
347  if (!Array.isArray(value)) return fallback;
348  if (value.length === 0) return [];
349  const used = new Set<unknown>();
350  const groups: unknown[][] = [];
351  for (const group of value) {
352    if (!Array.isArray(group)) continue;
353    const members = [...new Set(group.filter(item => (ELEMENTS as readonly unknown[]).includes(item) && !used.has(item)))];
354    if (members.length < 2) continue;
355    members.forEach(member => used.add(member));
356    groups.push(members);
357  }
358  return groups.length > 0 ? groups : fallback;
359};
360
361const HEX_COLOR = /^#[0-9a-fA-F]{6}$/;
362const color: Rule = (value, fallback) => (
363  COLOR_NAMES.includes(value as HudColorName)
364  || (Number.isInteger(value) && (value as number) >= 0 && (value as number) <= 255)
365  || (typeof value === 'string' && HEX_COLOR.test(value))
366    ? value
367    : fallback
368);
369
370// Exactly one visible grapheme: no controls, format, variation, separator, or unassigned code points.
371const INVISIBLE_CODEPOINT = /[\p{Cc}\p{Cf}\p{Variation_Selector}\p{Zl}\p{Zp}\p{Cn}]/u;
372const barChar: Rule = (value, fallback) => {
373  if (typeof value !== 'string' || value.length === 0) return fallback;
374  const graphemes = [...new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(value)];
375  return graphemes.length === 1 && !INVISIBLE_CODEPOINT.test(value) ? value : fallback;
376};
377
378// Expands a leading ~ and ${VAR}; unset variables are left as written.
379const usagePath: Rule = (value) => (
380  typeof value === 'string'
381    ? expandHomeDirPrefix(value.trim(), os.homedir())
382      .replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (match, name: string) => process.env[name] ?? match)
383    : ''
384);
385
386// Booleans need no rule: a default of type boolean accepts only booleans.
387const RULES: Record<string, Rule> = {
388  'language': oneOf(LANGUAGES),
389  'lineLayout': oneOf(LINE_LAYOUTS),
390  'pathLevels': oneOf(PATH_LEVELS),
391  'maxWidth': (value) => (isNumber(value) && value > 0 ? Math.min(Math.floor(value), MAX_TERMINAL_WIDTH) : null),
392  'elementOrder': names(ELEMENTS, true),
393  'projectLineOrder': names(FIRST_LINE_SEGMENTS, false),
394  'gitStatus.branchOverflow': oneOf(GIT_BRANCH_OVERFLOW_MODES),
395  'gitStatus.pushWarningThreshold': floorAtLeastZero,
396  'gitStatus.pushCriticalThreshold': floorAtLeastZero,
397  'display.addedDirsLayout': oneOf(ADDED_DIRS_LAYOUTS),
398  'display.contextValue': oneOf(CONTEXT_VALUE_MODES),
399  'display.usageValue': oneOf(USAGE_VALUE_MODES),
400  'display.toolNameMaxLength': count,
401  'display.toolsMaxVisible': count,
402  'display.skillsMaxVisible': count,
403  'display.authUserLength': count,
404  'display.effortFormat': oneOf(EFFORT_FORMATS),
405  'display.mergeGroups': mergeGroups,
406  'display.rightAlign': names(ELEMENTS, false),
407  'display.contextWarningThreshold': clamp(0, 100),
408  'display.contextCriticalThreshold': clamp(0, 100),
409  'display.usageThreshold': clamp(0, 100),
410  'display.sevenDayThreshold': clamp(0, 100),
411  'display.environmentThreshold': clamp(0, 100),
412  'display.externalUsagePath': usagePath,
413  'display.externalUsageWritePath': usagePath,
414  'display.externalUsageFreshnessMs': floorAtLeastZero,
415  'display.modelFormat': oneOf(MODEL_FORMATS),
416  'display.modelOverride': text(80),
417  'display.modelSource': oneOf(MODEL_SOURCES),
418  'display.providerName': text(40),
419  'display.customLine': text(80),
420  'display.customLinePosition': oneOf(CUSTOM_LINE_POSITIONS),
421  'display.timeFormat': oneOf(TIME_FORMATS),
422  'display.hourCycle': oneOf(HOUR_CYCLES),
423  'display.advisorOverride': text(80),
424  'display.autoCompactWindow': (value) => (Number.isInteger(value) && (value as number) > 0 ? value : null),
425  'colors.barFilled': barChar,
426  'colors.barEmpty': barChar,
427  'colors.*': color,
428};
429
430function isPlainObject(value: unknown): value is Record<string, unknown> {
431  return typeof value === 'object' && value !== null && !Array.isArray(value);
432}
433
434// Walks the defaults, so unknown user keys are dropped and every key is validated.
435function normalize(defaults: Record<string, unknown>, input: unknown, prefix = ''): Record<string, unknown> {
436  const source = isPlainObject(input) ? input : {};
437  const result: Record<string, unknown> = {};
438  for (const [key, fallback] of Object.entries(defaults)) {
439    const keyPath = prefix + key;
440    const rule = RULES[keyPath] ?? RULES[`${prefix}*`];
441    const value = source[key];
442    if (rule) {
443      result[key] = rule(value, fallback);
444    } else if (isPlainObject(fallback)) {
445      result[key] = normalize(fallback, value, `${keyPath}.`);
446    } else {
447      result[key] = typeof fallback === 'boolean' && typeof value === 'boolean' ? value : fallback;
448    }
449  }
450  return result;
451}
452
453// v0.0.x wrote `layout: "default" | "separators"`; some third-party tools write an object.
454function migrateLegacyLayout(config: Record<string, unknown>): Record<string, unknown> {
455  if (!('layout' in config) || 'lineLayout' in config) return config;
456  const { layout, ...rest } = config;
457  if (typeof layout === 'string') {
458    return { ...rest, lineLayout: 'compact', showSeparators: layout === 'separators' };
459  }
460  if (isPlainObject(layout)) {
461    const { lineLayout, showSeparators, pathLevels } = layout;
462    return {
463      ...rest,
464      ...(typeof lineLayout === 'string' && { lineLayout }),
465      ...(typeof showSeparators === 'boolean' && { showSeparators }),
466      ...((typeof pathLevels === 'number' || pathLevels === 'full') && { pathLevels }),
467    };
468  }
469  return rest;
470}
471
472export function mergeConfig(userConfig: Partial<HudConfig>): HudConfig {
473  const migrated = migrateLegacyLayout(userConfig as Record<string, unknown>);
474  const defaults = structuredClone(DEFAULT_CONFIG) as unknown as Record<string, unknown>;
475  return normalize(defaults, migrated) as unknown as HudConfig;
476}
477
478function hasSafeConfigShape(value: unknown, depth = 0): boolean {
479  if (depth > MAX_CONFIG_NESTING_DEPTH) return false;
480  if (Array.isArray(value)) return value.every(item => hasSafeConfigShape(item, depth + 1));
481  if (!isPlainObject(value)) return true;
482  return Object.entries(value).every(([key, child]) => (
483    !UNSAFE_CONFIG_KEYS.has(key) && hasSafeConfigShape(child, depth + 1)
484  ));
485}
486
487// Sections merge key by key; arrays and scalars replace the base value.
488function mergeOverrides(base: Record<string, unknown>, override: Record<string, unknown>): Record<string, unknown> {
489  const result = Object.assign(Object.create(null), base) as Record<string, unknown>;
490  for (const [key, value] of Object.entries(override)) {
491    const current = result[key];
492    result[key] = isPlainObject(current) && isPlainObject(value) ? mergeOverrides(current, value) : value;
493  }
494  return result;
495}
496
497// Checks and reads through one descriptor so a swapped or growing file can't slip past either guard.
498function readConfigFile(configPath: string): Record<string, unknown> | null {
499  try {
500    // O_NOFOLLOW rejects symlinks on POSIX; it is undefined on Windows.
501    const fd = fs.openSync(configPath, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
502    try {
503      if (!fs.fstatSync(fd).isFile()) {
504        debug('Ignoring %s: not a regular file', configPath);
505        return null;
506      }
507      // hud mod: one bounded whole read; O_NOFOLLOW becomes an lstat check.
508      if (fs.lstatSync(configPath).isSymbolicLink()) {
509        debug('Ignoring %s: not a regular file', configPath);
510        return null;
511      }
512      const content = fs.readFileSync(fd, 'utf-8');
513      if (new TextEncoder().encode(content).length > MAX_CONFIG_FILE_BYTES) {
514        debug('Ignoring %s: larger than %d bytes', configPath, MAX_CONFIG_FILE_BYTES);
515        return null;
516      }
517      const parsed: unknown = JSON.parse(content);
518      if (!isPlainObject(parsed) || !hasSafeConfigShape(parsed)) {
519        debug('Ignoring %s: not a bounded JSON object without unsafe keys', configPath);
520        return null;
521      }
522      return parsed;
523    } finally {
524      fs.closeSync(fd);
525    }
526  } catch (err) {
527    if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {
528      debug('Ignoring %s:', configPath, err instanceof Error ? err.message : err);
529    }
530    return null;
531  }
532}
533
534// The mod's own options laid over the loaded config (the mod, not upstream).
535let configPatch: (config: HudConfig) => HudConfig = (config) => config;
536
537export function setConfigPatch(patch: (config: HudConfig) => HudConfig): void {
538  configPatch = patch;
539}
540
541export async function loadConfig(): Promise<HudConfig> {
542  const base = readConfigFile(getConfigPath()) ?? {};
543  const override = readConfigFile(getConfigOverridePath());
544  return configPatch(mergeConfig((override ? mergeOverrides(base, override) : base) as Partial<HudConfig>));
545}
546
hooks/hud/i18n/index.ts 77 lines
1import type { Language, MessageKey, Messages } from "./types.js";
2import { en } from "./en.js";
3import { zhHans } from "./zh-Hans.js";
4import { zhHant } from "./zh-Hant.js";
5import { ja } from "./ja.js";
6import { ko } from "./ko.js";
7import { es } from "./es.js";
8import { fr } from "./fr.js";
9import { de } from "./de.js";
10import { ptBR } from "./pt-BR.js";
11import { ru } from "./ru.js";
12
13export type { Language, MessageKey, Messages };
14
15export type CanonicalLanguage = "en" | "zh-Hans" | "zh-Hant" | "ja" | "ko" | "es" | "fr" | "de" | "pt-BR" | "ru";
16
17const locales: Record<CanonicalLanguage, Messages> = {
18  en,
19  "zh-Hans": zhHans,
20  "zh-Hant": zhHant,
21  ja,
22  ko,
23  es,
24  fr,
25  de,
26  "pt-BR": ptBR,
27  ru,
28};
29
30// Resolve short language tags to canonical BCP 47 forms.
31// Based on CLDR likely subtags: zh → zh-Hans-CN
32// https://www.unicode.org/cldr/charts/latest/supplemental/likely_subtags.html
33const CANONICAL: Record<Language, CanonicalLanguage> = {
34  "en": "en",
35  "zh": "zh-Hans",
36  "zh-Hans": "zh-Hans",
37  "zh-Hant": "zh-Hant",
38  "zh-TW": "zh-Hant",
39  "ja": "ja",
40  "ko": "ko",
41  "es": "es",
42  "fr": "fr",
43  "de": "de",
44  "pt": "pt-BR",
45  "pt-BR": "pt-BR",
46  "ru": "ru",
47};
48
49let currentLanguage: Language = "en";
50
51export function setLanguage(lang: Language): void {
52  currentLanguage = lang;
53}
54
55// https://www.rfc-editor.org/info/bcp47
56export function getCanonicalLanguage(): CanonicalLanguage {
57  return CANONICAL[currentLanguage] ?? "en";
58}
59
60// https://www.unicode.org/reports/tr11/
61export function isCjkLanguage(): boolean {
62  const canon = getCanonicalLanguage();
63  return canon === "zh-Hans" || canon === "zh-Hant" || canon === "ja" || canon === "ko";
64}
65
66export function t(key: MessageKey): string {
67  const canon = getCanonicalLanguage();
68  return locales[canon]?.[key] ?? locales.en[key] ?? key;
69}
70
71// Minimal named-placeholder interpolation. Layout that varies by language
72// (spacing, affix position) lives in each locale's pattern string rather than in
73// render code. Unknown placeholders render as empty string (kept lenient).
74export function interpolate(pattern: string, params: Record<string, string | number>): string {
75  return pattern.replace(/\{(\w+)\}/g, (_, k) => String(params[k] ?? ""));
76}
77
hooks/hud/transcript.ts 391 lines
1import * as fs from '../shims/fs.js';
2import * as readline from '../shims/readline.js';
3import { createDebug } from './debug.js';
4import type { AgentEntry, SessionTokenUsage, TodoItem, ToolEntry, TranscriptData } from './types.js';
5import { sanitizeDisplayText } from './utils/sanitize.js';
6import { sanitizeTranscriptModel } from './model-source.js';
7
8const debug = createDebug('transcript');
9
10const TOOLS_KEPT = 20;
11const AGENTS_KEPT = 10;
12const NAME_MAX_LEN = 64;
13const ADVISOR_MODEL_MAX_LEN = 64;
14const MESSAGE_ID_MAX_LEN = 128;
15const MESSAGE_IDS_MAX = 4096;
16const MCP_ERRORS_MAX = 64;
17const MCP_TOOL = /^mcp__(.+?)__(.+)$/;
18// Claude Code's /effort output; anchored so prose quoting it can't flip ultracode.
19const EFFORT_COMMAND = /^<local-command-stdout>Set effort level to (\w+)/;
20
21interface Usage {
22  input_tokens?: unknown;
23  output_tokens?: unknown;
24  cache_creation_input_tokens?: unknown;
25  cache_read_input_tokens?: unknown;
26}
27
28interface Block {
29  type?: string;
30  id?: string;
31  name?: string;
32  input?: Record<string, unknown>;
33  tool_use_id?: string;
34  is_error?: boolean;
35}
36
37interface Entry {
38  type?: string;
39  subtype?: string;
40  operation?: string;
41  content?: unknown;
42  timestamp?: string;
43  isSidechain?: boolean;
44  advisorModel?: unknown;
45  message?: { id?: unknown; model?: unknown; content?: Block[] | string; usage?: Usage };
46  toolUseResult?: { resolvedModel?: unknown; isAsync?: unknown; status?: unknown };
47  compactMetadata?: { postTokens?: unknown };
48  attachment?: { type?: string };
49}
50
51const emptyTranscript = (): TranscriptData => ({ tools: [], skills: [], mcpServers: [], mcpErrors: [], agents: [], todos: [] });
52
53const ZERO_USAGE: SessionTokenUsage = { inputTokens: 0, outputTokens: 0, cacheCreationTokens: 0, cacheReadTokens: 0 };
54const USAGE_FIELDS = Object.keys(ZERO_USAGE) as (keyof SessionTokenUsage)[];
55
56const count = (value: unknown): number =>
57  typeof value === 'number' && Number.isFinite(value) ? Math.max(0, Math.trunc(value)) : 0;
58
59function addUsage(total: SessionTokenUsage, usage: SessionTokenUsage): void {
60  for (const field of USAGE_FIELDS) total[field] += usage[field];
61}
62
63function name(value: unknown): string | undefined {
64  if (typeof value !== 'string') return undefined;
65  const text = sanitizeDisplayText(value).trim();
66  if (!text) return undefined;
67  return text.length <= NAME_MAX_LEN ? text : `${text.slice(0, NAME_MAX_LEN - 1)}…`;
68}
69
70const mcpServer = (toolName: string): string | undefined => name(MCP_TOOL.exec(toolName)?.[1]);
71
72// Tool inputs are written by the model, so their text is untrusted terminal input.
73const text = (value: unknown): string | undefined =>
74  typeof value === 'string' ? sanitizeDisplayText(value) || undefined : undefined;
75
76function toolTarget(toolName: string, input: Record<string, unknown> | undefined): string | undefined {
77  if (!input) return undefined;
78  switch (toolName) {
79    case 'Read':
80    case 'Write':
81    case 'Edit':
82      return text(input.file_path ?? input.path);
83    case 'Glob':
84    case 'Grep':
85      return text(input.pattern);
86    case 'Skill':
87      return name(input.skill);
88    case 'Bash': {
89      const command = text(input.command)?.replace(/\s+/g, ' ').trim();
90      if (!command) return undefined;
91      return command.length > 30 ? `${command.slice(0, 30).trimEnd()}...` : command;
92    }
93  }
94  return undefined;
95}
96
97function taskStatus(status: unknown): TodoItem['status'] | null {
98  switch (status) {
99    case 'pending':
100    case 'not_started':
101      return 'pending';
102    case 'in_progress':
103    case 'running':
104      return 'in_progress';
105    case 'completed':
106    case 'complete':
107    case 'done':
108      return 'completed';
109    default:
110      return null;
111  }
112}
113
114function toTodo(value: unknown): TodoItem[] {
115  const todo = value as { content?: unknown; status?: unknown } | null;
116  const content = text(todo?.content);
117  const status = taskStatus(todo?.status);
118  return content && status ? [{ content, status }] : [];
119}
120
121export class Parser {
122  private tools = new Map<string, ToolEntry>();
123  private agents = new Map<string, AgentEntry>();
124  private skills = new Set<string>();
125  private mcpServers = new Set<string>();
126  private mcpErrors = new Set<string>();
127  private todos: TodoItem[] = [];
128  private taskIndex = new Map<string, number>();
129  // hud mod: Claude Code logs an assistant message again after its tool results, so a
130  // tool_use seen twice would be marked running again (and a TaskCreate counted twice).
131  private seenToolUses = new Set<string>();
132  private agentCompletions = new Map<string, Date>();
133  // Claude Code logs one API response several times, sometimes non-adjacently, so usage
134  // is the per-field max per message id. Ids evicted to bound memory settle into `settled`.
135  private usageById = new Map<string, SessionTokenUsage>();
136  private settled: SessionTokenUsage = { ...ZERO_USAGE };
137  private lastIdlessUsage: string | undefined;
138  private data: TranscriptData = { ...emptyTranscript(), compactionCount: 0 };
139
140  line(raw: string): void {
141    let entry: Entry | null = null;
142    try {
143      entry = raw.trim() ? JSON.parse(raw) : null;
144    } catch {
145      // Malformed lines are skipped.
146    }
147    if (!entry || typeof entry !== 'object') {
148      this.lastIdlessUsage = undefined;
149      return;
150    }
151
152    const time = entry.timestamp ? new Date(entry.timestamp) : null;
153    const at = time && !Number.isNaN(time.getTime()) ? time : null;
154    if (at && !this.data.sessionStart) this.data.sessionStart = at;
155
156    if (entry.type === 'assistant') {
157      this.assistant(entry, at);
158    } else {
159      this.lastIdlessUsage = undefined;
160    }
161    if (entry.type === 'user' && typeof entry.message?.content === 'string') {
162      const effort = EFFORT_COMMAND.exec(entry.message.content);
163      if (effort) this.data.ultracodeActive = effort[1].toLowerCase() === 'ultracode';
164    }
165    if (entry.type === 'attachment') {
166      if (entry.attachment?.type === 'ultra_effort_enter') this.data.ultracodeActive = true;
167      if (entry.attachment?.type === 'ultra_effort_exit') this.data.ultracodeActive = false;
168    }
169    if (entry.type === 'system' && entry.subtype === 'compact_boundary' && at) {
170      this.data.compactionCount = (this.data.compactionCount ?? 0) + 1;
171      const post = entry.compactMetadata?.postTokens;
172      this.data.contextTokens = typeof post === 'number' && Number.isFinite(post) && post >= 0 ? Math.trunc(post) : undefined;
173    }
174    // A background agent's tool_result lands at launch; its completion is this enqueue.
175    if (entry.type === 'queue-operation' && entry.operation === 'enqueue' && typeof entry.content === 'string' && at) {
176      const toolUseId = /<tool-use-id>([^<]+)<\/tool-use-id>/.exec(entry.content)?.[1];
177      if (toolUseId && /<task-id>[^<]+<\/task-id>/.test(entry.content)) this.agentCompletions.set(toolUseId, at);
178    }
179
180    if (Array.isArray(entry.message?.content)) {
181      for (const block of entry.message.content) {
182        if (block?.type === 'tool_use' && block.id && block.name) this.toolUse(block, at ?? new Date());
183        if (block?.type === 'tool_result' && block.tool_use_id) this.toolResult(block, entry, at ?? new Date());
184      }
185    }
186  }
187
188  private assistant(entry: Entry, at: Date | null): void {
189    if (at) this.data.lastAssistantResponseAt = at;
190    if (typeof entry.advisorModel === 'string' && entry.advisorModel) {
191      this.data.advisorModel = entry.advisorModel.slice(0, ADVISOR_MODEL_MAX_LEN);
192    }
193    const model = sanitizeTranscriptModel(entry.message?.model);
194    // Claude Code writes '<synthetic>' on assistant records it generates locally.
195    if (model && model !== '<synthetic>') this.data.lastAssistantModel = model;
196
197    const raw = entry.message?.usage;
198    if (!raw) {
199      this.lastIdlessUsage = undefined;
200      return;
201    }
202    const usage: SessionTokenUsage = {
203      inputTokens: count(raw.input_tokens),
204      outputTokens: count(raw.output_tokens),
205      cacheCreationTokens: count(raw.cache_creation_input_tokens),
206      cacheReadTokens: count(raw.cache_read_input_tokens),
207    };
208    if (entry.isSidechain !== true) {
209      this.data.contextTokens = usage.inputTokens + usage.cacheCreationTokens + usage.cacheReadTokens;
210    }
211
212    const id = entry.message?.id;
213    if (typeof id === 'string' && id && id.length <= MESSAGE_ID_MAX_LEN) {
214      this.lastIdlessUsage = undefined;
215      const previous = this.usageById.get(id);
216      this.usageById.set(id, previous ? maxUsage(previous, usage) : usage);
217      if (this.usageById.size > MESSAGE_IDS_MAX) {
218        const [oldestId, oldest] = this.usageById.entries().next().value as [string, SessionTokenUsage];
219        this.usageById.delete(oldestId);
220        addUsage(this.settled, oldest);
221      }
222      return;
223    }
224    // Without an id, only an identical record right after the previous one is a duplicate.
225    const fingerprint = JSON.stringify(usage);
226    if (fingerprint !== this.lastIdlessUsage) addUsage(this.settled, usage);
227    this.lastIdlessUsage = fingerprint;
228  }
229
230  private toolUse(block: Block, at: Date): void {
231    if (this.seenToolUses.has(block.id as string)) return;
232    this.seenToolUses.add(block.id as string);
233    const toolName = block.name as string;
234    const input = block.input;
235    const skill = toolName === 'Skill' ? name(input?.skill) : undefined;
236    if (skill) this.skills.add(skill);
237    const server = mcpServer(toolName);
238    if (server) this.mcpServers.add(server);
239
240    if (toolName === 'Task' || toolName === 'Agent') {
241      this.agents.set(block.id as string, {
242        id: block.id as string,
243        type: (input?.subagent_type as string) ?? 'agent',
244        model: sanitizeTranscriptModel(input?.model),
245        description: (input?.description as string) ?? undefined,
246        status: 'running',
247        startTime: at,
248        background: input?.run_in_background === true,
249      });
250    } else if (toolName === 'TodoWrite') {
251      if (Array.isArray(input?.todos)) this.replaceTodos(input.todos.flatMap(toTodo));
252    } else if (toolName === 'TaskCreate') {
253      const content = text(input?.subject) ?? text(input?.description);
254      this.todos.push({ content: content ?? 'Untitled task', status: taskStatus(input?.status) ?? 'pending' });
255      const taskId = typeof input?.taskId === 'string' || typeof input?.taskId === 'number' ? String(input.taskId) : block.id;
256      if (taskId) this.taskIndex.set(taskId, this.todos.length - 1);
257    } else if (toolName === 'TaskUpdate') {
258      const todo = this.todos[this.findTask(input?.taskId) ?? -1];
259      if (!todo) return;
260      const status = taskStatus(input?.status);
261      if (status) todo.status = status;
262      const content = text(input?.subject) ?? text(input?.description);
263      if (content) todo.content = content;
264    } else {
265      this.tools.set(block.id as string, {
266        id: block.id as string,
267        name: toolName,
268        target: toolTarget(toolName, input),
269        status: 'running',
270        startTime: at,
271      });
272    }
273  }
274
275  private toolResult(block: Block, entry: Entry, at: Date): void {
276    const id = block.tool_use_id as string;
277    const tool = this.tools.get(id);
278    if (tool) {
279      tool.status = block.is_error ? 'error' : 'completed';
280      tool.endTime = at;
281      const server = mcpServer(tool.name);
282      if (server && block.is_error) {
283        this.mcpErrors.add(server);
284        if (this.mcpErrors.size > MCP_ERRORS_MAX) this.mcpErrors.delete(this.mcpErrors.values().next().value as string);
285      } else if (server) {
286        this.mcpErrors.delete(server);
287      }
288    }
289
290    const agent = this.agents.get(id);
291    if (agent) {
292      // resolvedModel is what the subagent actually ran on, so it beats the caller's alias.
293      agent.model = sanitizeTranscriptModel(entry.toolUseResult?.resolvedModel) ?? agent.model;
294      if (entry.toolUseResult?.isAsync === true || entry.toolUseResult?.status === 'async_launched') {
295        agent.background = true;
296      }
297      if (!agent.background) agent.endTime = at;
298    }
299  }
300
301  // TodoWrite replaces the list; TaskCreate ids follow their todo by content, in order,
302  // so duplicate-content todos each keep their own id.
303  private replaceTodos(next: TodoItem[]): void {
304    const idsByContent = new Map<string, string[]>();
305    for (const [taskId, index] of [...this.taskIndex].sort((a, b) => a[1] - b[1])) {
306      const content = this.todos[index]?.content;
307      if (content === undefined) continue;
308      idsByContent.set(content, [...(idsByContent.get(content) ?? []), taskId]);
309    }
310    this.todos = [...next];
311    this.taskIndex.clear();
312    this.todos.forEach((todo, index) => {
313      const taskId = idsByContent.get(todo.content)?.shift();
314      if (taskId) this.taskIndex.set(taskId, index);
315    });
316  }
317
318  // TaskUpdate names a task by the id TaskCreate returned, or by its 1-based position.
319  private findTask(taskId: unknown): number | null {
320    if (typeof taskId !== 'string' && typeof taskId !== 'number') return null;
321    const key = String(taskId);
322    const mapped = this.taskIndex.get(key);
323    if (mapped !== undefined) return mapped;
324    const position = /^\d+$/.test(key) ? Number(key) - 1 : -1;
325    return position >= 0 && position < this.todos.length ? position : null;
326  }
327
328  finish(): TranscriptData {
329    for (const [id, endTime] of this.agentCompletions) {
330      const agent = this.agents.get(id);
331      if (agent?.background) agent.endTime = endTime;
332    }
333    for (const agent of this.agents.values()) {
334      if (agent.endTime) agent.status = 'completed';
335    }
336    const sessionTokens = { ...this.settled };
337    for (const usage of this.usageById.values()) addUsage(sessionTokens, usage);
338    return {
339      ...this.data,
340      tools: [...this.tools.values()].slice(-TOOLS_KEPT),
341      agents: [...this.agents.values()].slice(-AGENTS_KEPT),
342      skills: [...this.skills],
343      mcpServers: [...this.mcpServers],
344      mcpErrors: [...this.mcpErrors],
345      todos: this.todos,
346      sessionTokens,
347    };
348  }
349}
350
351function maxUsage(a: SessionTokenUsage, b: SessionTokenUsage): SessionTokenUsage {
352  return {
353    inputTokens: Math.max(a.inputTokens, b.inputTokens),
354    outputTokens: Math.max(a.outputTokens, b.outputTokens),
355    cacheCreationTokens: Math.max(a.cacheCreationTokens, b.cacheCreationTokens),
356    cacheReadTokens: Math.max(a.cacheReadTokens, b.cacheReadTokens),
357  };
358}
359
360// hud mod: the mod parses the transcript incrementally (only appended lines,
361// one Parser kept per transcript) and answers here; the stream read below
362// stays as upstream wrote it for when no provider is set.
363let transcriptProvider: ((transcriptPath: string) => Promise<TranscriptData | null>) | null = null;
364
365export function setTranscriptProvider(provider: (transcriptPath: string) => Promise<TranscriptData | null>): void {
366  transcriptProvider = provider;
367}
368
369export async function parseTranscript(transcriptPath: string): Promise<TranscriptData> {
370  if (transcriptProvider) {
371    const provided = await transcriptProvider(transcriptPath);
372    if (provided) return provided;
373  }
374  try {
375    if (!transcriptPath || !fs.statSync(transcriptPath).isFile()) return emptyTranscript();
376  } catch {
377    return emptyTranscript();
378  }
379  const parser = new Parser();
380  try {
381    const input = fs.createReadStream(transcriptPath);
382    for await (const raw of readline.createInterface({ input, crlfDelay: Infinity })) {
383      parser.line(raw);
384    }
385  } catch (err) {
386    // A read cut short still renders what was parsed.
387    debug('Transcript read failed:', err instanceof Error ? err.message : err);
388  }
389  return parser.finish();
390}
391
hooks/hud/types.ts 203 lines
1import type { HudConfig } from './config.js';
2import type { GitRepoIdentity, GitStatus } from './git.js';
3import type { AuthInfo } from './auth.js';
4import type { CostTotals } from './daily-cost.js';
5
6// The statusline payload Claude Code writes to stdin (code.claude.com/docs/en/statusline).
7export interface StdinData {
8  session_id?: string;
9  session_name?: string;
10  version?: string;
11  transcript_path?: string;
12  cwd?: string;
13  workspace?: {
14    current_dir?: string;
15    project_dir?: string;
16    added_dirs?: string[];
17    git_worktree?: string;
18    repo?: GitRepoIdentity;
19  } | null;
20  model?: {
21    id?: string;
22    display_name?: string;
23  };
24  output_style?: { name?: string };
25  context_window?: {
26    context_window_size?: number;
27    total_input_tokens?: number | null;
28    total_output_tokens?: number | null;
29    current_usage?: {
30      input_tokens?: number;
31      output_tokens?: number;
32      cache_creation_input_tokens?: number;
33      cache_read_input_tokens?: number;
34    } | null;
35    used_percentage?: number | null;
36    remaining_percentage?: number | null;
37  };
38  cost?: {
39    total_cost_usd?: number | null;
40    total_duration_ms?: number | null;
41    total_api_duration_ms?: number | null;
42    total_lines_added?: number | null;
43    total_lines_removed?: number | null;
44  } | null;
45  rate_limits?: {
46    five_hour?: RateLimitWindow | null;
47    seven_day?: RateLimitWindow | null;
48    spend_limit?: RateLimitWindow | null;
49  } | null;
50  // hud mod: the model-scoped weekly windows (e.g. Fable), as the external snapshot's model_scoped.
51  model_scoped?: ExternalUsageSnapshot['model_scoped'];
52  prompt_cache?: {
53    warm?: boolean;
54    caching_observed?: boolean;
55    ttl?: string;
56    expires_at?: number | null;
57    hit_ratio?: number | null;
58  } | null;
59  effort?: { level?: string } | null;
60  worktree?: { name?: string; path?: string; branch?: string } | null;
61}
62
63interface RateLimitWindow {
64  used_percentage?: number | null;
65  resets_at?: number | null;
66}
67
68export interface ToolEntry {
69  id: string;
70  name: string;
71  target?: string;
72  status: 'running' | 'completed' | 'error';
73  startTime: Date;
74  endTime?: Date;
75}
76
77export interface AgentEntry {
78  id: string;
79  type: string;
80  model?: string;
81  description?: string;
82  status: 'running' | 'completed';
83  startTime: Date;
84  endTime?: Date;
85  background?: boolean;
86}
87
88export interface TodoItem {
89  content: string;
90  status: 'pending' | 'in_progress' | 'completed';
91}
92
93export interface UsageData {
94  fiveHour: number | null;  // 0-100 percentage, null if unavailable
95  sevenDay: number | null;  // 0-100 percentage, null if unavailable
96  fiveHourResetAt: Date | null;
97  sevenDayResetAt: Date | null;
98  balanceLabel?: string | null;  // optional raw balance text (e.g. "¥6.35")
99  // Model-scoped weekly windows (e.g. Fable), from the external usage snapshot.
100  scopedWindows?: ScopedUsageWindow[];
101}
102
103/** One model-scoped weekly quota window (e.g. label "Fable", used percent 0-100). */
104export interface ScopedUsageWindow {
105  label: string;
106  percent: number | null;
107  resetAt: Date | null;
108}
109
110export interface ExternalUsageSnapshot {
111  five_hour?: {
112    used_percentage?: number | null;
113    resets_at?: string | number | null;
114  } | null;
115  seven_day?: {
116    used_percentage?: number | null;
117    resets_at?: string | number | null;
118  } | null;
119  updated_at?: string | number | null;
120  balance_label?: string | null;
121  // Model-scoped weekly windows (e.g. Fable), in the shape of Claude Code's /usage data.
122  model_scoped?: Array<{
123    display_name?: string | null;
124    utilization?: number | null;
125    resets_at?: string | null;
126  }> | null;
127}
128
129export interface MemoryInfo {
130  totalBytes: number;
131  usedBytes: number;
132  freeBytes: number;
133  usedPercent: number;
134}
135
136/** Check if usage limit is reached (either window at 100%) */
137export function isLimitReached(data: UsageData): boolean {
138  return data.fiveHour === 100 || data.sevenDay === 100;
139}
140
141export interface SessionTokenUsage {
142  inputTokens: number;
143  outputTokens: number;
144  cacheCreationTokens: number;
145  cacheReadTokens: number;
146}
147
148export interface TranscriptData {
149  tools: ToolEntry[];
150  skills: string[];
151  mcpServers: string[];
152  /**
153   * MCP servers whose latest observed tool result is an error, derived
154   * from `mcp__<server>__<tool>` results carrying is_error. Distinct from
155   * mcpServers, which is a plain activity list.
156   */
157  mcpErrors: string[];
158  agents: AgentEntry[];
159  todos: TodoItem[];
160  sessionStart?: Date;
161  // Last assistant response of any kind, subagents included. Drives the
162  // last-response element.
163  lastAssistantResponseAt?: Date;
164  sessionTokens?: SessionTokenUsage;
165  // Number of compact_boundary entries (manual /compact or auto compaction)
166  // with a valid timestamp seen in the transcript.
167  compactionCount?: number;
168  // Tokens in the main conversation's context as of its last request, or the
169  // post-compaction size after a compact boundary.
170  contextTokens?: number;
171  // Advisor model ID for the current session, captured from the top-level
172  // `advisorModel` field that Claude Code stamps onto every assistant record
173  // after `/advisor` is set (e.g. "claude-opus-4-7"). undefined when /advisor
174  // is off or no assistant turn has happened yet.
175  advisorModel?: string;
176  // Current ultracode effort state from the most recent transcript signal
177  // (`ultra_effort_enter`/`ultra_effort_exit` attachment or `/effort` output).
178  // undefined when ultracode was never entered this session.
179  ultracodeActive?: boolean;
180  // Model ID from the most recent assistant message's `message.model` field.
181  // This reflects what the API actually served — may differ from stdin.model
182  // when a proxy (e.g. cc-switch) routes to a different model. Transcript
183  // parsing sanitizes terminal controls and caps the retained value at 80 chars.
184  lastAssistantModel?: string;
185}
186
187export interface RenderContext {
188  stdin: StdinData;
189  transcript: TranscriptData;
190  claudeMdCount: number;
191  rulesCount: number;
192  mcpCount: number;
193  hooksCount: number;
194  costTotals: CostTotals | null;
195  outputSpeed: number | null;
196  gitStatus: GitStatus | null;
197  usageData: UsageData | null;
198  memoryUsage: MemoryInfo | null;
199  config: HudConfig;
200  extraLabel: string | null;
201  authInfo?: AuthInfo | null;
202}
203
hooks/hud/usage-pace.ts 98 lines
1import type { HudConfig } from './config.js';
2import type { ScopedUsageWindow, UsageData } from './types.js';
3
4export type UsagePace = 'normal' | 'warning' | 'critical';
5
6export const FIVE_HOUR_WINDOW_MS = 5 * 60 * 60 * 1000;
7export const SEVEN_DAY_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
8
9// Below this much usage a linear projection is noise (3% five minutes in
10// "projects" 180%), so pace stays normal.
11const MIN_USED_PERCENT = 10;
12// Amber once the current rate would end the window at 90% of the limit or more.
13const WARNING_PROJECTED_PERCENT = 90;
14// Red once the current rate would exhaust the limit before the window resets.
15const CRITICAL_PROJECTED_PERCENT = 100;
16
17/**
18 * Grades how fast a rate-limit window is being consumed by projecting the
19 * used percentage linearly to the window's reset. Returns null when there is
20 * no usable rate: missing data, a reset already past, or a reset at least a
21 * full window away (no time elapsed).
22 */
23export function getUsagePace(
24  percent: number | null,
25  resetAt: Date | null,
26  windowMs: number,
27  now: number = Date.now(),
28): UsagePace | null {
29  if (percent === null || !resetAt) {
30    return null;
31  }
32
33  const remainingMs = resetAt.getTime() - now;
34  if (!Number.isFinite(remainingMs) || remainingMs <= 0 || remainingMs >= windowMs) {
35    return null;
36  }
37
38  if (percent < MIN_USED_PERCENT) {
39    return 'normal';
40  }
41
42  const elapsedFraction = (windowMs - remainingMs) / windowMs;
43  const projected = percent / elapsedFraction;
44  if (projected > CRITICAL_PROJECTED_PERCENT) {
45    return 'critical';
46  }
47  if (projected >= WARNING_PROJECTED_PERCENT) {
48    return 'warning';
49  }
50  return 'normal';
51}
52
53/** True when pace should draw attention (amber or red). */
54export function isPaceAlert(pace: UsagePace | null): boolean {
55  return pace === 'warning' || pace === 'critical';
56}
57
58/** Pace of every usage window, plus the display rules pace imposes. */
59export interface UsagePaces {
60  fiveHour: UsagePace | null;
61  sevenDay: UsagePace | null;
62  /** Parallel to the scoped windows passed in. */
63  scoped: Array<UsagePace | null>;
64  /** Some window is at amber/red pace: show usage despite `usageThreshold`. */
65  alert: boolean;
66  /** Show the weekly window: at/above `sevenDayThreshold`, or at amber/red pace. */
67  showSevenDay: boolean;
68}
69
70/**
71 * Grades every window's pace (all null unless `display.usagePace` is on) and
72 * resolves the visibility rules both usage renderers share.
73 */
74export function resolveUsagePaces(
75  usage: UsageData,
76  scopedWindows: ScopedUsageWindow[],
77  display: Partial<HudConfig['display']> | undefined,
78  now: number = Date.now(),
79): UsagePaces {
80  const enabled = display?.usagePace === true;
81  const paceOf = (percent: number | null, resetAt: Date | null, windowMs: number): UsagePace | null =>
82    enabled ? getUsagePace(percent, resetAt, windowMs, now) : null;
83
84  const fiveHour = paceOf(usage.fiveHour, usage.fiveHourResetAt, FIVE_HOUR_WINDOW_MS);
85  const sevenDay = paceOf(usage.sevenDay, usage.sevenDayResetAt, SEVEN_DAY_WINDOW_MS);
86  const scoped = scopedWindows.map((w) => paceOf(w.percent, w.resetAt, SEVEN_DAY_WINDOW_MS));
87  const sevenDayThreshold = display?.sevenDayThreshold ?? 80;
88
89  return {
90    fiveHour,
91    sevenDay,
92    scoped,
93    alert: [fiveHour, sevenDay, ...scoped].some(isPaceAlert),
94    showSevenDay: usage.sevenDay !== null
95      && (usage.sevenDay >= sevenDayThreshold || isPaceAlert(sevenDay)),
96  };
97}
98
hooks/i18n.ts 628 lines
1// The mod's own strings (what it adds to claude-hud's lines), in the language
2// claude-hud is set to (`language` in its config), so one setting covers the HUD.
3import { type CanonicalLanguage, getCanonicalLanguage, interpolate } from './hud/i18n/index.js'
4
5/** A string, or its plural forms by `Intl.PluralRules` category (`other` required). */
6type Text = string | { one?: string; few?: string; many?: string; other: string }
7
8type Key =
9  | 'rc.label'
10  | 'rc.attached'
11  | 'rc.connected'
12  | 'surface.mobile'
13  | 'surface.desktop'
14  | 'forecast'
15  | 'limit.fiveHour'
16  | 'limit.sevenDay'
17  | 'limit.scoped'
18  | 'week'
19  | 'streak'
20  | 'git.dirty'
21  | 'git.ahead'
22  | 'compact.left'
23  | 'cache.cold'
24  | 'turn.growth'
25  | 'alert.context'
26  | 'alert.fiveHour'
27  | 'alert.sevenDay'
28  | 'alert.scoped'
29  | 'turn.done'
30  | 'cmd.description'
31  | 'theme.set'
32  | 'theme.list'
33  | 'theme.unknown'
34  | 'theme.ask'
35  | 'cmd.hidden'
36  | 'cmd.shown'
37  | 'pane.title'
38  | 'pane.opened'
39  | 'pane.closed'
40  | 'pane.tools'
41  | 'pane.noTools'
42  | 'pane.toolStats'
43  | 'pane.failed'
44  | 'pane.agents'
45  | 'pane.none'
46  | 'pane.todos'
47  | 'pane.spend'
48  | 'pane.turns'
49  | 'pane.turnRow'
50  | 'spend.today'
51  | 'spend.week'
52  | 'summary.language'
53  | 'desk.context'
54  | 'desk.cache'
55  | 'desk.resets'
56
57// French (and German, Spanish, Russian) set a percent sign off with a space; French
58// also a colon. A no-break space keeps the sign on its number.
59const NB = ' '
60
61export const MESSAGES: Record<CanonicalLanguage, Record<Key, Text>> = {
62  en: {
63    'rc.label': '⇄ Remote Control',
64    'rc.attached': 'connected: {who}',
65    'rc.connected': 'connected',
66    'surface.mobile': 'phone',
67    'surface.desktop': 'web/desktop',
68    forecast: '{label} runs out ≈{time} at this pace',
69    'limit.fiveHour': '5-hour limit',
70    'limit.sevenDay': '7-day limit',
71    'limit.scoped': '{name} weekly limit',
72    week: '7d',
73    streak: '{n}-day streak',
74    'git.dirty': { one: '{n} uncommitted change', other: '{n} uncommitted changes' },
75    'git.ahead': { one: '{n} unpushed commit', other: '{n} unpushed commits' },
76    'compact.left': '{tokens} to auto-compact',
77    'cache.cold': 'cache cold: next message re-caches {tokens}',
78    'turn.growth': 'last turn +{tokens}',
79    'alert.context': 'Context is {p}% full — consider /compact',
80    'alert.fiveHour': '5-hour limit at {p}%',
81    'alert.sevenDay': '7-day limit at {p}%',
82    'alert.scoped': '{name} weekly limit at {p}%',
83    'turn.done': '✓ Done in {d}',
84    'cmd.description': 'Show or hide the claude-hud band; detail opens the details pane; theme switches its look',
85    'theme.set': 'HUD theme: {name}',
86    'theme.list': 'HUD themes (now {name}): {list}. /hud theme <name>, next or reset; * needs a Nerd Font',
87    'theme.unknown': 'No theme named {name}. Themes: {list}',
88    'theme.ask': 'Which HUD theme? (now {name}; Other: type any of {list})',
89    'cmd.hidden': 'claude-hud band hidden',
90    'cmd.shown': 'claude-hud band shown',
91    'pane.title': 'HUD details',
92    'pane.opened': 'HUD details pane opened (/hud detail closes it)',
93    'pane.closed': 'HUD details pane closed',
94    'pane.tools': 'Time by tool',
95    'pane.noTools': 'No tool calls in this session yet',
96    'pane.toolStats': '×{count} · {total} total · {avg} avg',
97    'pane.failed': '{n} failed',
98    'pane.agents': 'Subagents',
99    'pane.none': 'None',
100    'pane.todos': 'Todos',
101    'pane.spend': 'Spend',
102    'pane.turns': 'Recent turns',
103    'pane.turnRow': '#{n} · {time} · {cost} · context {tokens}',
104    'spend.today': 'Today {spent}',
105    'spend.week': '7 days {spent}',
106    'summary.language': 'English',
107    'desk.context': 'context',
108    'desk.cache': 'cache until {time}',
109    'desk.resets': 'resets in {d}',
110  },
111  'zh-Hans': {
112    'rc.label': '⇄ 远程控制',
113    'rc.attached': '已连接 {who}',
114    'rc.connected': '已连接',
115    'surface.mobile': '手机',
116    'surface.desktop': '网页/桌面',
117    forecast: '{label}按当前速度 ≈{time} 用完',
118    'limit.fiveHour': '5 小时额度',
119    'limit.sevenDay': '7 天额度',
120    'limit.scoped': '{name} 周额度',
121    week: '7 天',
122    streak: '连续 {n} 天',
123    'git.dirty': '{n} 个改动未提交',
124    'git.ahead': '{n} 个提交未推送',
125    'compact.left': '距自动压缩 {tokens}',
126    'cache.cold': '缓存已过期,下条消息重写 {tokens}',
127    'turn.growth': '上一轮 +{tokens}',
128    'alert.context': '上下文已用 {p}%,可以考虑 /compact',
129    'alert.fiveHour': '5 小时额度已用 {p}%',
130    'alert.sevenDay': '7 天额度已用 {p}%',
131    'alert.scoped': '{name} 周额度已用 {p}%',
132    'turn.done': '✓ 本轮完成,用时 {d}',
133    'cmd.description': '显示 / 隐藏 claude-hud 横条;detail 打开详情面板;theme 切换主题',
134    'theme.set': 'HUD 主题:{name}',
135    'theme.list': 'HUD 主题(当前 {name}):{list}。/hud theme <名称>、next 或 reset;带 * 的需要 Nerd Font',
136    'theme.unknown': '没有名为 {name} 的主题。可选:{list}',
137    'theme.ask': '换哪套 HUD 主题?(当前 {name};也可在 Other 里输入:{list})',
138    'cmd.hidden': 'claude-hud 横条已隐藏',
139    'cmd.shown': 'claude-hud 横条已显示',
140    'pane.title': 'HUD 详情',
141    'pane.opened': 'HUD 详情面板已打开(/hud detail 关闭)',
142    'pane.closed': 'HUD 详情面板已关闭',
143    'pane.tools': '工具耗时',
144    'pane.noTools': '本会话还没有工具调用',
145    'pane.toolStats': '×{count} 共 {total} 均 {avg}',
146    'pane.failed': '失败 {n}',
147    'pane.agents': '子代理',
148    'pane.none': '无',
149    'pane.todos': '待办',
150    'pane.spend': '花费',
151    'pane.turns': '最近几轮',
152    'pane.turnRow': '#{n} · {time} · {cost} · 上下文 {tokens}',
153    'spend.today': '今日 {spent}',
154    'spend.week': '7 天 {spent}',
155    'summary.language': 'Simplified Chinese',
156    'desk.context': '上下文',
157    'desk.cache': '缓存至 {time}',
158    'desk.resets': '{d} 后重置',
159  },
160  'zh-Hant': {
161    'rc.label': '⇄ 遠端控制',
162    'rc.attached': '已連線 {who}',
163    'rc.connected': '已連線',
164    'surface.mobile': '手機',
165    'surface.desktop': '網頁/桌面',
166    forecast: '{label}依目前速度 ≈{time} 用完',
167    'limit.fiveHour': '5 小時額度',
168    'limit.sevenDay': '7 天額度',
169    'limit.scoped': '{name} 週額度',
170    week: '7 天',
171    streak: '連續 {n} 天',
172    'git.dirty': '{n} 個變更尚未提交',
173    'git.ahead': '{n} 個提交尚未推送',
174    'compact.left': '距自動壓縮 {tokens}',
175    'cache.cold': '快取已過期,下則訊息重寫 {tokens}',
176    'turn.growth': '上一輪 +{tokens}',
177    'alert.context': '上下文已使用 {p}%,可以考慮執行 /compact',
178    'alert.fiveHour': '5 小時額度已使用 {p}%',
179    'alert.sevenDay': '7 天額度已使用 {p}%',
180    'alert.scoped': '{name} 週額度已使用 {p}%',
181    'turn.done': '✓ 本輪完成,耗時 {d}',
182    'cmd.description': '顯示/隱藏 claude-hud 橫條;detail 開啟詳細資訊面板;theme 切換主題',
183    'theme.set': 'HUD 主題:{name}',
184    'theme.list': 'HUD 主題(目前 {name}):{list}。/hud theme <名稱>、next 或 reset;帶 * 的需要 Nerd Font',
185    'theme.unknown': '沒有名為 {name} 的主題。可選:{list}',
186    'theme.ask': '換哪套 HUD 主題?(目前 {name};也可在 Other 輸入:{list})',
187    'cmd.hidden': 'claude-hud 橫條已隱藏',
188    'cmd.shown': 'claude-hud 橫條已顯示',
189    'pane.title': 'HUD 詳細資訊',
190    'pane.opened': 'HUD 詳細資訊面板已開啟(/hud detail 可關閉)',
191    'pane.closed': 'HUD 詳細資訊面板已關閉',
192    'pane.tools': '工具耗時',
193    'pane.noTools': '本工作階段尚無工具呼叫',
194    'pane.toolStats': '×{count} 共 {total} 平均 {avg}',
195    'pane.failed': '失敗 {n}',
196    'pane.agents': '子代理程式',
197    'pane.none': '無',
198    'pane.todos': '待辦事項',
199    'pane.spend': '花費',
200    'pane.turns': '最近幾輪',
201    'pane.turnRow': '#{n} · {time} · {cost} · 上下文 {tokens}',
202    'spend.today': '今日 {spent}',
203    'spend.week': '7 天 {spent}',
204    'summary.language': 'Traditional Chinese as used in Taiwan',
205    'desk.context': '上下文',
206    'desk.cache': '快取至 {time}',
207    'desk.resets': '{d} 後重置',
208  },
209  ja: {
210    'rc.label': '⇄ リモートコントロール',
211    'rc.attached': '接続中: {who}',
212    'rc.connected': '接続中',
213    'surface.mobile': 'スマホ',
214    'surface.desktop': 'Web/デスクトップ',
215    forecast: '{label}は今のペースだと ≈{time} に使い切ります',
216    'limit.fiveHour': '5時間枠',
217    'limit.sevenDay': '7日間枠',
218    'limit.scoped': '{name} 週間枠',
219    week: '7日間',
220    streak: '{n}日連続',
221    'git.dirty': '未コミットの変更 {n} 件',
222    'git.ahead': '未プッシュのコミット {n} 件',
223    'compact.left': '自動圧縮まで {tokens}',
224    'cache.cold': 'キャッシュ切れ:次の送信で {tokens} を再キャッシュ',
225    'turn.growth': '直前のターン +{tokens}',
226    'alert.context': 'コンテキストの使用率が {p}% に達しました。/compact の実行を検討してください',
227    'alert.fiveHour': '5時間枠の使用率が {p}% に達しました',
228    'alert.sevenDay': '7日間枠の使用率が {p}% に達しました',
229    'alert.scoped': '{name} 週間枠の使用率が {p}% に達しました',
230    'turn.done': '✓ 応答完了({d})',
231    'cmd.description': 'claude-hud の表示を切り替えます。detail で詳細パネル、theme でテーマを切り替えます',
232    'theme.set': 'HUD テーマ:{name}',
233    'theme.list': 'HUD テーマ(現在 {name}):{list}。/hud theme <名前>、next、reset。* は Nerd Font が必要',
234    'theme.unknown': '{name} というテーマはありません。テーマ:{list}',
235    'theme.ask': 'どの HUD テーマにしますか?(現在 {name}。Other に入力も可:{list})',
236    'cmd.hidden': 'claude-hud を非表示にしました',
237    'cmd.shown': 'claude-hud を表示しました',
238    'pane.title': 'HUD 詳細',
239    'pane.opened': 'HUD 詳細パネルを開きました(/hud detail で閉じます)',
240    'pane.closed': 'HUD 詳細パネルを閉じました',
241    'pane.tools': 'ツール別の所要時間',
242    'pane.noTools': 'このセッションではまだツールが呼び出されていません',
243    'pane.toolStats': '×{count} 合計 {total} 平均 {avg}',
244    'pane.failed': '失敗 {n}',
245    'pane.agents': 'サブエージェント',
246    'pane.none': 'なし',
247    'pane.todos': 'ToDo',
248    'pane.spend': 'コスト',
249    'pane.turns': '最近のターン',
250    'pane.turnRow': '#{n} · {time} · {cost} · コンテキスト {tokens}',
251    'spend.today': '今日 {spent}',
252    'spend.week': '7日間 {spent}',
253    'summary.language': 'Japanese',
254    'desk.context': 'コンテキスト',
255    'desk.cache': 'キャッシュ {time} まで',
256    'desk.resets': '{d} 後にリセット',
257  },
258  ko: {
259    'rc.label': '⇄ 원격 제어',
260    'rc.attached': '연결됨: {who}',
261    'rc.connected': '연결됨',
262    'surface.mobile': '휴대폰',
263    'surface.desktop': '웹/데스크톱',
264    forecast: '{label}: 현재 속도면 ≈{time}에 소진',
265    'limit.fiveHour': '5시간 한도',
266    'limit.sevenDay': '7일 한도',
267    'limit.scoped': '{name} 주간 한도',
268    week: '7일',
269    streak: '{n}일 연속',
270    'git.dirty': '커밋하지 않은 변경 {n}개',
271    'git.ahead': '푸시하지 않은 커밋 {n}개',
272    'compact.left': '자동 압축까지 {tokens}',
273    'cache.cold': '캐시 만료: 다음 메시지가 {tokens} 재캐시',
274    'turn.growth': '직전 턴 +{tokens}',
275    'alert.context': '컨텍스트 사용량이 {p}%에 도달했습니다. /compact 실행을 고려해 보세요',
276    'alert.fiveHour': '5시간 한도의 {p}%를 사용했습니다',
277    'alert.sevenDay': '7일 한도의 {p}%를 사용했습니다',
278    'alert.scoped': '{name} 주간 한도의 {p}%를 사용했습니다',
279    'turn.done': '✓ 응답 완료 ({d})',
280    'cmd.description': 'claude-hud 표시/숨기기. detail을 붙이면 상세 패널을 열고, theme으로 테마를 바꿉니다',
281    'theme.set': 'HUD 테마: {name}',
282    'theme.list': 'HUD 테마 (현재 {name}): {list}. /hud theme <이름>, next, reset. *는 Nerd Font 필요',
283    'theme.unknown': '{name} 테마가 없습니다. 테마: {list}',
284    'theme.ask': '어떤 HUD 테마로 바꿀까요? (현재 {name}, Other에 입력 가능: {list})',
285    'cmd.hidden': 'claude-hud를 숨겼습니다',
286    'cmd.shown': 'claude-hud를 표시했습니다',
287    'pane.title': 'HUD 상세',
288    'pane.opened': 'HUD 상세 패널을 열었습니다(/hud detail로 닫기)',
289    'pane.closed': 'HUD 상세 패널을 닫았습니다',
290    'pane.tools': '도구별 소요 시간',
291    'pane.noTools': '이 세션에서는 아직 도구 호출이 없습니다',
292    'pane.toolStats': '×{count} · 합계 {total} · 평균 {avg}',
293    'pane.failed': '실패 {n}',
294    'pane.agents': '하위 에이전트',
295    'pane.none': '없음',
296    'pane.todos': '할 일',
297    'pane.spend': '비용',
298    'pane.turns': '최근 턴',
299    'pane.turnRow': '#{n} · {time} · {cost} · 컨텍스트 {tokens}',
300    'spend.today': '오늘 {spent}',
301    'spend.week': '7일 {spent}',
302    'summary.language': 'Korean',
303    'desk.context': '컨텍스트',
304    'desk.cache': '캐시 {time}까지',
305    'desk.resets': '{d} 후 초기화',
306  },
307  es: {
308    'rc.label': '⇄ Control remoto',
309    'rc.attached': 'conectado: {who}',
310    'rc.connected': 'conectado',
311    'surface.mobile': 'teléfono',
312    'surface.desktop': 'web/escritorio',
313    forecast: '{label}: a este ritmo se agota hacia las {time}',
314    'limit.fiveHour': 'Límite de 5 h',
315    'limit.sevenDay': 'Límite de 7 días',
316    'limit.scoped': 'Límite semanal de {name}',
317    week: '7 días',
318    streak: { one: '{n} día seguido', other: '{n} días seguidos' },
319    'git.dirty': { one: '{n} cambio sin confirmar', other: '{n} cambios sin confirmar' },
320    'git.ahead': { one: '{n} commit sin enviar', other: '{n} commits sin enviar' },
321    'compact.left': '{tokens} hasta la compactación',
322    'cache.cold': 'caché fría: el próximo mensaje recachea {tokens}',
323    'turn.growth': 'último turno +{tokens}',
324    'alert.context': `Contexto al {p}${NB}%: conviene ejecutar /compact`,
325    'alert.fiveHour': `Límite de 5 horas al {p}${NB}%`,
326    'alert.sevenDay': `Límite de 7 días al {p}${NB}%`,
327    'alert.scoped': `Límite semanal de {name} al {p}${NB}%`,
328    'turn.done': '✓ Respuesta lista en {d}',
329    'cmd.description': 'Muestra u oculta la barra de claude-hud; detail abre el panel de detalles; theme cambia el tema',
330    'theme.set': 'Tema del HUD: {name}',
331    'theme.list': 'Temas del HUD (ahora {name}): {list}. /hud theme <nombre>, next o reset; * requiere una Nerd Font',
332    'theme.unknown': 'No hay ningún tema llamado {name}. Temas: {list}',
333    'theme.ask': '¿Qué tema de HUD? (ahora {name}; en Other puedes escribir: {list})',
334    'cmd.hidden': 'Barra de claude-hud oculta',
335    'cmd.shown': 'Barra de claude-hud visible',
336    'pane.title': 'Detalles del HUD',
337    'pane.opened': 'Panel de detalles del HUD abierto (/hud detail lo cierra)',
338    'pane.closed': 'Panel de detalles del HUD cerrado',
339    'pane.tools': 'Tiempo por herramienta',
340    'pane.noTools': 'Todavía no hay llamadas a herramientas en esta sesión',
341    'pane.toolStats': '×{count} · total {total} · promedio {avg}',
342    'pane.failed': { one: '{n} error', other: '{n} errores' },
343    'pane.agents': 'Subagentes',
344    'pane.none': 'Ninguno',
345    'pane.todos': 'Tareas',
346    'pane.spend': 'Gasto',
347    'pane.turns': 'Últimos turnos',
348    'pane.turnRow': '#{n} · {time} · {cost} · contexto {tokens}',
349    'spend.today': 'Hoy: {spent}',
350    'spend.week': '7 días: {spent}',
351    'summary.language': 'Spanish',
352    'desk.context': 'contexto',
353    'desk.cache': 'caché hasta las {time}',
354    'desk.resets': 'se reinicia en {d}',
355  },
356  fr: {
357    'rc.label': '⇄ Contrôle à distance',
358    'rc.attached': `connecté${NB}: {who}`,
359    'rc.connected': 'connecté',
360    'surface.mobile': 'téléphone',
361    'surface.desktop': 'web/bureau',
362    forecast: `{label}${NB}: épuisée vers {time} à ce rythme`,
363    'limit.fiveHour': 'Limite de 5 h',
364    'limit.sevenDay': 'Limite de 7 jours',
365    'limit.scoped': 'Limite hebdomadaire {name}',
366    week: '7 jours',
367    streak: { one: '{n} jour d’affilée', other: '{n} jours d’affilée' },
368    'git.dirty': { one: '{n} modification non commitée', other: '{n} modifications non commitées' },
369    'git.ahead': { one: '{n} commit non poussé', other: '{n} commits non poussés' },
370    'compact.left': '{tokens} avant la compaction',
371    'cache.cold': 'cache froid : le prochain message recache {tokens}',
372    'turn.growth': 'dernier tour +{tokens}',
373    'alert.context': `Contexte rempli à {p}${NB}%${NB}: pensez à /compact`,
374    'alert.fiveHour': `Limite de 5 heures utilisée à {p}${NB}%`,
375    'alert.sevenDay': `Limite de 7 jours utilisée à {p}${NB}%`,
376    'alert.scoped': `Limite hebdomadaire {name} utilisée à {p}${NB}%`,
377    'turn.done': '✓ Réponse prête en {d}',
378    'cmd.description': `Affiche ou masque la barre claude-hud${NB}; detail ouvre le panneau de détails${NB}; theme change le thème`,
379    'theme.set': `Thème du HUD${NB}: {name}`,
380    'theme.list': `Thèmes du HUD (actuel${NB}: {name})${NB}: {list}. /hud theme <nom>, next ou reset${NB}; * demande une Nerd Font`,
381    'theme.unknown': `Aucun thème nommé {name}. Thèmes${NB}: {list}`,
382    'theme.ask': `Quel thème pour le HUD${NB}? (actuel${NB}: {name}${NB}; dans Other, tapez${NB}: {list})`,
383    'cmd.hidden': 'Barre claude-hud masquée',
384    'cmd.shown': 'Barre claude-hud affichée',
385    'pane.title': 'Détails du HUD',
386    'pane.opened': 'Panneau de détails du HUD ouvert (/hud detail pour le fermer)',
387    'pane.closed': 'Panneau de détails du HUD fermé',
388    'pane.tools': 'Temps par outil',
389    'pane.noTools': 'Aucun appel d’outil dans cette session pour l’instant',
390    'pane.toolStats': '×{count} · total {total} · moyenne {avg}',
391    'pane.failed': { one: '{n} échec', other: '{n} échecs' },
392    'pane.agents': 'Sous-agents',
393    'pane.none': 'Aucun',
394    'pane.todos': 'Tâches',
395    'pane.spend': 'Dépenses',
396    'pane.turns': 'Derniers tours',
397    'pane.turnRow': '#{n} · {time} · {cost} · contexte {tokens}',
398    'spend.today': `Aujourd’hui${NB}: {spent}`,
399    'spend.week': `7 jours${NB}: {spent}`,
400    'summary.language': 'French',
401    'desk.context': 'contexte',
402    'desk.cache': 'cache jusqu’à {time}',
403    'desk.resets': 'réinitialisé dans {d}',
404  },
405  de: {
406    'rc.label': '⇄ Fernsteuerung',
407    'rc.attached': 'verbunden: {who}',
408    'rc.connected': 'verbunden',
409    'surface.mobile': 'Smartphone',
410    'surface.desktop': 'Web/Desktop',
411    forecast: '{label}: bei diesem Tempo ≈{time} aufgebraucht',
412    'limit.fiveHour': '5-Stunden-Limit',
413    'limit.sevenDay': '7-Tage-Limit',
414    'limit.scoped': '{name}-Wochenlimit',
415    week: '7 Tage',
416    streak: { one: '{n} Tag in Folge', other: '{n} Tage in Folge' },
417    'git.dirty': { one: '{n} nicht committete Änderung', other: '{n} nicht committete Änderungen' },
418    'git.ahead': { one: '{n} nicht gepushter Commit', other: '{n} nicht gepushte Commits' },
419    'compact.left': '{tokens} bis zur Komprimierung',
420    'cache.cold': 'Cache kalt: nächste Nachricht cacht {tokens} neu',
421    'turn.growth': 'letzte Runde +{tokens}',
422    'alert.context': `Kontext zu {p}${NB}% belegt – /compact empfohlen`,
423    'alert.fiveHour': `5-Stunden-Limit zu {p}${NB}% ausgeschöpft`,
424    'alert.sevenDay': `7-Tage-Limit zu {p}${NB}% ausgeschöpft`,
425    'alert.scoped': `{name}-Wochenlimit zu {p}${NB}% ausgeschöpft`,
426    'turn.done': '✓ Antwort fertig nach {d}',
427    'cmd.description': 'claude-hud-Leiste ein- oder ausblenden; detail öffnet den Detailbereich; theme wechselt das Design',
428    'theme.set': 'HUD-Design: {name}',
429    'theme.list': 'HUD-Designs (aktiv: {name}): {list}. /hud theme <Name>, next oder reset; * braucht eine Nerd Font',
430    'theme.unknown': 'Kein Design namens {name}. Designs: {list}',
431    'theme.ask': 'Welches HUD-Design? (aktuell {name}; unter Other eintippen: {list})',
432    'cmd.hidden': 'claude-hud-Leiste ausgeblendet',
433    'cmd.shown': 'claude-hud-Leiste eingeblendet',
434    'pane.title': 'HUD-Details',
435    'pane.opened': 'HUD-Detailbereich geöffnet (/hud detail schließt ihn)',
436    'pane.closed': 'HUD-Detailbereich geschlossen',
437    'pane.tools': 'Zeit pro Tool',
438    'pane.noTools': 'Noch keine Tool-Aufrufe in dieser Sitzung',
439    'pane.toolStats': '×{count} · gesamt {total} · Ø {avg}',
440    'pane.failed': '{n} fehlgeschlagen',
441    'pane.agents': 'Subagenten',
442    'pane.none': 'Keine',
443    'pane.todos': 'Aufgaben',
444    'pane.spend': 'Ausgaben',
445    'pane.turns': 'Letzte Runden',
446    'pane.turnRow': '#{n} · {time} · {cost} · Kontext {tokens}',
447    'spend.today': 'Heute: {spent}',
448    'spend.week': '7 Tage: {spent}',
449    'summary.language': 'German',
450    'desk.context': 'Kontext',
451    'desk.cache': 'Cache bis {time}',
452    'desk.resets': 'zurückgesetzt in {d}',
453  },
454  'pt-BR': {
455    'rc.label': '⇄ Controle remoto',
456    'rc.attached': 'conectado: {who}',
457    'rc.connected': 'conectado',
458    'surface.mobile': 'celular',
459    'surface.desktop': 'web/desktop',
460    forecast: '{label}: no ritmo atual, esgota por volta das {time}',
461    'limit.fiveHour': 'Limite de 5 h',
462    'limit.sevenDay': 'Limite de 7 dias',
463    'limit.scoped': 'Limite semanal do {name}',
464    week: '7 dias',
465    streak: { one: '{n} dia seguido', other: '{n} dias seguidos' },
466    'git.dirty': { one: '{n} alteração sem commit', other: '{n} alterações sem commit' },
467    'git.ahead': { one: '{n} commit sem push', other: '{n} commits sem push' },
468    'compact.left': '{tokens} até a compactação',
469    'cache.cold': 'cache frio: a próxima mensagem recacheia {tokens}',
470    'turn.growth': 'último turno +{tokens}',
471    'alert.context': 'Contexto em {p}%: considere usar /compact',
472    'alert.fiveHour': 'Limite de 5 horas em {p}%',
473    'alert.sevenDay': 'Limite de 7 dias em {p}%',
474    'alert.scoped': 'Limite semanal do {name} em {p}%',
475    'turn.done': '✓ Resposta pronta em {d}',
476    'cmd.description': 'Mostra ou oculta a barra do claude-hud; detail abre o painel de detalhes; theme troca o tema',
477    'theme.set': 'Tema do HUD: {name}',
478    'theme.list': 'Temas do HUD (atual: {name}): {list}. /hud theme <nome>, next ou reset; * precisa de uma Nerd Font',
479    'theme.unknown': 'Nenhum tema chamado {name}. Temas: {list}',
480    'theme.ask': 'Qual tema do HUD? (agora {name}; em Other digite: {list})',
481    'cmd.hidden': 'Barra do claude-hud oculta',
482    'cmd.shown': 'Barra do claude-hud visível',
483    'pane.title': 'Detalhes do HUD',
484    'pane.opened': 'Painel de detalhes do HUD aberto (/hud detail fecha)',
485    'pane.closed': 'Painel de detalhes do HUD fechado',
486    'pane.tools': 'Tempo por ferramenta',
487    'pane.noTools': 'Nenhuma chamada de ferramenta nesta sessão ainda',
488    'pane.toolStats': '×{count} · total {total} · média {avg}',
489    'pane.failed': { one: '{n} falha', other: '{n} falhas' },
490    'pane.agents': 'Subagentes',
491    'pane.none': 'Nenhum',
492    'pane.todos': 'Tarefas',
493    'pane.spend': 'Gastos',
494    'pane.turns': 'Últimos turnos',
495    'pane.turnRow': '#{n} · {time} · {cost} · contexto {tokens}',
496    'spend.today': 'Hoje: {spent}',
497    'spend.week': '7 dias: {spent}',
498    'summary.language': 'Brazilian Portuguese',
499    'desk.context': 'contexto',
500    'desk.cache': 'cache até {time}',
501    'desk.resets': 'reinicia em {d}',
502  },
503  ru: {
504    'rc.label': '⇄ Удалённое управление',
505    'rc.attached': 'подключено: {who}',
506    'rc.connected': 'подключено',
507    'surface.mobile': 'телефон',
508    'surface.desktop': 'веб/компьютер',
509    forecast: '{label}: при текущем темпе будет исчерпан около {time}',
510    'limit.fiveHour': 'Лимит на 5 ч',
511    'limit.sevenDay': 'Лимит на 7 дн.',
512    'limit.scoped': 'Недельный лимит {name}',
513    week: '7 дн.',
514    streak: { one: '{n} день подряд', few: '{n} дня подряд', many: '{n} дней подряд', other: '{n} дня подряд' },
515    'git.dirty': {
516      one: '{n} незакоммиченное изменение',
517      few: '{n} незакоммиченных изменения',
518      many: '{n} незакоммиченных изменений',
519      other: '{n} незакоммиченного изменения',
520    },
521    'git.ahead': {
522      one: '{n} неотправленный коммит',
523      few: '{n} неотправленных коммита',
524      many: '{n} неотправленных коммитов',
525      other: '{n} неотправленного коммита',
526    },
527    'compact.left': '{tokens} до автосжатия',
528    'cache.cold': 'кэш остыл: следующее сообщение перекэширует {tokens}',
529    'turn.growth': 'прошлый ход +{tokens}',
530    'alert.context': `Контекст заполнен на {p}${NB}% — стоит выполнить /compact`,
531    'alert.fiveHour': `Лимит на 5 часов израсходован на {p}${NB}%`,
532    'alert.sevenDay': `Лимит на 7 дней израсходован на {p}${NB}%`,
533    'alert.scoped': `Недельный лимит {name} израсходован на {p}${NB}%`,
534    'turn.done': '✓ Ответ готов за {d}',
535    'cmd.description': 'Показать или скрыть панель claude-hud; detail открывает панель подробностей; theme меняет тему',
536    'theme.set': 'Тема HUD: {name}',
537    'theme.list': 'Темы HUD (сейчас {name}): {list}. /hud theme <имя>, next или reset; * нужен Nerd Font',
538    'theme.unknown': 'Темы {name} нет. Темы: {list}',
539    'theme.ask': 'Какую тему HUD выбрать? (сейчас {name}; в Other можно ввести: {list})',
540    'cmd.hidden': 'Панель claude-hud скрыта',
541    'cmd.shown': 'Панель claude-hud показана',
542    'pane.title': 'Подробности HUD',
543    'pane.opened': 'Панель подробностей HUD открыта (/hud detail закрывает её)',
544    'pane.closed': 'Панель подробностей HUD закрыта',
545    'pane.tools': 'Время по инструментам',
546    'pane.noTools': 'В этой сессии ещё не было вызовов инструментов',
547    'pane.toolStats': '×{count} · всего {total} · в среднем {avg}',
548    'pane.failed': 'ошибок: {n}',
549    'pane.agents': 'Субагенты',
550    'pane.none': 'Нет',
551    'pane.todos': 'Задачи',
552    'pane.spend': 'Расходы',
553    'pane.turns': 'Последние ходы',
554    'pane.turnRow': '#{n} · {time} · {cost} · контекст {tokens}',
555    'spend.today': 'Сегодня: {spent}',
556    'spend.week': '7 дн.: {spent}',
557    'summary.language': 'Russian',
558    'desk.context': 'контекст',
559    'desk.cache': 'кэш до {time}',
560    'desk.resets': 'сброс через {d}',
561  },
562}
563
564// The BCP 47 tag `Intl` formats and pluralizes with, per language.
565const INTL_TAG: Record<CanonicalLanguage, string> = {
566  en: 'en-US',
567  'zh-Hans': 'zh-CN',
568  'zh-Hant': 'zh-TW',
569  ja: 'ja-JP',
570  ko: 'ko-KR',
571  es: 'es',
572  fr: 'fr-FR',
573  de: 'de-DE',
574  'pt-BR': 'pt-BR',
575  ru: 'ru-RU',
576}
577
578/** The language the HUD draws in: claude-hud's, as its last config load set it. */
579export function language(): CanonicalLanguage {
580  return getCanonicalLanguage()
581}
582
583/** Whether the language sets text in CJK characters (two columns each). */
584export function isCjk(lang: CanonicalLanguage = language()): boolean {
585  return lang === 'zh-Hans' || lang === 'zh-Hant' || lang === 'ja' || lang === 'ko'
586}
587
588function pluralCategory(lang: CanonicalLanguage, n: number): string {
589  try {
590    return new Intl.PluralRules(INTL_TAG[lang]).select(n)
591  } catch {
592    return n === 1 ? 'one' : 'other'
593  }
594}
595
596/** The message `key`, its `{placeholders}` filled; `params.n` picks a plural form. */
597export function m(key: Key, params: Record<string, string | number> = {}, lang: CanonicalLanguage = language()): string {
598  const text = MESSAGES[lang][key] ?? MESSAGES.en[key]
599  const pattern =
600    typeof text === 'string'
601      ? text
602      : ((text as Record<string, string | undefined>)[typeof params.n === 'number' ? pluralCategory(lang, params.n) : 'other'] ??
603        text.other)
604  return interpolate(pattern, params)
605}
606
607/** "$3.20", "3,20 $", "US$ 3,20": a USD amount as the language writes it. */
608export function money(usd: number, lang: CanonicalLanguage = language()): string {
609  try {
610    return new Intl.NumberFormat(INTL_TAG[lang], {
611      style: 'currency',
612      currency: 'USD',
613      currencyDisplay: 'narrowSymbol',
614    }).format(usd)
615  } catch {
616    return `$${usd.toFixed(2)}`
617  }
618}
619
620/** The one-line task summary's prompt: the language by name and a length to keep to. */
621export function summaryPrompt(lang: CanonicalLanguage = language()): string {
622  const budget = isCjk(lang) ? 'at most 25 characters' : 'at most 8 words'
623  return (
624    `In ${m('summary.language', {}, lang)}, state in one line (${budget}) the task this session is working on right now. ` +
625    'Output only that line: no quotes, no prefix, no closing punctuation.'
626  )
627}
628