modscode EN

modscode / 図鑑 / tokenmunim

tokenmunim

Cost control for AI agents: a budget per task, a live ledger of every step, and a circuit breaker that stops loops, burn spikes and runaway spend.

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

何をするか

  • 欄・トーストを描く
  • /munim を足す
  • mcp__tokenmunim__start_task・mcp__tokenmunim__end_task の呼び出しを見張る(止めることがある)
  • session.start・turn.complete・turn.step・ui.closeにフックする
  • ターンをまたいで自分の状態を持つ

良いところ

  • ネットワークに出ない
  • TypeScript で書かれている
  • エラーを扱う

作り始めるためのコード

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

雛形(register.tsx)

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

// Drawn like tokenmunim by Piyush Sinha (pane, status, toast), as modscode read it from the mod's code:
// https://modscode.com/gallery/piyushsinha-9-tokenmunim/
// 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: "TokenMunim" })
  on('ui.render', { component: 'Pane', requestId: 'my-pane' }, async ($, e) => {
    const { Box, Text } = $.ui.resolve(e)
    const labelOf = '…'
    return (
      <Box flexDirection="column" paddingX={1}>
        <Box justifyContent="space-between">
          <Box>
            <Text bold>
              Token
            </Text>
            <Text bold color="#E8B04B">
              Munim
            </Text>
            <Text color="#666672">
              {"  cost control for AI agents"}
            </Text>
          </Box>
          <Box>
            <Text bold backgroundColor="#1C3626">
              {" ● LIVE "}
            </Text>
          </Box>
        </Box>
        <Box flexDirection="column" marginTop={1}>
          <Box>
            <Box marginRight={0}>
              <Text bold color="#17171B" backgroundColor="#E8B04B">
                {` ${labelOf} `}
              </Text>
            </Box>
            <Box marginRight={0}>
              <Text bold color="#17171B" backgroundColor="#E8B04B">
                {` ${labelOf} `}
              </Text>
            </Box>
            <Box marginRight={0}>
              <Text bold color="#17171B" backgroundColor="#E8B04B">
                {` ${labelOf} `}
              </Text>
            </Box>
          </Box>
          <Text color="#3B3B45">
            ────────
          </Text>
        </Box>
      </Box>
    )
  })

  on('session.start', async ($, e, next) => {
    const name = '…'
    const money = '…'
    await $.ui.toast(`TokenMunim: ${name} gets ${money} more budget`)
    await $.ui.toast(`TokenMunim: the next call goes through`)
    return next(e)
  })
}

Mod 自身のコード

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

plugin/hooks/register.tsx 404〜426 行 · ペイン
  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
    const kit = $.ui.resolve(e)
    // A reload forgets where the ledger lives; find it again on the first draw.
    if (ledgerFile === undefined) await locate($)
    const b = normalize(await read($, book))
    const v: View = migrateView(await read($, view))
    const now = await $.clock.now()
    const rows = e.props.scroll?.bodyRows ?? (e.viewport?.rows ?? 50) - 6
    return drawPane(
      kit,
      { book: b, view: v, now, limits, width: e.props.bodyColumns, rows, hasFile: ledgerFile !== undefined, startedAt },
      {
        setTab: tab => void update($, view, cur => ({ ...migrateView(cur), tab, entry: null })),
        toggle: (id, isFolded) => void update($, view, cur => toggleSection({ ...migrateView(cur) }, id, isFolded)),
        drill: task => void update($, view, cur => ({ ...migrateView(cur), task, tab: task === null ? cur.tab : 'activity', entry: null })),
        expand: entry => void update($, view, cur => ({ ...migrateView(cur), entry })),
        openLedger: () => void openLedger($),
        raise: (taskId, by) => void decide($, 'raise', taskId, by),
        allow: () => void decide($, 'allow'),
        skip: taskId => void decide($, 'skip', taskId),
      },
    )
  })
