@laoyuehanni/dsh-token-usage 0.4.14 → 0.4.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/README.md +2 -2
  2. package/README.zh.md +2 -2
  3. package/docs/DETAIL.md +18 -0
  4. package/docs/DETAIL.zh.md +18 -0
  5. package/lib/aux-request.d.ts +18 -13
  6. package/lib/aux-request.d.ts.map +1 -1
  7. package/lib/aux-request.js +32 -19
  8. package/lib/aux-request.js.map +1 -1
  9. package/lib/backup.d.ts +32 -0
  10. package/lib/backup.d.ts.map +1 -0
  11. package/lib/backup.js +114 -0
  12. package/lib/backup.js.map +1 -0
  13. package/lib/client/CostPill.d.ts +3 -4
  14. package/lib/client/CostPill.d.ts.map +1 -1
  15. package/lib/client/CostPill.js +50 -37
  16. package/lib/client/CostPill.js.map +1 -1
  17. package/lib/client/DashboardCards.d.ts +4 -2
  18. package/lib/client/DashboardCards.d.ts.map +1 -1
  19. package/lib/client/DashboardCards.js +2 -2
  20. package/lib/client/DashboardCards.js.map +1 -1
  21. package/lib/client/OverheadRows.d.ts +17 -12
  22. package/lib/client/OverheadRows.d.ts.map +1 -1
  23. package/lib/client/OverheadRows.js +32 -20
  24. package/lib/client/OverheadRows.js.map +1 -1
  25. package/lib/client/OverviewBoard.js +3 -3
  26. package/lib/client/OverviewBoard.js.map +1 -1
  27. package/lib/client/TokenUsageCard.d.ts.map +1 -1
  28. package/lib/client/TokenUsageCard.js +6 -0
  29. package/lib/client/TokenUsageCard.js.map +1 -1
  30. package/lib/client/TokenUsageSection.d.ts.map +1 -1
  31. package/lib/client/TokenUsageSection.js +11 -9
  32. package/lib/client/TokenUsageSection.js.map +1 -1
  33. package/lib/client/UsageRows.js +2 -2
  34. package/lib/client/UsageRows.js.map +1 -1
  35. package/lib/client/UsageView.d.ts +7 -6
  36. package/lib/client/UsageView.d.ts.map +1 -1
  37. package/lib/client/UsageView.js +100 -51
  38. package/lib/client/UsageView.js.map +1 -1
  39. package/lib/client/async-resource.d.ts +5 -2
  40. package/lib/client/async-resource.d.ts.map +1 -1
  41. package/lib/client/async-resource.js +14 -6
  42. package/lib/client/async-resource.js.map +1 -1
  43. package/lib/client/cost-inflate-motion.d.ts +0 -4
  44. package/lib/client/cost-inflate-motion.d.ts.map +1 -1
  45. package/lib/client/cost-inflate-motion.js +0 -19
  46. package/lib/client/cost-inflate-motion.js.map +1 -1
  47. package/lib/client/cost-inflate.d.ts +4 -6
  48. package/lib/client/cost-inflate.d.ts.map +1 -1
  49. package/lib/client/cost-inflate.js +3 -5
  50. package/lib/client/cost-inflate.js.map +1 -1
  51. package/lib/client/format.d.ts +11 -0
  52. package/lib/client/format.d.ts.map +1 -1
  53. package/lib/client/format.js +32 -3
  54. package/lib/client/format.js.map +1 -1
  55. package/lib/client/index.d.ts.map +1 -1
  56. package/lib/client/index.js.map +1 -1
  57. package/lib/client/locales.d.ts +25 -1
  58. package/lib/client/locales.d.ts.map +1 -1
  59. package/lib/client/locales.js +50 -2
  60. package/lib/client/locales.js.map +1 -1
  61. package/lib/client/project-rows.d.ts +3 -2
  62. package/lib/client/project-rows.d.ts.map +1 -1
  63. package/lib/client/project-rows.js +3 -2
  64. package/lib/client/project-rows.js.map +1 -1
  65. package/lib/client/session-stats.d.ts +52 -10
  66. package/lib/client/session-stats.d.ts.map +1 -1
  67. package/lib/client/session-stats.js +88 -11
  68. package/lib/client/session-stats.js.map +1 -1
  69. package/lib/client/use-cost-inflate.d.ts +5 -15
  70. package/lib/client/use-cost-inflate.d.ts.map +1 -1
  71. package/lib/client/use-cost-inflate.js +11 -51
  72. package/lib/client/use-cost-inflate.js.map +1 -1
  73. package/lib/client.js +517 -319
  74. package/lib/client.js.map +1 -1
  75. package/lib/field-completion.d.ts.map +1 -1
  76. package/lib/field-completion.js +4 -1
  77. package/lib/field-completion.js.map +1 -1
  78. package/lib/index.d.ts +4 -4
  79. package/lib/index.d.ts.map +1 -1
  80. package/lib/index.js +134 -22
  81. package/lib/index.js.map +1 -1
  82. package/lib/migrate.d.ts +7 -1
  83. package/lib/migrate.d.ts.map +1 -1
  84. package/lib/migrate.js +116 -9
  85. package/lib/migrate.js.map +1 -1
  86. package/lib/project-rows.d.ts +20 -4
  87. package/lib/project-rows.d.ts.map +1 -1
  88. package/lib/project-rows.js +33 -8
  89. package/lib/project-rows.js.map +1 -1
  90. package/lib/request-observe.d.ts +7 -5
  91. package/lib/request-observe.d.ts.map +1 -1
  92. package/lib/request-observe.js +19 -16
  93. package/lib/request-observe.js.map +1 -1
  94. package/lib/rollup.d.ts +6 -1
  95. package/lib/rollup.d.ts.map +1 -1
  96. package/lib/rollup.js +15 -1
  97. package/lib/rollup.js.map +1 -1
  98. package/lib/session-request-details.d.ts.map +1 -1
  99. package/lib/session-request-details.js +5 -1
  100. package/lib/session-request-details.js.map +1 -1
  101. package/lib/stats-route.d.ts.map +1 -1
  102. package/lib/stats-route.js +65 -8
  103. package/lib/stats-route.js.map +1 -1
  104. package/lib/stats.d.ts +42 -1
  105. package/lib/stats.d.ts.map +1 -1
  106. package/lib/stats.js +240 -16
  107. package/lib/stats.js.map +1 -1
  108. package/lib/sync.d.ts +32 -0
  109. package/lib/sync.d.ts.map +1 -1
  110. package/lib/sync.js +286 -30
  111. package/lib/sync.js.map +1 -1
  112. package/lib/usage-log.d.ts +14 -9
  113. package/lib/usage-log.d.ts.map +1 -1
  114. package/lib/usage-log.js +190 -144
  115. package/lib/usage-log.js.map +1 -1
  116. package/lib/usage-record.d.ts +150 -27
  117. package/lib/usage-record.d.ts.map +1 -1
  118. package/lib/usage-record.js +221 -34
  119. package/lib/usage-record.js.map +1 -1
  120. package/lib/web-call.d.ts +55 -0
  121. package/lib/web-call.d.ts.map +1 -0
  122. package/lib/web-call.js +222 -0
  123. package/lib/web-call.js.map +1 -0
  124. package/lib/wire.d.ts +122 -11
  125. package/lib/wire.d.ts.map +1 -1
  126. package/lib/wire.js +40 -7
  127. package/lib/wire.js.map +1 -1
  128. package/locale/en.json +5 -1
  129. package/locale/zh.json +2 -1
  130. package/package.json +3 -3
  131. package/lib/client/CostDeltaFlyLabel.d.ts +0 -8
  132. package/lib/client/CostDeltaFlyLabel.d.ts.map +0 -1
  133. package/lib/client/CostDeltaFlyLabel.js +0 -24
  134. package/lib/client/CostDeltaFlyLabel.js.map +0 -1
