modscode EN

modscode / 図鑑 / token-monster

token-monster

A pixel-art monster in a side pane that eats tokens and shows context, limits and activity at a glance

確かめやすいコードターミナル+デスクトップペインバンドトーストBoxButtonText

何をするか

  • 欄・プロンプトの上の帯・トーストを描く
  • /token-monster を足す
  • ツールの呼び出しを見張る(止めることがある)
  • agent.spawn・classic.PermissionDenied・classic.PermissionRequest・classic.SessionStart ほか 11 個にフックする
  • ターンをまたいで自分の状態を持つ

良いところ

  • ネットワークに出ない
  • プロセスを起こさない
  • TypeScript で書かれている
  • デスクトップ専用の分岐がある

作り始めるためのコード

2 種類あります。上のデザインから modscode が書いた雛形と、その Mod 自身のコードのうち描いている部分です。

雛形(register.tsx)

register.tsx
import type { Register } from 'claude-code'

// Drawn like token-monster by Carl Igelström (pane, band, toast), as modscode read it from the mod's code:
// https://modscode.com/gallery/ugglr-token-monster/
// Written by modscode from that reading, not copied from the mod: use it as you like.
// Each value below stands for one the mod works out at run time; put in your own.
export const register: Register = on => {
  // the pane: open it with $.ui.open({ id: 'my-pane', title: "token-monster" })
  on('ui.render', { component: 'Pane', requestId: 'my-pane' }, async ($, e) => {
    const { Box, Text, Button } = $.ui.resolve(e)
    const say = '…'
    const waitLine = '…'
    const percent = '…'
    const kilo = '…'
    const entry = '…'
    const entry2 = '…'
    const entry3 = '…'
    const name = '…'
    const used = '…'
    const left = '…'
    const name2 = '…'
    const used2 = '…'
    const left2 = '…'
    const name3 = '…'
    const used3 = '…'
    const left3 = '…'
    const rank = '…'
    const remark = '…'
    const dietLine = '…'
    return (
      <Box>
        <Text>
          {" "}
        </Text>
        <Box flexDirection="column">
          <Text bold>
            {say}
          </Text>
          <Text dimColor wrap="truncate-end">
            {waitLine}
          </Text>
          <Box>
            <Text dimColor>
              {"belly   "}
            </Text>
            <Text>
              ████████
            </Text>
            <Text>
              ████████
            </Text>
            <Text>
              ████████
            </Text>
            <Text dimColor>
              ░░░░░░░░
            </Text>
            <Text>
              ▒▒▒▒▒▒▒▒
            </Text>
            <Text>
              ▒▒▒▒▒▒▒▒
            </Text>
            <Text>
              ▒▒▒▒▒▒▒▒
            </Text>
            <Text>
              {` ${percent}%`}
              {" "}
              {`${kilo}/${kilo}`}
            </Text>
          </Box>
          <Box flexWrap="wrap">
            <Text>
              <Text>
                ▒
              </Text>
              <Text dimColor>
                {entry}
              </Text>
            </Text>
            <Text>
              <Text>
                ▒
              </Text>
              <Text dimColor>
                {entry2}
              </Text>
            </Text>
            <Text>
              <Text>
                ▒
              </Text>
              <Text dimColor>
                {entry3}
              </Text>
            </Text>
          </Box>
          <Box>
            <Text dimColor>
              {name}
            </Text>
            <Text>
              {used}
            </Text>
            <Text dimColor>
              {left}
            </Text>
            <Text>
              {` ${percent}%`}
              {" "}
            </Text>
          </Box>
          <Box>
            <Text dimColor>
              {name2}
            </Text>
            <Text>
              {used2}
            </Text>
            <Text dimColor>
              {left2}
            </Text>
            <Text>
              {` ${percent}%`}
              {" "}
            </Text>
          </Box>
          <Box>
            <Text dimColor>
              {name3}
            </Text>
            <Text>
              {used3}
            </Text>
            <Text dimColor>
              {left3}
            </Text>
            <Text>
              {` ${percent}%`}
              {" "}
            </Text>
          </Box>
          <Box>
            <Text dimColor>
              {`Lv ${rank}`}
            </Text>
            <Text>
              ━━━━━━━━
            </Text>
            <Text dimColor>
              ────────
            </Text>
            <Text dimColor>
              {` ${kilo} to Lv ${rank}1`}
            </Text>
          </Box>
          <Text dimColor>
            {remark}
          </Text>
          <Text color="yellow">
            {dietLine}
          </Text>
          <Box>
            <Button label="Monster" hotkey="m" plain />
            <Text>
              {" "}
            </Text>
            <Button label="Color" hotkey="c" plain />
            <Text>
              {" "}
            </Text>
            <Button label="Pet" hotkey="p" plain />
          </Box>
          <Box>
            <Button label="Diet: free context" hotkey="d" plain />
            <Text>
              {" "}
            </Text>
            <Button label="Sound: on" hotkey="s" plain />
          </Box>
          <Text dimColor>
            ctrl+x tab or a click gives me the keys
          </Text>
        </Box>
      </Box>
    )
  })

  // the band above the prompt; what else goes there is drawn under it
  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
    const { Box, Text } = $.ui.resolve(e)
    const words = '…'
    const used = '…'
    const left = '…'
    const percent = '…'
    const tail = '…'
    return (
      <Box flexDirection="column">
        <Box paddingX={1}>
          <Text bold>
            {words}
          </Text>
          <Text>
            {` ${used}`}
          </Text>
          <Text dimColor>
            {left}
          </Text>
          <Text>
            {` ${percent}%`}
          </Text>
          <Text dimColor>
            {tail}
          </Text>
        </Box>
        {await next(e)}
      </Box>
    )
  })

  on('session.start', async ($, e, next) => {
    const kilo = '…'
    await $.ui.toast(`Press Enter on /compact and me eat ~${kilo} tokens from the context.`)
    await $.ui.toast(`Me eating ~${kilo} tokens from the context. *burp*`)
    return next(e)
  })
}

