modscode EN

modscode / 図鑑 / session-meter

session-meter

Shows a live session pane (/ctx): context breakdown, usage limits with pace, tool calls and model requests; sends the model a one-time note when limits or context cross a threshold

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

何をするか

  • 欄を描く
  • /ctx を足す
  • ツールの呼び出しを見張る
  • prompt.submit・session.measure・session.start・turn.stepにフックする

良いところ

  • ネットワークに出ない
  • プロセスを起こさない
  • TypeScript で書かれている
  • エラーを扱う

作り始めるためのコード

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

雛形(register.tsx)

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

// Drawn like session-meter by Mehmet Aras (pane), as modscode read it from the mod's code:
// https://modscode.com/gallery/arasovic-session-meter/
// 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: "Session" })
  on('ui.render', { component: 'Pane', requestId: 'my-pane' }, async ($, e) => {
    const { Box, Text } = $.ui.resolve(e)
    const t = '…'
    const t2 = '…'
    const t3 = '…'
    const right = '…'
    const t4 = '…'
    const t5 = '…'
    const t6 = '…'
    const t7 = '…'
    const t8 = '…'
    const t9 = '…'
    const t10 = '…'
    const t11 = '…'
    const t12 = '…'
    const right2 = '…'
    const t13 = '…'
    const t14 = '…'
    const t15 = '…'
    const t16 = '…'
    const t17 = '…'
    const t18 = '…'
    const t19 = '…'
    const t20 = '…'
    const t21 = '…'
    const running = '…'
    const t22 = '…'
    const t23 = '…'
    const t24 = '…'
    const t25 = '…'
    const t26 = '…'
    const t27 = '…'
    const t28 = '…'
    const t29 = '…'
    const t30 = '…'
    const model = '…'
    const t31 = '…'
    const t32 = '…'
    const t33 = '…'
    const t34 = '…'
    const t35 = '…'
    const t36 = '…'
    const t37 = '…'
    const t38 = '…'
    const t39 = '…'
    return (
      <Box flexDirection="column" paddingTop={1}>
        <Text>
          <Text>
            {t}
          </Text>
          <Text>
            {t2}
          </Text>
          <Text>
            {t3}
          </Text>
        </Text>
        <Box flexDirection="column" marginTop={1}>
          <Text>
            <Text dimColor>
              {"╭─ "}
            </Text>
            <Text bold>
              Context
            </Text>
            <Text dimColor>
              {" "}
              ────────
            </Text>
            <Text dimColor>
              {" "}
              {right}
              {" "}
            </Text>
            <Text dimColor>
              ─╮
            </Text>
          </Text>
          <Text>
            <Text dimColor>
              {"│ "}
            </Text>
            <Text>
              {t4}
            </Text>
            <Text>
              {t5}
            </Text>
            <Text>
              {t6}
            </Text>
            <Text dimColor>
              {" │"}
            </Text>
          </Text>
          <Text>
            <Text dimColor>
              {"│ "}
            </Text>
            <Text>
              {t7}
            </Text>
            <Text>
              {t8}
            </Text>
            <Text>
              {t9}
            </Text>
            <Text dimColor>
              {" │"}
            </Text>
          </Text>
          <Text>
            <Text dimColor>
              {"│ "}
            </Text>
            <Text>
              {t10}
            </Text>
            <Text>
              {t11}
            </Text>
            <Text>
              {t12}
            </Text>
            <Text dimColor>
              {" │"}
            </Text>
          </Text>
          <Text dimColor>
            ╰
            ────────
            ╯
          </Text>
        </Box>
        <Box flexDirection="column" marginTop={1}>
          <Text>
            <Text dimColor>
              {"╭─ "}
            </Text>
            <Text bold>
              Limits
            </Text>
            <Text dimColor>
              {" "}
              ────────
            </Text>
            <Text dimColor>
              {" "}
              {right2}
              {" "}
            </Text>
            <Text dimColor>
              ─╮
            </Text>
          </Text>
          <Text>
            <Text dimColor>
              {"│ "}
            </Text>
            <Text>
              {t13}
            </Text>
            <Text>
              {t14}
            </Text>
            <Text>
              {t15}
            </Text>
            <Text dimColor>
              {" │"}
            </Text>
          </Text>
          <Text>
            <Text dimColor>
              {"│ "}
            </Text>
            <Text>
              {t16}
            </Text>
            <Text>
              {t17}
            </Text>
            <Text>
              {t18}
            </Text>
            <Text dimColor>
              {" │"}
            </Text>
          </Text>
          <Text>
            <Text dimColor>
              {"│ "}
            </Text>
            <Text>
              {t19}
            </Text>
            <Text>
              {t20}
            </Text>
            <Text>
              {t21}
            </Text>
            <Text dimColor>
              {" │"}
            </Text>
          </Text>
          <Text dimColor>
            ╰
            ────────
            ╯
          </Text>
        </Box>
        <Box flexDirection="column" marginTop={1}>
          <Text>
            <Text dimColor>
              {"╭─ "}
            </Text>
            <Text bold>
              Tools
            </Text>
            <Text dimColor>
              {" "}
              ────────
            </Text>
            <Text dimColor>
              {" "}
              {`${running} running`}
              {" "}
            </Text>
            <Text dimColor>
              ─╮
            </Text>
          </Text>
          <Text>
            <Text dimColor>
              {"│ "}
            </Text>
            <Text>
              {t22}
            </Text>
            <Text>
              {t23}
            </Text>
            <Text>
              {t24}
            </Text>
            <Text dimColor>
              {" │"}
            </Text>
          </Text>
          <Text>
            <Text dimColor>
              {"│ "}
            </Text>
            <Text>
              {t25}
            </Text>
            <Text>
              {t26}
            </Text>
            <Text>
              {t27}
            </Text>
            <Text dimColor>
              {" │"}
            </Text>
          </Text>
          <Text>
            <Text dimColor>
              {"│ "}
            </Text>
            <Text>
              {t28}
            </Text>
            <Text>
              {t29}
            </Text>
            <Text>
              {t30}
            </Text>
            <Text dimColor>
              {" │"}
            </Text>
          </Text>
          <Text dimColor>
            ╰
            ────────
            ╯
          </Text>
        </Box>
        <Box flexDirection="column" marginTop={1}>
          <Text>
            <Text dimColor>
              {"╭─ "}
            </Text>
            <Text bold>
              Requests
            </Text>
            <Text dimColor>
              {" "}
              ────────
            </Text>
            <Text dimColor>
              {" "}
              {model}
              {" "}
            </Text>
            <Text dimColor>
              ─╮
            </Text>
          </Text>
          <Text>
            <Text dimColor>
              {"│ "}
            </Text>
            <Text>
              {t31}
            </Text>
            <Text>
              {t32}
            </Text>
            <Text>
              {t33}
            </Text>
            <Text dimColor>
              {" │"}
            </Text>
          </Text>
          <Text>
            <Text dimColor>
              {"│ "}
            </Text>
            <Text>
              {t34}
            </Text>
            <Text>
              {t35}
            </Text>
            <Text>
              {t36}
            </Text>
            <Text dimColor>
              {" │"}
            </Text>
          </Text>
          <Text>
            <Text dimColor>
              {"│ "}
            </Text>
            <Text>
              {t37}
            </Text>
            <Text>
              {t38}
            </Text>
            <Text>
              {t39}
            </Text>
            <Text dimColor>
              {" │"}
            </Text>
          </Text>
          <Text dimColor>
            ╰
            ────────
            ╯
          </Text>
        </Box>
      </Box>
    )
  })
}