package/README.md CHANGED
@@ -23,8 +23,8 @@ Repo: <https://github.com/LaoYueHanNi/dsh-token-usage>
23
23
 
24
24
  ## Features
25
25
 
26
- - **Live recording**: every provider-billed model call is recorded as it happens — tokens, cost, model, session — conversation requests, context-compaction calls, and auxiliary system calls included: the Auto review authorization reviewer, session-title generation, and reasoning translation. Auxiliary calls bill into the totals and the model breakdown. The ones the host proves belong to a session (session-title generation) also join that session's totals, trend and request pool, tagged with their kind; the rest stay global and are broken out by kind in the **Runtime overhead** board. That history cannot be backfilled — the host keeps no usage record of those calls, and recording starts with the first request after upgrading.
27
- - **Web stats page**: filters (date range + model + `1d`/`7d`/`30d` shortcuts), eight compact summary cards in two rows, and a trend chart (hourly for one day, daily for wider ranges; hover a point for its total). The request card carries **failed** and **overhead** pills. The detail block is a five-tab switcher — **projects / models / sessions / providers / runtime overhead** — sharing the dashboard's row layout: project rows aggregate every matching root session before the session list is capped; directory-tail grouping intentionally merges folders with the same final segment. Rows sort by total tokens or cost (sessions also by last activity), and **Ctrl+click** on a listed session row opens that conversation (the host restores its last-selected view tab). The runtime-overhead tab breaks auxiliary calls down by kind; the by-provider tab lists each provider's usage by its route key — see the next entry, **Provider usage dimension**.
26
+ - **Live recording**: every provider-billed model call is recorded as it happens — tokens, cost, model, session — conversation requests, context-compaction calls, and auxiliary system calls included: the Auto review authorization reviewer, session-title generation, timeline report synthesis, and reasoning translation. **Web tools** are recorded separately per `web_search` and `web_fetch` tool call: invocation count, query count, duration, and failure state; when the host reports tokens for a search's model turn they bill into the totals and cost; when it does not, the runtime-overhead row shows only the call counts, never a per-search price. Auxiliary calls bill into the totals and the model breakdown. The ones the host proves belong to a session (such as session-title generation, Auto review, and session-scoped timeline reports on supporting hosts) also join that session's totals, trend and request pool, tagged with their kind; the rest stay global and are broken out by kind in the **Runtime overhead** board. That history cannot be backfilled — the host keeps no usage record of those calls, and recording starts with the first request after upgrading.
27
+ - **Web stats page**: filters (date range + model + `1d`/`7d`/`30d` shortcuts), eight compact summary cards in two rows, and a trend chart (hourly for one day, daily for wider ranges; hover a point for its total). The request card carries **failed** and **overhead** pills. The detail block is a five-tab switcher — **projects / models / sessions / providers / runtime overhead** — sharing the dashboard's row layout: project rows aggregate every matching root session before the session list is capped; directory-tail grouping intentionally merges folders with the same final segment. Rows sort by total tokens or cost (sessions also by last activity), and **Ctrl+click** on a listed session row opens that conversation (the host restores its last-selected view tab). The runtime-overhead tab breaks auxiliary calls down by kind and lists a collapsible web-tools row beside them (breaking down web search and web fetch calls); the by-provider tab lists each provider's usage by its route key — see the next entry, **Provider usage dimension**.
28
28
 
29
29
  ![Token Usage settings page](docs/images/settings-usage.png)
30
30
 
package/README.zh.md CHANGED
@@ -23,8 +23,8 @@
23
23
 
24
24
  ## 功能
25
25
 
26
- - **实时记录**:每一次 provider 计费调用发生即记录——token、费用、模型、会话;主对话请求、上下文压缩调用与系统辅助调用(自动审查、会话标题生成、推理翻译)都计入。辅助调用计入总量和按模型明细;其中宿主能证明归属到某个会话的(会话标题生成)额外计入该会话的总量、趋势与请求池,并在模型旁标出类别;其余保持全局口径,在**运行开销**看板按类别单独拆出。这部分历史无法回补——宿主不保存这些调用的用量记录,升级后的第一个请求才开始记录。
27
- - **Web 统计页**:过滤条(日期区间 + 模型下拉 + `1d`/`7d`/`30d` 快捷区间)、固定两行的八张紧凑汇总卡片和趋势图(单日按小时、更宽区间按日,悬停查看点位总量)。请求数卡片带「失败」与「开销」两个徽章。明细区是五页签切换——**按项目 / 按模型 / 按会话 / 按供应商 / 运行开销**——与大屏共用同一套行布局:项目行在会话列表截断前聚合全部匹配的顶层会话;目录尾段相同的工作区会合并。各行可按总 token 或费用排序(会话另支持最近活跃),**Ctrl+点击**可打开宿主列表中的会话(宿主恢复该会话上次选择的页签);运行开销页签按类别列出辅助调用的次数、费用与 token;供应商页签按路由键逐个列出供应商用量,详见下一条「按供应商统计维度」。
26
+ - **实时记录**:每一次 provider 计费调用发生即记录——token、费用、模型、会话;主对话请求、上下文压缩调用与系统辅助调用(自动审查、会话标题生成、时间线报告、推理翻译)都计入。**联网工具**单独记录每次 `web_search`(联网搜索)与 `web_fetch`(网页抓取)调用:调用次数、查询条数、耗时与失败状态;宿主若在搜索的模型轮次里报告了 token,就并入总 token 与费用;未报告时运行开销只显示调用次数,不显示费用、也不按次估价。辅助调用计入总量和按模型明细;其中宿主能证明归属到某个会话的(如标题生成,以及支持版本的自动审查与会话级时间线报告)额外计入该会话的总量、趋势与请求池,并在模型旁标出类别;其余保持全局口径,在**运行开销**看板按类别单独拆出。这部分历史无法回补——宿主不保存这些调用的用量记录,升级后的第一个请求才开始记录。
27
+ - **Web 统计页**:过滤条(日期区间 + 模型下拉 + `1d`/`7d`/`30d` 快捷区间)、固定两行的八张紧凑汇总卡片和趋势图(单日按小时、更宽区间按日,悬停查看点位总量)。请求数卡片带「失败」与「开销」两个徽章。明细区是五页签切换——**按项目 / 按模型 / 按会话 / 按供应商 / 运行开销**——与大屏共用同一套行布局:项目行在会话列表截断前聚合全部匹配的顶层会话;目录尾段相同的工作区会合并。各行可按总 token 或费用排序(会话另支持最近活跃),**Ctrl+点击**可打开宿主列表中的会话(宿主恢复该会话上次选择的页签);运行开销页签按类别列出辅助调用的次数、费用与 token,并单列可折叠的联网工具行(展开查看联网搜索与网页抓取各自的调用次数);供应商页签按路由键逐个列出供应商用量,详见下一条「按供应商统计维度」。
28
28
 
29
29
  ![设置内的 Token 用量页](docs/images/settings-usage_zh.png)
30
30
 