plugin/hooks/pane.tsx 157〜316 行 · ペイン
export function drawPane(kit: Kit, d: PaneData, act: PaneActions) {
  const { Box, Text, Button } = kit
  const { book: b, view, now, limits } = d
  const W = Math.max(30, d.width)
  const inner = W - 2
  // Inside a panel: one cell of padding a side.
  const C = inner - 2
  const wide = C >= 58
  const narrow = C < 46
  const R = Math.max(24, d.rows)

  const trip = b.trips[b.trips.length - 1]
  const active = b.tasks.find(k => k.id === b.active)
  const lastEntry = b.entries[b.entries.length - 1]
  const isLive = lastEntry !== undefined && now - lastEntry.at < 90_000

  // ---- building blocks -----------------------------------------------------

  const pill = (text: string, color: string, bg?: string) => (
    <Text bold color={color} backgroundColor={bg}>{` ${text} `}</Text>
  )

  const link = (key: string, label: string, onPress: () => void, dim = false) => (
    <Box key={`${key}-box`}>
      <Button key={key} plain dimColor={dim} label={label} hover={{ color: GOLD, underline: true }} onPress={onPress} />
    </Box>
  )

  const action = (key: string, label: string, onPress: () => void, primary: boolean) => (
    <Box key={`${key}-box`} backgroundColor={primary ? GOLD_DEEP : CHIP} marginRight={1}>
      <Button key={key} plain label={` ${label} `} hover={{ backgroundColor: primary ? GOLD : MUTED, color: INK }} onPress={onPress} />
    </Box>
  )

  const panel = (key: string, children: unknown, marginTop: number, bg: string = PANEL) => (
    <Box key={key} flexDirection="column" marginTop={marginTop} backgroundColor={bg} paddingX={1}>
      {children}
    </Box>
  )

  const section = (id: string, title: string, right: unknown, isFolded: boolean, body: unknown, marginTop: number) =>
    panel(
      `sec-${id}`,
      [
        <Box key={`sec-${id}-head`} justifyContent="space-between">
          <Box key={`fold-${id}-box`}>
            <Button key={`fold-${id}`} plain label={`${isFolded ? '▸' : '▾'} ${title}`} hover={{ color: GOLD, underline: true }} onPress={() => act.toggle(id, isFolded)} />
          </Box>
          {right}
        </Box>,
        isFolded ? null : body,
      ],
      marginTop,
    )

  const muted = (text: string, room: number, color: string = MUTED) => <Text color={color}>{cut(text, Math.max(0, room))}</Text>

  // ---- header and tabs -----------------------------------------------------

  // The header is one row, like an app's title bar: the wordmark in two
  // tones, the tagline when there is room, and status on the right. Nothing
  // clickable sits up here, beside the close mark of the pane's frame: the
  // ledger link lives in the footer.
  const elapsed = d.startedAt && d.startedAt > 0 ? `session ${span((now - d.startedAt) / 60_000)}` : ''
  const TAGLINE = '  cost control for AI agents'
  const statusWidth = 8
  const showTagline = 10 + TAGLINE.length + 1 + statusWidth <= inner
  const header = (
    <Box key="header" justifyContent="space-between">
      <Box>
        <Text bold>Token</Text>
        <Text bold color={GOLD}>Munim</Text>
        {showTagline ? <Text color={FAINT}>{TAGLINE}</Text> : null}
      </Box>
      <Box>
        {isLive ? pill('● LIVE', GREEN, GREEN_BG) : pill('○ IDLE', FAINT)}
      </Box>
    </Box>
  )

  const agentCount = Math.max(1, b.agents.length)
  const tabDefs: { id: Tab; long: string; short: string; n?: number }[] = [
    { id: 'overview', long: 'Overview', short: 'Home' },
    { id: 'tasks', long: 'Tasks', short: 'Tasks', n: b.tasks.length },
    { id: 'activity', long: 'Activity', short: 'Activity', n: b.entries.length },
    { id: 'alerts', long: 'Alerts', short: 'Alerts', n: b.trips.length },
    { id: 'agents', long: 'Agents', short: 'Agents', n: agentCount },
  ]
  // The richest tab labels that fit on one line; each label carries a space a side.
  const variants = [
    { counts: true, short: false, gap: 1 },
    { counts: false, short: false, gap: 1 },
    { counts: false, short: true, gap: 0 },
  ]
  const labelOf = (t: (typeof tabDefs)[number], v: (typeof variants)[number]) =>
    `${v.short ? t.short : t.long}${v.counts && t.n !== undefined ? ` ${t.n}` : ''}`
  const chosen =
    variants.find(v => tabDefs.reduce((w, t) => w + labelOf(t, v).length + 2, 0) + v.gap * (tabDefs.length - 1) <= inner) ??
    variants[variants.length - 1]!
  const tabBar = (
    <Box key="tabs" flexDirection="column" marginTop={1}>
      <Box>
        {tabDefs.map((t, i) => (
          <Box key={`tab-${t.id}`} marginRight={i < tabDefs.length - 1 ? chosen.gap : 0}>
            {t.id === view.tab ? (
              <Text bold color={INK} backgroundColor={GOLD}>{` ${labelOf(t, chosen)} `}</Text>
            ) : (
              <Button key={`tab-btn-${t.id}`} plain dimColor label={` ${labelOf(t, chosen)} `} hover={{ color: GOLD }} onPress={() => act.setTab(t.id)} />
            )}
          </Box>
        ))}
      </Box>
      <Text color={LINE}>{'─'.repeat(inner)}</Text>
    </Box>
  )

  // The footer: how long the session has run, the ledger file, the hint, and
  // the open task. The hint gives way first when the row runs short.
  const LEDGER = 'ledger ↗'
  const activeText = active !== undefined ? `▸ ${active.name}` : ''
  const footerBase = elapsed !== '' ? `${elapsed} · ` : ''
  const HINT = ' · /munim for commands'
  const footerUsed = footerBase.length + (d.hasFile ? LEDGER.length : 0) + Math.min(activeText.length, 16) + 2
  const footerHint = footerUsed + HINT.length <= inner ? HINT : ''
  const footer = (gap: number) => (
    <Box key="footer" marginTop={gap} justifyContent="space-between">
      <Box>
        {footerBase !== '' ? <Text color={FAINT}>{footerBase}</Text> : null}
        {d.hasFile ? link('open-ledger', LEDGER, act.openLedger) : null}
        {footerHint !== '' || !d.hasFile ? <Text color={FAINT}>{d.hasFile ? footerHint : '/munim for commands'}</Text> : null}
      </Box>
      {active !== undefined ? (
        <Text color={MUTED}>{cut(activeText, Math.max(0, inner - footerBase.length - (d.hasFile ? LEDGER.length : 19) - footerHint.length - 2))}</Text>
      ) : null}
    </Box>
  )

  // ---- plan limits ---------------------------------------------------------

  const plan = b.rateLimits.filter(w => w.kind === 'five_hour' || w.kind === 'seven_day')
  const windows = plan.length > 0 ? plan : b.rateLimits.filter(w => w.kind === 'spend_limit').slice(0, 1)
  const showPace = inner >= 50
  const limitBarW = Math.max(6, inner - 6 - 10 - 10 - (showPace ? 13 : 0))
  const limitsBlock = (marginTop: number) => (
    <Box key="limits" flexDirection="column" marginTop={marginTop}>
      {windows.length === 0 ? (
        <Box>
          <Text color={MUTED}>{'limits  '}</Text>
          <Text color={FAINT}>{cut('plan limits show after the next reply', inner - 8)}</Text>
        </Box>
      ) : null}
      {windows.map(w => {
        const left = Math.max(0, Math.min(100, 100 - w.percentUsed))
        const color = left >= 50 ? GREEN : left >= 20 ? AMBER : RED
        const resetMs = w.resetsAt ? Date.parse(w.resetsAt) - now : NaN
        const r = runway(b, w.kind, now)
        const filled = fill(left / 100, limitBarW)
        const pace =
          r.state === 'runs-out' ? { text: `⚠ out in ${span(r.minutes)}`, color: r.minutes < 30 ? RED : AMBER }
          : r.state === 'lasts' ? { text: '✓ lasts', color: GREEN }
ライセンスの全文(MIT)
MIT License

Copyright (c) 2026 Piyush Sinha

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 に読んだコミット e3c330a8dbbb のソースから。最初のまとまりが載せる条件で、残りは自分で判断するための材料です。後のコミットは、次に読むまで見ていません。

載せる条件: 確かめやすいコード
入口を読んだhooks/hooks.json が名指すモジュールをすべて読んだ。plugin/hooks/register.tsx
解析できるすべてのファイルが TypeScript か JavaScript として解析できる。4 ファイルを解析
コードが 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/… などは無い)。plugin/hooks/register.tsx:96 open(Windows にない); plugin/hooks/register.tsx:378 open(Windows にない)
通信fetch の送り先(https のホスト)がコードに書いてあるか。通信なし
プログラム起動するプログラムの名前がコードに書いてあり、シェル・インタプリタ・通信用の道具でないか。open(通信する)
読んで送るファイルや環境変数を読み、かつ通信するか。reads environment variables and files and reaches the network
ソースの鍵ソースに API キーや秘密鍵らしきものがあるか。ソースに鍵なし
ライセンスオープンなライセンス(MIT・Apache-2.0・BSD・ISC・Unlicense・0BSD・CC0)で全文があれば、modscode にコードを載せる。違えばリンクだけ。MIT

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

入れる

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

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

/plugin marketplace add PiyushSinha-9/tokenmunim
/plugin install tokenmunim@tokenmunim

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

Claude に聞く

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

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

Claude から探す: MCP コネクタ

似たデザイン