Tool rows as battle moves: a skill icon per tool, MISS on a failed call, COMBO on a folded run

使用 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 394 lines1import type { EngineInterface, Register } from 'claude-code'
2
3import { castSize, chargeSvg, flashSvg } from './cast-svg'
4
5// Each skill's icon and the color its cast bar charges in.
6// Emoji with default emoji presentation only: no VS16, so every terminal gives them two cells.
7const SKILLS: ReadonlyArray<readonly [RegExp, string, number]> = [
8 [/^(Bash|BashOutput|KillShell|TaskOutput|TaskStop|Monitor)$/, '🔥', 0xff7a1a],
9 [/^Read$|^NotebookRead$/, '📖', 0x5aa0ff],
10 [/^Grep$|^Glob$|^LS$|^ToolSearch$/, '🔍', 0x3fd0d0],
11 [/^Edit$|^MultiEdit$|^Write$|^NotebookEdit$/, '🔨', 0xd8b04a],
12 [/^Web(Fetch|Search)$/, '🔭', 0xa078ff],
13 [/^(Agent|Task|SendMessage)$/, '🧙', 0xc060ff],
14 [/^Todo|^Task(Create|Update|List|Get)$/, '📜', 0xc8a070],
15 [/^Skill$/, '✨', 0xffe040],
16 [/^mcp__/, '🔮', 0xff50c8],
17]
18const DEFAULT_SKILL = '🎯'
19const DEFAULT_SKILL_COLOR = 0xff5050
20const FAILED = '💀'
21const FLED = '🚫'
22const GROUP = '🌀'
23// Runs this long or longer read as a combo.
24export const COMBO_MIN = 3
25
26const skillOf = (tool: string) => SKILLS.find(([pattern]) => pattern.test(tool))
27
28export const skillIcon = (tool: string): string => skillOf(tool)?.[1] ?? DEFAULT_SKILL
29
30const skillColor = (tool: string): number => skillOf(tool)?.[2] ?? DEFAULT_SKILL_COLOR
31
32export const rowIcon = (row: { tool: string; isErrored: boolean; isInterrupted: boolean }): string => {
33 if (row.isInterrupted) return FLED
34 if (row.isErrored) return FAILED
35 return skillIcon(row.tool)
36}
37
38// A folded run shows its worst call: fled over failed over the plain group mark.
39export const groupIcon = (calls: ReadonlyArray<{ isErrored: boolean; isInterrupted: boolean }>): string => {
40 if (calls.some(call => call.isInterrupted)) return FLED
41 if (calls.some(call => call.isErrored)) return FAILED
42 return GROUP
43}
44
45// Cast bar: a Raster under a running row, repainted by blit; a short flash once the call lands.
46export const CAST_COLUMNS = 20
47const TICK_MS = 80
48// One sweep of the bar, in ticks; the bar then pulses for PULSE_TICKS before charging again.
49const CHARGE_TICKS = CAST_COLUMNS
50const PULSE_TICKS = 4
51// Long enough to read the damage the landing deals.
52export const FLASH_TICKS = 12
53// Rows whose blit keeps being refused (scrolled away, unmounted) stop animating after this.
54const MAX_MISSES = 25
55
56const DEFAULT = 0x01000000
57const TRACK = 0x3a3a3a
58const WHITE = 0xffffff
59const RED = 0xff3b3b
60const DIM_RED = 0x5a1010
61const GRAY = 0x808080
62const TRACK_GLYPH = 0x2500 // ─
63const FILL_GLYPH = 0x2501 // ━
64const HEAD_GLYPH = 0x2588 // █
65const SHADES = [0x2593, 0x2592, 0x2591] // ▓ ▒ ░
66
67export type Landing = 'hit' | 'miss' | 'fled'
68
69const pack = (cells: ReadonlyArray<readonly [number, number, number]>): string => {
70 const words = new Uint32Array(cells.length * 3)
71 cells.forEach(([glyph, fg, bg], i) => words.set([glyph, fg, bg], i * 3))
72 return btoa(String.fromCharCode(...new Uint8Array(words.buffer)))
73}
74
75const scale = (color: number, k: number): number => {
76 const ch = (shift: number) => Math.round(((color >> shift) & 0xff) * k) << shift
77 return ch(16) | ch(8) | ch(0)
78}
79
80export const castCells = (color: number, tick: number): ReadonlyArray<readonly [number, number, number]> => {
81 const t = tick % (CHARGE_TICKS + PULSE_TICKS)
82 return Array.from({ length: CAST_COLUMNS }, (_, i) => {
83 // Full bar pulsing between bright and the skill's color.
84 if (t >= CHARGE_TICKS) return [FILL_GLYPH, t % 2 === 0 ? WHITE : color, DEFAULT] as const
85 if (i < t) return [FILL_GLYPH, scale(color, 0.55 + 0.45 * (i / t)), DEFAULT] as const
86 if (i === t) return [HEAD_GLYPH, WHITE, DEFAULT] as const
87 return [TRACK_GLYPH, TRACK, DEFAULT] as const
88 })
89}
90
91export const flashCells = (landing: Landing, color: number, tick: number): ReadonlyArray<readonly [number, number, number]> => {
92 const fade = SHADES[Math.min(tick - 2, SHADES.length - 1)] ?? HEAD_GLYPH
93 const cell = (): readonly [number, number, number] => {
94 if (landing === 'miss') return tick % 2 === 0 ? [HEAD_GLYPH, RED, DEFAULT] : [HEAD_GLYPH, DIM_RED, DEFAULT]
95 if (landing === 'fled') return [tick < 2 ? FILL_GLYPH : fade, GRAY, DEFAULT]
96 if (tick === 0) return [HEAD_GLYPH, WHITE, DEFAULT]
97 return [tick === 1 ? HEAD_GLYPH : fade, color, DEFAULT]
98 }
99 return Array.from({ length: CAST_COLUMNS }, cell)
100}
101
102export const landingOf = (row: { isErrored: boolean; isInterrupted: boolean }): Landing =>
103 row.isInterrupted ? 'fled' : row.isErrored ? 'miss' : 'hit'
104
105const LANDING_LABEL: Record<Landing, string> = { hit: ' HIT!', miss: ' MISS', fled: ' FLED' }
106
107// A hit's damage is what it brought back: the output's size in characters.
108export const damageOf = (output: unknown): number => {
109 if (output === undefined || output === null) return 0
110 if (typeof output === 'string') return output.length
111 try {
112 return JSON.stringify(output)?.length ?? 0
113 } catch {
114 return 0
115 }
116}
117
118// A haul this big lands as a critical hit.
119export const CRIT_DAMAGE = 10_000
120
121export const formatDamage = (damage: number): string =>
122 damage < 1000 ? `${damage}` : `${(damage / 1000).toFixed(damage < 10_000 ? 1 : 0)}k`
123
124export type LandingText = { text: string; color?: string; dimColor?: boolean }
125
126// What a landing says beside its flash: a hit its damage, a critical one louder.
127export const landingText = (landing: Landing, damage = 0): LandingText => {
128 if (landing === 'miss') return { text: LANDING_LABEL.miss, color: 'error' }
129 if (landing === 'fled') return { text: LANDING_LABEL.fled, dimColor: true }
130 if (damage >= CRIT_DAMAGE) return { text: ` CRITICAL! -${formatDamage(damage)}`, color: 'warning' }
131 return { text: damage > 0 ? ` HIT! -${formatDamage(damage)}` : LANDING_LABEL.hit, color: 'success' }
132}
133
134// Longer runs climb the tiers: a combo, a super combo from ten, an ultra combo from twenty.
135export const comboLabel = (count: number): string | undefined => {
136 if (count < COMBO_MIN) return undefined
137 if (count >= 20) return ` ×${count} ULTRA COMBO`
138 if (count >= 10) return ` ×${count} SUPER COMBO`
139 return ` ×${count} COMBO`
140}
141
142export const comboColor = (count: number): string => (count >= 20 ? 'error' : count >= 10 ? 'permission' : 'warning')
143
144type TextElement = ReturnType<EngineInterface['ui']['resolve']>['Text']
145
146const landingLabel = (Text: TextElement, said: LandingText) => (
147 <Text {...(said.color === undefined ? {} : { color: said.color })} dimColor={said.dimColor === true} bold>
148 {said.text}
149 </Text>
150)
151
152// The engine's row stays whole; the icon sits in a gutter beside it.
153// Terminal rows open with a blank spacer row, so there the gutter starts one row down to meet the title.
154const gutterTop = (surface: string) => (surface === 'terminal' ? 1 : 0)
155
156// Rows seen running, by tool_use_id: charging while running, then flashing once, then done.
157type Cast = { color: number; tick: number; misses: number; landing?: Landing; damage?: number }
158const casts = new Map<string, Cast>()
159const landed = new Set<string>()
160// When each running call was first seen, by tool_use_id: the channelling line counts from it.
161const castStarts = new Map<string, number>()
162// The channelling lines under long calls, by their site's requestId: the call each counts for and the text shown.
163const channels = new Map<string, { toolUseId: string; shown: string; misses: number }>()
164
165// The seconds a long call has channelled, right-aligned in the line's few columns: ` 12s`, `1m 05s`.
166export const CHANNEL_COLUMNS = 7
167export const channelText = (ms: number): string => {
168 const seconds = Math.max(0, Math.floor(ms / 1000))
169 const text = seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m ${String(seconds % 60).padStart(2, '0')}s`
170 return text.padStart(CHANNEL_COLUMNS).slice(-CHANNEL_COLUMNS)
171}
172const CHANNEL_COLOR = 0xffd23c
173const channelCells = (text: string): string => pack([...text].map(ch => [ch.codePointAt(0) ?? 0x20, CHANNEL_COLOR, DEFAULT] as const))
174let ticker: ReturnType<EngineInterface['clock']['every']> | undefined
175// A tick still awaiting its blits makes the next one skip.
176let isPainting = false
177
178const frame = (cast: Cast): string =>
179 pack(cast.landing === undefined ? castCells(cast.color, cast.tick) : flashCells(cast.landing, cast.color, cast.tick))
180
181// One ticker paints every bar.
182async function paint($: EngineInterface) {
183 if (isPainting) return
184 isPainting = true
185 try {
186 let hasLanded = false
187 // Blits between frames fold into one, so every bar's goes out at once rather than a frame apiece.
188 const blits: Array<Promise<void>> = []
189 for (const [id, cast] of casts) {
190 cast.tick += 1
191 if (cast.landing !== undefined && cast.tick >= FLASH_TICKS) {
192 casts.delete(id)
193 landed.add(id)
194 hasLanded = true
195 continue
196 }
197 blits.push($.ui
198 .blit({ requestId: id, key: 'cast', cells: frame(cast) })
199 .catch(() => ({ deny: 'blit failed' }))
200 .then(shown => {
201 cast.misses = shown.deny === undefined ? 0 : cast.misses + 1
202 if (cast.misses >= MAX_MISSES) casts.delete(id)
203 }))
204 }
205 // Each channelling line ticks its seconds over; one whose call has landed (or that keeps being refused) stops.
206 const now = await $.clock.now()
207 for (const [site, channel] of channels) {
208 const start = castStarts.get(channel.toolUseId)
209 if (start === undefined || landed.has(channel.toolUseId) || casts.get(channel.toolUseId)?.landing !== undefined) {
210 channels.delete(site)
211 continue
212 }
213 const text = channelText(now - start)
214 if (text === channel.shown) continue
215 blits.push($.ui
216 .blit({ requestId: site, key: 'channel', cells: channelCells(text) })
217 .catch(() => ({ deny: 'blit failed' }))
218 .then(shown => {
219 if (shown.deny === undefined) {
220 channel.shown = text
221 channel.misses = 0
222 } else if ((channel.misses += 1) >= MAX_MISSES) channels.delete(site)
223 }))
224 }
225 await Promise.all(blits)
226 // A finished flash leaves its row: redraw so the bar goes.
227 if (hasLanded) $.ui.invalidate('ui.render')
228 } finally {
229 // A throw must not leave every later tick skipping.
230 isPainting = false
231 if (casts.size === 0 && channels.size === 0) {
232 ticker?.cancel()
233 ticker = undefined
234 }
235 }
236}
237
238function ensureTicker($: EngineInterface) {
239 ticker ??= $.clock.every(TICK_MS, () => void paint($))
240}
241
242// Off the terminal the bar animates itself: a row charges until its call lands, flashes once, then goes.
243type DrawnCast = { color: number; landing?: Landing; damage?: number }
244const drawnCasts = new Map<string, DrawnCast>()
245export const FLASH_MS = FLASH_TICKS * TICK_MS
246const CHARGE_MS = CHARGE_TICKS * TICK_MS
247const PULSE_MS = PULSE_TICKS * TICK_MS
248
249const castFor = ($: EngineInterface, props: { tool_use_id: string; tool: string; isRunning: boolean; isErrored: boolean; isInterrupted: boolean; output?: unknown }) => {
250 const id = props.tool_use_id
251 let cast = drawnCasts.get(id)
252 if (props.isRunning && cast === undefined && !landed.has(id)) {
253 cast = { color: skillColor(props.tool) }
254 drawnCasts.set(id, cast)
255 } else if (!props.isRunning && cast !== undefined && cast.landing === undefined) {
256 cast.landing = landingOf(props)
257 cast.damage = damageOf(props.output)
258 $.clock.after(FLASH_MS, () => {
259 drawnCasts.delete(id)
260 landed.add(id)
261 $.ui.invalidate('ui.render')
262 })
263 }
264 return cast
265}
266
267export const register: Register = on => {
268 // ToolResult carries no isInterrupted: remember the fled calls from their ToolUse rows.
269 const fled = new Set<string>()
270
271 on('ui.render', { component: 'ToolUse' }, async ($, e, next) => {
272 const drawn = await next(e)
273 const id = e.props.tool_use_id
274 if (e.props.isInterrupted) fled.add(id)
275 if (e.props.isRunning && !castStarts.has(id)) castStarts.set(id, await $.clock.now())
276 if (!e.props.isRunning) castStarts.delete(id)
277 if (e.surface !== 'terminal') {
278 const drawnCast = castFor($, e.props)
279 const { Box, Text, Svg } = $.ui.resolve(e)
280 return (
281 <Box flexDirection="row">
282 <Text>{`${rowIcon(e.props)} `}</Text>
283 <Box flexGrow={1} flexDirection="column">
284 {drawn}
285 {drawnCast && (
286 <Box flexDirection="row" alignItems="center" marginLeft={2}>
287 <Svg
288 key="cast"
289 source={
290 drawnCast.landing === undefined
291 ? chargeSvg(drawnCast.color, CAST_COLUMNS, CHARGE_MS, PULSE_MS)
292 : flashSvg(drawnCast.landing, drawnCast.color, CAST_COLUMNS, FLASH_MS)
293 }
294 alt={drawnCast.landing === undefined ? 'casting' : landingText(drawnCast.landing, drawnCast.damage).text.trim()}
295 {...castSize(CAST_COLUMNS)}
296 isInteractive
297 />
298 {drawnCast.landing === undefined ? (
299 <Text dimColor>{' casting…'}</Text>
300 ) : (
301 landingLabel(Text, landingText(drawnCast.landing, drawnCast.damage))
302 )}
303 </Box>
304 )}
305 </Box>
306 </Box>
307 )
308 }
309
310 let cast = casts.get(id)
311 if (e.props.isRunning && cast === undefined && !landed.has(id)) {
312 cast = { color: skillColor(e.props.tool), tick: 0, misses: 0 }
313 casts.set(id, cast)
314 } else if (!e.props.isRunning && cast !== undefined && cast.landing === undefined) {
315 cast.landing = landingOf(e.props)
316 cast.damage = damageOf(e.props.output)
317 cast.tick = 0
318 }
319 if (cast !== undefined) ensureTicker($)
320
321 const { Box, Text, Raster } = $.ui.resolve(e)
322 const bar = cast === undefined ? null : (
323 <Box flexDirection="row" marginLeft={2}>
324 <Raster key="cast" columns={CAST_COLUMNS} rows={1} cells={frame(cast)} />
325 {cast.landing === undefined
326 ? <Text dimColor>{' casting…'}</Text>
327 : landingLabel(Text, landingText(cast.landing, cast.damage))}
328 </Box>
329 )
330 return (
331 <Box flexDirection="row">
332 <Box marginTop={gutterTop(e.surface)}><Text>{`${rowIcon(e.props)} `}</Text></Box>
333 <Box flexGrow={1} flexDirection="column">{drawn}{bar}</Box>
334 </Box>
335 )
336 })
337
338 // A call running long enough to offer the background channels: its seconds tick by beside the engine's hint.
339 on('ui.render', { component: 'ToolProgress' }, async ($, e, next) => {
340 if (e.props.kind !== 'background_hint') return next(e)
341 const id = e.props.tool_use_id
342 const now = await $.clock.now()
343 const hint = e.props.hint.replace(/^\((.*)\)$/, '$1')
344 const rest = hint === '' ? '' : ` · ${hint}`
345 if (e.surface !== 'terminal') {
346 const { Box, Text } = $.ui.resolve(e)
347 return (
348 <Box flexDirection="row" marginLeft={2}>
349 <Text color="warning" bold>⌛ Channeling…</Text>
350 <Text dimColor wrap="truncate">{rest}</Text>
351 </Box>
352 )
353 }
354 const text = channelText(now - (castStarts.get(id) ?? now))
355 channels.set(e.requestId, { toolUseId: id, shown: text, misses: 0 })
356 ensureTicker($)
357 const { Box, Text, Raster } = $.ui.resolve(e)
358 return (
359 <Box flexDirection="row" marginLeft={2}>
360 <Text color="warning" bold>⌛ Channeling</Text>
361 <Raster key="channel" columns={CHANNEL_COLUMNS} rows={1} cells={channelCells(text)} />
362 <Text dimColor wrap="truncate">{rest}</Text>
363 </Box>
364 )
365 })
366
367 on('ui.render', { component: 'ToolResult' }, async ($, e, next) => {
368 const drawn = await next(e)
369 if (!e.props.isErrored || fled.has(e.props.tool_use_id)) return drawn
370 const { Box, Text } = $.ui.resolve(e)
371 return (
372 <Box flexDirection="column">
373 {drawn}
374 <Text color="error" bold>{' ❌ MISS!'}</Text>
375 </Box>
376 )
377 })
378
379 on('ui.render', { component: 'ToolGroup' }, async ($, e, next) => {
380 const drawn = await next(e)
381 if (e.props.isExpanded) return drawn
382 const combo = comboLabel(e.props.calls.length)
383 const { Box, Text } = $.ui.resolve(e)
384 return (
385 <Box flexDirection="row">
386 <Box marginTop={gutterTop(e.surface)}><Text>{`${groupIcon(e.props.calls)} `}</Text></Box>
387 <Box flexGrow={1} flexDirection="column">{drawn}</Box>
388 {/* The label keeps its width; only the drawn row shrinks, so the combo never wraps. */}
389 {combo === undefined ? null : <Box flexShrink={0} marginTop={gutterTop(e.surface)}><Text color={comboColor(e.props.calls.length)} bold wrap="truncate">{combo}</Text></Box>}
390 </Box>
391 )
392 })
393}
394hooks/cast-svg.ts 62 lines1// The cast bar for surfaces that draw SVG: the charge and the landing flash run by SMIL in the surface's
2// sandboxed frame, so nothing blits; the hook draws again only when the call lands and when the flash is over.
3
4import type { Landing } from './register'
5
6// CSS pixels a column is taken to span; an overestimate only scales the bar down to its slot.
7const COLUMN_PX = 8
8const HEIGHT = 6
9
10// The bar's size in CSS pixels, given to the Svg: a sandboxed frame left to size itself takes the browser's default
11// 150px height.
12export const castSize = (columns: number) => ({ width: columns * COLUMN_PX, height: HEIGHT })
13
14const hex = (rgb: number): string => `#${(rgb & 0xffffff).toString(16).padStart(6, '0')}`
15
16const shell = (width: number, body: string) =>
17 `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${HEIGHT}" viewBox="0 0 ${width} ${HEIGHT}">` +
18 `<clipPath id="c"><rect width="${width}" height="${HEIGHT}" rx="${HEIGHT / 2}"/></clipPath>` +
19 `<g clip-path="url(#c)"><rect width="${width}" height="${HEIGHT}" fill="#3a3a3a"/>${body}</g></svg>`
20
21// One charge sweeps the bar in `chargeMs` behind a white head, then the full bar pulses for `pulseMs`; again.
22export const chargeSvg = (color: number, columns: number, chargeMs: number, pulseMs: number): string => {
23 const width = columns * COLUMN_PX
24 const cycle = chargeMs + pulseMs
25 const full = (chargeMs / cycle).toFixed(4)
26 const pulse = [0, 0.25, 0.5, 0.75].map(step => ((chargeMs + pulseMs * step) / cycle).toFixed(4))
27 const c = hex(color)
28 return shell(
29 width,
30 `<linearGradient id="f"><stop offset="0" stop-color="${c}" stop-opacity="0.55"/><stop offset="1" stop-color="${c}"/></linearGradient>` +
31 `<rect height="${HEIGHT}" width="0" fill="url(#f)">` +
32 `<animate attributeName="width" values="0;${width};${width}" keyTimes="0;${full};1" dur="${cycle}ms" repeatCount="indefinite"/>` +
33 `<animate attributeName="fill" values="url(#f);${c};#ffffff;${c};#ffffff" keyTimes="0;${pulse.join(';')}" calcMode="discrete" dur="${cycle}ms" repeatCount="indefinite"/>` +
34 `</rect>` +
35 `<rect y="0" width="${COLUMN_PX}" height="${HEIGHT}" fill="#ffffff">` +
36 `<animate attributeName="x" values="0;${width - COLUMN_PX};${width}" keyTimes="0;${full};1" dur="${cycle}ms" repeatCount="indefinite"/>` +
37 `</rect>`,
38 )
39}
40
41// The landing, once through in `flashMs`: a hit glows in the skill's colour and fades, a miss blinks red, a
42// fled call greys out.
43export const flashSvg = (landing: Landing, color: number, columns: number, flashMs: number): string => {
44 const width = columns * COLUMN_PX
45 if (landing === 'miss') {
46 return shell(
47 width,
48 `<rect width="${width}" height="${HEIGHT}" fill="#ff3b3b">` +
49 `<animate attributeName="fill" values="#ff3b3b;#5a1010" calcMode="discrete" dur="${Math.round(flashMs / 2.5)}ms" repeatCount="indefinite"/>` +
50 `</rect>`,
51 )
52 }
53 const fill = landing === 'fled' ? '#808080' : hex(color)
54 return shell(
55 width,
56 `<rect width="${width}" height="${HEIGHT}" fill="${fill}">` +
57 (landing === 'hit' ? `<animate attributeName="fill" values="#ffffff;${fill}" keyTimes="0;0.2" calcMode="discrete" dur="${flashMs}ms" fill="freeze"/>` : '') +
58 `<animate attributeName="opacity" values="1;1;0.15" keyTimes="0;0.4;1" dur="${flashMs}ms" fill="freeze"/>` +
59 `</rect>`,
60 )
61}
62