A slime hops above the prompt while Claude works, with the session's key facts beside it

使用 GNU Stow 管理個人設定檔,方便在不同機器上快速部署一致的開發環境。
| 套件 | 說明 | 安裝後的路徑 |
|---|---|---|
zsh | Zsh shell 設定 | ~/.zshrc、~/zshrc.d/ → config/zsh/zshrc.d/ |
tmux | tmux 終端多工器設定 | ~/.tmux.conf |
ghostty | Ghostty 終端模擬器設定 | ~/.config/ghostty/config |
cmux | Cmux 終端機設定 | ~/.config/cmux/ |
herdr | Herdr 終端多工器設定(tmux 風格按鍵、gruvbox) | ~/.config/herdr/config.toml |
claude | Claude Code 系統提示 + output styles + hooks 範本 + RPG status line | ~/.claude/CLAUDE.md、~/.claude/output-styles/、~/.claude/rpg-statusline.sh |
claude-mods | Claude Code mods(hooks plugin:pane、band 等) | ~/.claude/mods/<mod>/ → 目錄 symlink |
codex | Codex CLI 系統提示 | ~/.codex/AGENTS.md |
hammerspoon | Hammerspoon macOS 自動化 | ~/.hammerspoon/ |
ripgrep | ripgrep 搜尋工具設定 | ~/.ripgreprc |
git | 全域 git ignore(XDG 路徑,免設定 git config) | ~/.config/git/ignore |
nvim | Neovim 設定(LazyVim + 香蕉黃 gruvbox、VS Code 風格按鍵) | ~/.config/nvim/ → 目錄 symlink |
config/shared/skills/為共享 skills 的單一來源,不是 stow 套件。stow-wrap.sh部署 AI CLI 套件時會自動將其 symlink 到每個工具的~/.<tool>/skills/。
# Homebrew
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
# GNU Stow
brew install stow
# CLI 增強工具
brew install eza bat htop fd fzf ripgrep zoxide jq direnv
# 開發工具(按需安裝)
brew install tmux pyenv neovim tree-sitter-cli
依照官方安裝腳本安裝:https://github.com/nvm-sh/nvm?tab=readme-ov-file#install--update-script
# Oh-My-Zsh
sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
# 第三方 plugins
git clone https://github.com/zsh-users/zsh-syntax-highlighting.git \
${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting
git clone https://github.com/zsh-users/zsh-autosuggestions.git \
${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions
git clone https://github.com/jeffreytse/zsh-vi-mode.git \
${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-vi-mode
# Powerlevel10k 主題
git clone --depth=1 https://github.com/romkatv/powerlevel10k.git \
${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}/themes/powerlevel10k
其餘 plugins(
git、macos、sudo、extract、colored-man-pages、command-not-found)為 Oh-My-Zsh 內建。zsh-vi-mode已啟用系統剪貼簿整合(ZVM_SYSTEM_CLIPBOARD_ENABLED=true)。
git clone https://github.com/junegunn/fzf-git.sh.git ~/fzf-git.sh
brew install --cask font-jetbrains-mono-nerd-font
# 關閉長按字元選單,改為按住重複輸入(vim 操作必要)
defaults write -g ApplePressAndHoldEnabled -bool false
需登出再登入或重新啟動 app 才會生效。
git clone <此 repo 的 URL> ~/dotfiles
cd ~/dotfiles
# 備份現有設定檔
mkdir -p ~/.dotfiles-backup
for f in ~/.zshrc ~/.tmux.conf ~/.ripgreprc \
~/.config/ghostty/config ~/.config/cmux/cmux.json \
~/.claude/CLAUDE.md ~/.codex/AGENTS.md \
~/.hammerspoon/init.lua; do
# 用 cp -L 解引用 symlink,確保備份的是實體內容
[ -e "$f" ] && mkdir -p ~/.dotfiles-backup/"$(dirname "${f#$HOME/}")" \
&& cp -L "$f" ~/.dotfiles-backup/"${f#$HOME/}" \
&& rm "$f"
done
# 部署所有套件
chmod +x scripts/stow-wrap.sh
for pkg in zsh tmux ghostty cmux herdr claude claude-mods codex hammerspoon ripgrep git nvim; do
./scripts/stow-wrap.sh "$pkg"
done
p10k configure
~/.p10k.zsh由 p10k 精靈產生,不納入版控。專案中的36-p10k-theme.zsh會自動覆寫 Gruvbox 色彩主題。
Codex 的 hooks.json 已由 stow 部署,按以下步驟完成設定:
~/.codex/config.toml 啟用 feature flag: ``toml [features] codex_hooks = true ``./scripts/stow-wrap.sh claude 時,stow-wrap 會自動呼叫 scripts/sync-ai-cli-settings.sh:~/.<tool>/settings.json 不存在 → 直接複製 .example 範本jq 智慧合併:permissions.allow/deny 取聯集去重;hooks 以 command 字串為鍵冪等附加;env 同 key 以範本為準。plugins、mcpServers 等使用者自訂內容完全保留settings.json.bak.YYYYMMDD-HHMMSS 備份Claude Code 的
settings.json含機器專屬設定(plugins、MCP servers),無法整檔由 stow 管理,故改採「不存在則複製、已存在則合併」策略。jq為必要相依(brew install jq)。可用--dry-run預覽合併動作。
cp ~/dotfiles/config/zsh/zshrc.d/90-local.zsh.example ~/dotfiles/config/zsh/zshrc.d/90-local.zsh
編輯 90-local.zsh 加入機器專屬的 PATH、環境變數或 secrets 來源。~/zshrc.d/ 是指向 config/zsh/zshrc.d/ 的 symlink,因此直接在 dotfiles 內操作即可。此檔案已加入 .gitignore,不會被提交。
敏感資訊(API key、token)建議放在
~/.secrets,並在90-local.zsh中 source 它。
exec zsh
ls -la ~/.zshrc ~/.tmux.conf
alias
which fzf eza
./scripts/stow-wrap.sh zsh # 部署套件
./scripts/stow-wrap.sh --dry-run zsh # 預覽模式
./scripts/stow-wrap.sh --debug zsh # 除錯模式
./scripts/stow-wrap.sh --list-ignore # 列出忽略規則
./scripts/stow-wrap.sh -D zsh # 移除套件 symlink
claude、codex、herdr套件會自動以--no-folding模式部署(腳本內的NO_FOLDING_PKGS),避免將目標目錄折疊為單一 symlink,確保非 dotfiles 管理的檔案不受影響。多套件混合執行時會自動拆分為獨立呼叫。部署完成後,
config/shared/skills/內的共享 skills 會自動 symlink 至各 AI CLI 工具的~/.<tool>/skills/(腳本內的AI_CLI_PKGS,目前為claude、codex);工具專屬 skill 優先,不會被覆蓋。bin雖同為 no-folding 套件但不參與 skills 注入。shared不是合法的套件名稱,傳入會直接報錯。
--no-folding 為什麼必要stow 預設會做 directory folding:若目標目錄在 $HOME 尚不存在,stow 不會逐檔建 symlink,而是直接把整個目錄做成一個指向 repo 的 symlink。之後任何寫入該目錄的檔案都會實際落在 dotfiles repo 內。
實際案例:曾有一個 bin 套件(放 cmux-notify)對應 ~/.local/bin/,但 ~/.local/ 同時是 uv、Claude Code installer 等工具的安裝位置。~/.local 被折疊成 ~/.local -> dotfiles/config/bin/.local 後,這些工具安裝的內容累積到 1.5 GB 全部落在 repo 內。該套件已隨 cmux-notify 一併移除,但教訓保留於此。
判斷準則:只要套件的目標路徑或其上層目錄可能被 dotfiles 以外的程式寫入,就要加進 NO_FOLDING_PKGS。
例外:nvim 刻意保留 folding,~/.config/nvim 整個指向 repo。寫入其中的只有 Neovim 自身產物——lazy-lock.json、lazyvim.json(應納入版控)與 spell/(.spl 已 gitignore);外掛與 LSP 安裝在 ~/.local/share/nvim,不受影響。
同理,
.gitignore不要使用*.local這類樣式 —— gitignore 的*可匹配零字元,會連名為.local的目錄整棵樹一起忽略,使上述污染在git status完全隱形。
~/.zshrc ← Stow symlink,最小化 loader
├── direnv 預載 ← 在 instant prompt 前完成首次 .envrc 載入,避免 p10k 警告
├── p10k instant prompt ← 最頂端載入,確保 prompt 即時顯示
└── source zshrc.d/*.zsh ← 依檔名順序載入以下模組
├── 00-paths.zsh ← PATH 設定($HOME/bin、$HOME/.local/bin)
├── 01-env.zsh ← 環境變數(Powerline、NVM、Pyenv、ripgrep)
├── 02-omz.zsh ← Oh-My-Zsh 框架、主題、plugins
├── 10-functions.zsh ← 載入 functions.d/*.sh 輔助函式
├── 20-aliases.zsh ← 條件式別名(htop、bat、eza、tmux)
├── 30-fzf.zsh ← FZF 模糊搜尋(色彩、fd、preview、rfv)
├── 31-zoxide.zsh ← Zoxide 智慧目錄跳轉
├── 32-direnv.zsh ← direnv 目錄式環境變數自動載入(須先 brew install direnv)
├── 35-p10k.zsh ← 載入 ~/.p10k.zsh(各機器獨立)
├── 36-p10k-theme.zsh ← Gruvbox 色彩主題覆寫
└── 90-local.zsh ← 機器專屬設定(不納入版控)
每個模組使用 guard 變數(不 export)防止同一 shell 內重複載入,不會影響 tmux 等子 shell 的初始化。
兩個工具各自維護獨立的系統提示檔,皆透過 stow 管理。目前內容相同,可依不同 LLM 特性分別微調。
config/shared/skills/ 是所有 AI CLI 工具共用 skills 的唯一來源。部署時 stow-wrap.sh 自動將每個 skill 目錄 symlink 到各工具的 ~/.<tool>/skills/<skill>,無需手動同步。
若特定工具需要專屬 skill,將其放入 config/<tool>/.<tool>/skills/<skill>/;該目錄下的 skill 由既有 promote 流程優先處理,不會被共享版本覆蓋。
新增 / 修改共享 skill 只需操作 config/shared/skills/,重新執行 ./scripts/stow-wrap.sh <AI 工具套件> 即可生效。
由 cmux 自行處理,dotfiles 不再維護通知腳本。
| 工具 | 安裝方式 | 產生的檔案 |
|---|---|---|
| Claude Code | cmux Claude wrapper 自動注入,無須設定 | 無(wrapper 動態注入) |
| 其他 agent | cmux hooks setup <agent> | 各 agent 自己的 hook 檔(cmux 管理) |
Claude Code 只要 cmux 設定中 automation.claudeCodeIntegration 為 true 即生效:cmux 用 wrapper 包住 claude 執行檔(PATH 最前面的 cmux-cli-shims/),啟動時動態注入自己的 hooks, 提供 running/idle/needsInput 狀態、Feed 審批、session restore 與 PushNotification 橋接。
其他 agent(codex、opencode、gemini 等)用 cmux hooks setup 安裝,cmux 會寫入該 agent 自己的設定檔(Codex 為 ~/.codex/hooks.json 與 config.toml)。這些檔案由 cmux 管理,不納入 dotfiles——否則 cmux 更新格式時 repo 內的手寫版本會悄悄失效。
歷史:先前由 dotfiles 維護一支
cmux-notify腳本供各工具呼叫,因 cmux 變更 socket 路徑 (/tmp/cmux.sock→~/.local/state/cmux/cmux-<uid>.sock)而靜默失效。既然 cmux 已內建整合, 該腳本與其所屬的bin套件已一併移除。細節見cmux docs agents。
rpg-statusline.sh)claude 套件含 ~/.claude/rpg-statusline.sh(stow symlink),風格對齊 claude-mods 的遊戲 UI。 settings.json.example 的 statusLine 指向它,merge-settings.jq 會以範本覆蓋本機 statusLine。
COLUMNS 以段為單位自動換行:model + effort 星等、⚡ fast mode、目錄 / 分支 / ✎ dirty / 增刪行數 / PR、資源條、session 時長MP 為 context window(與 rpg-hud 人物面板的 MP 同義、同變色門檻),⌛5h / ⌛7d 為用量限額並附重置日期時間,⛁ cap 為 spend limit(僅 gateway)refreshInterval: 2:調整視窗寬度不會觸發 status line 更新,靠每 2 秒重跑讓換行跟上新寬度slime-band,不重複顯示~/.claude/settings.json 的 statusLine,並從 settings.json.example 移除,否則下次 stow-wrap.sh claude 會加回cc-notify.sh)claude 套件另含 ~/.config/claude/cc-notify.sh(由 stow 部署為 symlink),在 Claude Code 「工作真正完成」時發一則 Telegram 訊息。完成的判定依據 Stop hook payload 的 background_tasks 與 session_crons:主對話停下且沒有在等自己啟動的背景 shell、subagent、monitor、workflow 或排程喚醒, 才視為完成;另加 CC_NOTIFY_IDLE_WINDOW 秒的 trailing-edge debounce,期間有新 prompt 就取消, 讓快速回覆的 checkpoint collapse 成單一通知。相關 hooks(UserPromptSubmit/SubagentStart/Stop) 已寫入 settings.json.example,由 sync 合併(合併只取聯集,移除舊 hook 需手動刪 live 設定)。
設定:複製 ~/.config/claude/telegram.env.example 為 telegram.env 並填入 TELEGRAM_BOT_TOKEN、 TELEGRAM_CHAT_ID(此檔含 secret,不納入版控);可選用 CC_NOTIFY_IDLE_WINDOW(預設 25s)、 CC_NOTIFY_MIN_SECONDS(預設 10s,整個工作短於此不通知)與 CC_NOTIFY_DEBUG=1(hook 輸入寫入 /tmp/claude-cc-debug.log)。未設定 telegram.env 時腳本靜默略過。
claude 套件含 config/claude/.claude/output-styles/,由 stow 以 --no-folding 逐檔 symlink 到 ~/.claude/output-styles/,因此 Claude Code 自己在該目錄產生的 style 不受影響。目前收錄:
| Style | 用途 |
|---|---|
eli5 | 極簡回覆,只講做了什麼、成不成功、下一步做什麼 |
ste | 受控技術語言(ASD-STE100 Issue 9 紀律):單一詞義、短句、主動語態、零歧義 |
新增 style:在 config/claude/.claude/output-styles/ 放入 <name>.md(frontmatter 需含 name、description),再跑 ./scripts/stow-wrap.sh claude。切換用 /output-style。
claude-mods 套件收錄 config/claude-mods/.claude/mods/<mod>/,由 CLAUDE_CODE_PLUGIN_DIRS (settings.json.example 的 env,經 sync-ai-cli-settings.sh 合併)載入。目前收錄 rpg-hud、 slime-band、skill-bar。
此套件刻意不用 --no-folding:plugin loader 讀 hooks/hooks.json 時不跟隨 symlink,且 module realpath 落在 plugin 目錄外會被判為 path traversal,逐檔 symlink 會讓 mod 整個載入失敗。folding 後 ~/.claude/mods/<mod> 是指向 repo 的目錄 symlink,engine 產生的 .claude-plugin/types/ 會寫進 repo (已 gitignore)。
新增 mod:在 config/claude-mods/.claude/mods/ 建目錄、把路徑加進 settings.json.example 的 CLAUDE_CODE_PLUGIN_DIRS,再跑 ./scripts/stow-wrap.sh claude claude-mods。驗證用 claude plugin validate ~/.claude/mods/<mod> 與 claude plugin test ~/.claude/mods/<mod>。
各工具的設定檔(config.toml、settings.json、config.json)包含機器專屬內容,不納入版控,各機器獨立維護。
git pull 只更新 repo 內的檔案,無法撤銷既有部署。從 repo 刪除一個檔案後,其他機器上仍會留下:
sync-ai-cli-settings.sh 合併進 live ~/.claude/settings.json 的項目(該腳本只增不減)[hooks.state] trusted hash)因此凡是「下架」性質的變更,都在 scripts/ 下附一支 migrate-<YYYYMMDD>-<描述>.sh,記錄該次變更需要在其他機器上執行的清理步驟。慣例:
--dry-run,預覽時不得寫入任何檔案cp -p 保留權限),並在輸出中告知備份路徑若尚未 pull,優先在 pull 之前執行
./scripts/stow-wrap.sh -D <套件>解除部署——套件目錄一旦被 pull 刪除,stow -D就無法再運作。
config/ 下建立新目錄,結構反映 $HOME 下的相對路徑scripts/stow-wrap.sh 的 NO_FOLDING_PKGS(原因見上方「--no-folding 為什麼必要」)./scripts/stow-wrap.sh <套件名> 部署ls -ld ~/<目標目錄>hooks/register.tsx 695 lines1import { atom, read, update } from 'claude-code'
2import type { ElementTable, EngineInterface, Register, Timer } from 'claude-code'
3
4import type { BandInfo, ContextInfo } from '../types'
5import { layoutGauge, manaLevel } from './context-bar'
6import { TUBE_ROWS, TUBE_TICKS, groundPixels, groundSvg } from './mana-tube'
7import type { ContextGauge } from './context-bar'
8import { SLIME_FRAMES, SLIME_PALETTE, SLIME_ROWS, SLIME_WIDTH } from './slime-sprite'
9import type { SlimePose } from './slime-sprite'
10import { formatTokens, layoutHud } from './hud'
11import type { HudFact, HudPixel } from './hud'
12import { CAST_MS, sceneSize, sceneSvg, sceneWidth, walkAt } from './desktop'
13import { SHIMMER_TICKS, bannerFor, readMoments } from './banner'
14import type { Banner } from './banner'
15import type { SceneSlime } from './desktop'
16
17const info = atom({ plugin: 'slime-band', key: 'info' } as const, {
18 branch: '',
19 dirty: 0,
20 lastMs: 0,
21 inTokens: 0,
22 outTokens: 0,
23})
24
25const EMPTY_CONTEXT: ContextInfo = { slices: [], total: 0, max: 0, percent: 0 }
26const contextInfo = atom({ plugin: 'slime-band', key: 'context' } as const, EMPTY_CONTEXT)
27
28const FRAME_MS = 80
29// The desktop tube: CSS pixels per tube pixel, a band column's CSS width, and how long each ripple step holds.
30const TUBE_FRAME_MS = FRAME_MS * TUBE_TICKS
31// Ticks each hop frame (squash, stretch) stays up.
32const RUN_TICKS = 3
33// How long the slime sits after a turn before it naps.
34export const NAP_AFTER_MS = 20_000
35// How long the slime naps at the inn once the conversation is compacted, the mana poured back.
36export const REST_MS = 4000
37// Ticks each 'z Z' frame of the nap stays up.
38const SNORE_TICKS = 10
39
40const UPPER_HALF = 0x2580
41const LOWER_HALF = 0x2584
42const SPACE = 0x20
43const DEFAULT_COLOR = 0x01000000
44const SNORE_COLOR = 0xc8d2ff
45const ALERT_COLOR = 0xffd23c
46const SWEAT_COLOR = 0x7ad0ff
47const NOTE_COLOR = 0xffb4dc
48const FLASH = 0xffffff
49const SPARKS = [0xfff07a, 0xffffff, 0xffd23c]
50// While the person types, the slime stops to listen, and keeps listening this long after the last key.
51export const LISTEN_MS = 3000
52// A sent prompt: the slime crouches, leaps with a flash, and a ring of sparks flies off it. Ticks in all.
53export const CAST_TICKS = 9
54// The ring's directions from the slime's middle, a step of radius each tick.
55const SPARK_RAYS: ReadonlyArray<readonly [number, number]> = [[1, 0], [-1, 0], [0, -1], [1, -1], [-1, -1], [2, -1], [-2, -1]]
56// Ticks the '!' stays lit, then dark, while the slime waits on the person.
57const ALERT_TICKS = 5
58
59// The track: the slime's six pixel rows, then a grass row and a soil row.
60export const TRACK_ROWS = SLIME_ROWS + 1
61const GRASS_Y = SLIME_ROWS * 2
62const GRASS = [0x4caf50, 0x66bb6a, 0x4caf50, 0x81c784]
63const SOIL = [0x8d5a2b, 0x8d5a2b, 0x6d4220, 0x8d5a2b, 0x7a4b24]
64
65// A fixed pattern by column, so the floor stays still while the slime moves.
66export const floorAt = (col: number, y: number): number | undefined => {
67 if (y === GRASS_Y) return GRASS[col % GRASS.length]
68 if (y === GRASS_Y + 1) return SOIL[(col * 3) % SOIL.length]
69 return undefined
70}
71
72// Waiting on the person (a permission prompt, a question) it sits up, never hopping or napping.
73export const slimePose = (isWorking: boolean, idleMs: number, tick: number, isWaiting = false): SlimePose => {
74 if (isWaiting) return 'sit'
75 if (isWorking) return Math.floor(tick / RUN_TICKS) % 2 === 0 ? 'run1' : 'run2'
76 return idleMs >= NAP_AFTER_MS ? 'sleep' : 'sit'
77}
78
79// One step along the track, turning round at either end.
80export const stepSlime = (x: number, dir: 1 | -1, trackWidth: number) => {
81 const last = Math.max(0, trackWidth - SLIME_WIDTH)
82 const next = x + dir
83 if (next < 0) return { x: Math.min(1, last), dir: 1 as const }
84 if (next > last) return { x: Math.max(0, last - 1), dir: -1 as const }
85 return { x: next, dir }
86}
87
88const pixelAt = (pose: SlimePose, row: number, col: number, dir: 1 | -1): number | undefined => {
89 const line = SLIME_FRAMES[pose][row] ?? ''
90 const ch = line[dir === 1 ? col : SLIME_WIDTH - 1 - col] ?? '.'
91 return SLIME_PALETTE[ch]
92}
93
94// Where the mana nears the rune, embers glow through cracks in the soil under the grass.
95const EMBER = 0xff5a3a
96const isCrack = (col: number) => (col * 7 + 3) % 13 === 0
97
98// The whole track as Raster cells: the slime at `x`, the HUD's big numbers, the grass and soil, then the
99// ground below them (the mana tube set in soil) when there is one; the rest see-through.
100export const composeTrack = (
101 trackWidth: number,
102 slime: {
103 x: number
104 dir: 1 | -1
105 pose: SlimePose
106 snore: number
107 alert?: boolean
108 sweat?: boolean
109 embers?: boolean
110 // Listening to the person type: a note above its head, 0 on its right, 1 on its left.
111 note?: number
112 // Ticks into a cast: the slime flashes white, then sparks fly from it.
113 cast?: number
114 },
115 hud: readonly HudPixel[] = [],
116 ground?: readonly (readonly number[])[],
117): string => {
118 const lit = new Map(hud.map(pixel => [pixel.y * trackWidth + pixel.x, pixel.rgb]))
119 const groundTop = GRASS_Y + 2
120 // The cast: a white flash as it leaps, then the ring of sparks widening, a colour per step, gone at the end.
121 const isFlash = slime.cast !== undefined && slime.cast >= 2 && slime.cast <= 3
122 const sparks = new Map<number, number>()
123 if (slime.cast !== undefined && slime.cast >= 3) {
124 const reach = slime.cast - 2
125 const centerX = slime.x + SLIME_WIDTH / 2
126 for (const [dx, dy] of SPARK_RAYS) {
127 const x = Math.round(centerX + dx * (reach + 3))
128 const y = 3 + dy * Math.min(reach, 3)
129 if (x >= 0 && x < trackWidth && y >= 0 && y < GRASS_Y) sparks.set(y * trackWidth + x, SPARKS[reach % SPARKS.length]!)
130 }
131 }
132 const rows = TRACK_ROWS + Math.ceil((ground?.length ?? 0) / 2)
133 const colorAt = (col: number, y: number): number | undefined => {
134 if (y >= groundTop) return ground?.[y - groundTop]?.[col]
135 if (slime.embers === true && y === GRASS_Y + 1 && isCrack(col)) return EMBER
136 const floor = floorAt(col, y)
137 if (floor !== undefined) return floor
138 const spriteCol = col - slime.x
139 if (spriteCol >= 0 && spriteCol < SLIME_WIDTH) {
140 const sprite = pixelAt(slime.pose, y, spriteCol, slime.dir)
141 if (sprite !== undefined) return isFlash ? FLASH : sprite
142 }
143 const spark = sparks.get(y * trackWidth + col)
144 if (spark !== undefined) return spark
145 return lit.get(y * trackWidth + col)
146 }
147 const words = new Uint32Array(trackWidth * rows * 3)
148 for (let row = 0; row < rows; row += 1) {
149 for (let col = 0; col < trackWidth; col += 1) {
150 const at = (row * trackWidth + col) * 3
151 const top = colorAt(col, row * 2)
152 const bottom = colorAt(col, row * 2 + 1)
153 if (top === undefined && bottom === undefined) {
154 words.set([SPACE, DEFAULT_COLOR, DEFAULT_COLOR], at)
155 } else if (top === undefined) {
156 // A default foreground is the text colour, not see-through: paint the lower half.
157 words.set([LOWER_HALF, bottom ?? DEFAULT_COLOR, DEFAULT_COLOR], at)
158 } else {
159 words.set([UPPER_HALF, top, bottom ?? DEFAULT_COLOR], at)
160 }
161 }
162 }
163 // While napping, a 'z' then a 'Z' drift up beside its head.
164 if (slime.pose === 'sleep' && slime.snore > 0) {
165 const col = Math.min(trackWidth - 1, slime.x + (slime.dir === 1 ? SLIME_WIDTH - 2 : 1))
166 const glyph = slime.snore === 1 ? 0x7a : 0x5a
167 words.set([glyph, SNORE_COLOR, DEFAULT_COLOR], (0 * trackWidth + col) * 3)
168 }
169 // Listening, a note bobs above its head, now on one side, now the other.
170 if (slime.note !== undefined) {
171 const col = Math.max(0, Math.min(trackWidth - 1, slime.x + (slime.note === 0 ? SLIME_WIDTH - 3 : 2)))
172 words.set([0x266a, NOTE_COLOR, DEFAULT_COLOR], (0 * trackWidth + col) * 3)
173 }
174 // Low on mana, a drop of sweat beads behind its head.
175 if (slime.sweat === true) {
176 const col = Math.max(0, Math.min(trackWidth - 1, slime.dir === 1 ? slime.x - 1 : slime.x + SLIME_WIDTH))
177 words.set([0x2c, SWEAT_COLOR, DEFAULT_COLOR], (1 * trackWidth + col) * 3)
178 }
179 // Waiting on the person, a '!' blinks just ahead of its face.
180 if (slime.alert === true) {
181 const col = Math.max(0, Math.min(trackWidth - 1, slime.dir === 1 ? slime.x + SLIME_WIDTH : slime.x - 1))
182 words.set([0x21, ALERT_COLOR, DEFAULT_COLOR], (0 * trackWidth + col) * 3)
183 }
184 return toBase64(new Uint8Array(words.buffer))
185}
186
187// btoa takes a binary string; chunks keep fromCharCode's argument list short.
188const toBase64 = (bytes: Uint8Array): string => {
189 let binary = ''
190 for (let at = 0; at < bytes.length; at += 0x8000) {
191 binary += String.fromCharCode(...bytes.subarray(at, at + 0x8000))
192 }
193 return btoa(binary)
194}
195
196export { formatTokens }
197
198// Module state, so a reload starts the slime over.
199const slime = {
200 x: 0,
201 dir: 1 as 1 | -1,
202 tick: 0,
203 isWorking: false,
204 idleSince: 0,
205 // The tool a permission prompt asks about, or 'AskUserQuestion', while the session waits on the person.
206 waitingFor: undefined as string | undefined,
207 // The loop that tool runs in: a subagent's id, undefined for the main loop.
208 waitingAgent: undefined as string | undefined,
209 trackWidth: 0,
210 // The columns left of the HUD, where the slime hops.
211 areaWidth: 0,
212 hud: [] as HudPixel[],
213 // While a banner shows: its letters in each colour of its shimmer, taking turns on the terminal.
214 shimmer: [] as HudPixel[][],
215 // Draws the band again once the banner's moment passes.
216 bannerTimer: undefined as Timer | undefined,
217 requestId: '',
218 ticker: undefined as Timer | undefined,
219 shown: '',
220 // The context window the ground below the grass shows as a tube of mana; none, and the track ends at the soil.
221 mana: undefined as ContextInfo | undefined,
222 // The mana near the rune: the slime sweats.
223 isManaCritical: false,
224 // Until when the slime listens to the person typing.
225 listenUntil: 0,
226 // Until when it naps at the inn after the conversation was compacted.
227 restUntil: 0,
228 // The tick a sent prompt's cast began, while it plays.
229 castFrom: undefined as number | undefined,
230 // On an SVG surface: when the cast began, so a redraw within it keeps the sparks.
231 castAt: 0,
232 listenTimer: undefined as Timer | undefined,
233 // The surface that last drew the band.
234 surface: undefined as string | undefined,
235 // On an SVG surface: the lap the scene animates, from where and when it set off.
236 walk: undefined as { x: number; dir: 1 | -1; last: number; since: number } | undefined,
237 napTimer: undefined as Timer | undefined,
238}
239
240// The track's rows: the slime and its floor, and the ground under them while it shows the mana.
241const trackRows = () => TRACK_ROWS + (slime.mana === undefined ? 0 : TUBE_ROWS)
242
243// An SVG surface animates the scene itself and is drawn again only when the slime's state changes.
244const redraw = ($: EngineInterface) => {
245 if (slime.surface !== undefined && slime.surface !== 'terminal') $.ui.invalidate('ui.render')
246}
247
248async function paint($: EngineInterface) {
249 if (slime.trackWidth === 0) return
250 const now = await $.clock.now()
251 slime.tick += 1
252 const isWaiting = slime.waitingFor !== undefined
253 const isListening = !isWaiting && now < slime.listenUntil
254 const cast = slime.castFrom === undefined ? undefined : slime.tick - slime.castFrom
255 if (cast !== undefined && cast >= CAST_TICKS) slime.castFrom = undefined
256 const casting = cast !== undefined && cast < CAST_TICKS ? cast : undefined
257 // Casting it crouches then leaps; listening it sits still; otherwise as the turn has it.
258 const isResting = now < slime.restUntil
259 const pose: SlimePose =
260 casting !== undefined
261 ? casting < 2 ? 'run1' : casting < 5 ? 'run2' : 'sit'
262 : isListening ? 'sit'
263 : isResting ? 'sleep'
264 : slimePose(slime.isWorking, now - slime.idleSince, slime.tick, isWaiting)
265 const alert = isWaiting && Math.floor(slime.tick / ALERT_TICKS) % 2 === 0
266 // The slime only travels while it is in the air.
267 if (pose === 'run2' && casting === undefined) {
268 const moved = stepSlime(slime.x, slime.dir, slime.areaWidth)
269 slime.x = moved.x
270 slime.dir = moved.dir
271 }
272 const snore = pose === 'sleep' ? Math.floor(slime.tick / SNORE_TICKS) % 3 : 0
273 const hud = slime.shimmer.length > 0 ? (slime.shimmer[Math.floor(slime.tick / SHIMMER_TICKS) % slime.shimmer.length] ?? slime.hud) : slime.hud
274 // Near the rune the slime sweats and the cracks glow, by turns.
275 const danger = slime.isManaCritical && Math.floor(slime.tick / ALERT_TICKS) % 2 === 1
276 const ground = slime.mana === undefined ? undefined : groundPixels(slime.mana, slime.trackWidth, slime.tick, slime.isWorking)
277 const cells = composeTrack(
278 slime.trackWidth,
279 {
280 x: slime.x,
281 dir: slime.dir,
282 pose,
283 snore,
284 alert,
285 sweat: danger,
286 embers: danger,
287 ...(isListening ? { note: Math.floor(slime.tick / ALERT_TICKS) % 2 } : {}),
288 ...(casting === undefined ? {} : { cast: casting }),
289 },
290 hud,
291 ground,
292 )
293 if (cells === slime.shown) return
294
295 // A refusal and a failed blit both mean the track is not on screen.
296 const done = await $.ui
297 .blit({ requestId: slime.requestId, key: 'track', cells, columns: slime.trackWidth, rows: trackRows() })
298 .catch(() => ({ deny: 'blit failed' }))
299 if (done.deny !== undefined) {
300 slime.ticker?.cancel()
301 slime.ticker = undefined
302 slime.shown = ''
303 return
304 }
305 slime.shown = cells
306}
307
308async function refreshGit($: EngineInterface) {
309 const cwd = await $.session.cwd()
310 const branch = await $.process.run(['git', 'branch', '--show-current'], { cwd, timeoutMs: 2000 })
311 const status = await $.process.run(['git', 'status', '--porcelain'], { cwd, timeoutMs: 2000 })
312 const isRepo = branch.exitCode === 0
313 await update($, info, value => ({
314 ...value,
315 branch: isRepo ? branch.stdout.trim() || '(detached)' : '',
316 dirty: isRepo ? status.stdout.split('\n').filter(line => line.trim() !== '').length : 0,
317 }))
318}
319
320// A local estimate, as /context's summary counts it: no token-count requests.
321async function refreshContext($: EngineInterface) {
322 const usage = await $.session.usage({ breakdown: 'summary' })
323 const breakdown = usage.context.breakdown
324 if (breakdown === undefined) return
325 await update($, contextInfo, () => ({
326 slices: breakdown.categories.map(c => ({ name: c.name, tokens: c.tokens, color: c.color, kind: c.kind })),
327 total: breakdown.totalTokens,
328 max: breakdown.rawMaxTokens,
329 percent: breakdown.percentage,
330 compactAt: breakdown.isAutoCompactEnabled ? breakdown.autoCompactThreshold : undefined,
331 }))
332}
333
334// Only what the person's status line leaves out: it already shows the model,
335// the branch and a dirty mark, so the band adds the count of changed files.
336// The big numbers need RGB; the labels use the matching named colour.
337const FACT_COLORS = {
338 yellow: 0xffd23c,
339 cyan: 0x56c8dc,
340 magenta: 0xc88cff,
341 blue: 0x5aa9ff,
342 green: 0x5ad27a,
343 red: 0xff5f5f,
344} as const
345
346// The banner's shimmer: its colour, then a flash of white.
347const SHIMMER = 0xffffff
348
349const LABEL_HEX: Record<string, string> = Object.fromEntries(
350 Object.entries(FACT_COLORS).map(([name, rgb]) => [name, `#${rgb.toString(16).padStart(6, '0')}`]),
351)
352
353const MODE_ALT: Record<SceneSlime['mode'], string> = {
354 walk: 'hopping while Claude works',
355 sit: 'sitting',
356 sleep: 'napping',
357 wait: 'waiting on you',
358 listen: 'listening to you type',
359}
360
361const fact = (
362 key: string,
363 icon: string,
364 value: string,
365 label: string,
366 color: keyof typeof FACT_COLORS,
367): HudFact => ({ key, icon, value, label, color, rgb: FACT_COLORS[color] })
368
369export const infoSegments = (value: BandInfo, turns: number): HudFact[] => {
370 const segments: HudFact[] = []
371 if (value.branch !== '' && value.dirty > 0) {
372 segments.push({ ...fact('dirty', '✎', `${value.dirty}`, 'changed', 'yellow'), dropFirst: true })
373 }
374 segments.push(fact('turns', '↻', `${turns}`, turns === 1 ? 'turn' : 'turns', 'cyan'))
375 if (value.lastMs > 0) {
376 segments.push(
377 // On a narrow band the turn's time goes, after the changed count, before the token counts.
378 { ...fact('last', '◷', `${Math.round(value.lastMs / 1000)}s`, 'last turn', 'magenta'), dropFirst: true },
379 fact('in', '↓', formatTokens(value.inTokens), 'in', 'blue'),
380 fact('out', '↑', formatTokens(value.outTokens), 'out', 'green'),
381 )
382 }
383 return segments
384}
385
386// A banner as the band's one fact: the word in big letters, what happened beneath it.
387export const bannerFact = (banner: Banner, rgb?: number): HudFact => ({
388 ...fact('banner', banner.icon, banner.word, banner.label, banner.color),
389 ...(rgb === undefined ? {} : { rgb }),
390})
391
392// The facts the band shows now, a banner in their place while one lasts; the band is drawn again when it ends.
393async function bandFacts($: EngineInterface, value: BandInfo): Promise<{ facts: HudFact[]; banner?: Banner }> {
394 const now = await $.clock.now()
395 const banner = bannerFor(await readMoments($), now)
396 slime.bannerTimer?.cancel()
397 slime.bannerTimer = banner === undefined ? undefined : $.clock.after(banner.until - now, () => $.ui.invalidate('ui.render'))
398 if (banner !== undefined) return { facts: [bannerFact(banner)], banner }
399 return { facts: infoSegments(value, await $.session.turns()) }
400}
401
402const SEPARATOR = ' │ '
403
404export const infoLine = (value: BandInfo, turns: number): string =>
405 infoSegments(value, turns)
406 .map(s => `${s.icon} ${s.value} ${s.label}`)
407 .join(SEPARATOR)
408
409
410type BandElements = Pick<ElementTable<'terminal'>, 'Box' | 'Text'>
411
412// Under the ground: what the mana is made of, with how full it is at the line's end; a long legend goes on below.
413const renderGauge = ({ Box, Text }: BandElements, gauge: ContextGauge) => {
414 const legendRow = (row: readonly ContextGauge['legend'][number][]) =>
415 row.map((item, i) => (
416 <Text key={item.name}>
417 {i > 0 ? ' ' : ''}
418 {`${item.icon} `}
419 <Text color={item.color}>{item.name}</Text>
420 <Text dimColor> {item.tokens}</Text>
421 </Text>
422 ))
423 const [first = [], ...rest] = gauge.legendRows
424 return [
425 <Box key="ctx-info" flexDirection="row" height={1}>
426 <Box flexGrow={1}>
427 <Text wrap="truncate">{legendRow(first)}</Text>
428 </Box>
429 {/* The fill keeps its width: the legend gives way, never the numbers. */}
430 <Box flexShrink={0} marginLeft={2}>
431 <Text wrap="truncate">{fillText(Text, gauge)}</Text>
432 </Box>
433 </Box>,
434 ...rest.map((row, at) => (
435 <Text key={`ctx-legend-${at + 1}`} wrap="truncate">
436 {legendRow(row)}
437 </Text>
438 )),
439 ]
440}
441
442// `45%` in the mana's colour, then what is used out of what.
443const fillText = (Text: ElementTable['Text'], gauge: ContextGauge) => {
444 const [percent = '', tokens = ''] = gauge.fill.split(' · ')
445 return [
446 <Text key="fill-percent" color={gauge.percentColor} bold>{percent}</Text>,
447 <Text key="fill-tokens" dimColor>{` · ${tokens}`}</Text>,
448 ]
449}
450
451export const register: Register = on => {
452 on('session.start', async ($, e, next) => {
453 slime.idleSince = await $.clock.now()
454 await refreshGit($).catch(() => undefined)
455
456 return next(e)
457 })
458
459 // The engine raises this whenever the window's fill moves: turns, compaction, /clear, a /model switch.
460 on('session.measure', async ($, e, next) => {
461 const result = await next(e)
462 if (e.changed.includes('context')) await refreshContext($).catch(() => undefined)
463 return result
464 })
465
466 // /clear and resume end this conversation without a session.start: drop its gauge until the next measure.
467 // A compaction is a night at the inn: the slime naps while the mana pours back. Not a precompute, which installs
468 // nothing, nor a subagent's own.
469 on('session.compact', async ($, e, next) => {
470 const result = await next(e)
471 if (e.trigger === 'precompute' || e.agentId !== undefined || result.skip !== undefined) return result
472 slime.restUntil = (await $.clock.now()) + REST_MS
473 redraw($)
474 $.clock.after(REST_MS, () => redraw($))
475 return result
476 })
477
478 on('session.end', async ($, e, next) => {
479 await update($, contextInfo, () => EMPTY_CONTEXT)
480 return next(e)
481 })
482
483 // A permission prompt is about to ask the person; the slime waits with them until that tool is done. A hook
484 // beneath that decides leaves no prompt to wait on.
485 on('classic.PermissionRequest', async ($, e, next) => {
486 const result = await next(e)
487 if (result.decision === undefined) {
488 slime.waitingFor = e.tool_name
489 slime.waitingAgent = e.agent_id
490 redraw($)
491 }
492 return result
493 })
494
495 // A question to the person waits on them while it is open; a call of the tool a prompt asked about, in the
496 // same loop, ends the wait once it has run or been refused.
497 on('tool.call', async ($, e, next) => {
498 if (e.tool === 'AskUserQuestion') {
499 slime.waitingFor = e.tool
500 slime.waitingAgent = e.agentId
501 redraw($)
502 }
503 try {
504 return await next(e)
505 } finally {
506 if (slime.waitingFor === e.tool && slime.waitingAgent === e.agentId) {
507 slime.waitingFor = undefined
508 redraw($)
509 }
510 }
511 })
512
513 // The person typing: the slime stops to listen, until the box empties or the keys stop for a while.
514 on('prompt.edit', async ($, e, next) => {
515 const box = await next(e)
516 const now = await $.clock.now()
517 const wasListening = now < slime.listenUntil
518 slime.listenUntil = box.text.trim() === '' ? 0 : now + LISTEN_MS
519 // Typing wakes it from a nap.
520 slime.idleSince = Math.max(slime.idleSince, now)
521 if (slime.surface !== undefined && slime.surface !== 'terminal') {
522 slime.listenTimer?.cancel()
523 slime.listenTimer = slime.listenUntil === 0 ? undefined : $.clock.after(LISTEN_MS, () => $.ui.invalidate('ui.render'))
524 if (wasListening !== slime.listenUntil > now) redraw($)
525 }
526 return box
527 })
528
529 on('prompt.submit', async ($, e, next) => {
530 slime.isWorking = true
531 slime.waitingFor = undefined
532 // Sent: the slime casts it.
533 slime.listenUntil = 0
534 slime.castFrom = slime.tick
535 slime.castAt = await $.clock.now()
536 redraw($)
537
538 return next(e)
539 })
540
541 on('turn.complete', async ($, e, next) => {
542 // A subagent's turn ends inside the main one; only the main turn rests the slime.
543 if (e.agentId === undefined) {
544 slime.isWorking = false
545 slime.waitingFor = undefined
546 slime.idleSince = await $.clock.now()
547 const usage = e.usage
548 await update($, info, value => ({
549 ...value,
550 lastMs: e.durationMs,
551 inTokens: usage ? usage.input_tokens + usage.cache_read_input_tokens : value.inTokens,
552 outTokens: usage ? usage.output_tokens : value.outTokens,
553 }))
554 await refreshGit($).catch(() => undefined)
555 redraw($)
556 }
557
558 return next(e)
559 })
560
561 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
562 if (e.props.hasSurvey) {
563 return next(e)
564 }
565 const engine = await next(e)
566 const value = await read($, info)
567 const context = await read($, contextInfo)
568
569 slime.surface = e.surface
570 if (e.surface !== 'terminal') {
571 const { Box, Text, Svg } = $.ui.resolve(e)
572 const now = await $.clock.now()
573 if (e.props.isWorking && !slime.isWorking) slime.isWorking = true
574 const segments = (await bandFacts($, value)).facts
575 const width = sceneWidth(e.props.bodyColumns)
576 const hud = layoutHud(segments, width)
577 const last = Math.max(0, hud.areaWidth - SLIME_WIDTH)
578 const isWaiting = slime.waitingFor !== undefined
579 const isListening = !isWaiting && now < slime.listenUntil
580 // A lap that ends (rest, a wait, the person typing, a resize) leaves the slime where it had hopped to.
581 if (slime.walk !== undefined && (!slime.isWorking || isWaiting || isListening || slime.walk.last !== last)) {
582 const at = walkAt(slime.walk.x, slime.walk.dir, slime.walk.last, now - slime.walk.since)
583 slime.x = at.x
584 slime.dir = at.dir
585 slime.walk = undefined
586 }
587 slime.x = Math.min(slime.x, last)
588 if (slime.isWorking && !isWaiting && !isListening && slime.walk === undefined) {
589 slime.walk = { x: slime.x, dir: slime.dir, last, since: now }
590 }
591 const idleMs = now - slime.idleSince
592 const isResting = now < slime.restUntil
593 const mode: SceneSlime['mode'] = isWaiting ? 'wait' : isListening ? 'listen' : isResting ? 'sleep' : slime.walk ? 'walk' : idleMs >= NAP_AFTER_MS ? 'sleep' : 'sit'
594 const castMs = now - slime.castAt < CAST_MS ? now - slime.castAt : undefined
595 slime.napTimer?.cancel()
596 slime.napTimer = mode === 'sit' ? $.clock.after(NAP_AFTER_MS - idleMs, () => $.ui.invalidate('ui.render')) : undefined
597 const gauge = layoutGauge(context, e.props.bodyColumns)
598 // The ground under the soil shows the mana, a step of its ripple each hop.
599 const ground = gauge === undefined ? undefined : { info: context, isWorking: slime.isWorking, frameMs: TUBE_FRAME_MS }
600 const scene = sceneSvg(
601 width,
602 hud,
603 { mode, x: slime.walk?.x ?? slime.x, dir: slime.walk?.dir ?? slime.dir, last, ...(castMs === undefined ? {} : { castMs }) },
604 LABEL_HEX,
605 ground,
606 )
607 const size = sceneSize(width, ground !== undefined)
608 const facts = segments.map(s => `${s.icon} ${s.value} ${s.label}`).join(', ')
609
610 return (
611 <Box flexDirection="column">
612 <Svg
613 key="track"
614 source={scene}
615 alt={`Slime ${MODE_ALT[mode]}. ${facts}${gauge === undefined ? '' : `. Mana ${gauge.fill}`}`}
616 width={size.width}
617 height={size.height}
618 isInteractive
619 />
620 {gauge && (
621 <Box flexDirection="column">
622 <Box flexDirection="row" justifyContent="space-between" columnGap={2}>
623 <Box flexDirection="row" flexWrap="wrap" columnGap={2} flexShrink={1}>
624 {gauge.legend.map(item => (
625 <Text key={item.name}>
626 {`${item.icon} `}
627 <Text color={item.color}>{item.name}</Text>
628 <Text dimColor> {item.tokens}</Text>
629 </Text>
630 ))}
631 </Box>
632 <Box flexShrink={0}>
633 <Text>{fillText(Text, gauge)}</Text>
634 </Box>
635 </Box>
636 </Box>
637 )}
638 {engine}
639 </Box>
640 )
641 }
642
643 const { Box, Text, Raster } = $.ui.resolve(e)
644 if (e.props.isWorking && !slime.isWorking) {
645 slime.isWorking = true
646 }
647 const trackWidth = e.props.bodyColumns
648 const gauge = layoutGauge(context, trackWidth)
649 // The ground animates with the slime's ticker, in step with its hops; its first frame is drawn here.
650 slime.mana = gauge === undefined ? undefined : context
651 slime.isManaCritical = gauge !== undefined && manaLevel(context) === 'critical'
652 let band = await bandFacts($, value)
653 let hud = layoutHud(band.facts, trackWidth)
654 // A band too narrow for the banner keeps its facts.
655 if (band.banner !== undefined && hud.pixels.length === 0) {
656 band = { facts: infoSegments(value, await $.session.turns()) }
657 hud = layoutHud(band.facts, trackWidth)
658 }
659 slime.trackWidth = trackWidth
660 slime.areaWidth = hud.areaWidth
661 slime.hud = hud.pixels
662 slime.shimmer = band.banner === undefined ? [] : [hud.pixels, layoutHud([bannerFact(band.banner, SHIMMER)], trackWidth).pixels]
663 slime.x = Math.min(slime.x, Math.max(0, hud.areaWidth - SLIME_WIDTH))
664 slime.requestId = e.requestId
665 slime.ticker ??= $.clock.every(FRAME_MS, () => void paint($))
666 const pose = slimePose(slime.isWorking, (await $.clock.now()) - slime.idleSince, slime.tick, slime.waitingFor !== undefined)
667 const ground = slime.mana === undefined ? undefined : groundPixels(slime.mana, trackWidth, slime.tick, slime.isWorking)
668 slime.shown = composeTrack(trackWidth, { x: slime.x, dir: slime.dir, pose, snore: 0 }, hud.pixels, ground)
669
670 // Each label sits centred over its big number.
671 let cursor = 0
672 const labelPieces = hud.labels.map(label => {
673 const length = [...label.text].length
674 const start = label.x + Math.floor((label.width - length) / 2)
675 const pad = ' '.repeat(Math.max(0, start - cursor))
676 cursor = start + length
677 return (
678 <Text key={label.text}>
679 {pad}
680 <Text color={label.color}>{label.text}</Text>
681 </Text>
682 )
683 })
684
685 return (
686 <Box flexDirection="column">
687 <Text wrap="truncate">{labelPieces}</Text>
688 <Raster key="track" columns={trackWidth} rows={trackRows()} cells={slime.shown} />
689 {gauge && renderGauge({ Box, Text }, gauge)}
690 {engine}
691 </Box>
692 )
693 })
694}
695hooks/context-bar.ts 153 lines1// The context window under the slime's floor: a crystal tube of mana (mana-tube.ts)
2// across the band, then one line with what the mana is made of on the left and how
3// full it is on the right. The plain one-line gauge (one run of blocks per category)
4// is the text form, for tests and alt text.
5
6import type { ContextCategoryKind } from 'claude-code'
7
8import type { ContextInfo } from '../types'
9import { formatTokens } from './hud'
10import { hexOf, iconOf, liquidOf } from './liquids'
11
12// A mana crystal: single-width, so column math stays exact.
13const PREFIX = '◈ '
14export const OPEN = '▕'
15export const CLOSE = '▏'
16const MIN_GAUGE = 10
17// The narrowest tube worth drawing.
18const MIN_TUBE = 16
19
20const GLYPH: Record<ContextCategoryKind, string> = {
21 used: '█',
22 buffer: '▒',
23 free: '░',
24 deferred: '',
25}
26
27export type GaugeRun = { glyph: string; length: number; color: string; dim: boolean }
28// `color` is the liquid's, as hex, so a name reads in the colour of its layer in the tube.
29export type LegendItem = { icon: string; name: string; tokens: string; color: string }
30export type ManaLevel = 'ok' | 'low' | 'critical'
31export type ContextGauge = {
32 prefix: string
33 // The band's full width: the tube's too.
34 width: number
35 runs: GaugeRun[]
36 suffix: string
37 percentColor: string
38 // How full, at the end of the legend's first line: `45% · 90k / 200k`.
39 fill: string
40 legend: LegendItem[]
41 // The legend broken into rows that fit, each item whole; the first leaves room for the fill.
42 legendRows: LegendItem[][]
43}
44
45const LEGEND_GAP = 2
46
47// The icon is an emoji two cells wide.
48export const itemWidth = (item: LegendItem): number => [...`${item.icon} ${item.name} ${item.tokens}`].length + 1
49
50export const rowWidth = (row: readonly LegendItem[]): number =>
51 row.reduce((sum, item, at) => sum + itemWidth(item) + (at > 0 ? LEGEND_GAP : 0), 0)
52
53// Greedy rows from the left edge; an item wider than a row gets one to itself.
54export const wrapLegend = (items: readonly LegendItem[], available: number): LegendItem[][] => {
55 const room = Math.max(1, available)
56 const rows: LegendItem[][] = []
57 let row: LegendItem[] = []
58 let used = 0
59 for (const item of items) {
60 const width = itemWidth(item)
61 const needed = row.length === 0 ? width : used + LEGEND_GAP + width
62 if (row.length > 0 && needed > room) {
63 rows.push(row)
64 row = [item]
65 used = width
66 } else {
67 row.push(item)
68 used = needed
69 }
70 }
71 if (row.length > 0) rows.push(row)
72 return rows
73}
74
75// Green while roomy, amber as it nears its limit, red just short of it. The
76// limit is where auto-compaction runs, or the full window when it is off.
77export const manaLevel = (info: Pick<ContextInfo, 'percent' | 'max' | 'compactAt'>): ManaLevel => {
78 const limit = info.compactAt !== undefined && info.max > 0 ? (info.compactAt / info.max) * 100 : 100
79 if (info.percent >= limit - 10) return 'critical'
80 if (info.percent >= limit - 25) return 'low'
81 return 'ok'
82}
83
84const LEVEL_COLOR: Record<ManaLevel, string> = { ok: '#5ad27a', low: '#ffd23c', critical: '#ff5f5f' }
85
86export const percentColor = (info: Pick<ContextInfo, 'percent' | 'max' | 'compactAt'>): string =>
87 LEVEL_COLOR[manaLevel(info)]
88
89// Cells per slice by largest remainder, so the runs fill the gauge exactly and
90// every non-empty slice keeps at least one cell.
91export const allocateCells = (slices: readonly ContextInfo['slices'][number][], width: number): number[] => {
92 const total = slices.reduce((sum, s) => sum + s.tokens, 0)
93 // Negated so a NaN total bails too: no slice would take a cell and the loop below would never end.
94 if (!(total > 0) || width <= 0) return slices.map(() => 0)
95 const exact = slices.map(s => (s.tokens / total) * width)
96 const cells = exact.map((x, at) => ((slices[at]?.tokens ?? 0) > 0 ? Math.max(1, Math.floor(x)) : 0))
97 let left = width - cells.reduce((sum, n) => sum + n, 0)
98 const order = exact.map((x, at) => ({ at, rest: x - Math.floor(x) })).sort((a, b) => b.rest - a.rest)
99 for (let i = 0; left > 0 && order.length > 0; i = (i + 1) % order.length) {
100 const at = order[i]?.at ?? 0
101 if ((slices[at]?.tokens ?? 0) > 0) {
102 cells[at] = (cells[at] ?? 0) + 1
103 left -= 1
104 }
105 }
106 // Minimums can overshoot on a narrow gauge: take back from the largest.
107 while (left < 0) {
108 const big = cells.indexOf(Math.max(...cells))
109 cells[big] = (cells[big] ?? 0) - 1
110 left += 1
111 }
112 return cells
113}
114
115// The tube and its line across `columns`; undefined when there is nothing to show or no room for it.
116export const layoutGauge = (info: ContextInfo, columns: number): ContextGauge | undefined => {
117 const slices = info.slices.filter(s => s.kind !== 'deferred')
118 if (slices.length === 0 || info.max <= 0) return undefined
119 const suffix = ` ${info.percent}% ${formatTokens(info.total)}/${formatTokens(info.max)}`
120 // bodyColumns already leaves out the engine's '[-]' column: the gauge takes it all.
121 if (columns < MIN_TUBE) return undefined
122 const fill = `${info.percent}% · ${formatTokens(info.total)} / ${formatTokens(info.max)}`
123 const width = columns - [...PREFIX].length - OPEN.length - CLOSE.length - [...suffix].length
124 if (width < MIN_GAUGE) return undefined
125 const cells = allocateCells(slices, width)
126 const runs: GaugeRun[] = []
127 slices.forEach((s, at) => {
128 const length = cells[at] ?? 0
129 if (length > 0) runs.push({ glyph: GLYPH[s.kind], length, color: s.color, dim: s.kind === 'free' })
130 })
131 const legend = slices
132 .filter(s => s.kind === 'used' && s.tokens > 0)
133 .map(s => ({ icon: iconOf(s.name), name: s.name, tokens: formatTokens(s.tokens), color: hexOf(liquidOf(s.name)) }))
134 const level = manaLevel(info)
135 return {
136 prefix: PREFIX,
137 width: columns,
138 runs,
139 suffix,
140 percentColor: LEVEL_COLOR[level],
141 fill,
142 legend,
143 legendRows: wrapLegend(legend, columns - fill.length - LEGEND_GAP),
144 }
145}
146
147// The plain-text gauge, for surfaces without colour runs and for tests.
148export const gaugeLine = (gauge: ContextGauge): string =>
149 `${gauge.prefix}${OPEN}${gauge.runs.map(r => r.glyph.repeat(r.length)).join('')}${CLOSE}${gauge.suffix}`
150
151export const legendLines = (gauge: ContextGauge): string[] =>
152 gauge.legendRows.map(row => row.map(item => `${item.icon} ${item.name} ${item.tokens}`).join(' '.repeat(LEGEND_GAP)))
153hooks/mana-tube.ts 180 lines1// The context window as a crystal tube of mana set in the soil under the slime's grass, a cross-section of the
2// ground it hops on: each /context category a layer of
3// liquid in its own colour, the empty glass beyond, and a red rune where auto-compaction runs, the buffer past
4// it hatched off. The surface ripples, bubbles rise while Claude works, and the liquid flushes red near the rune.
5
6import type { ContextInfo } from '../types'
7import { allocateCells, manaLevel } from './context-bar'
8import { hexOf, liquidOf } from './liquids'
9
10// Three terminal rows of half blocks: six pixels, the rims and four of liquid.
11export const TUBE_ROWS = 3
12const HEIGHT = TUBE_ROWS * 2
13// Ticks each step of the ripple and the bubbles holds.
14export const TUBE_TICKS = 3
15
16const GLASS = 0x8fa6cf
17const GLASS_DARK = 0x4a5878
18const EMPTY = 0x161b2a
19const EMPTY_SHINE = 0x2a3350
20const RUNE = 0xff3b3b
21const RUNE_GLOW = 0xffa0a0
22const HATCH = 0x6a1c28
23const BUFFER = 0x24141c
24const BUBBLE = 0xe6f6ff
25const FOAM = 0xbfe0ff
26const DANGER = 0xff3b3b
27
28const scale = (color: number, k: number): number => {
29 const channel = (shift: number) => Math.min(255, Math.round(((color >> shift) & 0xff) * k)) << shift
30 return channel(16) | channel(8) | channel(0)
31}
32
33const mix = (a: number, b: number, share: number): number => {
34 const channel = (shift: number) => Math.round(((a >> shift) & 0xff) * (1 - share) + ((b >> shift) & 0xff) * share) << shift
35 return channel(16) | channel(8) | channel(0)
36}
37
38const noise = (k: number): number => {
39 let hash = Math.imul(k + 1, 374761393)
40 hash = Math.imul(hash ^ (hash >>> 13), 1274126177)
41 return ((hash ^ (hash >>> 16)) >>> 0) / 4294967296
42}
43
44type Column = { kind: 'used' | 'free' | 'buffer'; color: number }
45
46// What fills each column inside the glass, left to right, as /context orders its rows.
47export const tubeColumns = (info: ContextInfo, inner: number): Column[] => {
48 const slices = info.slices.filter(s => s.kind !== 'deferred' && s.tokens > 0)
49 const cells = allocateCells(slices, inner)
50 const columns: Column[] = []
51 slices.forEach((s, at) => {
52 const kind = s.kind === 'free' || s.kind === 'buffer' ? s.kind : 'used'
53 for (let n = 0; n < (cells[at] ?? 0); n += 1) columns.push({ kind, color: liquidOf(s.name) })
54 })
55 return columns
56}
57
58// The tube `width` pixels wide at animation `tick`: a colour per pixel, undefined outside the rounded glass.
59export const tubePixels = (info: ContextInfo, width: number, tick: number, isWorking: boolean): (number | undefined)[][] => {
60 const inner = Math.max(0, width - 2)
61 const columns = tubeColumns(info, inner)
62 const step = Math.floor(tick / TUBE_TICKS)
63 const isCritical = manaLevel(info) === 'critical'
64 // Near the rune the liquid flushes red every other step.
65 const flush = isCritical && step % 2 === 0 ? 0.5 : 0
66 const surface = columns.reduce((last, column, at) => (column.kind === 'used' ? at : last), -1)
67 const rune = columns.findIndex(column => column.kind === 'buffer')
68 const pixels: (number | undefined)[][] = Array.from({ length: HEIGHT }, () => Array.from({ length: width }, () => undefined))
69 const set = (x: number, y: number, color: number) => {
70 const row = pixels[y]
71 if (row !== undefined && x >= 0 && x < width) row[x] = color
72 }
73
74 // The glass: rounded rims above and below, the ends between.
75 for (let x = 1; x < width - 1; x += 1) {
76 set(x, 0, GLASS)
77 set(x, HEIGHT - 1, GLASS_DARK)
78 }
79 for (let y = 1; y < HEIGHT - 1; y += 1) {
80 set(0, y, GLASS)
81 set(width - 1, y, GLASS_DARK)
82 }
83
84 columns.forEach((column, at) => {
85 const x = at + 1
86 for (let y = 1; y < HEIGHT - 1; y += 1) {
87 if (column.kind === 'free') {
88 // Empty glass, a line of reflection along its top.
89 set(x, y, y === 1 ? EMPTY_SHINE : EMPTY)
90 } else if (column.kind === 'buffer') {
91 set(x, y, (x + y) % 3 === 0 ? HATCH : BUFFER)
92 } else {
93 const base = flush > 0 ? mix(column.color, DANGER, flush) : column.color
94 // Lit along the top, shaded along the bottom, so the liquid reads round.
95 const shade = y === 1 ? 1.3 : y === HEIGHT - 2 ? 0.68 : 1
96 set(x, y, scale(base, shade))
97 }
98 }
99 })
100
101 // The surface sloshes: its last two columns take turns dipping under a fleck of foam, and every other step
102 // the liquid runs a column on along the bottom of the empty glass.
103 if (surface >= 0) {
104 const dip = step % 2 === 0 ? surface : surface - 1
105 if (dip >= 0) {
106 set(dip + 1, 1, EMPTY_SHINE)
107 set(dip + 1, 2, FOAM)
108 }
109 const color = columns[surface]?.color ?? FOAM
110 if (step % 2 === 1 && columns[surface + 1]?.kind === 'free') {
111 set(surface + 2, HEIGHT - 3, FOAM)
112 set(surface + 2, HEIGHT - 2, scale(color, 0.68))
113 }
114 }
115
116 // Bubbles rise through the liquid while Claude works, a few per stretch of it.
117 if (isWorking && surface > 2) {
118 const count = Math.max(1, Math.floor(surface / 10))
119 for (let k = 0; k < count; k += 1) {
120 const x = 1 + Math.floor(noise(k) * surface)
121 const y = HEIGHT - 2 - Math.floor((step + k * 3) % (HEIGHT - 2))
122 if (columns[x - 1]?.kind === 'used') set(x, y, BUBBLE)
123 }
124 }
125
126 // The rune where auto-compaction runs, through both rims; it glows while the mana nears it.
127 if (rune >= 0) {
128 const glow = isCritical && step % 2 === 1 ? RUNE_GLOW : RUNE
129 for (let y = 0; y < HEIGHT; y += 1) set(rune + 1, y, glow)
130 }
131 return pixels
132}
133
134// The soil the tube is set in, a few shades by position so it reads as earth.
135const SOIL = [0x8d5a2b, 0x8d5a2b, 0x6d4220, 0x8d5a2b, 0x7a4b24]
136export const soilAt = (x: number, y: number): number => SOIL[(x * 3 + y * 2) % SOIL.length]!
137
138// The ground under the grass, `width` pixels across: the tube with a column of soil at either end, and soil
139// where its rounded corners leave the glass.
140export const groundPixels = (info: ContextInfo, width: number, tick: number, isWorking: boolean): number[][] => {
141 const tube = tubePixels(info, Math.max(0, width - 2), tick, isWorking)
142 return Array.from({ length: HEIGHT }, (_, y) =>
143 Array.from({ length: width }, (_, x) => (x === 0 || x === width - 1 ? undefined : tube[y]?.[x - 1]) ?? soilAt(x, y)),
144 )
145}
146
147// Frames of the ground for a surface that animates SVG itself: one step of the ripple each.
148export const GROUND_FRAMES = 4
149
150// The ground's frames as SVG shown in turn by SMIL, `top` CSS pixels down; `px` CSS pixels per pixel.
151export const groundSvg = (info: ContextInfo, width: number, isWorking: boolean, px: number, frameMs: number, top: number): string => {
152 const frames = Array.from({ length: GROUND_FRAMES }, (_, frame) => groundPixels(info, width, frame * TUBE_TICKS, isWorking))
153 const rects = (pixels: number[][]) =>
154 pixels
155 .map((row, y) => {
156 let out = ''
157 let x = 0
158 while (x < row.length) {
159 const color = row[x]
160 let end = x + 1
161 while (end < row.length && row[end] === color) end += 1
162 out += `<rect x="${x * px}" y="${top + y * px}" width="${(end - x) * px}" height="${px}" fill="${hexOf(color ?? 0)}"/>`
163 x = end
164 }
165 return out
166 })
167 .join('')
168 const cycle = GROUND_FRAMES * frameMs
169 return frames
170 .map((frame, at) => {
171 const values = Array.from({ length: GROUND_FRAMES }, (_, n) => (n === at ? 'visible' : 'hidden')).join(';')
172 return (
173 `<g visibility="${at === 0 ? 'visible' : 'hidden'}">` +
174 `<animate attributeName="visibility" values="${values}" calcMode="discrete" dur="${cycle}ms" repeatCount="indefinite"/>` +
175 `${rects(frame)}</g>`
176 )
177 })
178 .join('')
179}
180hooks/slime-sprite.ts 51 lines1// One character per pixel; '.' is see-through. The slime faces right.
2export const SLIME_PALETTE: Record<string, number> = {
3 G: 0x5aa9ff,
4 g: 0x2a5fb4,
5 L: 0xd2e8ff,
6 K: 0x191e23,
7 P: 0xff8caa,
8}
9
10export const SLIME_WIDTH = 12
11// Six pixels tall: three terminal rows of half blocks.
12export const SLIME_ROWS = 3
13
14export const SLIME_FRAMES = {
15 // A slime: it hops (squash, then stretch) instead of running.
16 run1: [
17 '............',
18 '............',
19 '...GGGGGG...',
20 '.GLLGGGGGGG.',
21 'GGGGGKGGKGGG',
22 '.gggggggggg.',
23 ],
24 run2: [
25 '....GGGG....',
26 '...GLGGGG...',
27 '..GLGKGGKGG.',
28 '..GGGGGGGGG.',
29 '...GGGGGG...',
30 '....gggg....',
31 ],
32 sit: [
33 '............',
34 '....GGGG....',
35 '..GLLGGGGG..',
36 '.GLGGKGGKGG.',
37 '.GGGPGGGGPG.',
38 '..gggggggg..',
39 ],
40 sleep: [
41 '............',
42 '............',
43 '............',
44 '...GGGGGG...',
45 '.GLGggGGggG.',
46 'gggggggggggg',
47 ],
48} as const
49
50export type SlimePose = keyof typeof SLIME_FRAMES
51hooks/hud.ts 131 lines1// Big pixel numbers on the right of the slime's track: a 3x5 font in half
2// blocks, one colour per fact, its label in small text on the row below.
3
4// '#' is a lit pixel. Every glyph is five pixels tall.
5const FONT: Record<string, readonly string[]> = {
6 '0': ['###', '#.#', '#.#', '#.#', '###'],
7 '1': ['.#.', '##.', '.#.', '.#.', '###'],
8 '2': ['###', '..#', '###', '#..', '###'],
9 '3': ['###', '..#', '###', '..#', '###'],
10 '4': ['#.#', '#.#', '###', '..#', '..#'],
11 '5': ['###', '#..', '###', '..#', '###'],
12 '6': ['###', '#..', '###', '#.#', '###'],
13 '7': ['###', '..#', '.#.', '.#.', '.#.'],
14 '8': ['###', '#.#', '###', '#.#', '###'],
15 '9': ['###', '#.#', '###', '..#', '###'],
16 '.': ['.', '.', '.', '.', '#'],
17 k: ['#..', '#.#', '##.', '#.#', '#.#'],
18 s: ['.##', '#..', '.#.', '..#', '##.'],
19 // Capitals for the event banners: LEVEL UP!, VICTORY!, BOSS!
20 A: ['.#.', '#.#', '###', '#.#', '#.#'],
21 B: ['##.', '#.#', '##.', '#.#', '##.'],
22 C: ['.##', '#..', '#..', '#..', '.##'],
23 D: ['##.', '#.#', '#.#', '#.#', '##.'],
24 E: ['###', '#..', '##.', '#..', '###'],
25 F: ['###', '#..', '##.', '#..', '#..'],
26 G: ['.##', '#..', '#.#', '#.#', '.##'],
27 H: ['#.#', '#.#', '###', '#.#', '#.#'],
28 I: ['###', '.#.', '.#.', '.#.', '###'],
29 J: ['..#', '..#', '..#', '#.#', '.#.'],
30 K: ['#.#', '#.#', '##.', '#.#', '#.#'],
31 L: ['#..', '#..', '#..', '#..', '###'],
32 M: ['#.#', '###', '###', '#.#', '#.#'],
33 N: ['##.', '#.#', '#.#', '#.#', '#.#'],
34 O: ['.#.', '#.#', '#.#', '#.#', '.#.'],
35 P: ['##.', '#.#', '##.', '#..', '#..'],
36 Q: ['.#.', '#.#', '#.#', '##.', '.##'],
37 R: ['##.', '#.#', '##.', '#.#', '#.#'],
38 S: ['.##', '#..', '.#.', '..#', '##.'],
39 T: ['###', '.#.', '.#.', '.#.', '.#.'],
40 U: ['#.#', '#.#', '#.#', '#.#', '###'],
41 V: ['#.#', '#.#', '#.#', '#.#', '.#.'],
42 W: ['#.#', '#.#', '###', '###', '#.#'],
43 X: ['#.#', '#.#', '.#.', '#.#', '#.#'],
44 Y: ['#.#', '#.#', '.#.', '.#.', '.#.'],
45 Z: ['###', '..#', '.#.', '#..', '###'],
46 '!': ['#', '#', '#', '.', '#'],
47 ' ': ['..', '..', '..', '..', '..'],
48}
49
50// The slime keeps at least this many columns to hop in.
51export const SLIME_AREA_MIN = 24
52// Columns between two facts.
53const BLOCK_GAP = 3
54// The track is six pixels tall and glyphs five, plus one for the extrusion:
55// starting at the top puts the extrusion on the ground row the slime stands on.
56const GLYPH_TOP = 0
57// The extrusion: one pixel down and right of the face, in a darker shade.
58const DEPTH = 1
59const SHADE = 0.45
60
61const shade = (rgb: number): number =>
62 [16, 8, 0].reduce((out, shift) => out | (Math.round(((rgb >> shift) & 0xff) * SHADE) << shift), 0)
63
64// `dropFirst` facts go before any other when the band is narrow, in their order; the rest drop from the last.
65export type HudFact = { key: string; icon: string; value: string; label: string; color: string; rgb: number; dropFirst?: boolean }
66export type HudPixel = { x: number; y: number; rgb: number }
67export type HudLabel = { x: number; width: number; text: string; color: string }
68export type HudLayout = { areaWidth: number; pixels: HudPixel[]; labels: HudLabel[] }
69
70export const formatTokens = (n: number): string => {
71 if (n < 1000) return `${n}`
72 const k = n / 1000
73 return k >= 100 ? `${Math.round(k)}k` : `${k.toFixed(1)}k`
74}
75
76const glyphWidth = (ch: string): number => FONT[ch]?.[0]?.length ?? 0
77
78// Pixel width of a value: glyphs one column apart, plus the extrusion past the last one.
79export const valueWidth = (value: string): number =>
80 [...value].reduce((sum, ch, at) => sum + glyphWidth(ch) + (at > 0 ? 1 : 0), 0) + (value === '' ? 0 : DEPTH)
81
82const labelText = (fact: HudFact): string => `${fact.icon} ${fact.label}`
83
84const blockWidth = (fact: HudFact): number =>
85 Math.max(valueWidth(fact.value), [...labelText(fact)].length)
86
87// Right-aligned facts, flush with the band's edge (bodyColumns already leaves out
88// the engine's '[-]'); when the slime would be squeezed the `dropFirst` ones go,
89// then the last ones.
90export const layoutHud = (facts: readonly HudFact[], trackWidth: number): HudLayout => {
91 let shown = [...facts]
92 const widthOf = (list: readonly HudFact[]) =>
93 list.reduce((sum, fact) => sum + blockWidth(fact) + BLOCK_GAP, 0) - BLOCK_GAP
94 while (shown.length > 0 && trackWidth - widthOf(shown) - BLOCK_GAP < SLIME_AREA_MIN) {
95 const first = shown.findIndex(fact => fact.dropFirst)
96 shown = first === -1 ? shown.slice(0, -1) : shown.filter((_, at) => at !== first)
97 }
98 if (shown.length === 0) return { areaWidth: trackWidth, pixels: [], labels: [] }
99
100 const hudWidth = widthOf(shown)
101 const pixels: HudPixel[] = []
102 const labels: HudLabel[] = []
103 let x = trackWidth - hudWidth
104 for (const fact of shown) {
105 const width = blockWidth(fact)
106 // The number sits centred over its label.
107 let glyphX = x + Math.floor((width - valueWidth(fact.value)) / 2)
108 const face = new Map<string, HudPixel>()
109 for (const ch of fact.value) {
110 const rows = FONT[ch] ?? []
111 for (let y = 0; y < rows.length; y += 1) {
112 const row = rows[y] ?? ''
113 for (let dx = 0; dx < row.length; dx += 1) {
114 const pixel = { x: glyphX + dx, y: y + GLYPH_TOP, rgb: fact.rgb }
115 if (row[dx] === '#') face.set(`${pixel.x},${pixel.y}`, pixel)
116 }
117 }
118 glyphX += glyphWidth(ch) + 1
119 }
120 const rgb = shade(fact.rgb)
121 pixels.push(...face.values())
122 for (const pixel of face.values()) {
123 const side = { x: pixel.x + DEPTH, y: pixel.y + DEPTH, rgb }
124 if (!face.has(`${side.x},${side.y}`)) pixels.push(side)
125 }
126 labels.push({ x, width, text: labelText(fact), color: fact.color })
127 x += width + BLOCK_GAP
128 }
129 return { areaWidth: trackWidth - hudWidth - BLOCK_GAP, pixels, labels }
130}
131hooks/desktop.ts 193 lines1// The band on surfaces that draw SVG (desktop, editor, mobile): the slime's
2// track as one vector scene, animated by SMIL inside the surface's sandboxed
3// frame, so the hook redraws only when the slime's state changes, never per frame.
4
5import { SLIME_FRAMES, SLIME_PALETTE, SLIME_WIDTH } from './slime-sprite'
6import type { SlimePose } from './slime-sprite'
7import type { HudLayout } from './hud'
8import type { ContextInfo } from '../types'
9import { TUBE_ROWS, groundSvg } from './mana-tube'
10
11// CSS pixels per sprite pixel.
12export const PX = 6
13// CSS pixels a band column is taken to span; an overestimate only scales the scene down to its slot.
14const COLUMN_PX = 8
15// The label strip above the track, in sprite pixels.
16const LABEL_ROWS = 2
17// Sprite rows, then grass and soil.
18const SPRITE_ROWS = 6
19const TRACK_PIXELS = SPRITE_ROWS + 2
20
21// The terminal moves the slime one pixel per hop: a squash and a stretch of three 80ms ticks each.
22export const HOP_MS = 480
23const ALERT_MS = 400
24const SNORE_MS = 800
25
26const GRASS = ['#4caf50', '#66bb6a', '#4caf50', '#81c784']
27const SOIL = ['#8d5a2b', '#8d5a2b', '#6d4220', '#8d5a2b', '#7a4b24']
28const SNORE_COLOR = '#c8d2ff'
29const ALERT_COLOR = '#ffd23c'
30
31const hex = (rgb: number) => `#${rgb.toString(16).padStart(6, '0')}`
32
33// The track's width in sprite pixels for a band `columns` wide.
34export const sceneWidth = (columns: number): number => Math.max(SLIME_WIDTH * 2, Math.floor((columns * COLUMN_PX) / PX))
35
36// Horizontal runs of one colour, so a row of pixels is a handful of rects.
37const runsToRects = (rows: readonly (string | undefined)[][], top: number): string => {
38 let out = ''
39 rows.forEach((row, y) => {
40 let x = 0
41 while (x < row.length) {
42 const color = row[x]
43 let end = x + 1
44 while (end < row.length && row[end] === color) end += 1
45 if (color !== undefined) {
46 out += `<rect x="${x * PX}" y="${(y + top) * PX}" width="${(end - x) * PX}" height="${PX}" fill="${color}"/>`
47 }
48 x = end
49 }
50 })
51 return out
52}
53
54const spriteRects = (pose: SlimePose, dir: 1 | -1): string => {
55 const rows = SLIME_FRAMES[pose].map(line => {
56 const chars = [...line]
57 if (dir === -1) chars.reverse()
58 return chars.map(ch => {
59 const rgb = SLIME_PALETTE[ch]
60 return rgb === undefined ? undefined : hex(rgb)
61 })
62 })
63 return runsToRects(rows, LABEL_ROWS)
64}
65
66const blink = (ms: number, from: 'visible' | 'hidden', begin = '0s') => {
67 const to = from === 'visible' ? 'hidden' : 'visible'
68 return `<animate attributeName="visibility" values="${from};${to}" keyTimes="0;0.5" calcMode="discrete" dur="${ms}ms" begin="${begin}" repeatCount="indefinite"/>`
69}
70
71// Where the ping-pong walk is after `ms` of hopping from (x, dir) over an area whose last slime column is `last`.
72export const walkAt = (x: number, dir: 1 | -1, last: number, ms: number): { x: number; dir: 1 | -1 } => {
73 if (last <= 0) return { x: 0, dir }
74 const period = last * 2
75 const start = dir === 1 ? x : period - x
76 const u = (start + Math.floor(ms / HOP_MS)) % period
77 return u < last ? { x: u, dir: 1 } : { x: period - u, dir: -1 }
78}
79
80export type SceneSlime = {
81 // 'walk' hops back and forth from (x, dir); the others hold still at x. 'listen' sits with a note, the
82 // person typing.
83 mode: 'walk' | 'sit' | 'sleep' | 'wait' | 'listen'
84 x: number
85 dir: 1 | -1
86 // The slime's last column in the area left of the HUD.
87 last: number
88 // How far into a cast the scene is drawn, in ms: the ring of sparks plays once from there.
89 castMs?: number
90}
91
92// A cast's length, as the terminal plays it (CAST_TICKS of 80ms).
93export const CAST_MS = 720
94const NOTE_COLOR = '#ffb4dc'
95const SPARK_COLORS = ['#fff07a', '#ffffff', '#ffd23c']
96
97// Sparks flying out from the slime's middle and fading, once, `castMs` into the cast.
98const castGroup = (slime: SceneSlime): string => {
99 if (slime.castMs === undefined || slime.castMs >= CAST_MS) return ''
100 const cx = (slime.x + SLIME_WIDTH / 2) * PX
101 const cy = (LABEL_ROWS + 3) * PX
102 const begin = `-${slime.castMs}ms`
103 const rays: ReadonlyArray<readonly [number, number]> = [[1, 0], [-1, 0], [0, -1], [0.7, -0.7], [-0.7, -0.7], [1, -0.4], [-1, -0.4]]
104 return rays
105 .map(([dx, dy], at) => {
106 const to = PX * 9
107 return (
108 `<rect width="${PX}" height="${PX}" fill="${SPARK_COLORS[at % SPARK_COLORS.length]}" x="${cx}" y="${cy}" opacity="0">` +
109 `<animate attributeName="x" from="${cx}" to="${cx + dx * to}" dur="${CAST_MS}ms" begin="${begin}" fill="freeze"/>` +
110 `<animate attributeName="y" from="${cy}" to="${cy + dy * to * 0.5}" dur="${CAST_MS}ms" begin="${begin}" fill="freeze"/>` +
111 `<animate attributeName="opacity" values="1;1;0" keyTimes="0;0.6;1" dur="${CAST_MS}ms" begin="${begin}" fill="freeze"/>` +
112 `</rect>`
113 )
114 })
115 .join('')
116}
117
118const slimeGroup = (slime: SceneSlime): string => {
119 if (slime.mode !== 'walk' || slime.last <= 0) {
120 const pose: SlimePose = slime.mode === 'sleep' ? 'sleep' : slime.mode === 'walk' ? 'run1' : 'sit'
121 let group = `<g transform="translate(${slime.x * PX} 0)">${spriteRects(pose, slime.dir)}</g>`
122 const ahead = slime.dir === 1 ? slime.x + SLIME_WIDTH : slime.x - 1
123 if (slime.mode === 'listen') {
124 group += `<text x="${(slime.x + SLIME_WIDTH - 3) * PX}" y="${(LABEL_ROWS + 1.5) * PX}" fill="${NOTE_COLOR}" font-size="${PX * 2.2}">♪${blink(ALERT_MS * 2, 'visible')}</text>`
125 }
126 if (slime.mode === 'wait') {
127 group += `<text x="${(Math.max(0, ahead) + 0.5) * PX}" y="${(LABEL_ROWS + 3) * PX}" fill="${ALERT_COLOR}" font-weight="bold" font-size="${PX * 2.4}" text-anchor="middle">!${blink(ALERT_MS, 'visible')}</text>`
128 }
129 if (slime.mode === 'sleep') {
130 const zx = (slime.x + (slime.dir === 1 ? SLIME_WIDTH - 2 : 1)) * PX
131 group +=
132 `<text x="${zx}" y="${(LABEL_ROWS + 3) * PX}" fill="${SNORE_COLOR}" font-size="${PX * 1.6}">z${blink(SNORE_MS * 2, 'visible')}</text>` +
133 `<text x="${zx + PX * 2}" y="${(LABEL_ROWS + 1.5) * PX}" fill="${SNORE_COLOR}" font-size="${PX * 2}">Z${blink(SNORE_MS * 2, 'hidden')}</text>`
134 }
135 return group
136 }
137 // One ping-pong lap: right to `last`, then back. A negative begin starts it where the slime stands now.
138 const lapMs = slime.last * 2 * HOP_MS
139 const startMs = (slime.dir === 1 ? slime.x : slime.last * 2 - slime.x) * HOP_MS
140 const begin = `-${startMs}ms`
141 const facing = (dir: 1 | -1) =>
142 `<g visibility="hidden">` +
143 `<animate attributeName="visibility" values="${dir === 1 ? 'visible;hidden' : 'hidden;visible'}" keyTimes="0;0.5" calcMode="discrete" dur="${lapMs}ms" begin="${begin}" repeatCount="indefinite"/>` +
144 `<g>${spriteRects('run1', dir)}${blink(HOP_MS, 'visible')}</g>` +
145 `<g visibility="hidden">${spriteRects('run2', dir)}${blink(HOP_MS, 'hidden')}</g>` +
146 `</g>`
147 return (
148 `<g>` +
149 `<animateTransform attributeName="transform" type="translate" values="0 0;${slime.last * PX} 0;0 0" keyTimes="0;0.5;1" dur="${lapMs}ms" begin="${begin}" repeatCount="indefinite"/>` +
150 facing(1) +
151 facing(-1) +
152 `</g>`
153 )
154}
155
156const escapeXml = (text: string) => text.replace(/[&<>"]/g, ch => `&#${ch.charCodeAt(0)};`)
157
158// The scene's size in CSS pixels. Given to the Svg: a sandboxed frame left to size itself takes the browser's
159// default 150px height and pads the scene above and below.
160export const sceneSize = (width: number, hasGround = false) => ({
161 width: width * PX,
162 height: (LABEL_ROWS + TRACK_PIXELS + (hasGround ? TUBE_ROWS * 2 : 0)) * PX,
163})
164
165// The ground under the soil: the context window as a tube of mana, rippling `frameMs` a step.
166export type SceneGround = { info: ContextInfo; isWorking: boolean; frameMs: number }
167
168// The whole track: labels over the big numbers, the slime, the grass and soil under both, and the ground below.
169export const sceneSvg = (width: number, hud: HudLayout, slime: SceneSlime, labelColors: Record<string, string>, ground?: SceneGround): string => {
170 const { height } = sceneSize(width, ground !== undefined)
171 const floor = [0, 1].map(row =>
172 Array.from({ length: width }, (_, col) => (row === 0 ? GRASS[col % GRASS.length] : SOIL[(col * 3) % SOIL.length])),
173 )
174 const digits = hud.pixels.map(p => `<rect x="${p.x * PX}" y="${(p.y + LABEL_ROWS) * PX}" width="${PX}" height="${PX}" fill="${hex(p.rgb)}"/>`).join('')
175 // A monospace character is about 0.6em: at this size each label character spans one sprite pixel, as a cell does.
176 const labels = hud.labels
177 .map(
178 label =>
179 `<text x="${(label.x + label.width / 2) * PX}" y="${LABEL_ROWS * PX - 2}" fill="${labelColors[label.color] ?? '#999999'}" text-anchor="middle">${escapeXml(label.text)}</text>`,
180 )
181 .join('')
182 return (
183 `<svg xmlns="http://www.w3.org/2000/svg" width="${width * PX}" height="${height}" viewBox="0 0 ${width * PX} ${height}" shape-rendering="crispEdges" font-family="ui-monospace,SFMono-Regular,Menlo,monospace" font-size="${PX / 0.6}">` +
184 labels +
185 digits +
186 slimeGroup(slime) +
187 castGroup(slime) +
188 runsToRects(floor, LABEL_ROWS + SPRITE_ROWS) +
189 (ground === undefined ? '' : groundSvg(ground.info, width, ground.isWorking, PX, ground.frameMs, (LABEL_ROWS + TRACK_PIXELS) * PX)) +
190 `</svg>`
191 )
192}
193hooks/banner.ts 91 lines1import type { EngineInterface } from 'claude-code'
2
3// The big moments of rpg-hud's game, cried out in the band's big pixel letters for a moment: a level up, a boss
4// appearing or slain, the hero knocked out or revived, a commit saved or a push delivered, a companion sent off in
5// the background back from its quest. The band shows the facts again once it passes.
6
7export const BANNER_MS = 2500
8// Ticks each colour of a banner's shimmer holds on the terminal.
9export const SHIMMER_TICKS = 4
10
11export type BannerColor = 'yellow' | 'red' | 'green' | 'magenta' | 'cyan' | 'blue'
12
13export type Banner = { word: string; icon: string; label: string; color: BannerColor; until: number }
14
15// What the banners read of rpg-hud's state; all of it absent when that mod is not running.
16export type HudMoments = {
17 // Until when the status panel glows after a level up.
18 flashUntil?: number
19 bossFx?: { event: 'appear' | 'hit' | 'defeat' | 'enrage'; at: number; boss: { name: string } } | null
20 // `isBackground`: sent with run_in_background, so nothing in the transcript waits on its return.
21 pets?: readonly { status: string; endedAt?: number; description: string; isBackground?: boolean }[]
22 knockout?: { state: 'down' | 'up'; at: number } | null
23 mapFx?: { event: 'save' | 'deliver'; at: number } | null
24 // When the conversation was last compacted: a night at the inn.
25 restFx?: { at: number } | null
26}
27
28// Another plugin's state is read-only. Read while drawing, so its writes redraw the band.
29export async function readMoments($: EngineInterface): Promise<HudMoments> {
30 // The engine lists every value a module reads, so each key is written out.
31 const [flash, fx, pets, knockout, mapFx, restFx] = await Promise.all([
32 $.state.get({ plugin: 'rpg-hud', key: 'flashUntil' } as never).catch(() => undefined),
33 $.state.get({ plugin: 'rpg-hud', key: 'bossFx' } as never).catch(() => undefined),
34 $.state.get({ plugin: 'rpg-hud', key: 'pets' } as never).catch(() => undefined),
35 $.state.get({ plugin: 'rpg-hud', key: 'knockout' } as never).catch(() => undefined),
36 $.state.get({ plugin: 'rpg-hud', key: 'mapFx' } as never).catch(() => undefined),
37 $.state.get({ plugin: 'rpg-hud', key: 'restFx' } as never).catch(() => undefined),
38 ])
39 return {
40 flashUntil: flash?.value as HudMoments['flashUntil'],
41 bossFx: fx?.value as HudMoments['bossFx'],
42 pets: pets?.value as HudMoments['pets'],
43 knockout: knockout?.value as HudMoments['knockout'],
44 mapFx: mapFx?.value as HudMoments['mapFx'],
45 restFx: restFx?.value as HudMoments['restFx'],
46 }
47}
48
49// A label stays short, so the banner's block never crowds the slime off the band.
50const LABEL_MAX = 30
51const short = (text: string): string => (text.length > LABEL_MAX ? `${text.slice(0, LABEL_MAX - 1)}…` : text)
52
53// The banner showing at `now`, the biggest moment first: a slain boss, a boss appearing, a knockout, a level up,
54// a revive, a night at the inn, a delivery, a save, a return.
55// A pet the turn waited on reports in the transcript already; only one sent off in the background gets a banner.
56export const bannerFor = (moments: HudMoments, now: number): Banner | undefined => {
57 const fx = moments.bossFx
58 if (fx != null && now - fx.at < BANNER_MS) {
59 if (fx.event === 'defeat') return { word: 'VICTORY!', icon: '⚑', label: short(`${fx.boss.name} is defeated`), color: 'yellow', until: fx.at + BANNER_MS }
60 if (fx.event === 'appear') return { word: 'BOSS!', icon: '☠', label: short(`a wild ${fx.boss.name} appears`), color: 'red', until: fx.at + BANNER_MS }
61 if (fx.event === 'enrage') return { word: 'ENRAGED!', icon: '🔥', label: short(`${fx.boss.name} flies into a rage`), color: 'red', until: fx.at + BANNER_MS }
62 }
63 const ko = moments.knockout
64 if (ko != null && ko.state === 'down' && now - ko.at < BANNER_MS) {
65 return { word: 'GAME OVER', icon: '💀', label: 'a clean cast revives the hero', color: 'red', until: ko.at + BANNER_MS }
66 }
67 if (moments.flashUntil !== undefined && moments.flashUntil > now) {
68 return { word: 'LEVEL UP!', icon: '✦', label: 'the hero grows stronger', color: 'magenta', until: moments.flashUntil }
69 }
70 if (ko != null && ko.state === 'up' && now - ko.at < BANNER_MS) {
71 return { word: 'REVIVE!', icon: '✨', label: 'every heart restored', color: 'green', until: ko.at + BANNER_MS }
72 }
73 const rest = moments.restFx
74 if (rest != null && now - rest.at < BANNER_MS) {
75 return { word: 'REST AT INN', icon: '🌙', label: 'the mana is restored', color: 'blue', until: rest.at + BANNER_MS }
76 }
77 const map = moments.mapFx
78 if (map != null && now - map.at < BANNER_MS) {
79 return map.event === 'deliver'
80 ? { word: 'DELIVERED!', icon: '🏰', label: 'the loot reaches the castle', color: 'yellow', until: map.at + BANNER_MS }
81 : { word: 'SAVED!', icon: '💾', label: 'progress saved', color: 'cyan', until: map.at + BANNER_MS }
82 }
83 const back = (moments.pets ?? [])
84 .filter(pet => pet.isBackground === true && pet.status === 'ok' && pet.endedAt !== undefined && now - pet.endedAt < BANNER_MS)
85 .sort((a, b) => (b.endedAt ?? 0) - (a.endedAt ?? 0))[0]
86 if (back?.endedAt !== undefined) {
87 return { word: 'QUEST CLEAR', icon: '♣', label: short(`${back.description} returned`), color: 'green', until: back.endedAt + BANNER_MS }
88 }
89 return undefined
90}
91hooks/liquids.ts 36 lines1// What each /context category is as mana: the colour of its liquid in the tube, and the legend's mark for it.
2
3// Each category's mana by its name; another takes a colour from the rest by its name.
4const LIQUIDS: Readonly<Record<string, number>> = {
5 'System prompt': 0x8c7cff,
6 'System tools': 0x56c8dc,
7 'MCP tools': 0xff7ad9,
8 'Custom agents': 0xffa94d,
9 'Memory files': 0xffd23c,
10 Skills: 0x7cf29c,
11 Messages: 0x5aa9ff,
12}
13const SPARE = [0xc88cff, 0x4fd1c5, 0xf6ad55, 0x9ae6b4]
14
15export const liquidOf = (name: string): number => {
16 const known = LIQUIDS[name]
17 if (known !== undefined) return known
18 let hash = 0
19 for (const ch of name) hash = (hash * 31 + ch.charCodeAt(0)) >>> 0
20 return SPARE[hash % SPARE.length]!
21}
22
23export const hexOf = (rgb: number): string => `#${(rgb & 0xffffff).toString(16).padStart(6, '0')}`
24
25// The legend's mark for each category: what that mana is made of.
26const ICONS: Readonly<Record<string, string>> = {
27 'System prompt': '📜',
28 'System tools': '🔧',
29 'MCP tools': '🔌',
30 'Custom agents': '🤖',
31 'Memory files': '🧠',
32 Skills: '✨',
33 Messages: '💬',
34}
35export const iconOf = (name: string): string => ICONS[name] ?? '🔮'
36types/index.d.ts 33 lines1export type BandInfo = {
2 branch: string
3 dirty: number
4 lastMs: number
5 inTokens: number
6 outTokens: number
7}
8
9// One /context row (the SDK's ContextCategory), its colour a theme key. The
10// contract must stand alone, so register.tsx's mapping and context-bar.ts's
11// GLYPH table are what tsc holds to the SDK's kinds.
12export type ContextSlice = {
13 name: string
14 tokens: number
15 color: string
16 kind: 'used' | 'free' | 'buffer' | 'deferred'
17}
18
19export type ContextInfo = {
20 slices: ContextSlice[]
21 total: number
22 max: number
23 percent: number
24 // Tokens at which auto-compaction runs; absent when it is off.
25 compactAt?: number
26}
27
28declare module 'claude-code' {
29 interface PluginState {
30 'slime-band': { info: BandInfo; context: ContextInfo }
31 }
32}
33