package/docs/DETAIL.md ADDED
@@ -0,0 +1,18 @@
1
+ Every provider-billed call is recorded as it happens — tokens, cost, model, session — and you can read it back from the sidebar's **Token Usage** entry, from **Settings → Token Usage**, or from the **Usage** tab inside a conversation.
2
+
3
+ ## What you can do
4
+
5
+ - **Read the totals**: the dashboard shows summary cards with cost, a trend chart (hourly for a single day, daily for wider ranges; hover a point for its total), and a five-tab detail block — **projects / models / sessions / providers / runtime overhead**. The date range and model filters are shared, with `1d` / `7d` / `30d` shortcuts; the request card carries **failed** and **overhead** pills.
6
+ - **Cut the usage your way**: rows sort by total tokens or cost (sessions also by last activity), project rows aggregate every matching root session, the runtime-overhead tab breaks auxiliary system calls (title generation, automatic review, timeline reports, reasoning translation) down by kind and lists a collapsible web-tools row (web search / web fetch calls) separately, and the by-provider tab lists each provider route key with cache hit rate and billed cost — each entry remembering its own sort choice.
7
+ - **Follow one conversation**: the conversation pane's **Usage** tab adds the current session's cards, four-bucket token strip, trend chart and per-model table; switch **Session / With subagents** to include child sessions, drill into each one and back, and hover the failure pill for a per-class breakdown. **Latest request** and **Live requests** also show waiting, streaming, failed and cancelled requests while they run, one row per provider attempt.
8
+ - **Know what it costs**: cost is computed per request from per-model rates; click a priced model name for its full price table, or Ctrl+click it to filter the dashboard to that model. The **Pricing table** entry at the end of the filter row opens every model in the cloud feed, and **Model alias associations** beside its title manages the local alias→model links.
9
+ - **Watch provider quota**: the button left of the model chip in the input bar shows the selected provider's remaining quota — plan windows, account balance or remaining credits, and every upstream account behind a Magpie gateway.
10
+ - **Make it fit**: the **configuration card** on the host's **Plugins** page sets the data directory (a saved absolute path migrates history immediately), the **Pricing region** dropdown (Gitee / GitHub mirror, which also picks ¥ or $), and **Pin to sidebar**, which moves the entry out of the **More** menu into a resident sidebar row.
11
+
12
+ ## Some limits
13
+
14
+ - An unpriced model is billed at ¥0 and flagged; pricing comes only from the cloud mirror synced at startup, so a hand-edited `pricing.json` is no longer read. Costs are reselected from history when rates or rules change.
15
+ - History from before installation is backfilled on the first startup (idempotent); unreadable session logs are skipped and counted. Auxiliary calls cannot be backfilled — the host keeps no usage record of them, so recording starts with the first request after upgrading. Web-tool (`web_search` / `web_fetch`) call records can be backfilled from session logs (`tool/call` + `tool/result` are persisted; an existing data directory needs one manual full sync from the settings page), while tokens are counted only when the host reports that turn's usage.
16
+ - Usage with no route key is never folded into a named provider: it stays a single dimmed **Missing provider** row (deleted session logs, history older than the route-key field, and runtime overhead such as title generation carry none).
17
+ - Saving a new data directory is refused while a conversation is running — wait for it to end. Removing the plugin leaves the data files under `~/.dsh/token-usage/`; delete them yourself if you no longer need them.
18
+ - Unsupported providers hide the quota button (Volcengine, ZenMux, Zhipu Team plan, Claude / Codex / Gemini / Grok subscriptions, GitHub Copilot).
@@ -0,0 +1,18 @@
1
+ 每一次 provider 计费调用发生即记录——token、费用、模型、会话;这些数据能在三处读回:侧栏「Token 用量」大屏、设置 → Token 用量,以及对话面板的「用量」页签。
2
+
3
+ ## 你可以这样用
4
+
5
+ - **看总量**:大屏上是带费用的汇总卡片、趋势图(单日按小时、更宽区间按日,悬停看点位总量)与五页签明细区——**按项目 / 按模型 / 按会话 / 按供应商 / 运行开销**。日期区间与模型筛选两处共用,另有 `1d` / `7d` / `30d` 快捷区间;请求数卡片带「失败」与「开销」两个徽章。
6
+ - **按你关心的维度切开**:各行可按总 token 或费用排序(会话另支持最近活跃),项目行在截断前聚合全部匹配的顶层会话,运行开销页签按类别拆出标题生成、自动审查、时间线报告、推理翻译等辅助调用,并单列可折叠的联网工具(联网搜索 / 网页抓取)调用次数,供应商页签按路由键列出各自的缓存命中率与已计费用——两个入口各自记住自己的排序选择。
7
+ - **盯住单个会话**:对话面板的「用量」页签给出当前会话的数值卡、四项 token 明细条、趋势图与按模型表;「本会话 / 含子会话」一键切换范围,子会话表逐行钻取并可逐级返回,悬停失败胶囊看按类别明细。「最新请求」与「实时请求」还会在等待、生成、失败、取消时即时呈现,每次 provider 尝试各占一行。
8
+ - **看懂花了多少**:费用按模型单价逐条计算;点击有定价的模型名弹出完整价格表,按住 Ctrl 点击可只看该模型。过滤条行尾的「定价表」入口浏览云端定价的全部模型,其标题旁的「模型别名关联」管理本地的「模型别名 → 模型」关联。
9
+ - **盯住供应商配额**:输入栏模型选择器左侧的按钮跟随当前供应商展示套餐余量——套餐窗口、账户余额或剩余额度,Magpie 网关后面的每个上游账号都列出来。
10
+ - **调成顺手的样子**:宿主**插件页**里本插件的**配置卡**可改数据目录(保存绝对路径立即迁移历史)、「定价区域」下拉(Gitee / GitHub 镜像,同时决定 ¥ 或 $),以及**「常驻侧边栏」**——开启后入口移出「更多」菜单、成为左侧栏固定一行。
11
+
12
+ ## 一些边界
13
+
14
+ - 未定价模型按 ¥0 计费并高亮提示;定价只来自启动时同步的云端镜像,手工编辑的 `pricing.json` 升级后不再读取。费率或规则变化后,费用从历史记录重新计算。
15
+ - 安装前的历史在首次启动自动补齐(幂等);无法解析的会话日志跳过并计数。辅助调用无法回补——宿主不保存这些调用的用量记录,升级后的第一个请求才开始记录。联网工具(`web_search` / `web_fetch`)的调用记录可从会话日志回补(`tool/call` + `tool/result` 已持久化;已有数据目录需在设置页手动全量同步一次),token 只在宿主报告该轮用量时才计入。
16
+ - 没有路由键的用量不并入任何命名供应商,而是单列成弱化的「缺失供应商」余量行(会话日志已删除、路由键字段加入之前的历史、标题生成等运行开销天然没有路由键)。
17
+ - 对话进行中保存新的数据目录会被拒绝,等对话结束再保存。移除插件后数据文件仍留在 `~/.dsh/token-usage/`,不需要时请自行删除。
18
+ - 不支持的供应商不显示配额按钮(火山方舟、ZenMux、智谱团队版、Claude / Codex / Gemini / Grok 官方订阅、GitHub Copilot)。
@@ -2,19 +2,20 @@
2
2
  * Auxiliary (bypass) model requests of the token-usage plugin: classification
3
3
  * and record projection for provider calls that are NOT part of a
4
4
  * conversation turn — the Auto review authorization gate, session-title
5
- * generation, and reasoning translation. Those calls are issued through
6
- * `ctx.llm.stream()` by their owning host packages and do not produce an
7
- * `assistant/message` usage event, so the plugin records them on the
8
- * `llm/stream` waterfall every streaming call passes through
9
- * (see `LlmRuntime.stream`).
5
+ * generation, timeline report synthesis, and reasoning translation. Those
6
+ * calls are issued through `ctx.llm.stream()` by their owning host packages
7
+ * and do not produce an `assistant/message` usage event, so the plugin
8
+ * records them on the `llm/stream` waterfall every streaming call passes
9
+ * through (see `LlmRuntime.stream`).
10
10
  *