Mod 自身のコード

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

session-meter/hooks/register.tsx 286〜439 行 · ペイン
  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
    const { Box, Text } = $.ui.resolve(e)
    const b = await read($, breakdown)
    const r = await read($, reading)
    const turns = await read($, history)
    const list = await read($, samples)
    const sent = await read($, notes)
    const calls = await read($, tools)
    const asks = await read($, requests)
    const now = await $.clock.now()
    const w = Math.max(28, e.props.bodyColumns - 1)
    const inner = w - 6
    if (!b) return <Text dimColor>Waiting for the first context reading.</Text>

    const draw = (row: Row, width: number) =>
      fit(row, width).map((s, j) => <Text key={String(j)} color={s.c} dimColor={s.d} bold={s.b}>{s.t}</Text>)
    const frame = (title: string, tone: string, rows: Row[], right = '') => {
      const rule = Math.max(0, w - 6 - title.length - (right ? right.length + 2 : 0))
      return (
        <Box key={title} flexDirection="column" marginTop={1}>
          <Text>
            <Text color={tone} dimColor>╭─ </Text>
            <Text color={tone} bold>{title}</Text>
            <Text color={tone} dimColor> {'─'.repeat(rule)}</Text>
            {right ? <Text dimColor> {right} </Text> : null}
            <Text color={tone} dimColor>─╮</Text>
          </Text>
          {rows.map((row, i) => (
            <Text key={String(i)}>
              <Text color={tone} dimColor>│  </Text>
              {draw(row, inner)}
              <Text color={tone} dimColor>  │</Text>
            </Text>
          ))}
          <Text color={tone} dimColor>╰{'─'.repeat(w - 2)}╯</Text>
        </Box>
      )
    }

    // Context: one stacked bar of what fills it, the compaction mark, a legend, the size over turns, the heaviest items.
    const used = b.categories.filter(c => c.kind === 'used' && c.tokens > 0)
    const bar: Row = used.map(c => ({ t: '█'.repeat(cells(c.tokens, b.window, inner)), c: c.color }))
    const filled = width(bar)
    const mark = b.threshold === undefined ? -1 : Math.min(inner - 1, cells(b.threshold, b.window, inner))
    for (let i = filled; i < inner; i++) bar.push(i === mark ? { t: '┊', c: 'warning' } : { t: '·', d: true, c: mark >= 0 && i > mark ? 'error' : undefined })
    // The legend is a two-column grid, names left and counts right-aligned in each column.
    const colW = Math.floor((inner - 3) / 2)
    const keys = [
      ...used.map(c => ({ mark: '■', c: c.color, name: c.name, n: tokens(c.tokens) })),
      ...(b.threshold === undefined ? [] : [{ mark: '┊', c: 'warning', name: 'compacts at', n: tokens(b.threshold) }]),
    ]
    const key = (k: (typeof keys)[number]): Row => spread([{ t: `${k.mark} `, c: k.c }, { t: k.name.slice(0, colW - k.n.length - 3) }], [{ t: k.n, d: true }], colW)
    const legend: Row[] = []
    for (let i = 0; i < keys.length; i += 2) {
      const [a, z] = [keys[i], keys[i + 1]]
      if (a) legend.push([...key(a), ...(z ? [{ t: '   ' }, ...key(z)] : [])])
    }
    const last = turns.at(-1)
    const prev = turns.at(-2)
    const delta = last !== undefined && prev !== undefined ? last - prev : undefined
    const chartCols = inner - 12
    const chart = turns.length < 2 ? [] : braille(turns, b.window, chartCols, 2)
    const contextRows: Row[] = [
      spread([{ t: tokens(b.tokens), b: true }, { t: ` of ${tokens(b.window)}`, d: true }], [{ t: `${Math.round(b.percent)}%`, c: zone(b.percent), b: true }], inner),
      [],
      bar,
      [],
      ...legend,
      [],
      ...(chart.length
        ? [
            [{ t: chart[0] ?? '', c: 'suggestion' }, { t: '  ' }, { t: `${delta !== undefined && delta >= 0 ? '+' : '-'}${tokens(Math.abs(delta ?? 0))}`, b: true }],
            [{ t: chart[1] ?? '', c: 'suggestion' }, { t: '  last turn', d: true }],
          ]
        : [[{ t: 'Size over turns shows after two turns.', d: true }]]),
      ...(b.heaviest.length ? [[] as Row, ...b.heaviest.map(item => spread([{ t: '▸ ', d: true }, { t: item.name }], [{ t: tokens(item.tokens), d: true }], inner))] : []),
    ]

    // Limits: each window's meter, its reset, and whether the current pace lasts until then.
    const limitRows: Row[] = []
    const tones: string[] = []
    const glance: Row = [{ t: 'ctx ', d: true }, { t: `${Math.round(b.percent)}%`, c: zone(b.percent), b: true }]
    for (const win of WINDOWS) {
      const limit = r.limits.find(l => l.kind === win.kind)
      if (!limit) continue
      const p = pace(list, win.kind, now)
      const tone = limit.percentUsed >= 80 || (p.kind === 'full' && p.inMs < 3_600_000) ? 'error' : p.kind === 'full' ? 'warning' : 'success'
      tones.push(tone)
      const pct = `${Math.round(limit.percentUsed)}%`.padStart(4)
      const reset = `↻${duration(resetsIn(limit.resetsAt, now))}`.padEnd(7)
      if (limitRows.length) limitRows.push([])
      limitRows.push([{ t: `${win.label} `, b: true }, { t: '▕', d: true }, ...meter(limit.percentUsed, inner - 18), { t: '▏', d: true }, { t: ` ${pct} `, c: tone, b: true }, { t: reset, d: true }])
      limitRows.push(
        p.kind === 'measuring'
          ? [{ t: '   measuring pace…', d: true }]
          : p.kind === 'full'
            ? [{ t: `   full in ~${duration(p.inMs)} at this pace`, c: tone }]
            : [{ t: '   lasts until the reset at this pace', d: true }],
      )
      glance.push({ t: `   ${win.label} `, d: true }, { t: `${Math.round(limit.percentUsed)}%`, c: tone, b: true })
    }
    // toTimeString starts with the local HH:MM:SS.
    const hhmm = (ms: number) => new Date(ms).toTimeString().slice(0, 5)
    if (sent.length) limitRows.push([], ...sent.map(n => [{ t: `${hhmm(n.at)} `, d: true }, { t: `note sent: ${n.text}` }]))
    const limitTone = tones.includes('error') ? 'error' : tones.includes('warning') ? 'warning' : 'success'

    // Tools and Requests share the rows left below; each keeps at least three.
    // The top padding and glance row, each frame's two borders and top margin, and the Requests column header.
    const fixed = 2 + (contextRows.length + 3) + (limitRows.length ? limitRows.length + 3 : 0) + 3 + 4
    const left = Math.max(6, e.props.scroll.bodyRows - fixed)
    const toolCount = Math.max(3, Math.ceil(left / 2))
    const askCount = Math.max(3, left - toolCount)

    const shown = [...calls.filter(t => t.ok === undefined), ...calls.filter(t => t.ok !== undefined)].slice(0, toolCount)
    const running = calls.filter(t => t.ok === undefined).length
    const toolRows: Row[] = shown.length
      ? shown.map(t => {
          const icon = t.ok === undefined ? { t: '◌', c: 'warning' } : t.ok ? { t: '✓', c: 'success' } : { t: '✗', c: 'error' }
          const time = t.ms === undefined ? '…' : elapsed(t.ms)
          return spread([icon, { t: ` ${(t.sub ? `↳${t.name}` : t.name).padEnd(7)} `, b: !t.sub, d: t.sub }, { t: t.target.slice(0, inner - 16), d: true }], [{ t: time, d: true }], inner)
        })
      : [[{ t: 'No tool calls yet.', d: true }]]
    const toolTone = shown.find(t => t.ok !== undefined)?.ok === false ? 'error' : 'success'

    const askRows: Row[] = asks.length
      ? [
          [{ t: 'loop          in   out  cache   time', d: true }],
          ...asks.slice(0, askCount).map(q => {
            const hit = q.input ? Math.round((q.cached / q.input) * 100) : 0
            const cacheTone = hit < 20 ? 'error' : hit < 50 ? 'warning' : undefined
            return [
              { t: q.agent.padEnd(10).slice(0, 10), b: q.agent === 'main', d: q.agent !== 'main' },
              { t: tokens(q.input).padStart(6) + tokens(q.output).padStart(6) },
              { t: `${hit}%`.padStart(7), c: cacheTone, d: cacheTone === undefined },
              { t: elapsed(q.ms).padStart(7), d: true },
            ]
          }),
        ]
      : [[{ t: 'No model requests yet.', d: true }]]
    const lastHit = asks[0] && asks[0].input ? asks[0].cached / asks[0].input : 1
    const model = asks[0]?.model.replace(/^claude-/, '') ?? ''

    return (
      <Box flexDirection="column" paddingTop={1}>
        <Text>
          {draw(glance, w - 3)}
        </Text>
        {frame('Context', zone(b.percent), contextRows)}
        {limitRows.length ? frame('Limits', limitTone, limitRows) : null}
        {frame('Tools', toolTone, toolRows, running ? `${running} running` : '')}
        {frame('Requests', lastHit < 0.5 ? 'warning' : 'success', askRows, model)}
      </Box>
    )
  })
ライセンスの全文(MIT)
MIT License

Copyright (c) 2026 Mehmet Aras

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

載せる条件: 確かめやすいコード
入口を読んだhooks/hooks.json が名指すモジュールをすべて読んだ。session-meter/hooks/register.tsx
解析できるすべてのファイルが TypeScript か JavaScript として解析できる。1 ファイルを解析
コードが 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 arasovic/claude-code-mods
/plugin install session-meter@claude-code-mods

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

Claude に聞く

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

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

Claude から探す: MCP コネクタ

似たデザイン