SLOPSHOPPER

model-review

現在のセッションのモデル・effort・トークン・推定コストと、モデル選択の妥当性を表示する(読み取り専用)

paneguardcommandtoaststatusprompt
v0.37.0no licenseupdated 2026-10-23dtakamiya/claude-code-mods/mods/model-review
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · model-review
│ ┃ モデル振り返り ✕ › fix the failing auth test and add an audit log call │ ┃ ✓ 問題なし · 結論: 目立った指摘なし │ ┃ ⏺ Read(src/auth.ts) │ ┃ 1 ターン · サブエージェント 0 ⎿ Read 6 lines │ ┃ 金額 API 換算の推定 $0.0777〜$0.0906 · ⏺ Update(src/auth.ts) │ ┃ 実(API 換算) $0.0000(読み込み後)· 差 ⎿ Added 2 lines, removed 1 line │ ┃ -$0.0777(推定が大きい) ⏺ Bash(bun test) │ ┃ ⎿ 3 pass, 1 fail │ ┃ ▎モデル × effort(コスト比) │ ┃ opus-5-5 effort - 1 ターン ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ $0.0777 │ ┃ ヒット 93% · 入力 2,100 · 出力 1,480 ✻ Worked for 42s · done 4:20 PM │ ┃ キャッシュ 読 91,000 / 書 4,300 │ ┃ › /model-review │ ┃ ▎高コストターン ⎿ model-review: モデル振り返りペインを開きました。 │ ┃ opus-5-5 $0.0777 │ ┃ #1(たった今) · ツール 9 回 · 42 秒 │ ┃ │ ┃ ▎いま切り替えたら(目安) │ ┃ ・haiku-5-5 へ: 再構築 +$0.0110 · 1 │ ┃ ターンあたり -$0.0753 · 約 1 ターンで回収 │ ┃ ・sonnet-5-5 へ: 再構築 +$0.2287 · 1 │ ┃ ターンあたり -$0.0388 · 約 6 ターンで回収 │ ┃ 直近のメインのターンのトークン内訳を各モデル │ ┃ の単価で置き換えた目安です。実際の使用量・キ │ ┃ ャッシュの温度・effort の違いは含みません。 ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts ⚠ model-review: API換算 $0.42 · 5h 31%

Draws

Pane · モデル振り返り
✓ 問題なし · 結論: 目立った指摘なし 1 ターン · サブエージェント 0 金額 API 換算の推定 $0.0777〜$0.0906 · 実(API 換算) $0.0000(読み込み後)· 差 -$0.0777(推定が大きい) ▎モデル × effort(コスト比) opus-5-5 effort - 1 ターン $0.0777 ヒット 93% · 入力 2,100 · 出力 1,480 キャッシュ 読 91,000 / 書 4,300 ▎高コストターン opus-5-5 $0.0777 #1(たった今) · ツール 9 回 · 42 秒 ▎いま切り替えたら(目安) ・haiku-5-5 へ: 再構築 +$0.0110 · 1 ターンあたり -$0.0753 · 約 1 ターンで回収 ・sonnet-5-5 へ: 再構築 +$0.2287 · 1 ターンあたり -$0.0388 · 約 6 ターンで回収 直近のメインのターンのトークン内訳を各モデルの単価で置き換え た目安です。実際の使用量・キャッシュの温度・effort の違いは含みません。 ▎コスト 使用率 5h 31% 金額は API 換算の参考値で、請求額ではありません。サブスクの枠は上の使用 率で見てください(ペースは直近の測定からの目安で、上限への到 達を断定しません) 内訳 出力 38% · 書込 28% · 読込 23% · 入力 11% 内訳の合計 $0.0777(推定の下限と同じ基準) ▎信頼度 含まない: fast mode の割増・advisor の費用(取得不可)・トークン以外の料金(Web 検索など)・Bedrock / Vertex 価格と地域割増。推定は書込の TTL 不明のため 5 分単価(下限)〜1 時間単価(上限)の幅 用語 ヒット率: プロンプトのうちキャッシュから読んだ割合(高いほど安い) / 読み込み後: この Mod を読み込んでからの実コスト / 差(実 − 推定): + は推定より実額が大きい 軽作業 = ツール 3 回以下・編集なし・出力 1,000 tokens 以下 / 重い = ツール 10 回以上・長時間・エラー。更新は /model-review
README

model-review

セッションで使ったモデル・effort・トークン・推定コストを集計し、モデル選択の妥当性(過剰・不足・委譲・サブエージェント・切替)を観察として表示する mod。読み取り専用で、書込・コマンド実行・モデル以外の通信は行わない。

使い方

/plugin install model-review --marketplace dtakamiya/claude-code-mods
/model-review
  • /model-review でペイン「モデル振り返り」を開く。ペインを置けない画面では同じ内容をテキストで返す(先頭は結論の 1 行、その次に金額の 1 行)。結論の行は状態を印と語で示す: ✖ 要対応(不足)・▲ 要確認(過剰・サブ・切替、またはキャッシュ書込 > 読込の連続・実コストが推定の上限を大きく上回る)・△ 参考(委譲だけ)・? 判定不能(全ターン単価不明)・✓ 問題なし(0.31.0)。
  • /model-review copy でテキストレポートをクリップボードにコピーする(入力・プロンプトは含まない)。
  • /model-review text でペインを置ける画面でもペインを開かず、テキストレポートをそのまま返す(トランスクリプトに残したいとき)。
  • /model-review help で使える引数の一覧を返す。引数は前後の空白・大文字小文字を無視し、知らない引数(打ち間違いを含む)ではペインを開かずに help を案内する。
  • 記録されるのは、この mod の読み込み後に完了したターンだけ。過去のセッションは遡れない。
  • 指摘は「参考の観察」で、モデル選択の誤りを断定しない。

表示する内容

  • モデル × effort ごとのターン数、トークン、キャッシュのヒット率、推定コスト。
  • 指摘: 過剰(軽作業に重いモデル/effort)、不足(重い作業・エラー連続に軽いモデル/low)、委譲(メインが多くのツールを使うのにサブエージェント未使用)、サブエージェントの比重、切替。
  • 直近と過去の区別(0.20.0): 指摘ごとに「最後は N ターン前」を出す。結論の ▲ はメインの直近 20 ターン(仮置き)に該当がある指摘だけで決め、それより前にだけ該当した指摘は「過去の指摘」として別に並べる(対処が効けば ✓ に戻る)。
  • plan mode のターン(0.25.0): prompt.attachment の plan_mode を観察して印を付け、モデル起因の過剰から外す(effort 起因は残す)。注記に件数を出す。
  • opusplan の候補(0.30.0): plan 外で Opus の過剰があり plan mode も使っているとき、次の一手に /model opusplan(計画は Opus・実行は Sonnet)を添える。直近のメインが Sonnet 以下なら出さない。
  • 指摘ごとの「次の一手」の候補(0.18.0): 例「候補: 軽作業が続くあいだは /model sonnet で Sonnet へ(軽作業の平均で 1 ターンあたり約 -$0.0200、再構築 +$0.2400・約 12 ターンで回収の目安。戻すときにも再構築)」。回収に 10 ターンを超えるときは「Sonnet への切替は元を取りにくい(再構築 +$0.2400 の回収に約 12 ターン、…)。軽作業が 12 ターン以上続くなら /model sonnet」のように、元を取りにくいことを先に書く(0.32.5)。候補は目安で、切替を勧める断定ではない。
  • 使用率の消費ペース(0.28.0): 5h / 7d などの使用率が取れる環境(サブスク)では、ペイン・テキストレポートに「このペースだと約 40 分で上限(目安)・リセットまで 1 時間 10 分」を出し、status 行は「5h 72%(上限まで40分)」とする(0.32.5 で矢印「↑40分」から語に変えた)。金額は「API 換算(請求額ではない)」と明示する。ペースは直近 15 分の測定から求めた目安で、上限への到達を断定しない。使用率が取れない環境の表示は変わらない。
  • 1 ターンあたりの費用の推移(0.26.0): 最初の 10 ターンと直近 10 ターンの平均(プロンプト長つき)と、最新の /compact の前後。20 ターン未満では出さない。表示のみで指摘にはしない。
  • 費用の推移の候補(0.29.0): 直近の平均が最初の 3 倍以上で、直近の窓の中で compact していないとき、/compact(と /clear)を候補として添える。プロンプト長も 1.5 倍以上に伸びていて、畳み込み済みのターンがないときだけ。表示のみで自動では実行しない。
  • 切替の注記(直近のモデル・effort の切替と、キャッシュへの影響の見積り)。
  • 高コストのターン上位、Haiku・Sonnet 換算の差額、単価不明のモデル名。
  • コストの内訳(書込・出力・読込・入力の割合)。書込や出力が大きいときは見直しの手がかりを添える。書込は TTL 不明のため 5 分単価(下限)で、単価不明のターンは除く。

しきい値の一覧と根拠の強さは docs/design/threshold-rationale.md。いずれも実測の裏付けがない仮置き。

status 行とトースト(0.16.0)

コストか使用率が動いたときだけ、status 行に「API換算 $1.23 · 5h 72%」の形で 1 行出す(/model-review を開かなくても見える)。使用率が取れる環境(サブスク)の金額は API 単価での換算で請求額ではないため「API換算」と書き、コスト上限のトーストにも「請求額ではありません」と添える。ペイン・テキストレポートの実額も「実(API 換算)」と書く(0.32.2)。使用率が取れない環境(サブスク外・初回前)ではコストだけを「実コスト $1.23」の形で出す。設定(/config または pluginConfigs):

  • showStatus(既定: オン)— status 行の表示。
  • costLimitUsd(既定: 0 = 無効)— 実コストがこの額に達したらトーストで 1 度知らせる。
  • rateLimitPercent(既定: 0 = 無効)— 5h / 7d などの使用率がこの値に達したらトーストで 1 度知らせる。枠がリセットされて下回った後に再び達したときは、もう一度知らせる。
  • notifyOnSwitch(既定: オン、0.27.0)— /model などで別のモデルへ切り替える直前、キャッシュが温かいときだけ、「キャッシュを作り直すため約 $0.30 かかる見込み(120,000 tokens)」の形で、見積り(engine の estimated_cache_write_usd)をトーストで知らせる。切替は止めない。組織が管理する Claude Code では classic hook がインストール済み plugin を素通りするため、このトーストは出ない(validate の注意)。
  • mutedConcerns(既定: 空 = 無効、0.21.0)— 分かったうえで選んでいる設定の指摘を、種類ごとに止める。overspec(過剰)・underspec(不足)・delegation(委譲)・subagent(サブ)・switch(切替)を、英名か短い名前でカンマ区切りに書く(例: overspec,delegation)。止めた種類は結論の件数に入らず、ペイン・テキストレポートの指摘の節に「止めている指摘(設定 mutedConcerns): 過剰 3 / 40 件」の 1 行だけが残る。大文字小文字・全角/半角の違いは同じ名前として読み、知らない名前は無視する。userConfig に複数選択の型がないため文字列で受ける。

上限は利用者が決める値で、Mod は仮置きの推奨値を持たない。設定の変更は reload(/reload-plugins)後に反映される。reload するとトーストの通知済みの記録が消えるため、超過中なら reload 後にもう一度出る。status 行・トーストは目視未確認。

ペインの幅

ペイン本文の桁数(bodyColumns)で出し方を変える。しきい値 40 / 70 は仮置きで、目視未確認(hooks/pane-model.ts の NARROW_BELOW_COLUMNS / WIDE_FROM_COLUMNS)。実機で inline・dock の桁数を見て決め直す。

  • 狭(40 桁未満): 高コストターン・「いま切り替えたら」・用語・グループのキャッシュ行を省き、トークン行は ヒット N% だけにする。信頼度は switch の注記と免責だけ残し、末尾に 狭幅のため一部省略 を 1 行出す。所見・金額・コスト・判定基準は切らない。
  • 通常(40〜69 桁)・広(70 桁以上、桁数が不明・異常値のときも): 全行を出す。バーの幅は桁数に合わせて縮む(上限 14 セル)。
  • 全幅共通: グループが 1 つのときはバーと割合を出さない(金額は出す)。
  • テキストのレポート(/model-review text)は幅によらず全文。

推定の限界

  • コストは TurnUsage のトークン数に単価表を掛けた推定。請求額ではない。
  • advisor の費用と fast mode の割増は含まれない(TurnUsage に載らないため。Q-009)。推定は過小になりうる。ペインの advisor 表示は回数のみ。
  • Web 検索などトークン以外の料金は含まれない(公式の価格表では Web 検索は 1,000 回あたり $10 の別料金。Claude Code の WebSearch がこの課金になるかは未確認。Q-015)。推定は過小になりうる。
  • 単価表は Claude API(第一者)の価格。Bedrock / Vertex の価格と地域の割増(地域エンドポイント・inference_geo: "us" などで約 1.1 倍)は含まれない(Q-015)。
  • キャッシュ書込は TTL の内訳がなく、5 分単価を基本に 1 時間単価を上限とする幅で示す。
  • 単価表にないモデルは「単価不明」として名前を画面に出し、合計から除く。単価表の取得日から 60 日を過ぎると改定の確認を促す注記が出る。
  • 長いセッションでは、直近 500 ターンより前(古い分)を集計値に畳み込む。件数・コスト・モデル別は全体を含み、指摘・切替・ループ別・高コスト順は直近 500 ターンが対象。
  • 実コスト($.session.usage の累計)が取れない環境では推定のみを表示する。