Mod 自身のコード

Mod のライセンス(MIT)に従って載せています。全文は下にあります。写すときは著作権表示を残してください。

hooks/register.tsx 1001〜1160 行 · ペイン
  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
    const elements = $.ui.resolve(e)
    const { Box, Button, Text } = elements
    const at = await read($, now)
    const full = (await read($, belly)) ?? { percent: 0, tokens: 0, window: 0, ate: 0, fedAt: at, burpAt: null, known: false, compactAt: null, fill: 0 }
    const limits = await read($, pantry)
    const activity = await read($, doing)
    const dieting = (await read($, armed)).length
    const plate = await read($, serving)
    const { monster, color } = await read($, look)
    const power = await read($, level)
    const helpers = scene.minions
    const hits = await read($, combo)
    const eaten = await read($, xp)
    const rank = levelOf(eaten)
    const isLoud = await read($, sound)
    const asked = await read($, waiting)
    const kept = cold(scene) ? scene.cache : null
    // Waiting on the person outranks everything: that is what needs them now.
    // About to burst outranks super mode: that line is the /compact warning.
    // What it said back to a pet or a hello shows for a moment, over its mood; hatching, it cracks.
    const { eye, say } =
      asked !== null
        ? CALLING
        : ((await read($, chat)) ?? ((await read($, egg)) ? { eye: 'o', say: '*crack* ... *crack*' } : voice(full, at, power, helpers)))
    const chain = onFire(hits)
    const remark = larder(limits)
    const tint = hex(PALETTE[color] ?? 0x3d7bff)
    const pie = await read($, slices)
    // Biggest first; free space is the empty part of the bar, not a legend entry.
    // Categories sharing a color merge (two MCP rows are one "mcp"); the five biggest
    // show, then the reserve.
    const merged = new Map<string, { color: string; short: string; kind: string; tokens: number }>()

    for (const row of pie.filter(one => one.kind !== 'free')) {
      const look = sliceLook(row.name)
      const known = merged.get(look.short)

      merged.set(look.short, { ...look, kind: row.kind, tokens: (known?.tokens ?? 0) + row.tokens })
    }

    const parts = [...merged.values()]
    const legend = [
      ...parts.filter(part => part.kind !== 'buffer').sort((a, b) => b.tokens - a.tokens).slice(0, 5),
      ...parts.filter(part => part.kind === 'buffer'),
    ]
    const entry = (part: (typeof legend)[number]) => `■ ${part.short} ${kilo(part.tokens)}  `
    const dietLine = dieting > 0 ? `eating ~${kilo(plate)} tokens from the context on your next /compact` : ''
    // The readout's height at `columns` wide, line by line, so the sprite takes only
    // what is left and the buttons never fall off the bottom of the pane.
    const lines = (columns: number) => {
      let legendLines = legend.length > 0 ? 1 : 0

      for (let used = 0, i = 0; i < legend.length; i++) {
        const w = entry(legend[i]!).length

        if (used + w > columns && used > 0) {
          legendLines += 1
          used = 0
        }
        used += w
      }

      // What it says can wrap: a gag or a fed-up line runs past a narrow readout.
      return (
        2 +
        Math.ceil(say.length / columns) +
        legendLines +
        limits.length +
        1 +
        (remark === undefined ? 0 : 1) +
        Math.ceil(dietLine.length / columns) +
        2 +
        (e.props.isFocused ? 0 : 1)
      )
    }
    // Stacked, the sprite takes up to 64 columns and the readout stays a 48 column block
    // under it. A pane too short for that (fewer than 10 sprite rows) and wide enough
    // for both puts the sprite beside the readout instead, as tall as it, twice as wide.
    const { bodyColumns, scroll } = e.props
    const wide = Math.max(16, Math.min(64, bodyColumns))
    const beside = Math.min(48, bodyColumns - 1 - 2 * Math.min(scroll.bodyRows, lines(Math.min(48, wide))))
    const isBeside =
      e.surface === 'terminal' && 'Raster' in elements && scroll.bodyRows - lines(Math.min(48, wide)) - 1 < 10 && beside >= 40
    const columns = isBeside ? beside : Math.min(48, wide)
    const readoutLines = lines(columns)
    const width = Math.max(6, Math.min(BAR, columns - 23))
    const grown = Math.round(((eaten - xpFor(rank)) / (xpFor(rank + 1) - xpFor(rank))) * width)
    const row = (name: string, percent: number, tail: string) => {
      const [used, left] = bar(percent, width)

      return (
        <Box>
          <Text dimColor>{name.padEnd(8)}</Text>
          <Text color={barColor(percent)}>{used}</Text>
          <Text dimColor>{left}</Text>
          <Text>
            {` ${Math.round(percent)}%`.padStart(5)} {tail}
          </Text>
        </Box>
      )
    }
    const layers = stack(pie, full.window || 1, width)
    let sprite

    // Raster draws on the terminal only; elsewhere it is an empty fragment.
    if (e.surface === 'terminal' && 'Raster' in elements) {
      const { Raster } = elements

      // After a hot reload the scene starts over: take the level from the banked tokens.
      if (scene.rank === 0) levelUp(scene, rank)
      // Mid-resize the pane can report no rows at all; a Raster under one cell is refused.
      const rows = isBeside ? Math.max(1, Math.min(scroll.bodyRows, readoutLines)) : Math.max(6, Math.min(22, scroll.bodyRows - readoutLines - 1))
      const across = isBeside ? Math.max(1, Math.min(2 * rows, bodyColumns - 1 - columns)) : wide

      canvas = { columns: across, rows }
      if (loop === undefined) {
        settle(scene)
        loop = $.clock.every(1000 / FPS, () => void frame($))
      }
      sprite = <Raster key="sprite" columns={across} rows={rows} cells={encode(paint(scene, across, rows * 2), across, rows, is256)} />
    } else {
      const drawing = ASCII[monster] ?? ASCII.cookie!

      sprite = (
        <Box flexDirection="column">
          {(activity === '' ? drawing.closed : drawing.open).map(line => (
            <Text color={tint}>{line.replaceAll('E', eye)}</Text>
          ))}
        </Box>
      )
    }

    const readout = (
      <Box flexDirection="column" width={columns}>
        <Text color={tint} bold>
          {say}
        </Text>
        <Text dimColor wrap="truncate-end">
          {asked !== null
            ? waitLine(asked)
            : activity !== ''
              ? `> ${activity}${chain}`
              : kept !== null
                ? `cold cache: next prompt re-reads ~${kilo(kept.tokens)} uncached`
                : full.ate > 0
                  ? `last bite +${kilo(full.ate)}, fed ${span(at - full.fedAt)} ago`
                  : `fed ${span(at - full.fedAt)} ago`}
        </Text>
        {pie.length === 0 ? (
          row('belly', full.percent, `${kilo(full.tokens)}/${kilo(full.window)}`)
        ) : (
          <Box>
            <Text dimColor>{'belly'.padEnd(8)}</Text>
            {layers.content.map(part => (
              <Text color={part.color}>{'█'.repeat(part.cells)}</Text>
            ))}
            <Text dimColor>{'░'.repeat(layers.free)}</Text>
            {layers.reserve.map(part => (
              <Text color={part.color}>{'▒'.repeat(part.cells)}</Text>
hooks/register.tsx 956〜999 行 · バンド
  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
    if (e.props.hasSurvey) return next(e)

    const pane = (await $.ui.panes()).find(one => one.id === PANE)

    if (pane?.isShown === true && pane.isPlaced) return next(e)

    const { Box, Text } = $.ui.resolve(e)
    const at = await read($, now)
    const full = await read($, belly)

    if (full === null) return next(e)

    const limits = await read($, pantry)
    const activity = await read($, doing)
    const power = await read($, level)
    const hits = await read($, combo)
    const asked = await read($, waiting)
    const tint = hex(PALETTE[(await read($, look)).color] ?? 0x3d7bff)
    const { eye, say } = asked !== null ? CALLING : voice(full, at, power, scene.minions)
    const [used, left] = bar(full.percent, 8)
    const pieces = [
      ...limits.map(limit => `  ${limitName(limit.kind)} ${Math.round(limit.percentUsed)}%`),
      '  /token-monster',
    ]
    const head = `(${eye})(${eye}) ${asked !== null ? waitLine(asked) : activity !== '' ? `> ${activity}${onFire(hits)}` : say}`
    const meter = ` ${used}${left} ${full.percent}%`
    const room = e.props.bodyColumns - 2
    // What fits: the face and words first, cut short if they must, then the gauges.
    const words = head.slice(0, Math.max(10, room - meter.length))
    const tail = pieces.filter((_, index) => words.length + meter.length + pieces.slice(0, index + 1).join('').length <= room)

    return (
      <Box paddingX={1}>
        <Text color={tint} bold>
          {words}
        </Text>
        <Text color={barColor(full.percent)}>{` ${used}`}</Text>
        <Text dimColor>{left}</Text>
        <Text>{` ${full.percent}%`}</Text>
        <Text dimColor>{tail.join('')}</Text>
      </Box>
    )
  })
ライセンスの全文(MIT)
MIT License

Copyright (c) 2026 Carl Igelström

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

コードが呼ぶもの

環境変数Claude を動かすツール呼び出し保存

コードから読み取ったデザイン

読み取ったコミットのソースから描いたもので、動かした結果ではありません。一覧は 3 回描き、条件はデスクトップアプリで描く最初の分岐を取り、動かしたときにだけ決まる値は仮の例(点線の下線)にするか省きます。色と書体はこのサイトのものです。

コードから読めること

2026-10-06 に読んだコミット a73ac7e31176 のソースから。最初のまとまりが載せる条件で、残りは自分で判断するための材料です。後のコミットは、次に読むまで見ていません。

載せる条件: 確かめやすいコード
入口を読んだhooks/hooks.json が名指すモジュールをすべて読んだ。hooks/register.tsx
解析できるすべてのファイルが TypeScript か JavaScript として解析できる。6 ファイルを解析
コードが Mod の中で完結import は Mod 自身のファイルかエンジンのモジュールだけ。パッケージも require もない。コードはすべて Mod の中
読める圧縮した行・eval・new Function・計算した道の import()・符号化した塊がない。圧縮・eval・符号化した塊なし
呼び出しが見える通信とプログラム起動はその場で $.http.fetch・$.process.run と書き、他へ渡さない。外への呼び出しはすべてその場の $ で
入れる前に自分で判断する材料
描く場所コードから読んだ、描く先。ターミナル・デスクトップアプリ・両方・何も描かない(フックだけ: 見張りやプロンプトの書き換え)のどれか。出すだけで、外す理由にはしない。ターミナルとデスクトップアプリに同じように描く
入れる手順リポジトリ自身の .claude-plugin/marketplace.json にこの Mod が載っていて、ページに書いた手順でそのマーケットプレイスから入れられるか。リポジトリの .claude-plugin/marketplace.json に載っており、そこから入れられる
Windows のプログラム$.process で起動するプログラムが Windows にあるか(tail・date・open・osascript・/usr/… などは無い)。Windows にないプログラムを使わない
通信fetch の送り先(https のホスト)がコードに書いてあるか。通信なし
プログラム起動するプログラムの名前がコードに書いてあり、シェル・インタプリタ・通信用の道具でないか。プログラムを起動しない
読んで送るファイルや環境変数を読み、かつ通信するか。通信しない
ソースの鍵ソースに API キーや秘密鍵らしきものがあるか。ソースに鍵なし
ライセンスオープンなライセンス(MIT・Apache-2.0・BSD・ISC・Unlicense・0BSD・CC0)で全文があれば、modscode にコードを載せる。違えばリンクだけ。MIT

コードの文面を読んだだけで、安全の審査ではありません。動かしてはおらず、起動するプログラムの中で何が起きるかも見えません。入れる前の確認はあなたの役目です。 載せる条件

入れる

入れる前に、必ず自分で確かめてください。Mod はサンドボックスなしで、あなたの権限で動きます。modscode はこのコードの安全を保証しません。下のコードを読み(またはフォルダーで claude plugin validate .)、触るものを見て、読んだコミットを入れてください。

リポジトリがそのままマーケットプレイスです。このマーケットプレイスを足し(ターミナルでは次のコマンド、デスクトップアプリではプラグインの設定)、そこから Mod を入れます。

/plugin marketplace add ugglr/claude-token-monster
/plugin install token-monster@token-monster

入るのはマーケットプレイスの最新のコミットで、ここで読んだもの(a73ac7e31176)と違うことがあります。入れる前に見比べてください。

Claude に聞く

modscode のコネクタを入れると、Claude がこのデザイン・コードが触るもの・コードを読んで、それをもとに作れます。たとえば:

modscode のデザイン「ugglr-token-monster」をコードごと読んで、同じようなペインを作って

Claude から探す: MCP コネクタ

似たデザイン