11
11
  * Classification never relies on host exports that older DSH builds may not
12
- * ship: the conversation loop always carries a `sessionId`, compaction and
13
- * title requests carry their `purpose`, and the two remaining bypass callers
14
- * (Auto review, translator) are recognized by their fixed system prompts.
15
- * Anything else lands in the defensive `other` bucket rather than being
16
- * dropped, so a future host feature still shows up in the runtime-overhead
17
- * totals.
12
+ * ship: declared purposes (`LlmRequestPurposeMap`) take precedence
13
+ * (`compaction` is excluded because `compaction/summary` logs it;
14
+ * `session-title`, `auto-review`, and `timeline-report` map directly, and
15
+ * any unrecognized `purpose` falls into `other` even when carrying a
16
+ * `sessionId`), while older unmarked Auto review and translator calls fall
17
+ * back to their fixed system prompt prefixes. Ordinary conversation-loop
18
+ * requests carry a `sessionId` with `purpose === undefined`.
18
19
  *
19
20
  * @module token-usage/aux-request
20
21
  */
@@ -47,8 +48,9 @@ export interface AuxRequestRecordInput {
47
48
  requestId: string;
48
49
  /** Stream-start wall time, epoch milliseconds. */
49
50
  time: number;
50
- /** Owning conversation when the host stamped one (currently title
51
- * generation; older unowned bypass calls stay empty). */
51
+ /** Owning session when the host stamped one (session-title, auto-review,
52
+ * and session-scoped timeline-report calls; older or global bypass calls
53
+ * stay empty). */
52
54
  sessionId?: string;
53
55
  /** Provider model id the bypass call routed to. */
54
56
  model: string;
@@ -62,6 +64,9 @@ export interface AuxRequestRecordInput {
62
64
  * Historical auxiliary rows cannot be backfilled: they never landed in
63
65
  * the session log. */
64
66
  provider?: string;
67
+ /** Optional provider-neutral `LlmFailure.code` when a refused bypass call
68
+ * (such as `CONTENT_REFUSED`) still emitted billed usage. */
69
+ failureCode?: string;
65
70
  }
66
71
  /**
67
72
  * Build the log row for one settled auxiliary model request. The row carries
@@ -1 +1 @@
1
- {"version":3,"file":"aux-request.d.ts","sourceRoot":"","sources":["../src/aux-request.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAA;AACvE,OAAO,EAAgB,KAAK,OAAO,EAAE,KAAK,WAAW,EAAE,MAAM,mBAAmB,CAAA;AAEhF;;;;GAIG;AACH,eAAO,MAAM,yBAAyB,kBAAkB,CAAA;AAExD;;;GAGG;AACH,eAAO,MAAM,yBAAyB,iCAAiC,CAAA;AAEvE;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,GAAG,SAAS,CAkBhF;AAED,yEAAyE;AACzE,MAAM,WAAW,qBAAqB;IACpC,0CAA0C;IAC1C,OAAO,EAAE,OAAO,CAAA;IAChB,yEAAyE;IACzE,SAAS,EAAE,MAAM,CAAA;IACjB,kDAAkD;IAClD,IAAI,EAAE,MAAM,CAAA;IACZ;6DACyD;IACzD,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,mDAAmD;IACnD,KAAK,EAAE,MAAM,CAAA;IACb;;+DAE2D;IAC3D,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,wEAAwE;IACxE,KAAK,CAAC,EAAE,UAAU,CAAA;IAClB;;0BAEsB;IACtB,QAAQ,CAAC,EAAE,MAAM,CAAA;CAClB;AAED;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,qBAAqB,GAAG,WAAW,CAa9E"}
1
+ {"version":3,"file":"aux-request.d.ts","sourceRoot":"","sources":["../src/aux-request.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAA;AACvE,OAAO,EAAgB,KAAK,OAAO,EAAE,KAAK,WAAW,EAAE,MAAM,mBAAmB,CAAA;AAEhF;;;;GAIG;AACH,eAAO,MAAM,yBAAyB,kBAAkB,CAAA;AAExD;;;GAGG;AACH,eAAO,MAAM,yBAAyB,iCAAiC,CAAA;AAEvE;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,GAAG,SAAS,CA0BhF;AAED,yEAAyE;AACzE,MAAM,WAAW,qBAAqB;IACpC,0CAA0C;IAC1C,OAAO,EAAE,OAAO,CAAA;IAChB,yEAAyE;IACzE,SAAS,EAAE,MAAM,CAAA;IACjB,kDAAkD;IAClD,IAAI,EAAE,MAAM,CAAA;IACZ;;sBAEkB;IAClB,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,mDAAmD;IACnD,KAAK,EAAE,MAAM,CAAA;IACb;;+DAE2D;IAC3D,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,wEAAwE;IACxE,KAAK,CAAC,EAAE,UAAU,CAAA;IAClB;;0BAEsB;IACtB,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB;iEAC6D;IAC7D,WAAW,CAAC,EAAE,MAAM,CAAA;CACrB;AAED;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,qBAAqB,GAAG,WAAW,CAc9E"}
@@ -2,19 +2,20 @@
2
2
  * Auxiliary (bypass) model requests of the token-usage plugin: classification
3
3
  * and record projection for provider calls that are NOT part of a
4
4
  * conversation turn — the Auto review authorization gate, session-title
5
- * generation, and reasoning translation. Those calls are issued through
6
- * `ctx.llm.stream()` by their owning host packages and do not produce an
7
- * `assistant/message` usage event, so the plugin records them on the
8
- * `llm/stream` waterfall every streaming call passes through
9
- * (see `LlmRuntime.stream`).
5
+ * generation, timeline report synthesis, and reasoning translation. Those
6
+ * calls are issued through `ctx.llm.stream()` by their owning host packages
7
+ * and do not produce an `assistant/message` usage event, so the plugin
8
+ * records them on the `llm/stream` waterfall every streaming call passes
9
+ * through (see `LlmRuntime.stream`).
10
10
  *
11
11
  * Classification never relies on host exports that older DSH builds may not
12
- * ship: the conversation loop always carries a `sessionId`, compaction and
13
- * title requests carry their `purpose`, and the two remaining bypass callers
14
- * (Auto review, translator) are recognized by their fixed system prompts.
15
- * Anything else lands in the defensive `other` bucket rather than being
16
- * dropped, so a future host feature still shows up in the runtime-overhead
17
- * totals.
12
+ * ship: declared purposes (`LlmRequestPurposeMap`) take precedence
13
+ * (`compaction` is excluded because `compaction/summary` logs it;
14
+ * `session-title`, `auto-review`, and `timeline-report` map directly, and
15
+ * any unrecognized `purpose` falls into `other` even when carrying a
16
+ * `sessionId`), while older unmarked Auto review and translator calls fall
17
+ * back to their fixed system prompt prefixes. Ordinary conversation-loop
18
+ * requests carry a `sessionId` with `purpose === undefined`.
18
19
  *
19
20
  * @module token-usage/aux-request
20
21
  */
@@ -38,21 +39,32 @@ export const TRANSLATION_PROMPT_PREFIX = 'Translate the following text';
38
39
  * (which logs its own `compaction/summary` event carrying usage).
39
40
  */
40
41
  export function classifyAuxRequest(options) {
42
+ // Widen from the imported DSH version's `purpose` union so keys declared by
43
+ // newer/optional producer packages (LlmRequestPurposeMap) typecheck cleanly
44
+ // without casts across host versions.
45
+ const purpose = options.purpose;
41
46
  // Compaction summaries are already recorded from `compaction/summary`.
42
- if (options.purpose === 'compaction')
47
+ if (purpose === 'compaction')
43
48
  return undefined;
44
- // Title generation is a bypass call, but its purpose marker is explicit.
45
- if (options.purpose === 'session-title')
49
+ if (purpose === 'session-title')
46
50
  return 'session-title';
47
- // Newer Auto-review hosts may stamp the owning session while older hosts
48
- // still omit it. The fixed policy remains authoritative in either shape.
51
+ if (purpose === 'auto-review')
52
+ return 'auto-review';
53
+ if (purpose === 'timeline-report')
54
+ return 'timeline-report';
55
+ // Ordinary conversation requests never set `purpose`; any unrecognized
56
+ // purpose value belongs to a host auxiliary producer and should land in
57
+ // `other` rather than be dropped as a conversation request.
58
+ if (purpose !== undefined)
59
+ return 'other';
60
+ // Legacy Auto-review hosts omitted `purpose` (and sometimes `sessionId`);
61
+ // the fixed policy prompt remains authoritative fallback.
49
62
  const system = options.system;
50
63
  if (typeof system === 'string' && system.startsWith(AUTO_REVIEW_PROMPT_PREFIX))
51
64
  return 'auto-review';
52
65
  // Every conversation-loop request is marked with the session it serves
53
- // (dsh-agent-loop freezes `sessionId` into its request); the loop records
54
- // the call through `assistant/message`. A hand-built request without a
55
- // session is the bypass shape.
66
+ // (dsh-agent-loop freezes `sessionId` into its request) and leaves
67
+ // `purpose` absent; the loop records the call through `assistant/message`.
56
68
  if (options.sessionId !== undefined)
57
69
  return undefined;
58
70
  if (typeof system === 'string') {
@@ -80,6 +92,7 @@ export function recordFromAuxRequest(input) {
80
92
  ...(usage !== undefined ? { usage } : {}),
81
93
  kind: 'aux',
82
94
  auxKind: input.auxKind,
95
+ ...(input.failureCode !== undefined && input.failureCode !== '' ? { failureCode: input.failureCode } : {}),
83
96
  ...(input.provider !== undefined && input.provider !== '' ? { provider: input.provider } : {}),
84
97
  };
85
98
  }
@@ -1 +1 @@
1
- {"version":3,"file":"aux-request.js","sourceRoot":"","sources":["../src/aux-request.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAGH,OAAO,EAAE,YAAY,EAAkC,MAAM,mBAAmB,CAAA;AAEhF;;;;GAIG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAG,eAAe,CAAA;AAExD;;;GAGG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAG,8BAA8B,CAAA;AAEvE;;;;;;GAMG;AACH,MAAM,UAAU,kBAAkB,CAAC,OAAwB;IACzD,uEAAuE;IACvE,IAAI,OAAO,CAAC,OAAO,KAAK,YAAY;QAAE,OAAO,SAAS,CAAA;IACtD,yEAAyE;IACzE,IAAI,OAAO,CAAC,OAAO,KAAK,eAAe;QAAE,OAAO,eAAe,CAAA;IAC/D,yEAAyE;IACzE,0EAA0E;IAC1E,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAA;IAC7B,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,CAAC,UAAU,CAAC,yBAAy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AAY,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;IACvC,OAAO;QACL,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,IAAI,EAAE,KAAK,CAAC,IAAI;QAChB,SAAS,EAAE,KAAK,CAAC,SAAS,IAAI,EAAE;QAChC,KAAK,EAAE,KAAK,CAAC,KAAK;QAClB,GAAG,CAAC,KAAK,CAAC,aAAa,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,KAAK,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACpF,GAAG,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACzC,IAAI,EAAE,KAAK;QACX,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,GAAG,CAAC,KAAK,CAAC,WAAW,KAAK,SAAS,IAAI,KAAK,CAAC,WAAW,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,KAAK,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC1G,GAAG,CAAC,KAAK,CAAC,QAAQ,KAAK,SAAS,IAAI,KAAK,CAAC,QAAQ,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAC/F,CAAA;AACH,CAAC"}
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Automatic rolling backups before rewriting existing usage day files.
3
+ *
4
+ * Every batch maintenance pass that removes, refiles, or mutates rows in
5
+ * existing `usage-YYYY-MM-DD.jsonl` files copies the touched source files into
6
+ * `<dataDir>/.backups/<timestamp>-<reason>/` before touching the originals.
7
+ * Zero-change runs create no directory, a failed copy aborts the rewrite, and
8
+ * older snapshots beyond the newest five are pruned automatically.
9
+ *
10
+ * @module token-usage/backup
11
+ */
12
+ import { type LoggerLike } from './log.ts';
13
+ /** Subdirectory under `<dataDir>` holding pre-rewrite snapshots. */
14
+ export declare const BACKUPS_DIR = ".backups";
15
+ /** Maximum number of rolling backup snapshots retained per data directory. */
16
+ export declare const MAX_BACKUP_COUNT = 5;
17
+ /** Maintenance operations that back up touched day files before rewriting. */
18
+ export type BackupReason = 'reconcile' | 'refile' | 'backfill-timing' | 'complete-fields';
19
+ /** Exact snapshot directory name grammar (`YYYYMMDD-HHmmss-SSS-NN-<reason>`). */
20
+ export declare const BACKUP_SNAPSHOT_DIR: RegExp;
21
+ /** Whether a directory entry name matches a plugin-created backup snapshot. */
22
+ export declare function isBackupSnapshotName(name: string): boolean;
23
+ /**
24
+ * Back up every existing day file in `fileNames` before an in-place rewrite.
25
+ * @param dir - data directory containing the day files.
26
+ * @param fileNames - day-file names that the caller is about to modify.
27
+ * @param reason - maintenance pass label stored in the snapshot directory name.
28
+ * @param logger - diagnostic sink for non-fatal pruning warnings.
29
+ * @returns the created snapshot directory path, or `null` when no listed file exists.
30
+ */
31
+ export declare function backupDayFiles(dir: string, fileNames: readonly string[], reason: BackupReason, logger?: LoggerLike): Promise<string | null>;
32
+ //# sourceMappingURL=backup.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"backup.d.ts","sourceRoot":"","sources":["../src/backup.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAIH,OAAO,EAAiB,KAAK,UAAU,EAAE,MAAM,UAAU,CAAA;AAEzD,oEAAoE;AACpE,eAAO,MAAM,WAAW,aAAa,CAAA;AAErC,8EAA8E;AAC9E,eAAO,MAAM,gBAAgB,IAAI,CAAA;AAEjC,8EAA8E;AAC9E,MAAM,MAAM,YAAY,GAAG,WAAW,GAAG,QAAQ,GAAG,iBAAiB,GAAG,iBAAiB,CAAA;AAEzF,iFAAiF;AACjF,eAAO,MAAM,mBAAmB,QAAoF,CAAA;AAEpH,+EAA+E;AAC/E,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAE1D;AAsCD;;;;;;;GAOG;AACH,wBAAsB,cAAc,CAClC,GAAG,EAAE,MAAM,EACX,SAAS,EAAE,SAAS,MAAM,EAAE,EAC5B,MAAM,EAAE,YAAY,EACpB,MAAM,GAAE,UAA0B,GACjC,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CA4CxB"}
package/lib/backup.js ADDED
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Automatic rolling backups before rewriting existing usage day files.
3
+ *
4
+ * Every batch maintenance pass that removes, refiles, or mutates rows in
5
+ * existing `usage-YYYY-MM-DD.jsonl` files copies the touched source files into
6
+ * `<dataDir>/.backups/<timestamp>-<reason>/` before touching the originals.
7
+ * Zero-change runs create no directory, a failed copy aborts the rewrite, and
8
+ * older snapshots beyond the newest five are pruned automatically.
9
+ *
10
+ * @module token-usage/backup
11
+ */
12
+ import { access, copyFile, mkdir, readdir, rm } from 'node:fs/promises';
13
+ import { join } from 'node:path';
14
+ import { consoleLogger } from "./log.js";
15
+ /** Subdirectory under `<dataDir>` holding pre-rewrite snapshots. */
16
+ export const BACKUPS_DIR = '.backups';
17
+ /** Maximum number of rolling backup snapshots retained per data directory. */
18
+ export const MAX_BACKUP_COUNT = 5;
19
+ /** Exact snapshot directory name grammar (`YYYYMMDD-HHmmss-SSS-NN-<reason>`). */
20
+ export const BACKUP_SNAPSHOT_DIR = /^\d{8}-\d{6}-\d{3}-\d{2}-(?:reconcile|refile|backfill-timing|complete-fields)$/u;
21
+ /** Whether a directory entry name matches a plugin-created backup snapshot. */
22
+ export function isBackupSnapshotName(name) {
23
+ return BACKUP_SNAPSHOT_DIR.test(name);
24
+ }
25
+ let lastTimestampMs = -1;
26
+ let sameMsCounter = 0;
27
+ /**
28
+ * Format a Windows-safe, lexicographically monotonic snapshot directory name
29
+ * (`YYYYMMDD-HHmmss-SSS-NN-<reason>`). Rapid calls within the same millisecond
30
+ * increment the two-digit tiebreaker (and step the synthetic clock if > 99) so
31
+ * snapshot names never collide and always sort oldest-to-newest.
32
+ */
33
+ function nextSnapshotName(reason) {
34
+ const now = Date.now();
35
+ let effectiveMs;
36
+ if (now > lastTimestampMs) {
37
+ effectiveMs = now;
38
+ sameMsCounter = 0;
39
+ }
40
+ else if (sameMsCounter < 99) {
41
+ effectiveMs = lastTimestampMs;
42
+ sameMsCounter += 1;
43
+ }
44
+ else {
45
+ effectiveMs = lastTimestampMs + 1;
46
+ sameMsCounter = 0;
47
+ }
48
+ lastTimestampMs = effectiveMs;
49
+ const date = new Date(effectiveMs);
50
+ const year = String(date.getFullYear());
51
+ const month = String(date.getMonth() + 1).padStart(2, '0');
52
+ const day = String(date.getDate()).padStart(2, '0');
53
+ const hours = String(date.getHours()).padStart(2, '0');
54
+ const minutes = String(date.getMinutes()).padStart(2, '0');
55
+ const seconds = String(date.getSeconds()).padStart(2, '0');
56
+ const millis = String(date.getMilliseconds()).padStart(3, '0');
57
+ const seq = String(sameMsCounter).padStart(2, '0');
58
+ return `${year}${month}${day}-${hours}${minutes}${seconds}-${millis}-${seq}-${reason}`;
59
+ }
60
+ /**
61
+ * Back up every existing day file in `fileNames` before an in-place rewrite.
62
+ * @param dir - data directory containing the day files.
63
+ * @param fileNames - day-file names that the caller is about to modify.
64
+ * @param reason - maintenance pass label stored in the snapshot directory name.
65
+ * @param logger - diagnostic sink for non-fatal pruning warnings.
66
+ * @returns the created snapshot directory path, or `null` when no listed file exists.
67
+ */
68
+ export async function backupDayFiles(dir, fileNames, reason, logger = consoleLogger) {
69
+ const unique = [...new Set(fileNames)];
70
+ const existing = [];
71
+ for (const name of unique) {
72
+ try {
73
+ await access(join(dir, name));
74
+ existing.push(name);
75
+ }
76
+ catch {
77
+ // Newly created target files have no prior version to back up.
78
+ }
79
+ }
80
+ if (existing.length === 0)
81
+ return null;
82
+ const backupsRoot = join(dir, BACKUPS_DIR);
83
+ const snapshotDir = join(backupsRoot, nextSnapshotName(reason));
84
+ await mkdir(snapshotDir, { recursive: true });
85
+ try {
86
+ for (const name of existing) {
87
+ await copyFile(join(dir, name), join(snapshotDir, name));
88
+ }
89
+ }
90
+ catch (error) {
91
+ // Clean up any partial snapshot so callers aborting the rewrite leave no
92
+ // half-populated backup behind.
93
+ await rm(snapshotDir, { recursive: true, force: true }).catch(() => undefined);
94
+ throw error;
95
+ }
96
+ try {
97
+ const entries = await readdir(backupsRoot, { withFileTypes: true });
98
+ const snapshots = entries
99
+ .filter(entry => entry.isDirectory() && isBackupSnapshotName(entry.name))
100
+ .map(entry => entry.name)
101
+ .sort((left, right) => (left < right ? -1 : left > right ? 1 : 0));
102
+ const excess = snapshots.length - MAX_BACKUP_COUNT;
103
+ if (excess > 0) {
104
+ for (const obsolete of snapshots.slice(0, excess)) {
105
+ await rm(join(backupsRoot, obsolete), { recursive: true, force: true });
106
+ }
107
+ }
108
+ }
109
+ catch (error) {
110
+ logger.warn('[token-usage] failed to prune old backups:', error);
111
+ }
112
+ return snapshotDir;
113
+ }
114
+ //# sourceMappingURL=backup.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"backup.js","sourceRoot":"","sources":["../src/backup.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,kBAAkB,CAAA;AACvE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,OAAO,EAAE,aAAa,EAAmB,MAAM,UAAU,CAAA;AAEzD,oEAAoE;AACpE,MAAM,CAAC,MAAM,WAAW,GAAG,UAAU,CAAA;AAErC,8EAA8E;AAC9E,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,CAAA;AAKjC,iFAAiF;AACjF,MAAM,CAAC,MAAM,mBAAmB,GAAG,iFAAiF,CAAA;AAEpH,+EAA+E;AAC/E,MAAM,UAAU,oBAAoB,CAAC,IAAY;IAC/C,OAAO,mBAAmB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;AACvC,CAAC;AAED,IAAI,eAAe,GAAG,CA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,KAAK,EAAE,IAAI,EAAE,CAAC,CAAA;YACzE,CAAC;QACH,CAAC;IACH,CAAC;IAAC,OAAO,KAAc,EAAE,CAAC;QACxB,MAAM,CAAC,IAAI,CAAC,4CAA4C,EAAE,KAAK,CAAC,CAAA;IAClE,CAAC;IAED,OAAO,WAAW,CAAA;AACpB,CAAC"}
@@ -21,10 +21,9 @@
21
21
  * cadence, inherited whole): `sessionStats` projection churn plus mirror
22
22
  * `updatedAt` is debounced 250 ms into one fetch, a failed FIRST fetch
23
23
  * retries itself on a 3 s cadence, and later failures keep the prior
24
- * figures. When cost rises on a new request the figure plays `costPop`
25
- * and a +Δ label FALLS below the pill (the dock sits under the composer;
26
- * the header chip's upward rise would climb into the message scrollport).
27
- * Reduced-motion users get silent figure updates.
24
+ * figures. When usage grows on a new request the figure plays `costPop` —
25
+ * a scale + colour pop whose amplitude follows that step's token
26
+ * intensity. Reduced-motion users get silent figure updates.
28
27
  *
29
28
  * Visibility contract: a session with no recorded requests renders
30
29
  * nothing; a transient fetch miss keeps the previous render.
@@ -1 +1 @@
1
- {"version":3,"file":"CostPill.d.ts","sourceRoot":"","sources":["../../src/client/CostPill.tsx"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAGH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,OAAO,CAAA;AACtC,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,kCAAkC,CAAA;AAQjF,OAAO,KAAK,EAAkB,YAAY,EAAE,MAAM,YAAY,CAAA;AAmB9D;;yDAEyD;AACzD,eAAO,MAAM,sBAAsB,OAAQ,CAAA;AAM3C;;;yDAGyD;AACzD,MAAM,MAAM,aAAa,GACvB,YAAY,CAAC,4BAA4B,CAAC,GACxC,WAAW,CAAC,aAAa,CAAC,CAAA;AAE9B;;;;GAIG;AACH,MAAM,WAAW,UAAU;IACzB,QAAQ,EAAE,MAAM,CAAA;IAChB,QAAQ,EAAE,MAAM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@@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
22
22
  * cadence, inherited whole): `sessionStats` projection churn plus mirror
23
23
  * `updatedAt` is debounced 250 ms into one fetch, a failed FIRST fetch
24
24
  * retries itself on a 3 s cadence, and later failures keep the prior
25
- * figures. When cost rises on a new request the figure plays `costPop`
26
- * and a +Δ label FALLS below the pill (the dock sits under the composer;
27
- * the header chip's upward rise would climb into the message scrollport).
28
- * Reduced-motion users get silent figure updates.
25
+ * figures. When usage grows on a new request the figure plays `costPop` —
26
+ * a scale + colour pop whose amplitude follows that step's token
27
+ * intensity. Reduced-motion users get silent figure updates.
29
28
  *
30
29
  * Visibility contract: a session with no recorded requests renders
31
30
  * nothing; a transient fetch miss keeps the previous render.
@@ -42,7 +41,6 @@ import { ModelAssociationBadge, PricingAssociationProvider, UnpricedModelTag } f
42
41
  import { usePricingAssociationRefresh } from "./pricing-associations.js";
43
42
  import { buildChildIndex, buildStatsFreshnessKey, subtreeIds } from "./session-stats.js";
44
43
  import { useColorSchemeMirror } from "./use-color-scheme.js";
45
- import { CostDeltaFlyLabel } from "./CostDeltaFlyLabel.js";
46
44
  import { useCostInflate } from "./use-cost-inflate.js";
47
45
  import styles from './CostPill.module.css';
48
46
  /** Refresh debounce: bursts of session-mirror updates (one request's events)
@@ -94,22 +92,46 @@ export function CostPill({ sessionId, useSessions, useProjection, t }) {
94
92
  const scopeIds = useMemo(() => (sessionId === '' ? [] : subtreeIds(byId, sessionId, childIndex)), [byId, sessionId, childIndex]);
95
93
  const hasSubs = scopeIds.length > 1;
96
94
  const liveStats = useProjection('sessionStats');
95
+ // Identity of the id SET: a late mirror delivery changes it, while a real
96
+ // settled request only changes updatedAt / projection fingerprints.
97
+ const scopeIdsKey = scopeIds.join(',');
97
98
  const freshnessKey = buildStatsFreshnessKey(scopeIds, {
98
99
  activeSessionId: sessionId,
99
100
  rows: byId,
100
101
  liveSessionStats: liveStats,
101
102
  });
102
- const requestKey = `${scopeIds.join('\n')}\n\t${freshnessKey}`;
103
- const debouncedKey = useDebouncedValue(requestKey, REFRESH_DEBOUNCE_MS);
104
- const scopeResetKey = scopeIds.join('\n');
105
- const { flies, onSummary } = useCostInflate(scopeResetKey, costRef);
103
+ const debouncedFreshnessKey = useDebouncedValue(freshnessKey, REFRESH_DEBOUNCE_MS, sessionId);
104
+ const scopeResetKey = `${sessionId}:${scopeIds.length}`;
105
+ const { onSummary } = useCostInflate(scopeResetKey, costRef);
106
106
  // The trigger's poll: subtree totals only (`fields=chip`), the lightest
107
107
  // read that feeds cost / tokens / hit rate.
108
+ // A late session-mirror / sessionStats delivery reruns the trigger's
109
+ // effect inside the first debounce window. Coalesce that run: it belongs
110
+ // to the same batch of events as the mount read, not a new settled
111
+ // request. A real pricing-association change is a new intent and refetches.
112
+ const recentRef = useRef(undefined);
108
113
  const [treeRes, retryTree] = useAsyncResource(signal => {
109
- const [idsPart] = debouncedKey.split('\n\t');
110
- const ids = (idsPart ?? '').split('\n').filter(id => id !== '');
111
- return fetchSummary(ids, 'chip', signal);
112
- }, [debouncedKey, associationTick], { silentAfterFirst: true, retryToken: 0 });
114
+ const recent = recentRef.current;
115
+ // Two debounce windows cover a mirror that arrives a little after
116
+ // mount; `coalesced` allows it at most once. Only a changed id SET
117
+ // within the SAME session coalesces — switching sessions, projection /
118
+ // updatedAt churn, and pricing-association changes must refetch.
119
+ const canReuse = recent !== undefined
120
+ && !recent.coalesced
121
+ && recent.sessionId === sessionId
122
+ && recent.scopeIdsKey !== scopeIdsKey
123
+ && recent.associationTick === associationTick
124
+ && Date.now() - recent.at < REFRESH_DEBOUNCE_MS * 2;
125
+ if (canReuse && recent !== undefined) {
126
+ recentRef.current = { ...recent, scopeIdsKey, at: Date.now(), coalesced: true };
127
+ return Promise.resolve(recent.value);
128
+ }
129
+ return fetchSummary(sessionId, 'subtree', 'chip', signal).then(value => {
130
+ if (value !== null)
131
+ recentRef.current = { sessionId, scopeIdsKey, associationTick, at: Date.now(), value, coalesced: false };
132
+ return value;
133
+ });
134
+ }, [debouncedFreshnessKey, associationTick], { silentAfterFirst: true, retryToken: 0, scopeKey: sessionId });
113
135
  const summary = treeRes.status === 'ready' ? treeRes.value : null;
114
136
  useEffect(() => {
115
137
  if (summary !== null)
@@ -126,18 +148,8 @@ export function CostPill({ sessionId, useSessions, useProjection, t }) {
126
148
  // Panel reads, LAZY: nothing flies while the panel is closed. The detail
127
149
  // read (`fields=session`) carries byModel; the solo read splits the fold.
128
150
  // Both re-fire when request churn debounces through while open.
129
- const [detailRes] = useAsyncResource(signal => {
130
- if (!open)
131
- return Promise.resolve(null);
132
- const [idsPart] = debouncedKey.split('\n\t');
133
- const ids = (idsPart ?? '').split('\n').filter(id => id !== '');
134
- return fetchSummary(ids, 'session', signal);
135
- }, [open, debouncedKey, associationTick], { silentAfterFirst: true, retryToken: 0 });
136
- const [selfRes] = useAsyncResource(signal => {
137
- if (!open || sessionId === '')
138
- return Promise.resolve(null);
139
- return fetchSummary([sessionId], 'chip', signal);
140
- }, [open, sessionId, debouncedKey, associationTick], { silentAfterFirst: true, retryToken: 0 });
151
+ const [detailRes] = useAsyncResource(signal => open ? fetchSummary(sessionId, 'subtree', 'session', signal) : Promise.resolve(null), [open, debouncedFreshnessKey, associationTick], { silentAfterFirst: true, retryToken: 0, scopeKey: sessionId });
152
+ const [selfRes] = useAsyncResource(signal => open && sessionId !== '' ? fetchSummary(sessionId, 'self', 'chip', signal) : Promise.resolve(null), [open, sessionId, debouncedFreshnessKey, associationTick], { silentAfterFirst: true, retryToken: 0, scopeKey: sessionId });
141
153
  // Session switches close the panel — the split it explains no longer holds.
142
154
  useEffect(() => {
143
155
  setOpen(false);
@@ -200,7 +212,7 @@ export function CostPill({ sessionId, useSessions, useProjection, t }) {
200
212
  const detail = detailRes.status === 'ready' ? detailRes.value : null;
201
213
  const split = selfSummary !== null ? splitUsage(summary, selfSummary) : null;
202
214
  const subCount = scopeIds.length - 1;
203
- return (_jsx("div", { ref: rootRef, className: styles.root, children: _jsxs(PricingAssociationProvider, { resolutions: detail?.modelResolutions, feedVersion: summary.feedVersion, view: view, t: t, children: [_jsxs("button", { type: "button", className: styles.pill, "aria-haspopup": "dialog", "aria-expanded": open, "aria-label": `${ariaLabel},${t('panel.openHint')}`, onClick: () => { setOpen(!open); }, children: [_jsxs("svg", { className: styles.glyph, viewBox: "0 0 14 14", width: "14", height: "14", "aria-hidden": true, children: [_jsx("circle", { cx: "7", cy: "7", r: "5.5", fill: "none", stroke: "currentColor", strokeWidth: "1.2" }), _jsx("path", { d: "M4.8 4.5 L7 7.2 L9.2 4.5 M7 7.2 V10 M5.2 8 H8.8 M5.2 9.4 H8.8", fill: "none", stroke: "currentColor", strokeWidth: "1.2" })] }), _jsx("span", { ref: costRef, className: styles.cost, children: costText }), _jsx("span", { className: styles.deltaLayer, "aria-hidden": "true", children: flies.map(fly => (_jsx(CostDeltaFlyLabel, { text: fly.text, vars: fly.vars }, fly.id))) })] }), open && (_jsxs("div", { className: styles.panel, role: "dialog", "aria-label": t('panel.title'), style: { left: panelLeft }, children: [_jsxs("span", { className: styles.panelHead, children: [_jsxs("span", { className: styles.panelTitle, children: [t('panel.title'), hasSubs && _jsx("span", { className: styles.scopeTag, children: t('pill.scopeTag') })] }), _jsx("span", { className: styles.panelTotal, children: costText })] }), _jsxs("span", { className: styles.usageLine, children: [_jsx("span", { children: t('panel.tokens', { value: tokensValue }) }), _jsx("span", { className: styles.dot, children: "\u00B7" }), _jsx("span", { children: t('panel.hitRate', { value: hit.text }) })] }), _jsxs("div", { className: styles.rows, children: [_jsx(PricingStatus, { costState: summary.costState, pricingUnavailableReason: summary.pricingUnavailableReason, associationStorageError: summary.associationStorageError, t: t }), _jsxs("span", { className: styles.row, children: [_jsx("span", { className: styles.rowLabel, children: t('panel.self') }), _jsx("span", { className: styles.rowValue, children: split === null
215
+ return (_jsx("div", { ref: rootRef, className: styles.root, children: _jsxs(PricingAssociationProvider, { resolutions: detail?.modelResolutions, feedVersion: summary.feedVersion, view: view, t: t, children: [_jsxs("button", { type: "button", className: styles.pill, "aria-haspopup": "dialog", "aria-expanded": open, "aria-label": `${ariaLabel},${t('panel.openHint')}`, onClick: () => { setOpen(!open); }, children: [_jsxs("svg", { className: styles.glyph, viewBox: "0 0 14 14", width: "14", height: "14", "aria-hidden": true, children: [_jsx("circle", { cx: "7", cy: "7", r: "5.5", fill: "none", stroke: "currentColor", strokeWidth: "1.2" }), _jsx("path", { d: "M4.8 4.5 L7 7.2 L9.2 4.5 M7 7.2 V10 M5.2 8 H8.8 M5.2 9.4 H8.8", fill: "none", stroke: "currentColor", strokeWidth: "1.2" })] }), _jsx("span", { ref: costRef, className: styles.cost, children: costText })] }), open && (_jsxs("div", { className: styles.panel, role: "dialog", "aria-label": t('panel.title'), style: { left: panelLeft }, children: [_jsxs("span", { className: styles.panelHead, children: [_jsxs("span", { className: styles.panelTitle, children: [t('panel.title'), hasSubs && _jsx("span", { className: styles.scopeTag, children: t('pill.scopeTag') })] }), _jsx("span", { className: styles.panelTotal, children: costText })] }), _jsxs("span", { className: styles.usageLine, children: [_jsx("span", { children: t('panel.tokens', { value: tokensValue }) }), _jsx("span", { className: styles.dot, children: "\u00B7" }), _jsx("span", { children: t('panel.hitRate', { value: hit.text }) })] }), _jsxs("div", { className: styles.rows, children: [_jsx(PricingStatus, { costState: summary.costState, pricingUnavailableReason: summary.pricingUnavailableReason, associationStorageError: summary.associationStorageError, t: t }), _jsxs("span", { className: styles.row, children: [_jsx("span", { className: styles.rowLabel, children: t('panel.self') }), _jsx("span", { className: styles.rowValue, children: split === null
204
216
  ? _jsx("span", { className: styles.pending, children: "\u2026" })
205
217
  : _jsxs(_Fragment, { children: [costsAvailable(summary.costState) && costsAvailable(selfSummary?.costState) ? formatCost(split.selfCost, view) : '—', _jsx("span", { className: styles.tok, children: t('panel.tokens', { value: formatTokens(split.selfTokens) }) })] }) })] }), hasSubs && (_jsxs("span", { className: `${styles.row} ${styles.rowSub}`, children: [_jsx("span", { className: styles.rowLabel, children: t('panel.subs', { count: subCount }) }), _jsx("span", { className: styles.rowValue, children: split === null
206
218
  ? _jsx("span", { className: styles.pending, children: "\u2026" })
@@ -220,20 +232,21 @@ function looksLikeUsageSummary(value) {
220
232
  && value.total !== null;
221
233
  }
222
234
  /**
223
- * Fetch one stats summary. Throws on transport failure (network, abort,
224
- * non-2xx response, or a payload that doesn't look like a stats summary) so
225
- * the hook can keep the previous render in place.
226
- * @param sessionIds - the scope's session ids; an empty list skips the
227
- * fetch (returning null rather than throwing, so the hook's first-load
228
- * gate stays at "loading").
229
- * @param fields - `chip` for totals-only reads, `session` when byModel is
230
- * needed (the detail panel's per-model block).
235
+ * Fetch one stats summary. The request carries a RANGE RULE (root + scope),
236
+ * never an enumerated subtree — the host expands it from its lineage index,
237
+ * so the pill's chip/detail reads stay short even for hundreds of subagents.
238
+ * Throws on transport failure (network, abort, non-2xx response, or a payload
239
+ * that doesn't look like a stats summary) so the hook can keep the previous
240
+ * render in place.
241
+ * @param root - the scope's root session id; empty skips the fetch.
242
+ * @param scope - `subtree` for the folded total, `self` for the split.
243
+ * @param fields - `chip` for totals-only reads, `session` for byModel.
231
244
  * @param signal - the cancellation signal from the hook.
232
245
  */
233
- async function fetchSummary(sessionIds, fields, signal) {
234
- if (sessionIds.length === 0)
246
+ async function fetchSummary(root, scope, fields, signal) {
247
+ if (root === '')
235
248
  return null;
236
- const response = await fetch(STATS_PATH + encodeStatsQuery({ sessionIds, fields }), {
249
+ const response = await fetch(STATS_PATH + encodeStatsQuery({ root, scope, fields }), {
237
250
  headers: { accept: 'application/json' },
238
251
  signal,
239
252
  });