単価表の更新手順

  1. 公式の価格表(https://platform.claude.com/docs/en/about-claude/pricing)を取得する。
  2. hooks/pricing.ts の RATE_TABLE と PRICE_TABLE_FETCHED_AT を更新する。
  3. 新世代が出たら HAIKU_REFERENCE_MODEL / SONNET_REFERENCE_MODEL / OPUS_REFERENCE_MODEL を差し替える(pricing.test.ts が、参照モデルと CACHE_SAFE_EFFORT_MODELS が表に引けることを確認する)。
  4. .claude-plugin/plugin.json の version を上げ、CHANGELOG.md に書く。

pricing.test.ts の「単価表の取得日が古くなりすぎていない」は、取得から 120 日で意図して落ちる。落ちたら上の手順で更新する。

開発

claude plugin validate mods/model-review / claude plugin test mods/model-review / scripts/typecheck.sh model-review <claude-code.d.ts>。手順は CLAUDE.md。ペインの見た目は目視未確認。動作確認済みバージョン: Claude Code 2.1.309(validate / test / tsc)。

Source 33 files
hooks/register.tsx 266 lines
1import { atom, read, update } from 'claude-code'
2import type { Register, SessionUsage } from 'claude-code'
3
4import { PaneBody } from './pane'
5import { EMPTY_REVIEW, appendTurn, stampTurn, withBaseline, withCostSample } from './state'
6import { beginTurn, finishTurn, liveDrafts, markPlanMode, pruneDrafts, recordStep, recordTool, type Drafts } from './recorder'
7import { buildPaneRows } from './pane-model'
8import { buildReportLines } from './report'
9import { ARGUMENT_HINT, COPIED_TEXT, HELP_TEXT, UNKNOWN_ARG_TEXT, copyFailedText, parseCommandMode } from './copy'
10import { evaluateAlerts, formatStatus, needsRedraw, readLimits, readShowStatus } from './glance'
11import { readMutedConcerns } from './mute'
12import { addRateSamples, paceHints, rateView, type RateSamples } from './pace'
13import { formatSwitchNotice, readNotifyOnSwitch } from './switchnotice'
14import { recordSpawn, resolveAgentType, type AgentTypes } from './agenttype'
15
16const PANE_ID = 'model-review'
17const PANE_TITLE = 'モデル振り返り'
18const ADVISOR_TOOL_NAME = 'advisor'
19const PANE_OPENED_TEXT = 'モデル振り返りペインを開きました。'
20// 例外の中身は入力由来の文字列を含みうるので出さず、固定文言だけをログに残す。
21const COST_READ_FAILED_TEXT = 'model-review: 累計コストの取得に失敗したため、実コストを記録しなかった'
22const GLANCE_FAILED_TEXT = 'model-review: status 行の更新に失敗したため、この更新を省いた'
23const RECORD_FAILED_TEXT = 'model-review: 記録に失敗したため、この更新を記録しなかった'
24
25// validate の静的走査が読めるよう、参照はこのファイルに置く(リテラルの plugin / key)。
26const reviewAtom = atom({ plugin: 'model-review', key: 'review' } as const, EMPTY_REVIEW)
27
28/** 累計コストを取る。取れなかった(例外・未定義)ときは null。 */
29async function readCostUsd(loadUsage: () => Promise<SessionUsage>, log: (text: string) => void): Promise<number | null> {
30  try {
31    return (await loadUsage()).cost?.usd ?? null
32  } catch {
33    log(COST_READ_FAILED_TEXT)
34    return null
35  }
36}
37
38/**
39 * 記録処理を実行する。失敗しても固定文言を debug に残すだけで、呼び出し側の処理(ツールの実行など)は止めない。
40 * `next(e)` は包まない(包むと、失敗の後にもう一度 next を呼んで二重実行しうる)。
41 */
42async function recordSafely(work: () => void | Promise<void>, log: (text: string) => void): Promise<void> {
43  try {
44    await work()
45  } catch {
46    try {
47      log(RECORD_FAILED_TEXT)
48    } catch {
49      // ログも失敗したときは何もしない。記録の失敗でホストの処理を止めない。
50    }
51  }
52}
53
54const logDebug =
55  ($: { readonly ui: { log: (text: string, options: { to: 'debug' }) => unknown } }) =>
56  (text: string): void => {
57    void $.ui.log(text, { to: 'debug' })
58  }
59
60export const register: Register = (on, options) => {
61  const limits = readLimits(options)
62  const showStatus = readShowStatus(options)
63  const muted = readMutedConcerns(options)
64  const notifyOnSwitch = readNotifyOnSwitch(options)
65  // 知らせ済みの上限と、直近に出した status 文。reload で消えるので、reload 後は超過中の上限をもう一度知らせうる。
66  let notified: ReadonlySet<string> = new Set()
67  let lastStatus: string | undefined
68  // 進行中のターンの下書き(ループごと)。値は差し替えるだけで、中身は書き換えない。
69  let drafts: Drafts = {}
70  // /compact(自動を含む)が通った後、まだ完了していないメインのターンに印を付けるための旗。
71  let compactPending = false
72  // agentId → サブエージェントの種類。reload で消えるので、消えた後は $.agent.list() で補う。
73  let agentTypes: AgentTypes = {}
74  // 使用率の直近の測定(消費ペースの計算用)。reload で消えるので、reload 直後はペースが出ない。
75  let rateSamples: RateSamples = {}
76
77  on('session.start', async ($, e, next) => {
78    await $.command.register({
79      name: 'model-review',
80      description: 'セッションのモデル・effort・トークン・推定コストと、モデル選択の妥当性を表示する(読み取り専用)',
81      argumentHint: ARGUMENT_HINT,
82    })
83    const costUsd = await readCostUsd(
84      () => $.session.usage(),
85      text => $.ui.log(text, { to: 'debug' }),
86    )
87    await update($, reviewAtom, state => withBaseline(state, costUsd))
88    lastStatus = undefined
89    return next(e)
90  })
91
92  on('command.run', { command: 'model-review' }, async ($, e) => {
93    const mode = parseCommandMode(e.args)
94    // 引数を間違えたときに黙ってペインを開かない。help・不明な引数は記録を読まずに返す。
95    if (mode === 'help') return { text: HELP_TEXT }
96    if (mode === 'unknown') return { text: UNKNOWN_ARG_TEXT }
97    const costUsd = await readCostUsd(
98      () => $.session.usage(),
99      text => $.ui.log(text, { to: 'debug' }),
100    )
101    if (costUsd !== null) await update($, reviewAtom, state => withCostSample(state, costUsd))
102    const nowMs = await $.clock.now()
103    const lines = buildReportLines(await read($, reviewAtom), nowMs, muted, rateView(rateSamples, nowMs))
104    if (mode === 'copy') {
105      // コピー内容はテキストレポートそのもの(input・プロンプトは記録していないので含まれない)。
106      const copied = await $.ui.copy({ text: lines.join('\n') })
107      return { text: copied.isCopied ? COPIED_TEXT : copyFailedText(copied.reason) }
108    }
109    if (mode === 'text') return { text: lines.join('\n') }
110    const opened = await $.ui.open({ id: PANE_ID, title: PANE_TITLE })
111    return { text: opened.isPlaced ? PANE_OPENED_TEXT : lines.join('\n') }
112  })
113
114  on('session.measure', async ($, e, next) => {
115    const costUsd = e.cost?.usd
116    // 表示は記録(await)より先に。記録の失敗や遅れで status 行が止まったり、古い値で上書きされたりしないように。
117    if (needsRedraw(e.changed)) {
118      try {
119        const glance = { costUsd, rateLimits: e.rateLimits }
120        // 時刻が取れなければペースは出さない(測定は捨てずに残す)。
121        const nowMs = await $.clock.now().catch(() => undefined)
122        if (nowMs !== undefined && e.rateLimits.length > 0) rateSamples = addRateSamples(rateSamples, e.rateLimits, nowMs)
123        if (showStatus) {
124          const text = formatStatus(glance, nowMs === undefined ? undefined : paceHints(rateSamples, nowMs))
125          if (text !== lastStatus) {
126            lastStatus = text
127            void $.ui.status(text)
128          }
129        }
130        const result = evaluateAlerts(glance, limits, notified)
131        notified = result.notified
132        for (const alert of result.alerts) void $.ui.toast(alert)
133      } catch {
134        void $.ui.log(GLANCE_FAILED_TEXT, { to: 'debug' })
135      }
136    }
137    if (costUsd !== undefined) await update($, reviewAtom, state => withCostSample(state, costUsd))
138    return next(e)
139  })
140
141  // 切替の直前に、温かいキャッシュを捨てる見積りを知らせる。観察のみ: 結果は書き換えず、例外でも切替は止めない。
142  on('classic.PreModelSwitch', async ($, e, next) => {
143    if (notifyOnSwitch) {
144      await recordSafely(() => {
145        const text = formatSwitchNotice({
146          fromModel: e.from_model,
147          toModel: e.to_model,
148          contextTokens: e.context_tokens,
149          isCacheWarm: e.prompt_cache_warm,
150          estimatedCacheWriteUsd: e.estimated_cache_write_usd,
151          pricing: e.pricing,
152        })
153        if (text !== undefined) void $.ui.toast(text)
154      }, logDebug($))
155    }
156    return next(e)
157  }).catch(($, e, next) => next(e))
158
159  // 種類の名前だけを覚える(prompt・description は読まない)。記録の失敗で spawn は止めない。
160  on('agent.spawn', async ($, e, next) => {
161    const result = await next(e)
162    await recordSafely(() => {
163      agentTypes = recordSpawn(agentTypes, result.agentId, e.subagentType)
164    }, logDebug($))
165    return result
166  }).catch(($, e, next) => next(e))
167
168  // 実行中のターンの途中経過は $.state に載らないので、変わるたびにペインを描き直させる(毎秒 10 回まで)。
169  on('turn.start', async ($, e, next) => {
170    await recordSafely(async () => {
171      const nowMs = await $.clock.now()
172      // 読めなくてもターンの記録は止めない(フォールバックの推定ができないだけ)。
173      // 食い違いはメインのループだけで数えるので、サブエージェントでは読まない。
174      const sessionModel =
175        e.agentId !== undefined
176          ? null
177          : await Promise.resolve()
178              .then(() => $.session.model())
179              .catch(() => null)
180      drafts = pruneDrafts(beginTurn(drafts, e, nowMs, sessionModel), nowMs)
181      $.ui.invalidate('ui.render')
182    }, logDebug($))
183    return next(e)
184  })
185
186  // モデルと effort は turn.start ではなく、応答ごとの turn.step にしか載らない。
187  on('turn.step', async function* ($, e, next) {
188    const result = yield* next(e)
189    await recordSafely(async () => {
190      // 時刻は先に取る。await をまたいで drafts を読むと、並行するループの更新を上書きして失う。
191      const nowMs = await $.clock.now()
192      drafts = recordStep(
193        drafts,
194        {
195          turnId: e.turnId,
196          agentId: e.agentId,
197          model: e.model,
198          effort: e.effort,
199          usage: result.usage,
200          advisorCalls: (result.serverToolUses ?? []).filter(use => use.name === ADVISOR_TOOL_NAME).length,
201        },
202        nowMs,
203      )
204      $.ui.invalidate('ui.render')
205    }, logDebug($))
206    return result
207  })
208
209  // 入力(e の tool 以外)は記録しない。記録が失敗してもツールは通す。
210  on('tool.call', async ($, e, next) => {
211    await recordSafely(async () => {
212      const nowMs = await $.clock.now()
213      drafts = recordTool(drafts, { agentId: e.agentId, tool: e.tool }, nowMs)
214      $.ui.invalidate('ui.render')
215    }, logDebug($))
216    return next(e)
217  }).catch(($, e, next) => next(e))
218
219  on('turn.complete', async ($, e, next) => {
220    await recordSafely(async () => {
221      // 種類は drafts を読む前に引く。spawn で覚えていなければ $.agent.list() で補う(reload 後)。
222      const agentType =
223        e.agentId === undefined
224          ? null
225          : (resolveAgentType(agentTypes, e.agentId) ?? resolveAgentType(agentTypes, e.agentId, await $.agent.list().catch(() => [])))
226      const finished = finishTurn(drafts, {
227        turnId: e.turnId,
228        agentId: e.agentId,
229        usage: e.usage,
230        durationMs: e.durationMs,
231        reason: e.reason,
232        afterCompact: e.agentId === undefined && compactPending,
233        agentType,
234      })
235      if (e.agentId === undefined) compactPending = false
236      drafts = finished.drafts
237      // 時刻は付加情報。取れなくてもターンの記録は落とさない。
238      const completedAtMs = await $.clock.now().catch(() => undefined)
239      await update($, reviewAtom, state => appendTurn(state, stampTurn(state, finished.record, completedAtMs)))
240      $.ui.invalidate('ui.render')
241    }, logDebug($))
242    return next(e)
243  })
244
245  // plan mode の reminder を見たら進行中のメインのターンに印を付ける。観察のみで、結果は書き換えず next(e) をそのまま返す。
246  on('prompt.attachment', { type: 'plan_mode' }, async ($, e, next) => {
247    await recordSafely(() => {
248      drafts = markPlanMode(drafts, e.agentId)
249    }, logDebug($))
250    return next(e)
251  }).catch(($, e, next) => next(e))
252
253  // compact が実際に通ったら(skip でなければ)、次に完了するメインのターンを再構築の対象外にする。
254  on('session.compact', async ($, e, next) => {
255    const result = await next(e)
256    if (e.agentId === undefined && e.trigger !== 'precompute' && result.skip === undefined) compactPending = true
257    return result
258  }).catch(($, e, next) => next(e))
259
260  on('ui.render', { component: 'Pane', requestId: PANE_ID }, async ($, e) => {
261    const nowMs = await $.clock.now()
262    const rows = buildPaneRows(await read($, reviewAtom), liveDrafts(drafts, nowMs), nowMs, e.props.bodyColumns, muted, rateView(rateSamples, nowMs))
263    return <PaneBody ui={$.ui.resolve(e)} rows={rows} />
264  })
265}
266
hooks/pane.tsx 106 lines
1// 行モデル → Box / Text。ロジックを持たない(色とグリフの対応だけ)。色はテーマキーで、生の色名は使わない。
2import type { Elements } from 'claude-code'
3
4import { type Tone } from './conclusion'
5import { type PaneRow, type Tier } from './pane-model'
6
7type Ui = Pick<Elements['terminal'], 'Box' | 'Text'>
8
9const FILLED_GLYPH = '█'
10const EMPTY_GLYPH = '░'
11const TONE_COLOR: Record<Tone, 'success' | 'warning' | 'error' | 'suggestion' | undefined> = {
12  success: 'success',
13  warning: 'warning',
14  error: 'error',
15  suggestion: 'suggestion',
16  plain: undefined,
17}
18// モデル階層の色: 軽いほど success、重いほど warning。未知は色なし。
19const TIER_COLOR: Record<Tier, 'success' | 'suggestion' | 'warning' | undefined> = {
20  haiku: 'success',
21  sonnet: 'suggestion',
22  opus: 'warning',
23  other: undefined,
24}
25
26export function PaneBody({ ui, rows }: { ui: Ui; rows: readonly PaneRow[] }) {
27  const { Box, Text } = ui
28  // dim は飾り(空きのセル・免責)だけ。値や説明は subtle で、暗い背景でも読めるようにする。
29  const dim = (text: string) => <Text color="inactive" dimColor>{text}</Text>
30  const sub = (text: string) => <Text color="subtle">{text}</Text>
31
32  const renderRow = (row: PaneRow) => {
33    switch (row.kind) {
34      case 'title':
35        return <Text wrap="wrap">{sub(`${row.turns} ターン  ·  サブエージェント ${row.subagents}`)}</Text>
36      case 'conclusion':
37        return <Text bold wrap="wrap" color={TONE_COLOR[row.tone]}>{row.text}</Text>
38      case 'heading':
39        return <Text bold wrap="wrap">{`▎${row.text}`}</Text>
40      case 'group':
41        return (
42          <Box flexDirection="column">
43            <Text wrap="wrap">
44              <Text bold color={TIER_COLOR[row.tier]}>{row.model}</Text>
45              <Text>{'  '}</Text>
46              <Text color="subtle">{`effort ${row.effort}`}</Text>
47              {sub(`  ${row.turns} ターン`)}
48            </Text>
49            <Text wrap="wrap">
50              <Text bold>{`  ${row.costText}`}</Text>
51              {row.barWidth === 0 ? null : <Text>{'  '}</Text>}
52              <Text color={TIER_COLOR[row.tier]}>{FILLED_GLYPH.repeat(row.filled)}</Text>
53              {dim(EMPTY_GLYPH.repeat(row.barWidth - row.filled))}
54              {row.percentText === '' ? null : sub(`  ${row.percentText}`)}
55            </Text>
56            {row.tokenText === '' ? null : <Text color="subtle" wrap="wrap">{`  ${row.tokenText}`}</Text>}
57            {row.cacheText === '' ? null : <Text color="subtle" wrap="wrap">{`  ${row.cacheText}`}</Text>}
58          </Box>
59        )
60      case 'turn':
61        return (
62          <Box flexDirection="column">
63            <Text wrap="wrap">
64              <Text bold color={TIER_COLOR[row.tier]}>{row.model}</Text>
65              <Text bold>{`  ${row.costText}`}</Text>
66            </Text>
67            <Text color="subtle" wrap="wrap">{`  ${row.label} · ${row.detail}`}</Text>
68          </Box>
69        )
70      case 'kv':
71        return (
72          <Text wrap="wrap">
73            {sub(`${row.label}  `)}
74            <Text color={TONE_COLOR[row.tone]}>{row.value}</Text>
75          </Text>
76        )
77      case 'badge':
78        return (
79          <Text wrap="wrap">
80            <Text bold inverse color={TONE_COLOR[row.tone]}>{` ${row.label} `}</Text>
81            <Text>{` ${row.text}`}</Text>
82          </Text>
83        )
84      case 'example':
85        return <Text color="subtle" wrap="wrap">{`  ・${row.text}`}</Text>
86      case 'next':
87        return <Text color="suggestion" wrap="wrap">{`  → ${row.text}`}</Text>
88      case 'ok':
89        return (
90          <Text>
91            <Text color="success" bold>{'✓ '}</Text>
92            <Text>{row.text}</Text>
93          </Text>
94        )
95      case 'note':
96        return <Text color="subtle" wrap="wrap">{row.text}</Text>
97      case 'message':
98        return <Text color="subtle" wrap="wrap">{row.text}</Text>
99      default:
100        return <Text>{' '}</Text>
101    }
102  }
103
104  return <Box flexDirection="column">{rows.map(renderRow)}</Box>
105}
106
hooks/state.ts 77 lines
1// $.state に置く値(atom の初期値と、その書き換え)。すべて新しいオブジェクトを返す。
2import type { ReviewState, TurnRecord } from '../types'
3import { EMPTY_ARCHIVE, trimTurns } from './archive'
4
5export const EMPTY_REVIEW: ReviewState = {
6  turns: [],
7  sessionCostUsd: { baseline: null, current: null },
8}
9
10export function appendTurn(state: ReviewState, record: TurnRecord): ReviewState {
11  return trimTurns({ ...state, turns: [...state.turns, record] })
12}
13
14/** これまでに完了したメインのターン数。畳んだぶんも含むので、畳んでも通し番号はずれない。 */
15export const mainTurnCount = (state: ReviewState): number =>
16  (state.archived === undefined ? 0 : state.archived.turns - state.archived.subagents) +
17  state.turns.filter(record => record.agentId === null).length
18
19/**
20 * 記録に通し番号と完了時刻を足す。サブエージェントは親(まだ完了していないメインのターン)の番号を持つ。
21 * 時刻は呼び出し側が $.clock.now() で取って渡す。有限でなければ時刻は付けない。
22 */
23export function stampTurn(state: ReviewState, record: TurnRecord, nowMs?: number): TurnRecord {
24  return {
25    ...record,
26    mainSeq: mainTurnCount(state) + 1,
27    ...(typeof nowMs === 'number' && Number.isFinite(nowMs) ? { completedAtMs: nowMs } : {}),
28  }
29}
30
31/** 有限な金額だけを受け付ける。NaN・Infinity は null と同じく無視する(状態を壊さない)。 */
32const isUsableCost = (costUsd: number | null): costUsd is number => costUsd !== null && Number.isFinite(costUsd)
33
34/**
35 * 基準点は最初に取れた有限の値だけを使う。Mod 読み込み時の総額がここに入る。
36 * 基準点を取った時点のターン数(turns の長さ)も残す。これより後のターンだけが基準点からの実コストに入る。
37 */
38export function withBaseline(state: ReviewState, costUsd: number | null): ReviewState {
39  if (state.sessionCostUsd.baseline !== null || !isUsableCost(costUsd)) return state
40  return {
41    ...state,
42    sessionCostUsd: { ...state.sessionCostUsd, baseline: costUsd, baselineTurns: state.turns.length },
43  }
44}
45
46/**
47 * 直近値を書く。直前の値(なければ基準点)より小さい値が来たら(セッション再開などで累計が巻き戻った)、基準点を取り直す。
48 * 累計は減らないので、基準点以上でも直前より下がれば巻き戻りとみなす(基準点 0 のままの再開もここで拾う)。
49 * 取り直さないと実コストが負になったり、巻き戻る前の費用が推定にだけ残ったりする。
50 * 畳んだ集計のうち基準点より後のぶんも、取り直した基準点より前になるので消す。
51 */
52export function withCurrent(state: ReviewState, costUsd: number): ReviewState {
53  if (!isUsableCost(costUsd)) return state
54  const { baseline, current } = state.sessionCostUsd
55  const previous = current ?? baseline
56  if (baseline !== null && previous !== null && costUsd < previous) {
57    return {
58      ...state,
59      ...(state.archived === undefined ? {} : { archived: { ...state.archived, sinceBaseline: EMPTY_ARCHIVE.sinceBaseline } }),
60      sessionCostUsd: { baseline: costUsd, current: costUsd, baselineTurns: state.turns.length },
61    }
62  }
63  // 同じ値なら同じ状態を返す。新しいオブジェクトを返すと、測定のたびに atom の書込みと再描画が走る。
64  if (current === costUsd) return state
65  return { ...state, sessionCostUsd: { ...state.sessionCostUsd, current: costUsd } }
66}
67
68/** 基準点からの実コストに入るターン(基準点より後に完了したもの)。基準点ターン数がなければ最初から数える。 */
69export function turnsSinceBaseline(review: ReviewState): readonly TurnRecord[] {
70  return review.turns.slice(review.sessionCostUsd.baselineTurns ?? 0)
71}
72
73/** 累計コストを取れた時点で書く。起動時に取れなかった基準点は、ここで初めて設定される。 */
74export function withCostSample(state: ReviewState, costUsd: number): ReviewState {
75  return withCurrent(withBaseline(state, costUsd), costUsd)
76}
77
hooks/recorder.ts 422 lines
1// ターンの記録を組み立てる純粋な reducer。$ に触れず、入力を受けて新しいオブジェクトを返す。
2// tool.call は turnId を持たないため、ループ(メイン or サブエージェント)ごとに下書きを持つ。
3import type { CostParts, ModelShare, TurnRecord } from '../types'
4import { UNKNOWN_MODEL, ZERO_PARTS, ZERO_TOKENS, addParts } from './domain'
5import { sanitizeAgentType } from './agenttype'
6import { effortToRecord } from './effort'
7import { HAIKU_REFERENCE_MODEL, normalizeModelId, SONNET_REFERENCE_MODEL, priceUsage, priceUsageParts, type CacheWriteTtl, type TokenUsageLike } from './pricing'
8
9export const MAIN_LOOP_KEY = 'main'
10export { UNKNOWN_MODEL }
11export const EDIT_TOOLS: ReadonlySet<string> = new Set(['Edit', 'MultiEdit', 'Write', 'NotebookEdit'])
12/** 応答・ツール呼び出しが止まってからこの時間を過ぎた未完了の下書きは、実行中の表示から外す(turn.complete が来ないまま中断されたターン用)。 */
13export const LIVE_DRAFT_LIFETIME_MS = 10 * 60 * 1000
14
15export type LoopDraft = {
16  readonly turnId: string
17  readonly agentId: string | null
18  readonly model: string | null
19  readonly effort: string | null
20  readonly stepCount: number
21  /** 記録できた応答の 4 種トークンの合計。終了時の usage と比べて、欠けた応答を見つけるために使う。 */
22  readonly stepTokenTotal: number
23  /** 単価が分かっている応答の推定コストの合計。 */
24  readonly pricedCostUsd: number
25  /** 単価が分かっている応答の推定コストの、種類別の合計(5 分単価)。 */
26  readonly pricedParts: CostParts
27  /** 書込を 1 時間単価で計算した推定コストの合計(上限側)。 */
28  readonly pricedUpperCostUsd: number
29  /** 単価不明のモデルで応答した step があるか。 */
30  readonly hasUnpricedStep: boolean
31  /** 同じ応答を Haiku 単価で計算した推定コストの合計(応答ごとに単価段を判定)。 */
32  readonly haikuPricedCostUsd: number
33  /** 同じ応答を Sonnet 単価で計算した推定コストの合計。 */
34  readonly sonnetPricedCostUsd: number
35  /** 最初の応答のキャッシュ書込トークン数。 */
36  readonly firstStepCacheWrite: number
37  /** 最初の応答のプロンプト長(入力 + 読込 + 書込)。 */
38  readonly firstStepPromptTokens: number
39  /** 最初の応答のキャッシュ読込トークン数。書込と合わせて、モデル切替で書き直すキャッシュの量になる。 */
40  readonly firstStepCacheRead: number
41  /** 記録できた応答のうち、最も長いプロンプト長。応答の記録が欠けたとき、合計の usage の単価段をこの長さで決める。 */
42  readonly maxStepPromptTokens: number
43  readonly advisorCalls: number
44  readonly toolCount: number
45  readonly editCount: number
46  /** 最後に開始・応答・ツール呼び出しがあった時刻(ms)。取れなかったときは null。 */
47  readonly lastActivityMs: number | null
48  /** 応答したモデルごとの内訳(出現順)。終了時、2 モデル以上のときだけ記録に残す。 */
49  readonly byModel: readonly ModelShare[]
50  /** ターン開始時に読んだセッションのモデル。読めなければ null。 */
51  readonly sessionModel: string | null
52  /** 応答のモデルがセッションのモデルと食い違った応答の数。 */
53  readonly divergedSteps: number
54  /** plan mode の reminder をこのターンで見たか(メインのループだけ)。 */
55  readonly planMode: boolean
56  /** turn.start を見て作った下書きか。false なら reload で下書きが消えた後に途中から拾った下書き。 */
57  readonly started: boolean
58}
59
60export type Drafts = Readonly<Record<string, LoopDraft>>
61
62export type StepInput = {
63  readonly turnId: string
64  readonly agentId?: string
65  readonly model: string
66  readonly effort?: string | number
67  readonly usage?: TokenUsageLike | null
68  /** この応答で API が実行した advisor の呼び出し回数。 */
69  readonly advisorCalls?: number
70}
71
72export type ToolInput = {
73  readonly agentId?: string
74  readonly tool: string
75}
76
77export type TurnEndInput = {
78  readonly turnId: string
79  readonly agentId?: string
80  readonly usage?: TokenUsageLike
81  readonly durationMs: number
82  readonly reason: TurnRecord['reason']
83  /** この終了が /compact の直後のターンか。 */
84  readonly afterCompact?: boolean
85  /** サブエージェントの種類(subagentType の名前だけ)。分からなければ無し。 */
86  readonly agentType?: string | null
87}
88
89export type FinishedTurn = {
90  readonly drafts: Drafts
91  readonly record: TurnRecord
92}
93
94/**
95 * 外部から届いた usage を検証した値。トークン数は有限な非負数、model は文字列。
96 * model が文字列でなければ null にし、単価不明として扱う。
97 */
98export type SafeUsage = {
99  readonly model: string | null
100  readonly input_tokens: number
101  readonly output_tokens: number
102  readonly cache_read_input_tokens: number
103  readonly cache_creation_input_tokens: number
104}
105
106const loopKey = (agentId: string | undefined): string => agentId ?? MAIN_LOOP_KEY
107
108const emptyDraft = (turnId: string, agentId: string | null): LoopDraft => ({
109  turnId,
110  agentId,
111  model: null,
112  effort: null,
113  stepCount: 0,
114  stepTokenTotal: 0,
115  pricedCostUsd: 0,
116  pricedParts: ZERO_PARTS,
117  pricedUpperCostUsd: 0,
118  hasUnpricedStep: false,
119  haikuPricedCostUsd: 0,
120  sonnetPricedCostUsd: 0,
121  firstStepCacheWrite: 0,
122  firstStepPromptTokens: 0,
123  firstStepCacheRead: 0,
124  maxStepPromptTokens: 0,
125  advisorCalls: 0,
126  toolCount: 0,
127  editCount: 0,
128  lastActivityMs: null,
129  byModel: [],
130  sessionModel: null,
131  divergedSteps: 0,
132  planMode: false,
133  started: false,
134})
135
136const draftOf = (drafts: Drafts, agentId: string | undefined, turnId: string): LoopDraft =>
137  drafts[loopKey(agentId)] ?? emptyDraft(turnId, agentId ?? null)
138
139const withDraft = (drafts: Drafts, agentId: string | undefined, draft: LoopDraft): Drafts => ({
140  ...drafts,
141  [loopKey(agentId)]: draft,
142})
143
144/** 同じループに残っていた未完了の下書きは置き換える(中断されたターンの残りを引きずらない)。 */
145export function beginTurn(
146  drafts: Drafts,
147  turn: { readonly turnId: string; readonly agentId?: string },
148  nowMs?: number,
149  sessionModel?: string | null,
150): Drafts {
151  const started = {
152    ...emptyDraft(turn.turnId, turn.agentId ?? null),
153    lastActivityMs: nowMs ?? null,
154    // `opus` などのエイリアス・opusplan は応答のモデル ID と一致しないので、完全な ID(claude-…)のときだけ比べる。
155    sessionModel: typeof sessionModel === 'string' && sessionModel.startsWith('claude-') ? sessionModel : null,
156    started: true,
157  }
158  return withDraft(drafts, turn.agentId, started)
159}
160
161/** 数値として使えるのは有限な非負数だけ。それ以外(欠損・NaN・負数)は 0 とする。 */
162const tokenCountOf = (value: unknown): number => (typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : 0)
163
164/** 回数は 0 以上の整数だけを受け付ける。NaN・負数・小数・非数は 0 とする。 */
165const countOf = (value: unknown): number => (typeof value === 'number' && Number.isInteger(value) && value >= 0 ? value : 0)
166
167/** 所要時間は有限な非負数だけを受け付ける。それ以外は不明(undefined)として記録しない。 */
168const durationOf = (value: unknown): number | undefined =>
169  typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined
170
171/** usage の値を検証する。オブジェクトでなければ usage なしとして null を返す。 */
172export function sanitizeUsage(raw: unknown): SafeUsage | null {
173  if (typeof raw !== 'object' || raw === null) return null
174  const fields = raw as Readonly<Record<keyof TokenUsageLike, unknown>>
175  return {
176    model: typeof fields.model === 'string' ? fields.model : null,
177    input_tokens: tokenCountOf(fields.input_tokens),
178    output_tokens: tokenCountOf(fields.output_tokens),
179    cache_read_input_tokens: tokenCountOf(fields.cache_read_input_tokens),
180    cache_creation_input_tokens: tokenCountOf(fields.cache_creation_input_tokens),
181  }
182}
183
184/**
185 * model が不明(null)なら単価不明として null。それ以外は指定した単価(既定は 5 分単価)で計算する。
186 * tierPromptTokens は合計の usage を評価するときの 1 応答の長さ(省略時は usage 自身の長さ)。
187 */
188const priceAs = (usage: SafeUsage, model: string | null, writeTtl: CacheWriteTtl = '5m', tierPromptTokens?: number): number | null =>
189  model === null ? null : priceUsage({ ...usage, model }, writeTtl, tierPromptTokens)
190
191const promptTokensOf = (usage: SafeUsage | null): number =>
192  usage === null ? 0 : usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens
193
194const totalTokensOf = (usage: SafeUsage): number =>
195  usage.input_tokens + usage.output_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens
196
197const addShare = (shares: readonly ModelShare[], model: string, usage: SafeUsage | null, priced: number | null): readonly ModelShare[] => {
198  // usage のない応答はトークンも費用も 0 なので、内訳の行を増やさない。
199  if (usage === null) return shares
200  const tokens = tokenCountsOf(usage)
201  // 日付違いなどの別表記は同じモデルとして数える(表記は最初のものを残す)。
202  const found = shares.find(share => normalizeModelId(share.model) === normalizeModelId(model))
203  const base: ModelShare = found ?? { model, tokens: ZERO_TOKENS, costUsd: 0, steps: 0 }
204  const next: ModelShare = {
205    model,
206    tokens: {
207      input: base.tokens.input + tokens.input,
208      output: base.tokens.output + tokens.output,
209      cacheRead: base.tokens.cacheRead + tokens.cacheRead,
210      cacheWrite: base.tokens.cacheWrite + tokens.cacheWrite,
211    },
212    costUsd: base.costUsd === null || priced === null ? null : base.costUsd + priced,
213    steps: base.steps + 1,
214  }
215  return found === undefined ? [...shares, next] : shares.map(share => (share === found ? next : share))
216}
217
218/** メインのループだけで判定する(サブエージェントは定義のモデルで動くのが通常のため)。セッションのモデルが分かっていて、応答のモデルがそれと(日付違いなどを除いて)違うときだけ true。 */
219const isDiverged = (sessionModel: string | null, stepModel: string): boolean =>
220  sessionModel !== null && normalizeModelId(sessionModel) !== normalizeModelId(stepModel)
221
222export function recordStep(drafts: Drafts, step: StepInput, nowMs?: number): Drafts {
223  const prev = draftOf(drafts, step.agentId, step.turnId)
224  const usage = sanitizeUsage(step.usage)
225  const priced = usage ? priceAs(usage, usage.model) : null
226  const parts = usage && usage.model !== null ? priceUsageParts({ ...usage, model: usage.model }) : null
227  const pricedUpper = usage ? priceAs(usage, usage.model, '1h') : null
228  const pricedAsHaiku = usage ? priceAs(usage, HAIKU_REFERENCE_MODEL) : null
229  const pricedAsSonnet = usage ? priceAs(usage, SONNET_REFERENCE_MODEL) : null
230  const next: LoopDraft = {
231    ...prev,
232    turnId: step.turnId,
233    model: usage?.model ?? prev.model ?? step.model,
234    effort: effortToRecord(step.effort),
235    stepCount: prev.stepCount + 1,
236    stepTokenTotal: prev.stepTokenTotal + (usage ? totalTokensOf(usage) : 0),
237    pricedCostUsd: prev.pricedCostUsd + (priced ?? 0),
238    pricedParts: parts === null ? prev.pricedParts : addParts(prev.pricedParts, parts),
239    pricedUpperCostUsd: prev.pricedUpperCostUsd + (pricedUpper ?? 0),
240    hasUnpricedStep: prev.hasUnpricedStep || (usage !== null && priced === null),
241    haikuPricedCostUsd: prev.haikuPricedCostUsd + (pricedAsHaiku ?? 0),
242    sonnetPricedCostUsd: prev.sonnetPricedCostUsd + (pricedAsSonnet ?? 0),
243    firstStepCacheWrite: prev.stepCount === 0 ? (usage?.cache_creation_input_tokens ?? 0) : prev.firstStepCacheWrite,
244    firstStepPromptTokens: prev.stepCount === 0 ? promptTokensOf(usage) : prev.firstStepPromptTokens,
245    firstStepCacheRead: prev.stepCount === 0 ? (usage?.cache_read_input_tokens ?? 0) : prev.firstStepCacheRead,
246    maxStepPromptTokens: Math.max(prev.maxStepPromptTokens, promptTokensOf(usage)),
247    advisorCalls: prev.advisorCalls + countOf(step.advisorCalls),
248    lastActivityMs: nowMs ?? prev.lastActivityMs,
249    byModel: addShare(prev.byModel, usage?.model ?? step.model, usage, priced),
250    divergedSteps: prev.divergedSteps + (step.agentId === undefined && isDiverged(prev.sessionModel, usage?.model ?? step.model) ? 1 : 0),
251  }
252  return withDraft(drafts, step.agentId, next)
253}
254
255/**
256 * plan mode の reminder を見たら、進行中のメインのターンに印を付ける。観察のみ(reminder の中身・計画ファイルのパスは読まない)。
257 * 進行中のメインの下書きがないとき(ターンの外で届いたとき)は何もしない。サブエージェントのループは対象外。
258 */
259export function markPlanMode(drafts: Drafts, agentId: string | undefined): Drafts {
260  const prev = drafts[MAIN_LOOP_KEY]
261  if (agentId !== undefined || prev === undefined) return drafts
262  return prev.planMode ? drafts : { ...drafts, [MAIN_LOOP_KEY]: { ...prev, planMode: true } }
263}
264
265export function recordTool(drafts: Drafts, call: ToolInput, nowMs?: number): Drafts {
266  const prev = draftOf(drafts, call.agentId, '')
267  const next: LoopDraft = {
268    ...prev,
269    toolCount: prev.toolCount + 1,
270    editCount: prev.editCount + (EDIT_TOOLS.has(call.tool) ? 1 : 0),
271    lastActivityMs: nowMs ?? prev.lastActivityMs,
272  }
273  return withDraft(drafts, call.agentId, next)
274}
275
276/** 動きが止まってからこの時間を過ぎた未完了の下書きは、捨てる(turn.complete が来ないまま残った下書きでメモリが増え続けないように)。 */
277export const DRAFT_RETENTION_MS = 6 * LIVE_DRAFT_LIFETIME_MS
278
279/**
280 * 保持期限を過ぎた未完了の下書きを捨てる。liveDrafts(表示から外すだけで、動きが再開すれば戻る)より長い期限で、
281 * 戻る見込みのない下書きだけを消す。最後の動きの時刻が不明な下書きは消さない。何も消さなければ同じ値を返す。
282 */
283export function pruneDrafts(drafts: Drafts, nowMs: number | undefined): Drafts {
284  if (nowMs === undefined) return drafts
285  const stale = Object.entries(drafts).filter(([, draft]) => draft.lastActivityMs !== null && nowMs - draft.lastActivityMs > DRAFT_RETENTION_MS)
286  if (stale.length === 0) return drafts
287  const staleKeys = new Set(stale.map(([key]) => key))
288  return Object.fromEntries(Object.entries(drafts).filter(([key]) => !staleKeys.has(key)))
289}
290
291/**
292 * 表示用に、寿命を過ぎた未完了の下書きを外したコピーを返す。元の下書きは変えないので、動きが再開すれば戻る。
293 * 最後の動きの時刻が不明な下書きは外さない。
294 */
295export function liveDrafts(drafts: Drafts, nowMs: number): Drafts {
296  const isLive = (draft: LoopDraft): boolean =>
297    draft.lastActivityMs === null || nowMs - draft.lastActivityMs <= LIVE_DRAFT_LIFETIME_MS
298  return Object.fromEntries(Object.entries(drafts).filter(([, draft]) => isLive(draft)))
299}
300
301function tokenCountsOf(usage: SafeUsage | null): TurnRecord['tokens'] {
302  if (!usage) return ZERO_TOKENS
303  return {
304    input: usage.input_tokens,
305    output: usage.output_tokens,
306    cacheRead: usage.cache_read_input_tokens,
307    cacheWrite: usage.cache_creation_input_tokens,
308  }
309}
310
311/** step の合計が終了時の usage より少なければ、step の記録が欠けている(イベントの取りこぼし)とみなす。 */
312const isStepRecordIncomplete = (draft: LoopDraft, usage: SafeUsage | null): boolean =>
313  usage !== null && totalTokensOf(usage) > draft.stepTokenTotal
314
315/**
316 * ターン全体の usage で計算するときの単価段の長さ。単価段は 1 応答ごとに決まるので、合計の長さでは判定しない。
317 * 記録できた応答があれば、その最長のプロンプト長で代用する。応答が 1 つも記録されていなければ(1 応答とみなして)合計の長さのまま。
318 */
319const fallbackTierOf = (draft: LoopDraft): number | undefined => (draft.stepCount > 0 ? draft.maxStepPromptTokens : undefined)
320
321/**
322 * 推定コストの共通規則。応答ごとに計算した合計を優先し、step が欠けていればターン全体の usage で計算する。
323 * どちらも取れなければ null(単価不明と同じ扱い)。0 と書くと 0 円に読めてしまう。
324 */
325function resolveCost(
326  draft: LoopDraft,
327  usage: SafeUsage | null,
328  perStepUsd: number,
329  priceTurn: (turnUsage: SafeUsage, tierPromptTokens: number | undefined) => number | null,
330): number | null {
331  if (draft.hasUnpricedStep) return null
332  if (draft.stepCount > 0 && !isStepRecordIncomplete(draft, usage)) return perStepUsd
333  return usage === null ? null : priceTurn(usage, fallbackTierOf(draft))
334}
335
336function costOf(draft: LoopDraft, usage: SafeUsage | null): number | null {
337  return resolveCost(draft, usage, draft.pricedCostUsd, (turnUsage, tier) => priceAs(turnUsage, turnUsage.model, '5m', tier))
338}
339
340/** costOf と同じ規則の、種類別の内訳。costUsd が null のターンは null。 */
341function partsOf(draft: LoopDraft, usage: SafeUsage | null): CostParts | null {
342  if (draft.hasUnpricedStep) return null
343  if (draft.stepCount > 0 && !isStepRecordIncomplete(draft, usage)) return draft.pricedParts
344  if (usage === null || usage.model === null) return null
345  return priceUsageParts({ ...usage, model: usage.model }, '5m', fallbackTierOf(draft))
346}
347
348/** costOf と同じ規則で、キャッシュ書込を 1 時間単価にした推定コスト(上限側)。 */
349function upperCostOf(draft: LoopDraft, usage: SafeUsage | null): number | null {
350  return resolveCost(draft, usage, draft.pricedUpperCostUsd, (turnUsage, tier) => priceAs(turnUsage, turnUsage.model, '1h', tier))
351}
352
353/** costOf と同じ規則で、Haiku 単価に置き換えた推定コスト。 */
354function haikuCostOf(draft: LoopDraft, usage: SafeUsage | null): number | null {
355  return resolveCost(draft, usage, draft.haikuPricedCostUsd, (turnUsage, tier) => priceAs(turnUsage, HAIKU_REFERENCE_MODEL, '5m', tier))
356}
357
358/** costOf と同じ規則で、Sonnet 単価に置き換えた推定コスト。 */
359function sonnetCostOf(draft: LoopDraft, usage: SafeUsage | null): number | null {
360  return resolveCost(draft, usage, draft.sonnetPricedCostUsd, (turnUsage, tier) => priceAs(turnUsage, SONNET_REFERENCE_MODEL, '5m', tier))
361}
362
363/**
364 * 最初の応答のキャッシュ書込とプロンプト長。応答(step)がないターンは終了時の usage で補い、
365 * どちらもなければ未取得(undefined)にする。0 と書くと切替の再構築が 0 円に読めてしまう。
366 */
367function firstStepOf(
368  draft: LoopDraft,
369  usage: SafeUsage | null,
370): { readonly cacheWrite: number | undefined; readonly cacheRead: number | undefined; readonly promptTokens: number | undefined } {
371  if (draft.stepCount > 0) {
372    return { cacheWrite: draft.firstStepCacheWrite, cacheRead: draft.firstStepCacheRead, promptTokens: draft.firstStepPromptTokens }
373  }
374  if (!usage) return { cacheWrite: undefined, cacheRead: undefined, promptTokens: undefined }
375  return { cacheWrite: usage.cache_creation_input_tokens, cacheRead: usage.cache_read_input_tokens, promptTokens: promptTokensOf(usage) }
376}
377
378/** サブエージェントのターンで、使える種類の名前があるときだけ載せる。 */
379const agentTypeField = (end: TurnEndInput): { readonly agentType?: string } => {
380  const type = end.agentId === undefined ? null : sanitizeAgentType(end.agentType)
381  return type === null ? {} : { agentType: type }
382}
383
384/** 2 モデル以上が応答したときだけ内訳を残す。step の記録が欠けているときは合計と合わないので残さない。 */
385const byModelField = (draft: LoopDraft, usage: SafeUsage | null): { readonly byModel?: readonly ModelShare[] } =>
386  draft.byModel.length > 1 && !isStepRecordIncomplete(draft, usage) ? { byModel: draft.byModel } : {}
387
388export function finishTurn(drafts: Drafts, end: TurnEndInput): FinishedTurn {
389  const key = loopKey(end.agentId)
390  const draft = draftOf(drafts, end.agentId, end.turnId)
391  const usage = sanitizeUsage(end.usage)
392  const first = firstStepOf(draft, usage)
393  const record: TurnRecord = {
394    turnId: end.turnId,
395    agentId: end.agentId ?? null,
396    model: usage?.model ?? draft.model ?? UNKNOWN_MODEL,
397    effort: draft.effort,
398    tokens: tokenCountsOf(usage),
399    costUsd: costOf(draft, usage),
400    costUpperUsd: upperCostOf(draft, usage),
401    costParts: partsOf(draft, usage),
402    toolCount: draft.toolCount,
403    editCount: draft.editCount,
404    durationMs: durationOf(end.durationMs),
405    reason: end.reason,
406    haikuCostUsd: haikuCostOf(draft, usage),
407    sonnetCostUsd: sonnetCostOf(draft, usage),
408    firstStepCacheWrite: first.cacheWrite,
409    firstStepPromptTokens: first.promptTokens,
410    firstStepCacheRead: first.cacheRead,
411    advisorCalls: draft.advisorCalls,
412    ...byModelField(draft, usage),
413    ...(draft.divergedSteps > 0 ? { divergedSteps: draft.divergedSteps } : {}),
414    ...(end.afterCompact === true ? { afterCompact: true } : {}),
415    ...(draft.planMode ? { planMode: true } : {}),
416    ...agentTypeField(end),
417    ...(draft.started ? {} : { partial: true }),
418  }
419  const remaining = Object.fromEntries(Object.entries(drafts).filter(([candidate]) => candidate !== key))
420  return { drafts: remaining, record }
421}
422
hooks/pane-model.ts 394 lines
1// ペインの行モデルを組み立てる純粋関数。`$` にも JSX にも依存しない。描画は pane.tsx。
2// 集計は analysis.ts、節の順序と出し分けは sections.ts、文面の共通部分は summary.ts。ここはペイン固有の並び・バー・用語・結論行を持つ。
3import type { ArchivedGroup, ReviewState } from '../types'
4import { analyzeReview, type ReviewAnalysis } from './analysis'
5import { BREAKDOWN_LABEL, type BreakdownView } from './breakdown'
6import { GROWTH_LABEL, type GrowthView } from './growth'
7import type { RateView } from './pace'
8import { HEAVY_TOOL_CALLS, LIGHT_MAX_OUTPUT_TOKENS, LIGHT_MAX_TOOL_CALLS, mainTurnsAfter, modelRank, type Concern, type ConcernKind } from './analyze'
9import { shortModel } from './domain'
10import { cellWidth, formatInt, formatUsd } from './format'
11import type { Drafts, LoopDraft } from './recorder'
12import { CONCERN_TEXT, FINDING_LABEL, HEADING, NO_CONCERNS_TEXT, PAST_CONCERNS_HEADING, TERM_TEXT, type TermKey } from './labels'
13import { CONCERN_TONE, NO_RECORDS_CONCLUSION, type Tone } from './conclusion'
14import { WHATIF_NOTE } from './whatif'
15import { turnLabelText } from './turnref'
16import { alwaysNoteText, type FindingNote } from './notes'
17import {
18  buildSections,
19  type ConcernsSection,
20  type CostSection,
21  type GroupsSection,
22  type LoopsSection,
23  type Section,
24  type TopTurnsSection,
25  type WhatIfSection,
26} from './sections'
27import {
28  NO_TURNS_LINE,
29  concernDetailText,
30  groupFacts,
31  hitRateText,
32  moneyLineBody,
33  toolDetailText,
34  turnOriginLabel,
35} from './summary'
36
37/** コスト比バーの最大幅。狭い画面では barWidthFor が縮める。 */
38export const BAR_WIDTH = 14
39/** バーを出す最小の幅(比が読める最小)。これに収まらないときはバーを出さず、金額と割合だけにする。 */
40export const MIN_BAR_WIDTH = 4
41/** バーは本文の桁数のこの割合(1/5)までにとどめる。狭い画面で金額・割合より先にバーを縮める。 */
42const BAR_MAX_SHARE_OF_COLUMNS = 5
43/** バー行の固定部分: 先頭の字下げ 2 + 金額との間 2 + 割合との間 2 + 割合(`100%` で 4)。 */
44const BAR_ROW_FIXED_CELLS = 10
45
46/**
47 * 狭(< NARROW_BELOW_COLUMNS)の区分のしきい値(本文の桁数)。仮置き・目視未確認(mr-011)。実機で inline・dock の桁数を見て決め直す。
48 * 狭幅だけ行を省く。通常と広は全行を出す。
49 */
50export const NARROW_BELOW_COLUMNS = 40
51/** 広(≥ WIDE_FROM_COLUMNS)の区分のしきい値。仮置き・目視未確認(mr-011)。 */
52export const WIDE_FROM_COLUMNS = 70
53/** 狭幅で行を省いたことを、信頼度の節の末尾に 1 行で示す(省いた内容は /model-review text で全文が読める)。 */
54const NARROW_OMITTED_NOTE = '狭幅のため一部省略'
55
56export type WidthClass = 'narrow' | 'normal' | 'wide'
57
58/** 桁数として使える値(有限で正の数)だけを返す。undefined・NaN・Infinity・0・負数は不明(undefined)。 */
59function knownColumns(columns: number | undefined): number | undefined {
60  return columns !== undefined && Number.isFinite(columns) && columns > 0 ? columns : undefined
61}
62
63/** 桁数の区分。不明(undefined を含む)は広と同じ扱い。 */
64export function widthClassOf(columns: number | undefined): WidthClass {
65  const known = knownColumns(columns)
66  if (known === undefined || known >= WIDE_FROM_COLUMNS) return 'wide'
67  return known < NARROW_BELOW_COLUMNS ? 'narrow' : 'normal'
68}
69
70/** 描画の条件。columns は正規化後の桁数(不明は undefined)、narrow は狭幅で行を省くかどうか。 */
71type Layout = { readonly columns: number | undefined; readonly narrow: boolean }
72
73export type Tier = 'haiku' | 'sonnet' | 'opus' | 'other'
74
75export type PaneRow =
76  | { kind: 'conclusion'; text: string; tone: Tone }
77  | { kind: 'message'; text: string }
78  | { kind: 'blank' }
79  | { kind: 'title'; turns: number; subagents: number }
80  | { kind: 'heading'; text: string }
81  | { kind: 'group'; model: string; effort: string; tier: Tier; turns: number; barWidth: number; filled: number; percentText: string; costText: string; tokenText: string; cacheText: string }
82  | { kind: 'turn'; label: string; model: string; tier: Tier; costText: string; detail: string }
83  | { kind: 'kv'; label: string; value: string; tone: Tone }
84  | { kind: 'badge'; label: string; tone: Tone; text: string }
85  | { kind: 'example'; text: string }
86  | { kind: 'next'; text: string }
87  | { kind: 'ok'; text: string }
88  | { kind: 'note'; text: string }
89
90const TIER_OF_RANK: Readonly<Record<number, Tier>> = { 0: 'haiku', 1: 'sonnet', 2: 'opus' }
91
92const tierOf = (model: string): Tier => TIER_OF_RANK[modelRank(model)] ?? 'other'
93
94const MIN_VISIBLE_SHARE = 0.01
95
96/** コスト比(0〜1)。単価不明(null)や合計 0 は null。 */
97function costShare(costUsd: number | null, totalUsd: number): number | null {
98  if (costUsd === null || totalUsd <= 0) return null
99  return costUsd / totalUsd
100}
101
102/**
103 * 本文の桁数(bodyColumns)と金額の桁数から、バーが収まる幅を決める。金額は削らず、バーを縮める。
104 * MIN_BAR_WIDTH に収まらなければ 0(バーを出さない)。桁数が分からなければ(undefined)最大幅。
105 */
106export function barWidthFor(columns: number | undefined, costText: string): number {
107  if (columns === undefined) return BAR_WIDTH
108  const room = columns - BAR_ROW_FIXED_CELLS - cellWidth(costText)
109  const width = Math.min(BAR_WIDTH, room, Math.floor(columns / BAR_MAX_SHARE_OF_COLUMNS))
110  return width < MIN_BAR_WIDTH ? 0 : width
111}
112
113/** コスト比を 0〜width のセル数にする。1% 未満は 0、それ以上は最低 1 セル。 */
114function filledCells(share: number | null, width: number): number {
115  if (share === null || share < MIN_VISIBLE_SHARE) return 0
116  return Math.min(width, Math.max(1, Math.round(share * width)))
117}
118
119function percentText(share: number | null): string {
120  if (share === null) return ''
121  return share < MIN_VISIBLE_SHARE ? '<1%' : `${Math.round(share * 100)}%`
122}
123
124/**
125 * グループの行。1 グループのときはバーも割合も出さない(比べる相手がなく、満タンと 100% は情報がない)。
126 * 狭幅はトークン行をヒット率だけにし、キャッシュ行は出さない(ヒット率は判断の中心なので残す)。
127 */
128function groupRow(group: ArchivedGroup, totalUsd: number, layout: Layout, singleGroup: boolean): PaneRow {
129  const facts = groupFacts(group)
130  const share = costShare(group.costUsd, totalUsd)
131  const barWidth = singleGroup ? 0 : barWidthFor(layout.columns, facts.costText)
132  return {
133    kind: 'group',
134    model: shortModel(group.model),
135    effort: facts.effort,
136    tier: tierOf(group.model),
137    turns: group.turns,
138    barWidth,
139    filled: filledCells(share, barWidth),
140    percentText: singleGroup ? '' : percentText(share),
141    costText: facts.costText,
142    tokenText: layout.narrow ? (facts.hit ?? '') : `${facts.hit === null ? '' : `${facts.hit} · `}入力 ${facts.input} · 出力 ${facts.output}`,
143    cacheText: layout.narrow ? '' : `キャッシュ 読 ${facts.cacheRead} / 書 ${facts.cacheWrite}`,
144  }
145}
146
147function breakdownRows(view: BreakdownView | null): PaneRow[] {
148  if (view === null) return []
149  return [
150    { kind: 'kv', label: BREAKDOWN_LABEL, value: view.items, tone: 'plain' },
151    ...(view.hint === null ? [] : [{ kind: 'next', text: view.hint } satisfies PaneRow]),
152    { kind: 'note', text: view.note },
153  ]
154}
155
156function growthRows(view: GrowthView | null): PaneRow[] {
157  if (view === null) return []
158  return [
159    { kind: 'kv', label: GROWTH_LABEL, value: view.trend, tone: 'plain' },
160    ...(view.compact === null ? [] : [{ kind: 'kv', label: '  compact の前後', value: view.compact, tone: 'plain' } satisfies PaneRow]),
161    ...(view.hint === null ? [] : [{ kind: 'note', text: `→ ${view.hint}` } satisfies PaneRow]),
162    { kind: 'note', text: view.note },
163  ]
164}
165
166function rateRows(rate: RateView | null): PaneRow[] {
167  if (rate === null) return []
168  return [
169    ...rate.rows.map((row): PaneRow => ({ kind: 'kv', label: `使用率 ${row.label}`, value: row.text, tone: 'plain' })),
170    { kind: 'note', text: rate.note },
171  ]
172}
173
174/** タイトルの直下の金額行。テキストの「金額:」と同じ文面(moneyLineBody)を使う。 */
175const moneyRow = (analysis: ReviewAnalysis, isSubscription: boolean): PaneRow => ({
176  kind: 'kv',
177  label: '金額',
178  value: moneyLineBody(analysis.estimate, analysis.diff, isSubscription),
179  tone: 'plain',
180})
181
182/** 直近の指摘は種類の色と「次の一手」つき。過去の指摘は色なし(plain)で、次の一手を付けない。 */
183function oneConcernRows(concern: Concern, next: string | null, recent: boolean): PaneRow[] {
184  return [
185    {
186      kind: 'badge',
187      label: CONCERN_TEXT[concern.kind].label,
188      tone: recent ? CONCERN_TONE[concern.kind] : 'plain',
189      text: concernDetailText(concern),
190    },
191    ...concern.examples.map((text): PaneRow => ({ kind: 'example', text })),
192    ...(next === null ? [] : [{ kind: 'next', text: next } satisfies PaneRow]),
193  ]
194}
195
196/** 所見の中の警告(再構築・TTL 乖離)。バッジは種類の名前、本文はそのまま。 */
197const findingRows = (findings: readonly FindingNote[]): PaneRow[] =>
198  findings.map((note): PaneRow => ({ kind: 'badge', label: FINDING_LABEL[note.kind], tone: 'warning', text: note.text }))
199
200/**
201 * 所見の節(見出し・指摘・警告・空行)。直近の指摘を先に、所見の警告を指摘の後に、窓より前にだけ該当した指摘は注記の小見出しの下に分けて並べる。
202 * 止めている種類は最後に注記 1 行だけ。結論が「目立った指摘なし」を言うときは OK 行を出さない。
203 * 中身が 1 行も残らないときは、見出しと空行ごと出さない(警告も中身に数える)。
204 */
205function concernSectionRows(section: ConcernsSection): PaneRow[] {
206  const { recent, findings, past, nextSteps, numericNote, mutedLine, noConcerns } = section
207  const body: PaneRow[] = [
208    ...recent.flatMap(concern => oneConcernRows(concern, nextSteps.get(concern) ?? null, true)),
209    ...(recent.length === 0 && !noConcerns ? [{ kind: 'ok', text: NO_CONCERNS_TEXT } satisfies PaneRow] : []),
210    ...findingRows(findings),
211    ...(past.length === 0
212      ? []
213      : [{ kind: 'note', text: PAST_CONCERNS_HEADING } satisfies PaneRow, ...past.flatMap(concern => oneConcernRows(concern, null, false))]),
214    ...(numericNote === null ? [] : [{ kind: 'note', text: numericNote } satisfies PaneRow]),
215    ...(mutedLine === null ? [] : [{ kind: 'note', text: mutedLine } satisfies PaneRow]),
216  ]
217  return body.length === 0 ? [] : [{ kind: 'heading', text: HEADING.concerns }, ...body, { kind: 'blank' }]
218}
219
220function groupSectionRows(section: GroupsSection, layout: Layout): PaneRow[] {
221  const singleGroup = section.groups.length === 1
222  return [
223    { kind: 'heading', text: HEADING.groups },
224    ...section.groups.map(group => groupRow(group, section.totalUsd, layout, singleGroup)),
225    { kind: 'blank' },
226  ]
227}
228
229function topTurnRows(section: TopTurnsSection, nowMs?: number): PaneRow[] {
230  return [
231    { kind: 'heading', text: HEADING.topTurns },
232    ...section.turns.map((record): PaneRow => ({
233      kind: 'turn',
234      label: turnLabelText(record, mainTurnsAfter(section.records, record), turnOriginLabel(record), nowMs),
235      model: shortModel(record.model),
236      tier: tierOf(record.model),
237      costText: formatUsd(record.costUsd),
238      detail: toolDetailText(record),
239    })),
240    { kind: 'blank' },
241  ]
242}
243
244function loopRows(section: LoopsSection): PaneRow[] {
245  const { view } = section
246  return [
247    { kind: 'heading', text: HEADING.loops },
248    ...view.rows.map((row): PaneRow => ({ kind: 'kv', label: row.label, value: row.detail, tone: 'plain' })),
249    ...(view.subagentNote === null ? [] : [{ kind: 'note', text: view.subagentNote } as const]),
250    { kind: 'blank' },
251  ]
252}
253
254function whatIfRows(section: WhatIfSection): PaneRow[] {
255  return [
256    { kind: 'heading', text: HEADING.whatIf },
257    ...section.options.map((text): PaneRow => ({ kind: 'example', text })),
258    { kind: 'note', text: WHATIF_NOTE },
259    { kind: 'blank' },
260  ]
261}
262
263const advisorRows = (text: string | null): PaneRow[] => (text === null ? [] : [{ kind: 'kv', label: 'advisor', value: text, tone: 'plain' }])
264
265/** ペイン末尾の免責。advisor の行があるときは、その行に免責があるので advisor の句を外す(レポートは ALWAYS_NOTE のまま)。 */
266export const paneAlwaysNote = (hasAdvisorRow: boolean): string => alwaysNoteText({ omitAdvisor: hasAdvisorRow })
267
268/** 画面に出る行と同じ条件で、説明すべき用語を選ぶ。 */
269function shownTerms(analysis: ReviewAnalysis): TermKey[] {
270  const hasActual = analysis.diff !== null
271  const candidates: ReadonlyArray<readonly [TermKey, boolean]> = [
272    ['hitRate', analysis.groups.some(group => hitRateText(group.tokens) !== null)],
273    ['afterLoad', hasActual],
274    ['sonnetEquivalent', analysis.concerns.some(concern => concern.kind === 'overspec' && concern.amountUsd !== null)],
275    ['diff', hasActual],
276  ]
277  return candidates.flatMap(([term, shown]) => (shown ? [term] : []))
278}
279
280function glossaryRows(terms: readonly TermKey[]): PaneRow[] {
281  if (terms.length === 0) return []
282  return [{ kind: 'note', text: `用語  ${terms.map(term => TERM_TEXT[term]).join(' / ')}` }]
283}
284
285/**
286 * コストの節。使用率・内訳・推移・advisor の行があるときだけ、見出しと空行を出す(金額は直下の金額行に出すので、ここには置かない)。
287 */
288function costSectionRows(section: CostSection, rate: RateView | null): PaneRow[] {
289  const body: PaneRow[] = [
290    ...rateRows(rate),
291    ...breakdownRows(section.breakdown),
292    ...growthRows(section.growth),
293    ...advisorRows(section.advisorText),
294  ]
295  return body.length === 0 ? [] : [{ kind: 'heading', text: HEADING.cost }, ...body, { kind: 'blank' }]
296}
297
298const CRITERIA_NOTE = `軽作業 = ツール ${LIGHT_MAX_TOOL_CALLS} 回以下・編集なし・出力 ${formatInt(LIGHT_MAX_OUTPUT_TOKENS)} tokens 以下 / 重い = ツール ${HEAVY_TOOL_CALLS} 回以上・長時間・エラー`
299/** 実コストが取れているときだけ、判定基準の末尾に付ける更新の案内。取れないときはコスト行の「再取得」の案内に任せる。 */
300const REFRESH_SUFFIX = '。更新は /model-review'
301
302const isStarted = (draft: LoopDraft): boolean => draft.stepCount > 0 || draft.toolCount > 0
303
304/** 完了前のターン(ループごと)の途中経過。まだ何も起きていないものは出さない。 */
305function liveRows(drafts: Drafts): PaneRow[] {
306  const started = Object.values(drafts).filter(isStarted)
307  if (started.length === 0) return []
308  return [
309    ...started.map((draft): PaneRow => ({
310      kind: 'kv',
311      label: '実行中',
312      value: `${draft.agentId === null ? 'メイン' : 'サブエージェント'} ${shortModel(draft.model ?? '-')} · 応答 ${draft.stepCount} 回 · ツール ${draft.toolCount} 回 · 推定 ${formatUsd(draft.hasUnpricedStep ? null : draft.pricedCostUsd)}`,
313      tone: 'suggestion',
314    })),
315    { kind: 'blank' },
316  ]
317}
318
319/** 狭幅で省くのは高コストターンといま切り替えたら。所見・モデル × effort・コストは幅によらず出す。 */
320function sectionRows(section: Section, layout: Layout, nowMs: number | undefined, rate: RateView | null): PaneRow[] {
321  switch (section.kind) {
322    case 'concerns':
323      return concernSectionRows(section)
324    case 'groups':
325      return groupSectionRows(section, layout)
326    case 'topTurns':
327      return layout.narrow ? [] : topTurnRows(section, nowMs)
328    case 'loops':
329      return loopRows(section)
330    case 'whatIf':
331      return layout.narrow ? [] : whatIfRows(section)
332    case 'cost':
333      return costSectionRows(section, rate)
334  }
335}
336
337/**
338 * 信頼度の節(見出し・切替などの注記・畳み込み・免責)。所見の警告は所見の中に出すので、ここにはバッジを置かない。
339 * 狭幅は switch 以外の注記と畳み込みの注記を省く(switch は結論の「注意」の件数に数えるので残す)。免責は残す。
340 */
341function reliabilityRows(analysis: ReviewAnalysis, narrow: boolean): PaneRow[] {
342  const notes = narrow ? analysis.trustNotes.filter(note => note.kind === 'switch') : analysis.trustNotes
343  return [
344    { kind: 'heading', text: HEADING.reliability },
345    ...notes.map((note): PaneRow => ({ kind: 'note', text: note.text })),
346    ...(narrow || analysis.archiveNote === null ? [] : [{ kind: 'note', text: analysis.archiveNote } satisfies PaneRow]),
347    { kind: 'note', text: paneAlwaysNote(analysis.advisorText !== null) },
348    ...(narrow ? [{ kind: 'note', text: NARROW_OMITTED_NOTE } satisfies PaneRow] : []),
349  ]
350}
351
352/**
353 * 最下段の用語と判定基準。信頼度の後に空行を挟み、用語は判定基準の直前に置く。狭幅は用語を省く。
354 * 実コストがあるときは判定基準の末尾に更新の案内を付ける。
355 */
356function closingRows(analysis: ReviewAnalysis, narrow: boolean): PaneRow[] {
357  const criteria = analysis.diff === null ? CRITERIA_NOTE : `${CRITERIA_NOTE}${REFRESH_SUFFIX}`
358  return [{ kind: 'blank' }, ...(narrow ? [] : glossaryRows(shownTerms(analysis))), { kind: 'note', text: criteria }]
359}
360
361/**
362 * `columns` はペイン本文の桁数(bodyColumns)。バー幅と行の省略を決める。省略時は広い扱い(最大幅・全行)。
363 * 桁数の正規化はここで 1 回だけ行い、バー幅と区分の両方に同じ値を渡す。
364 * `muted` は設定で止めている指摘の種類(結論・指摘の節から外す)。
365 * 節の順序と出し分けは sections.ts、集計は analysis.ts(同じ記録なら前回の結果を使う)。
366 */
367export function buildPaneRows(
368  review: ReviewState,
369  drafts: Drafts = {},
370  nowMs?: number,
371  columns?: number,
372  muted?: ReadonlySet<ConcernKind>,
373  rate: RateView | null = null,
374): PaneRow[] {
375  const live = liveRows(drafts)
376  const layout: Layout = { columns: knownColumns(columns), narrow: widthClassOf(columns) === 'narrow' }
377  if (review.turns.length === 0) {
378    const body: PaneRow[] = live.length === 0 ? [{ kind: 'message', text: NO_TURNS_LINE }] : live.slice(0, -1)
379    return [{ kind: 'conclusion', ...NO_RECORDS_CONCLUSION }, ...body]
380  }
381  const analysis = analyzeReview(review, nowMs, muted)
382  return [
383    { kind: 'conclusion', ...analysis.conclusion },
384    { kind: 'blank' },
385    { kind: 'title', turns: analysis.totalTurns, subagents: analysis.subagents },
386    moneyRow(analysis, rate !== null),
387    { kind: 'blank' },
388    ...live,
389    ...buildSections(analysis).flatMap(section => sectionRows(section, layout, nowMs, rate)),
390    ...reliabilityRows(analysis, layout.narrow),
391    ...closingRows(analysis, layout.narrow),
392  ]
393}
394
hooks/report.ts 209 lines
1// テキストレポート(/model-review text・copy)の行を組み立てる純粋関数。
2// 集計は analysis.ts、節の順序と出し分けは sections.ts(ペインと共有)、文面の部品は summary.ts。ここはテキストだけの並びと書式を持つ。
3import type { ArchivedGroup, ReviewState, TurnRecord } from '../types'
4import { analyzeReview, type ReviewAnalysis } from './analysis'
5import { BREAKDOWN_LABEL } from './breakdown'
6import { GROWTH_LABEL } from './growth'
7import type { RateView } from './pace'
8import { formatInt, formatUsd, formatUsdRange } from './format'
9import { ALWAYS_NOTE, type FindingNote } from './notes'
10import { PRICE_TABLE_FETCHED_AT } from './pricing'
11import { CONCERN_TEXT, FINDING_LABEL, HEADING, NO_CONCERNS_TEXT, PAST_CONCERNS_HEADING } from './labels'
12import { NO_RECORDS_CONCLUSION } from './conclusion'
13import { WHATIF_NOTE } from './whatif'
14import { HEAVY_TOOL_CALLS, LIGHT_MAX_OUTPUT_TOKENS, LIGHT_MAX_TOOL_CALLS, mainTurnsAfter, type Concern, type ConcernKind } from './analyze'
15import {
16  buildSections,
17  type ConcernsSection,
18  type CostSection,
19  type LoopsSection,
20  type Section,
21  type TopTurnsSection,
22  type WhatIfSection,
23} from './sections'
24import {
25  ACTUAL_COST_UNAVAILABLE_TEXT,
26  NO_TURNS_LINE,
27  allUnpricedText,
28  concernDetailText,
29  groupFacts,
30  moneyLineFrom,
31  signedUsdText,
32  toolDetailText,
33  turnOriginLabel,
34  unpricedExclusionText,
35} from './summary'
36import { hasSeq, turnRefText } from './turnref'
37
38export { formatInt, formatUsd } from './format'
39export { NO_TURNS_LINE } from './summary'
40
41function groupLine(group: ArchivedGroup): string {
42  const facts = groupFacts(group)
43  return [
44    `${group.model}  effort ${facts.effort}`,
45    `ターン ${group.turns}`,
46    ...(facts.hit === null ? [] : [facts.hit]),
47    `入力 ${facts.input}`,
48    `出力 ${facts.output}`,
49    `キャッシュ読 ${facts.cacheRead}`,
50    `書 ${facts.cacheWrite}`,
51    `推定 ${facts.costText}`,
52  ].join('  ')
53}
54
55function rateLines(rate: RateView | null): string[] {
56  return rate === null ? [] : [...rate.rows.map(row => `使用率 ${row.label}: ${row.text}`), `  ${rate.note}`]
57}
58
59function costLines(section: CostSection, isSubscription: boolean): string[] {
60  const totalLabel = isSubscription ? '推定(API 換算・参考)' : '推定'
61  const { estimate, breakdown, growth, diff } = section
62  const estimateLine = estimate.allUnpriced
63    ? `${totalLabel}: ${allUnpricedText(section.totalTurns)}`
64    : `${totalLabel}: ${formatUsdRange(estimate.lowUsd, estimate.highUsd)}${estimate.unpricedTurns > 0 ? unpricedExclusionText(estimate.unpricedTurns) : ''}`
65  const breakdownLines =
66    breakdown === null ? [] : [`${BREAKDOWN_LABEL}: ${breakdown.items}`, ...(breakdown.hint === null ? [] : [`  → ${breakdown.hint}`]), `  ${breakdown.note}`]
67  const growthLines =
68    growth === null
69      ? []
70      : [
71          `${GROWTH_LABEL}: ${growth.trend}`,
72          ...(growth.compact === null ? [] : [`  compact の前後: ${growth.compact}`]),
73          ...(growth.hint === null ? [] : [`  → ${growth.hint}`]),
74          `  ${growth.note}`,
75        ]
76  if (diff === null) {
77    return [estimateLine, ...breakdownLines, ...growthLines, `セッション${ACTUAL_COST_UNAVAILABLE_TEXT.replace(' ', ': ')}`]
78  }
79  return [
80    estimateLine,
81    ...breakdownLines,
82    ...growthLines,
83    `実(${isSubscription ? 'API 換算・請求額ではない・' : ''}読み込み後): ${formatUsd(diff.actualUsd)}`,
84    `差(実 − 推定): ${signedUsdText(diff.diffUsd)}(${diffDirection(diff.diffUsd)}推定は単価表の値。ターン外の要求は含まない)`,
85  ]
86}
87
88/** 差の向き。括弧を重ねないよう、後ろの説明と同じ括弧の中に入れる文の頭として返す。差が 0 なら空文字。 */
89const diffDirection = (diffUsd: number): string => (diffUsd > 0 ? '実が大きい。' : diffUsd < 0 ? '推定が大きい。' : '')
90
91/** 指摘 1 件の行。過去の指摘には「次の一手」を付けない(いま直す対象ではないため)。 */
92function oneConcernLines(concern: Concern, next: string | null): string[] {
93  return [
94    `  【${CONCERN_TEXT[concern.kind].label}】 ${concernDetailText(concern)}`,
95    ...concern.examples.map(example => `    ・${example}`),
96    ...(next === null ? [] : [`    → ${next}`]),
97  ]
98}
99
100/** 所見の中の警告 1 行(指摘の【過剰】と同じ形)。 */
101const findingLine = (note: FindingNote): string => `  【${FINDING_LABEL[note.kind]}】 ${note.text}`
102
103/**
104 * 直近の指摘を先に、所見の警告(再構築・TTL 乖離)を指摘の後に、窓より前にだけ該当した指摘は小見出しの下に分けて並べる。
105 * 止めている種類は最後に 1 行だけ。
106 */
107function concernLines(section: ConcernsSection): string[] {
108  const { recent, findings, past, nextSteps, numericNote, mutedLine } = section
109  return [
110    `■ ${HEADING.concerns} · ヒューリスティック`,
111    ...(recent.length === 0 ? [`  ${NO_CONCERNS_TEXT}`] : recent.flatMap(concern => oneConcernLines(concern, nextSteps.get(concern) ?? null))),
112    ...findings.map(findingLine),
113    ...(past.length === 0 ? [] : [`  ${PAST_CONCERNS_HEADING}`, ...past.flatMap(concern => oneConcernLines(concern, null))]),
114    ...(numericNote === null ? [] : [`  ${numericNote}`]),
115    ...(mutedLine === null ? [] : [`  ${mutedLine}`]),
116    '',
117  ]
118}
119
120/** 通し番号のある記録は「#37(12 分前)」、古い記録は従来どおり「ターン <turnId>(種別)」。 */
121const reportTurnRef = (record: TurnRecord, records: readonly TurnRecord[], nowMs?: number): string =>
122  !hasSeq(record)
123    ? `${turnRefText(record, 0)}(${turnOriginLabel(record)})`
124    : turnRefText(record, mainTurnsAfter(records, record), nowMs)
125
126function topTurnLines(section: TopTurnsSection, nowMs?: number): string[] {
127  return [
128    `■ ${HEADING.topTurns}`,
129    ...section.turns.map(
130      record => `  ${formatUsd(record.costUsd)}  ${reportTurnRef(record, section.records, nowMs)}  ${record.model}  ${toolDetailText(record)}`,
131    ),
132    '',
133  ]
134}
135
136function loopLines(section: LoopsSection): string[] {
137  const { view } = section
138  return [
139    `■ ${HEADING.loops}`,
140    ...view.rows.map(row => `  ${row.label}  ${row.detail}`),
141    ...(view.subagentNote === null ? [] : [`  ${view.subagentNote}`]),
142    '',
143  ]
144}
145
146const whatIfLines = (section: WhatIfSection): string[] => [`■ ${HEADING.whatIf}`, ...section.options.map(text => `  ${text}`), `  ${WHATIF_NOTE}`, '']
147
148/** コストの節。見出しの後に、推定・内訳・推移・実コスト・使用率・advisor を並べ、節の終わりに空行を置く(次は信頼度)。 */
149function costSectionLines(section: CostSection, rate: RateView | null): string[] {
150  return [
151    `■ ${HEADING.cost}`,
152    ...costLines(section, rate !== null),
153    ...rateLines(rate),
154    ...(section.advisorText === null ? [] : [`advisor ${section.advisorText}`]),
155    '',
156  ]
157}
158
159function sectionLines(section: Section, nowMs: number | undefined, rate: RateView | null): string[] {
160  switch (section.kind) {
161    case 'concerns':
162      return concernLines(section)
163    case 'groups':
164      return [`■ ${HEADING.groups}`, ...section.groups.map(groupLine), '']
165    case 'topTurns':
166      return topTurnLines(section, nowMs)
167    case 'loops':
168      return loopLines(section)
169    case 'whatIf':
170      return whatIfLines(section)
171    case 'cost':
172      return costSectionLines(section, rate)
173  }
174}
175
176const CRITERIA_LINES = [
177  `判定基準(参考): 軽作業 = ツール ${LIGHT_MAX_TOOL_CALLS} 回以下・編集系なし・出力 ${formatInt(LIGHT_MAX_OUTPUT_TOKENS)} tokens 以下。重い = ツール ${HEAVY_TOOL_CALLS} 回以上、または長時間・エラー。`,
178  `単価は pricing.ts の表(platform.claude.com の価格表、${PRICE_TABLE_FETCHED_AT} 取得)。Haiku 5.5 はプロンプト 10 万 tokens 超の応答で単価が上がるため、応答ごとに判定している。`,
179]
180
181/** 末尾の信頼度(切替などの注記・畳み込み・免責)と判定基準。コストの節の後に、空行を挟んで続く。 */
182const footerLines = (analysis: ReviewAnalysis): string[] => [
183  `■ ${HEADING.reliability}`,
184  ...analysis.trustNotes.map(note => note.text),
185  ...(analysis.archiveNote === null ? [] : [analysis.archiveNote]),
186  ALWAYS_NOTE,
187  '',
188  ...CRITERIA_LINES,
189]
190
191/**
192 * テキストレポートの行。先頭はペインと同じ結論の 1 行。記録がなければ結論と案内の 2 行だけを返す。
193 * `muted` は設定で止めている指摘の種類(結論・指摘の節から外す)。
194 * 節の順序と出し分けは sections.ts、集計は analysis.ts で、ペインと同じものを使う。
195 */
196export function buildReportLines(review: ReviewState, nowMs?: number, muted?: ReadonlySet<ConcernKind>, rate: RateView | null = null): string[] {
197  if (review.turns.length === 0) return [NO_RECORDS_CONCLUSION.text, NO_TURNS_LINE]
198  const analysis = analyzeReview(review, nowMs, muted)
199  return [
200    analysis.conclusion.text,
201    moneyLineFrom(analysis.estimate, analysis.diff, rate !== null),
202    '',
203    `対象: ${analysis.totalTurns} ターン(サブエージェント ${analysis.subagents} 件)。Mod 読み込み前のターンは含みません。`,
204    '',
205    ...buildSections(analysis).flatMap(section => sectionLines(section, nowMs, rate)),
206    ...footerLines(analysis),
207  ]
208}
209
hooks/copy.ts 32 lines
1// `/model-review [copy|text|help]` の引数判定と応答文。`$` に触れない純粋関数。
2export type CommandMode = 'open' | 'copy' | 'text' | 'help' | 'unknown'
3
4const NAMED_MODES: ReadonlyMap<string, CommandMode> = new Map([
5  ['copy', 'copy'],
6  ['text', 'text'],
7  ['help', 'help'],
8])
9
10/** 前後の空白と大文字小文字は無視する。引数なしはペイン、知らない引数は unknown(ペインは開かない)。 */
11export function parseCommandMode(args: string): CommandMode {
12  const arg = args.trim().toLowerCase()
13  if (arg === '') return 'open'
14  return NAMED_MODES.get(arg) ?? 'unknown'
15}
16
17/** 型の `argumentHint`(コマンド名の後ろに薄く出る)。 */
18export const ARGUMENT_HINT = '[copy|text|help]'
19
20export const HELP_TEXT = [
21  '/model-review の使い方',
22  '  (引数なし) ペイン「モデル振り返り」を開く(置けない画面ではテキストで返す)',
23  '  copy         テキストレポートをクリップボードにコピーする',
24  '  text         ペインを開かず、テキストレポートをそのまま返す',
25  '  help         この一覧を出す',
26].join('\n')
27
28export const UNKNOWN_ARG_TEXT = '不明な引数です。/model-review help を参照してください。'
29
30export const COPIED_TEXT = 'テキストレポートをクリップボードにコピーしました。'
31export const copyFailedText = (reason: string): string => `コピーできませんでした: ${reason}`
32
hooks/glance.ts 96 lines
1// status 行の常時表示と、上限超過トーストの判定。純粋関数($ に触れない)。
2import { formatUsd } from './format'
3
4export type RateWindow = { readonly kind: string; readonly percentUsed: number }
5
6export type Glance = {
7  /** 累計の実コスト(USD)。取れない環境では undefined。 */
8  readonly costUsd?: number
9  readonly rateLimits: readonly RateWindow[]
10}
11
12/** 利用者が設定した上限。null は無効。既定はどちらも無効。 */
13export type Limits = { readonly costUsd: number | null; readonly ratePercent: number | null }
14
15const RATE_LABELS: Readonly<Record<string, string>> = { five_hour: '5h', seven_day: '7d', spend_limit: '上限枠' }
16const UNITS_TO_REDRAW: readonly string[] = ['cost', 'rateLimits']
17
18/** 設定値を上限にする。正の有限な数だけ有効で、0・負・NaN・数以外は無効(null)。 */
19export function readLimits(options: Readonly<Record<string, unknown>>): Limits {
20  const positive = (value: unknown): number | null =>
21    typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : null
22  return { costUsd: positive(options.costLimitUsd), ratePercent: positive(options.rateLimitPercent) }
23}
24
25/** 設定で表示を切れる。省略時は表示する。 */
26export function readShowStatus(options: Readonly<Record<string, unknown>>): boolean {
27  return options.showStatus !== false
28}
29
30/** コストか使用率が動いた測定だけ描き直す。context だけの変化では描き直さない。 */
31export function needsRedraw(changed: readonly string[]): boolean {
32  return changed.some(unit => UNITS_TO_REDRAW.includes(unit))
33}
34
35export const rateLabel = (kind: string): string => RATE_LABELS[kind] ?? kind
36export const formatPercent = (percent: number): string => `${Number.isInteger(percent) ? percent : percent.toFixed(1)}%`
37
38// status 行は短く。コストは 2 桁(レポートの 4 桁表示より粗くてよい)。
39const formatCostShort = (usd: number): string => `$${usd.toFixed(2)}`
40
41/**
42 * 使用率が取れる環境(サブスク)か。サブスクの累計コストは API 単価での換算で、請求額ではない。
43 * 常に目に入る status 行・トーストで「実コスト」と書くと請求額に読めるため、語を分ける。
44 */
45const isSubscription = (glance: Glance): boolean => glance.rateLimits.length > 0
46
47/**
48 * status 行の 1 行。コストも使用率も無ければ undefined(行を消す)。
49 * 使用率が空(サブスク外・初回前)のときはコストだけを出す。`hints` は枠の種類ごとの短い印(消費ペース)。
50 */
51export function formatStatus(glance: Glance, hints: ReadonlyMap<string, string> = new Map()): string | undefined {
52  const parts: string[] = []
53  if (glance.costUsd !== undefined && Number.isFinite(glance.costUsd)) {
54    parts.push(`${isSubscription(glance) ? 'API換算' : '実コスト'} ${formatCostShort(glance.costUsd)}`)
55  }
56  for (const window of glance.rateLimits) {
57    if (Number.isFinite(window.percentUsed)) parts.push(`${rateLabel(window.kind)} ${formatPercent(window.percentUsed)}${hints.has(window.kind) ? `(${hints.get(window.kind)})` : ''}`)
58  }
59  return parts.length === 0 ? undefined : parts.join(' · ')
60}
61
62export type AlertResult = {
63  /** 今回新しく知らせるトースト文。 */
64  readonly alerts: readonly string[]
65  /** 次回に渡す「通知済みの上限」。超過が解けたもの(枠のリセットなど)は外れ、次に超えたとき再び知らせる。 */
66  readonly notified: ReadonlySet<string>
67}
68
69/** 上限を超えた項目のうち、まだ知らせていないものだけを返す。同じ上限は超過が続く限り 1 度だけ。 */
70export function evaluateAlerts(glance: Glance, limits: Limits, notified: ReadonlySet<string>): AlertResult {
71  const exceeded = new Map<string, string>()
72  if (limits.costUsd !== null && glance.costUsd !== undefined && glance.costUsd >= limits.costUsd) {
73    exceeded.set(
74      'cost',
75      isSubscription(glance)
76        ? `API 換算コストが上限 ${formatUsd(limits.costUsd)} に達しました(現在 ${formatCostShort(glance.costUsd)}・請求額ではありません)`
77        : `実コストが上限 ${formatUsd(limits.costUsd)} に達しました(現在 ${formatCostShort(glance.costUsd)})`,
78    )
79  }
80  if (limits.ratePercent !== null) {
81    for (const window of glance.rateLimits) {
82      if (window.percentUsed >= limits.ratePercent) {
83        exceeded.set(
84          `rate:${window.kind}`,
85          `${rateLabel(window.kind)} の使用率が上限 ${formatPercent(limits.ratePercent)} に達しました(現在 ${formatPercent(window.percentUsed)})`,
86        )
87      }
88    }
89  }
90  const alerts = [...exceeded].filter(([key]) => !notified.has(key)).map(([, text]) => text)
91  // コストが取れない測定では判断できないので、知らせ済みの印を保つ(戻ったときの再通知を防ぐ)。
92  const kept = new Set(exceeded.keys())
93  if (glance.costUsd === undefined && notified.has('cost')) kept.add('cost')
94  return { alerts, notified: kept }
95}
96
hooks/mute.ts 59 lines
1// 利用者が意図して選んだ設定の指摘を、種類ごとに止める(設定 mutedConcerns)。$ に触れない純粋関数。
2// 止めた種類は結論行と指摘の節から外し、「止めている指摘」の 1 行だけを残す(何も見えなくはしない)。
3import { isRecentConcern, type Concern, type ConcernKind } from './analyze'
4import { CONCERN_TEXT, countText } from './labels'
5
6const KINDS = Object.keys(CONCERN_TEXT) as ConcernKind[]
7
8/** 設定に書ける名前(ConcernKind の英名と、画面の短い名前)から種類へ。 */
9const KIND_BY_NAME: ReadonlyMap<string, ConcernKind> = new Map(
10  KINDS.flatMap(kind => [[kind, kind] as const, [CONCERN_TEXT[kind].label, kind] as const]),
11)
12
13/** 名前の区切り: カンマ(半角・全角)・読点・空白。 */
14const NAME_SEPARATOR = /[,,、\s]+/
15
16/** 全角英字・半角カナも同じ名前として読む(NFKC)。大文字小文字は無視する。 */
17const normalizeName = (name: string): string => name.normalize('NFKC').trim().toLowerCase()
18
19/** 設定 mutedConcerns を読む。文字列以外・空・知らない名前は無視する。 */
20export function readMutedConcerns(options: Readonly<Record<string, unknown>>): ReadonlySet<ConcernKind> {
21  const value = options.mutedConcerns
22  if (typeof value !== 'string') return new Set()
23  return new Set(value.split(NAME_SEPARATOR).flatMap(name => KIND_BY_NAME.get(normalizeName(name)) ?? []))
24}
25
26/** 止めた種類とそれ以外に分ける(順序は保つ)。 */
27export function splitMuted(
28  concerns: readonly Concern[],
29  muted: ReadonlySet<ConcernKind>,
30): { readonly shown: readonly Concern[]; readonly hidden: readonly Concern[] } {
31  return {
32    shown: concerns.filter(concern => !muted.has(concern.kind)),
33    hidden: concerns.filter(concern => muted.has(concern.kind)),
34  }
35}
36
37/** 止めている種類 1 つ分。該当があれば件数(指摘の節と同じ表記)を添え、窓より前にだけ該当したものは「過去」と書く。 */
38function mutedPart(kind: ConcernKind, hit: Concern | undefined): string {
39  const label = CONCERN_TEXT[kind].label
40  if (hit === undefined) return label
41  return `${label} ${countText(hit)}${isRecentConcern(hit) ? '' : '(過去)'}`
42}
43
44/** 指摘の節に残す 1 行。止めている種類を画面の順(CONCERN_TEXT の順)に並べる。何も止めていなければ null。 */
45export function mutedLineText(muted: ReadonlySet<ConcernKind>, hidden: readonly Concern[]): string | null {
46  if (muted.size === 0) return null
47  const parts = KINDS.filter(kind => muted.has(kind)).map(kind => mutedPart(kind, hidden.find(concern => concern.kind === kind)))
48  return `止めている指摘(設定 mutedConcerns): ${parts.join(' / ')}`
49}
50
51/** ペインとテキストレポートが同じ扱いにするための入口。表示する指摘と、止めている 1 行を返す。 */
52export function applyMute(
53  concerns: readonly Concern[],
54  muted: ReadonlySet<ConcernKind>,
55): { readonly concerns: readonly Concern[]; readonly mutedLine: string | null } {
56  const { shown, hidden } = splitMuted(concerns, muted)
57  return { concerns: shown, mutedLine: mutedLineText(muted, hidden) }
58}
59
hooks/pace.ts 158 lines
1// サブスクの使用率(5h / 7d など)の消費ペースと、リセットまでの見込み。$ に触れない純粋関数。
2// 上限への到達は断定せず、直近の測定の増え方から出した「目安」として示す。
3import { formatPercent, rateLabel, type RateWindow } from './glance'
4
5/** ペースを求めるのに使う、直近の測定の窓(ms)。これより古い測定は捨てる(仮置き)。 */
6export const PACE_WINDOW_MS = 15 * 60_000
7/** ペースを出すのに要る、最初と最後の測定の間隔(ms)。短いと 1 回の増分に左右される(仮置き)。 */
8export const PACE_MIN_SPAN_MS = 2 * 60_000
9/** リセット時刻がこれ以上ずれたら、別の枠(リセットをまたいだ)とみなす。同じ枠でも報告が数秒揺れることがあるため(仮置き)。 */
10export const RESET_CHANGE_TOLERANCE_MS = 5 * 60_000
11/** 1 つの枠で覚える測定の最大数。 */
12export const PACE_MAX_POINTS = 60
13
14export type RateWindowInput = RateWindow & { readonly resetsAt?: string }
15
16type Point = { readonly atMs: number; readonly percent: number }
17
18export type WindowSamples = {
19  readonly points: readonly Point[]
20  /** リセット時刻(ms)。`resetsAt` が無い・読めないときは null。 */
21  readonly resetsAtMs: number | null
22}
23
24/** 枠の種類ごとの直近の測定。 */
25export type RateSamples = Readonly<Record<string, WindowSamples>>
26
27const resetsAtMsOf = (resetsAt: string | undefined): number | null => {
28  const parsed = resetsAt === undefined ? Number.NaN : Date.parse(resetsAt)
29  return Number.isFinite(parsed) ? parsed : null
30}
31
32/**
33 * 測定を足す。リセットをまたいだ(使用率が下がった、またはリセット時刻が替わった)枠は、それまでの測定を捨てる。
34 * 今回の測定に無い枠は前の測定のまま残す(一部の枠だけの報告でも履歴を消さない)。有限でない使用率は無視する。
35 */
36export function addRateSamples(samples: RateSamples, limits: readonly RateWindowInput[], nowMs: number): RateSamples {
37  const updated = Object.fromEntries(
38    limits
39      .filter(limit => Number.isFinite(limit.percentUsed))
40      .map((limit): [string, WindowSamples] => {
41        const prev = samples[limit.kind]
42        const resetsAtMs = resetsAtMsOf(limit.resetsAt)
43        const last = prev?.points[prev.points.length - 1]
44        const crossedReset =
45          last !== undefined && (limit.percentUsed < last.percent || (resetsAtMs !== null && prev?.resetsAtMs != null && Math.abs(resetsAtMs - prev.resetsAtMs) >= RESET_CHANGE_TOLERANCE_MS))
46        const kept = prev === undefined || crossedReset ? [] : prev.points.filter(point => point.atMs >= nowMs - PACE_WINDOW_MS)
47        return [limit.kind, { points: [...kept, { atMs: nowMs, percent: limit.percentUsed }].slice(-PACE_MAX_POINTS), resetsAtMs }]
48      }),
49  )
50  return { ...samples, ...updated }
51}
52
53export type WindowPace = {
54  readonly kind: string
55  readonly percent: number
56  /** リセットまでの時間(ms)。分からなければ null。 */
57  readonly resetInMs: number | null
58  /** このペースで上限に届くまでの時間(ms)。測定が足りない・消費が増えていないときは null。 */
59  readonly etaMs: number | null
60}
61
62function paceOf(kind: string, window: WindowSamples, nowMs: number): WindowPace | null {
63  const first = window.points[0]
64  const last = window.points[window.points.length - 1]
65  if (first === undefined || last === undefined) return null
66  const resetInMs = window.resetsAtMs === null ? null : Math.max(0, window.resetsAtMs - nowMs)
67  // 最後の測定から増えていない時間も含めて、いまのペースとする(増えた直後の値だけで楽観・悲観しない)。
68  const span = Math.max(nowMs, last.atMs) - first.atMs
69  const delta = last.percent - first.percent
70  // 最後の測定が古いときは、いまの消費ペースとは言えない。
71  const hasPace = span >= PACE_MIN_SPAN_MS && delta > 0 && nowMs - last.atMs <= PACE_WINDOW_MS
72  const etaMs = !hasPace ? null : last.percent >= 100 ? 0 : ((100 - last.percent) / delta) * span
73  return { kind, percent: last.percent, resetInMs, etaMs }
74}
75
76/** 枠ごとのペース。測定のない枠と、リセット時刻を過ぎた枠(次の報告まで古い値のため)は含まない。 */
77export function ratePaces(samples: RateSamples, nowMs: number): readonly WindowPace[] {
78  return Object.entries(samples).flatMap(([kind, window]) => {
79    if (window.resetsAtMs !== null && window.resetsAtMs < nowMs) return []
80    const pace = paceOf(kind, window, nowMs)
81    return pace === null ? [] : [pace]
82  })
83}
84
85const MS_PER_MINUTE = 60_000
86const MINUTES_PER_HOUR = 60
87
88/** 「40 分」「1 時間 10 分」。1 分未満は「1 分未満」。 */
89export function formatSpan(ms: number): string {
90  const minutes = Math.round(ms / MS_PER_MINUTE)
91  if (minutes < 1) return '1 分未満'
92  if (minutes < MINUTES_PER_HOUR) return `${minutes} 分`
93  const hours = Math.floor(minutes / MINUTES_PER_HOUR)
94  const rest = minutes % MINUTES_PER_HOUR
95  return rest === 0 ? `${hours} 時間` : `${hours} 時間 ${rest} 分`
96}
97
98/** リセットより前に上限へ届く見込みか。届く見込みなら true(リセット時刻が不明なら、ペースがあれば true)。 */
99const reachesBeforeReset = (pace: WindowPace): boolean =>
100  pace.etaMs !== null && (pace.resetInMs === null || pace.etaMs < pace.resetInMs)
101
102/** 「72% · このペースだと約 40 分で上限(目安) · リセットまで 1 時間 10 分」。枠のラベルは含まない。 */
103export function paceText(pace: WindowPace): string {
104  const parts = [formatPercent(pace.percent)]
105  if (pace.percent >= 100) {
106    parts.push('上限に達しています')
107  } else if (pace.etaMs !== null) {
108    parts.push(
109      reachesBeforeReset(pace)
110        ? `このペースだと約 ${formatSpan(pace.etaMs)}で上限(目安)`
111        : 'このペースならリセットまでは持つ見込み(目安)',
112    )
113  }
114  if (pace.resetInMs !== null) parts.push(`リセットまで ${formatSpan(pace.resetInMs)}`)
115  return parts.join(' · ')
116}
117
118const HINT_PREFIX = '上限まで'
119
120/** 「5h 72% · このペースだと約 40 分で上限(目安) · リセットまで 1 時間 10 分」。 */
121export const paceLine = (pace: WindowPace): string => `${rateLabel(pace.kind)} ${paceText(pace)}`
122
123/** status 行用の短い印。上限に届く見込みのときだけ「上限まで40分」「上限まで1時間10分」(矢印だけでは意味が読めないため語で書く)。 */
124export function paceHint(pace: WindowPace): string | undefined {
125  if (pace.etaMs === null || pace.percent >= 100 || !reachesBeforeReset(pace)) return undefined
126  const minutes = Math.max(1, Math.round(pace.etaMs / MS_PER_MINUTE))
127  if (minutes < MINUTES_PER_HOUR) return `${HINT_PREFIX}${minutes}分`
128  const rest = minutes % MINUTES_PER_HOUR
129  return `${HINT_PREFIX}${Math.floor(minutes / MINUTES_PER_HOUR)}時間${rest === 0 ? '' : `${rest}分`}`
130}
131
132/** status 行に添える印(枠の種類 → 印)。 */
133export function paceHints(samples: RateSamples, nowMs: number): ReadonlyMap<string, string> {
134  return new Map(ratePaces(samples, nowMs).flatMap((pace): [string, string][] => {
135    const hint = paceHint(pace)
136    return hint === undefined ? [] : [[pace.kind, hint]]
137  }))
138}
139
140export const SUBSCRIPTION_COST_NOTE =
141  '金額は API 換算の参考値で、請求額ではありません。サブスクの枠は上の使用率で見てください(ペースは直近の測定からの目安で、上限への到達を断定しません)'
142
143export type RateView = {
144  /** 枠ごとの 1 行(ラベルと本文)。 */
145  readonly rows: readonly { readonly label: string; readonly text: string }[]
146  readonly note: string
147}
148
149/** ペイン・レポート用。枠の測定がなければ(サブスク外)null で、表示は今のまま。 */
150export function rateView(samples: RateSamples, nowMs: number): RateView | null {
151  const paces = ratePaces(samples, nowMs)
152  if (paces.length === 0) return null
153  return {
154    rows: paces.map(pace => ({ label: rateLabel(pace.kind), text: paceText(pace) })),
155    note: SUBSCRIPTION_COST_NOTE,
156  }
157}
158
hooks/switchnotice.ts 33 lines
1// モデル切替の直前トースト。$ に触れない純粋関数。切替は止めず、知らせるだけ。
2import { formatInt } from './format'
3
4export type PreSwitch = {
5  readonly fromModel: string
6  readonly toModel: string
7  readonly contextTokens: number
8  readonly isCacheWarm: boolean
9  readonly estimatedCacheWriteUsd: number
10  readonly pricing: 'configured' | 'catalog' | 'default'
11}
12
13/** 設定で切れる。省略時は知らせる。 */
14export function readNotifyOnSwitch(options: Readonly<Record<string, unknown>>): boolean {
15  return options.notifyOnSwitch !== false
16}
17
18/** 入力が数として使えるか。使えない見積りは出さない。 */
19const isUsable = (value: number): boolean => Number.isFinite(value) && value >= 0
20
21/**
22 * トースト文。キャッシュが温かくない(捨てるものがない)・同じモデルへの切替・見積りが使えないときは undefined。
23 * 見積りは engine の値で、単価が既定の仮定のときはそう添える。
24 * 毎回出るトーストなので、「温かいキャッシュ」などの用語や「切替は止めません」の断りは書かず、かかる額を先に短く書く。
25 */
26export function formatSwitchNotice(input: PreSwitch): string | undefined {
27  if (!input.isCacheWarm || input.fromModel === input.toModel) return undefined
28  if (!isUsable(input.contextTokens) || !isUsable(input.estimatedCacheWriteUsd)) return undefined
29  const usd = `約 $${input.estimatedCacheWriteUsd.toFixed(2)}`
30  const assumed = input.pricing === 'default' ? '・単価は仮定' : ''
31  return `${input.fromModel} → ${input.toModel}: キャッシュを作り直すため${usd} かかる見込み(${formatInt(Math.round(input.contextTokens))} tokens${assumed})`
32}
33
hooks/agenttype.ts 42 lines
1// サブエージェントの種類(agent.spawn の subagentType)を agentId に対応づける純粋な reducer。$ に触れない。
2// 記録するのは種類の名前だけ。description・prompt は受け取らない。
3export const UNKNOWN_AGENT_TYPE = '種類不明'
4const MAX_TYPE_LENGTH = 64
5/** 覚えておく agentId の上限。超えたら古い順に捨てる(捨てた分は $.agent.list() で補える)。 */
6export const MAX_AGENT_TYPES = 256
7
8export type AgentTypes = Readonly<Record<string, string>>
9
10export type ListedAgent = { readonly id: string; readonly type: string }
11
12/** 種類の名前として使えるのは、制御文字を含まない 1〜64 文字の文字列だけ。それ以外は null(推測しない)。 */
13export function sanitizeAgentType(raw: unknown): string | null {
14  if (typeof raw !== 'string') return null
15  const text = raw.trim()
16  // eslint-disable-next-line no-control-regex
17  return text.length === 0 || text.length > MAX_TYPE_LENGTH || /[\u0000-\u001f\u007f]/.test(text) ? null : text
18}
19
20/** spawn の結果を対応表に足す。agentId か種類が使えなければ表を変えない。 */
21export function recordSpawn(types: AgentTypes, agentId: unknown, subagentType: unknown): AgentTypes {
22  const type = sanitizeAgentType(subagentType)
23  if (typeof agentId !== 'string' || agentId === '' || type === null) return types
24  const { [agentId]: _previous, ...rest } = types
25  const entries = Object.entries(rest)
26  // 追加順を保つので、先頭が最も古い。上限を超えるぶんだけ先頭から捨てる。
27  const kept = entries.length >= MAX_AGENT_TYPES ? entries.slice(entries.length - MAX_AGENT_TYPES + 1) : entries
28  return { ...Object.fromEntries(kept), [agentId]: type }
29}
30
31/**
32 * agentId の種類を引く。spawn で覚えた表を先に見て、なければ $.agent.list() の結果で補う
33 * (reload で表が消えた後に途中から拾う場合)。どちらにもなければ null。
34 */
35export function resolveAgentType(types: AgentTypes, agentId: string | undefined, listed: readonly ListedAgent[] = []): string | null {
36  if (agentId === undefined) return null
37  const known = types[agentId]
38  if (known !== undefined) return known
39  const found = listed.find(agent => agent.id === agentId)
40  return found === undefined ? null : sanitizeAgentType(found.type)
41}
42