@laoyuehanni/dsh-token-usage 0.3.7

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 (215) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +178 -0
  3. package/README.zh.md +182 -0
  4. package/cordis.patch.yml +7 -0
  5. package/lib/client/CostDeltaFlyLabel.d.ts +8 -0
  6. package/lib/client/CostDeltaFlyLabel.d.ts.map +1 -0
  7. package/lib/client/CostDeltaFlyLabel.js +24 -0
  8. package/lib/client/CostDeltaFlyLabel.js.map +1 -0
  9. package/lib/client/HitRateText.d.ts +21 -0
  10. package/lib/client/HitRateText.d.ts.map +1 -0
  11. package/lib/client/HitRateText.js +16 -0
  12. package/lib/client/HitRateText.js.map +1 -0
  13. package/lib/client/QuotaButton.d.ts +70 -0
  14. package/lib/client/QuotaButton.d.ts.map +1 -0
  15. package/lib/client/QuotaButton.js +346 -0
  16. package/lib/client/QuotaButton.js.map +1 -0
  17. package/lib/client/SessionStatsChip.d.ts +47 -0
  18. package/lib/client/SessionStatsChip.d.ts.map +1 -0
  19. package/lib/client/SessionStatsChip.js +141 -0
  20. package/lib/client/SessionStatsChip.js.map +1 -0
  21. package/lib/client/StatCard.d.ts +26 -0
  22. package/lib/client/StatCard.d.ts.map +1 -0
  23. package/lib/client/StatCard.js +10 -0
  24. package/lib/client/StatCard.js.map +1 -0
  25. package/lib/client/TokenUsageCard.d.ts +41 -0
  26. package/lib/client/TokenUsageCard.d.ts.map +1 -0
  27. package/lib/client/TokenUsageCard.js +164 -0
  28. package/lib/client/TokenUsageCard.js.map +1 -0
  29. package/lib/client/TokenUsageSection.d.ts +32 -0
  30. package/lib/client/TokenUsageSection.d.ts.map +1 -0
  31. package/lib/client/TokenUsageSection.js +266 -0
  32. package/lib/client/TokenUsageSection.js.map +1 -0
  33. package/lib/client/TrendChart.d.ts +53 -0
  34. package/lib/client/TrendChart.d.ts.map +1 -0
  35. package/lib/client/TrendChart.js +141 -0
  36. package/lib/client/TrendChart.js.map +1 -0
  37. package/lib/client/UsageView.d.ts +42 -0
  38. package/lib/client/UsageView.d.ts.map +1 -0
  39. package/lib/client/UsageView.js +158 -0
  40. package/lib/client/UsageView.js.map +1 -0
  41. package/lib/client/async-resource.d.ts +54 -0
  42. package/lib/client/async-resource.d.ts.map +1 -0
  43. package/lib/client/async-resource.js +90 -0
  44. package/lib/client/async-resource.js.map +1 -0
  45. package/lib/client/card-form.d.ts +171 -0
  46. package/lib/client/card-form.d.ts.map +1 -0
  47. package/lib/client/card-form.js +300 -0
  48. package/lib/client/card-form.js.map +1 -0
  49. package/lib/client/cost-inflate-motion.d.ts +17 -0
  50. package/lib/client/cost-inflate-motion.d.ts.map +1 -0
  51. package/lib/client/cost-inflate-motion.js +61 -0
  52. package/lib/client/cost-inflate-motion.js.map +1 -0
  53. package/lib/client/cost-inflate.d.ts +28 -0
  54. package/lib/client/cost-inflate.d.ts.map +1 -0
  55. package/lib/client/cost-inflate.js +49 -0
  56. package/lib/client/cost-inflate.js.map +1 -0
  57. package/lib/client/day.d.ts +49 -0
  58. package/lib/client/day.d.ts.map +1 -0
  59. package/lib/client/day.js +84 -0
  60. package/lib/client/day.js.map +1 -0
  61. package/lib/client/format.d.ts +120 -0
  62. package/lib/client/format.d.ts.map +1 -0
  63. package/lib/client/format.js +163 -0
  64. package/lib/client/format.js.map +1 -0
  65. package/lib/client/index.d.ts +26 -0
  66. package/lib/client/index.d.ts.map +1 -0
  67. package/lib/client/index.js +131 -0
  68. package/lib/client/index.js.map +1 -0
  69. package/lib/client/locales.d.ts +131 -0
  70. package/lib/client/locales.d.ts.map +1 -0
  71. package/lib/client/locales.js +230 -0
  72. package/lib/client/locales.js.map +1 -0
  73. package/lib/client/quota-format.d.ts +69 -0
  74. package/lib/client/quota-format.d.ts.map +1 -0
  75. package/lib/client/quota-format.js +147 -0
  76. package/lib/client/quota-format.js.map +1 -0
  77. package/lib/client/session-stats.d.ts +105 -0
  78. package/lib/client/session-stats.d.ts.map +1 -0
  79. package/lib/client/session-stats.js +142 -0
  80. package/lib/client/session-stats.js.map +1 -0
  81. package/lib/client/trend-chart/axis.d.ts +21 -0
  82. package/lib/client/trend-chart/axis.d.ts.map +1 -0
  83. package/lib/client/trend-chart/axis.js +33 -0
  84. package/lib/client/trend-chart/axis.js.map +1 -0
  85. package/lib/client/trend-chart/bucket.d.ts +24 -0
  86. package/lib/client/trend-chart/bucket.d.ts.map +1 -0
  87. package/lib/client/trend-chart/bucket.js +28 -0
  88. package/lib/client/trend-chart/bucket.js.map +1 -0
  89. package/lib/client/trend-chart/index.d.ts +12 -0
  90. package/lib/client/trend-chart/index.d.ts.map +1 -0
  91. package/lib/client/trend-chart/index.js +9 -0
  92. package/lib/client/trend-chart/index.js.map +1 -0
  93. package/lib/client/trend-chart/points.d.ts +46 -0
  94. package/lib/client/trend-chart/points.d.ts.map +1 -0
  95. package/lib/client/trend-chart/points.js +82 -0
  96. package/lib/client/trend-chart/points.js.map +1 -0
  97. package/lib/client/trend-chart/scale.d.ts +47 -0
  98. package/lib/client/trend-chart/scale.d.ts.map +1 -0
  99. package/lib/client/trend-chart/scale.js +75 -0
  100. package/lib/client/trend-chart/scale.js.map +1 -0
  101. package/lib/client/use-color-scheme.d.ts +18 -0
  102. package/lib/client/use-color-scheme.d.ts.map +1 -0
  103. package/lib/client/use-color-scheme.js +37 -0
  104. package/lib/client/use-color-scheme.js.map +1 -0
  105. package/lib/client/use-cost-inflate.d.ts +33 -0
  106. package/lib/client/use-cost-inflate.d.ts.map +1 -0
  107. package/lib/client/use-cost-inflate.js +108 -0
  108. package/lib/client/use-cost-inflate.js.map +1 -0
  109. package/lib/client.js +3892 -0
  110. package/lib/client.js.map +1 -0
  111. package/lib/index.d.ts +132 -0
  112. package/lib/index.d.ts.map +1 -0
  113. package/lib/index.js +599 -0
  114. package/lib/index.js.map +1 -0
  115. package/lib/migrate.d.ts +60 -0
  116. package/lib/migrate.d.ts.map +1 -0
  117. package/lib/migrate.js +126 -0
  118. package/lib/migrate.js.map +1 -0
  119. package/lib/pricing.d.ts +212 -0
  120. package/lib/pricing.d.ts.map +1 -0
  121. package/lib/pricing.js +492 -0
  122. package/lib/pricing.js.map +1 -0
  123. package/lib/quota/adapters/deepseek-balance.d.ts +18 -0
  124. package/lib/quota/adapters/deepseek-balance.d.ts.map +1 -0
  125. package/lib/quota/adapters/deepseek-balance.js +76 -0
  126. package/lib/quota/adapters/deepseek-balance.js.map +1 -0
  127. package/lib/quota/adapters/kimi.d.ts +26 -0
  128. package/lib/quota/adapters/kimi.d.ts.map +1 -0
  129. package/lib/quota/adapters/kimi.js +91 -0
  130. package/lib/quota/adapters/kimi.js.map +1 -0
  131. package/lib/quota/adapters/minimax.d.ts +24 -0
  132. package/lib/quota/adapters/minimax.d.ts.map +1 -0
  133. package/lib/quota/adapters/minimax.js +136 -0
  134. package/lib/quota/adapters/minimax.js.map +1 -0
  135. package/lib/quota/adapters/opencode-go.d.ts +25 -0
  136. package/lib/quota/adapters/opencode-go.d.ts.map +1 -0
  137. package/lib/quota/adapters/opencode-go.js +105 -0
  138. package/lib/quota/adapters/opencode-go.js.map +1 -0
  139. package/lib/quota/adapters/openrouter.d.ts +15 -0
  140. package/lib/quota/adapters/openrouter.d.ts.map +1 -0
  141. package/lib/quota/adapters/openrouter.js +54 -0
  142. package/lib/quota/adapters/openrouter.js.map +1 -0
  143. package/lib/quota/adapters/zhipu.d.ts +38 -0
  144. package/lib/quota/adapters/zhipu.d.ts.map +1 -0
  145. package/lib/quota/adapters/zhipu.js +246 -0
  146. package/lib/quota/adapters/zhipu.js.map +1 -0
  147. package/lib/quota/credentials.d.ts +79 -0
  148. package/lib/quota/credentials.d.ts.map +1 -0
  149. package/lib/quota/credentials.js +130 -0
  150. package/lib/quota/credentials.js.map +1 -0
  151. package/lib/quota/http.d.ts +49 -0
  152. package/lib/quota/http.d.ts.map +1 -0
  153. package/lib/quota/http.js +114 -0
  154. package/lib/quota/http.js.map +1 -0
  155. package/lib/quota/provider-tracking.d.ts +45 -0
  156. package/lib/quota/provider-tracking.d.ts.map +1 -0
  157. package/lib/quota/provider-tracking.js +52 -0
  158. package/lib/quota/provider-tracking.js.map +1 -0
  159. package/lib/quota/quota-route.d.ts +22 -0
  160. package/lib/quota/quota-route.d.ts.map +1 -0
  161. package/lib/quota/quota-route.js +57 -0
  162. package/lib/quota/quota-route.js.map +1 -0
  163. package/lib/quota/quota-service.d.ts +54 -0
  164. package/lib/quota/quota-service.d.ts.map +1 -0
  165. package/lib/quota/quota-service.js +171 -0
  166. package/lib/quota/quota-service.js.map +1 -0
  167. package/lib/quota/registry.d.ts +24 -0
  168. package/lib/quota/registry.d.ts.map +1 -0
  169. package/lib/quota/registry.js +38 -0
  170. package/lib/quota/registry.js.map +1 -0
  171. package/lib/quota/types.d.ts +79 -0
  172. package/lib/quota/types.d.ts.map +1 -0
  173. package/lib/quota/types.js +24 -0
  174. package/lib/quota/types.js.map +1 -0
  175. package/lib/record-cache.d.ts +38 -0
  176. package/lib/record-cache.d.ts.map +1 -0
  177. package/lib/record-cache.js +143 -0
  178. package/lib/record-cache.js.map +1 -0
  179. package/lib/rollup.d.ts +52 -0
  180. package/lib/rollup.d.ts.map +1 -0
  181. package/lib/rollup.js +117 -0
  182. package/lib/rollup.js.map +1 -0
  183. package/lib/stats-route.d.ts +88 -0
  184. package/lib/stats-route.d.ts.map +1 -0
  185. package/lib/stats-route.js +313 -0
  186. package/lib/stats-route.js.map +1 -0
  187. package/lib/stats.d.ts +158 -0
  188. package/lib/stats.d.ts.map +1 -0
  189. package/lib/stats.js +426 -0
  190. package/lib/stats.js.map +1 -0
  191. package/lib/sync-state.d.ts +27 -0
  192. package/lib/sync-state.d.ts.map +1 -0
  193. package/lib/sync-state.js +56 -0
  194. package/lib/sync-state.js.map +1 -0
  195. package/lib/sync.d.ts +74 -0
  196. package/lib/sync.d.ts.map +1 -0
  197. package/lib/sync.js +64 -0
  198. package/lib/sync.js.map +1 -0
  199. package/lib/trend-bucket.d.ts +48 -0
  200. package/lib/trend-bucket.d.ts.map +1 -0
  201. package/lib/trend-bucket.js +87 -0
  202. package/lib/trend-bucket.js.map +1 -0
  203. package/lib/usage-log.d.ts +64 -0
  204. package/lib/usage-log.d.ts.map +1 -0
  205. package/lib/usage-log.js +144 -0
  206. package/lib/usage-log.js.map +1 -0
  207. package/lib/usage-record.d.ts +59 -0
  208. package/lib/usage-record.d.ts.map +1 -0
  209. package/lib/usage-record.js +115 -0
  210. package/lib/usage-record.js.map +1 -0
  211. package/lib/wire.d.ts +452 -0
  212. package/lib/wire.d.ts.map +1 -0
  213. package/lib/wire.js +144 -0
  214. package/lib/wire.js.map +1 -0
  215. package/package.json +100 -0
package/lib/wire.d.ts ADDED
@@ -0,0 +1,452 @@
1
+ /**
2
+ * Browser-safe wire vocabulary of the token-usage plugin: the stats endpoint
3
+ * path and the JSON shapes the web settings page consumes. No runtime imports
4
+ * and no I/O, so the host half (route handler) and the browser half (settings
5
+ * page) share one vocabulary, and the client bundle can inline this module.
6
+ *
7
+ * @module token-usage/wire
8
+ */
9
+ import type { UsageRecord } from './usage-record.ts';
10
+ export type { UsageFields, UsageRecord } from './usage-record.ts';
11
+ /** The stats endpoint path, served by the host half's webServer route. */
12
+ export declare const STATS_PATH = "/token-usage/stats";
13
+ /** How much of the stats payload a consumer asked for. `full` is the
14
+ * settings page's whole CostedSummary; `session` is the usage tab; `chip`
15
+ * is the header strip (totals only). */
16
+ export type StatsFields = 'chip' | 'session' | 'full';
17
+ /** Encode one repeated query key (`sessionId=a&sessionId=b`). Empty list yields ''. */
18
+ export declare function encodeRepeatedParam(key: string, values: readonly string[]): string;
19
+ /**
20
+ * Parse every occurrence of `key` off a URL or `URLSearchParams`, dropping
21
+ * blanks and duplicates, preserving first-seen order.
22
+ */
23
+ export declare function decodeRepeatedParam(source: URL | URLSearchParams, key: string): string[];
24
+ /**
25
+ * One child-row group: the row's id (first token) plus every session id
26
+ * folded into that row. Tree scope sends `[child, ...descendants]`; session
27
+ * scope sends `[child]` alone. Tokens are comma-joined on the wire.
28
+ */
29
+ export interface ChildGroup {
30
+ id: string;
31
+ sessionIds: readonly string[];
32
+ }
33
+ /** Encode child groups as repeated `childId=<id>[,member…]` parameters. */
34
+ export declare function encodeChildGroups(groups: readonly (readonly string[])[]): string;
35
+ /** Parse `childId=` groups; the first comma-separated token is the row id. */
36
+ export declare function decodeChildGroups(source: URL | URLSearchParams): ChildGroup[];
37
+ /**
38
+ * Build the stats query string (including the leading `?`, or '' when
39
+ * unconstrained). `fields: 'full'` is omitted — that is the default the
40
+ * settings page already hits.
41
+ */
42
+ export declare function encodeStatsQuery(options: {
43
+ sessionIds?: readonly string[];
44
+ childGroups?: readonly (readonly string[])[];
45
+ fields?: StatsFields;
46
+ }): string;
47
+ /**
48
+ * Encode a session-scope id list as a `sessionId=` query fragment pair:
49
+ * every id becomes its own `sessionId=<encoded>` parameter (RFC-style
50
+ * `?a=1&a=2`), so a parent-and-children fetch aggregates the whole subtree
51
+ * in one request. The empty list yields '' (no query string at all).
52
+ * @param ids - the session ids to filter by.
53
+ */
54
+ export declare function encodeSessionScope(ids: readonly string[]): string;
55
+ /**
56
+ * Parse the `sessionId=` parameters off a URL or a parsed `URLSearchParams`:
57
+ * every occurrence of the key becomes one entry, in URL order (so a parent
58
+ * + children fetch preserves the caller-supplied order). Empty values are
59
+ * dropped (defensive: a `?sessionId=` blank yields no entry) and duplicates
60
+ * are deduped.
61
+ * @param source - the URL or its parsed params.
62
+ * @returns the deduplicated id list.
63
+ */
64
+ export declare function decodeSessionScope(source: URL | URLSearchParams): string[];
65
+ /**
66
+ * The quota endpoint path: the input-bar quota button polls this for the
67
+ * current provider's rate-limit / balance snapshot. Served by the host
68
+ * half's quota route; the query carries `?session=<id>` so the host can
69
+ * resolve the provider the ACTIVE session is using.
70
+ */
71
+ export declare const QUOTA_PATH = "/token-usage/quota";
72
+ /** The migration-progress endpoint path, polled by the browser card. */
73
+ export declare const MIGRATION_PATH = "/token-usage/migration";
74
+ /**
75
+ * The directory-guard endpoint path, consulted by the browser card before a
76
+ * staged directory save commits. The settings wire swallows a refused write
77
+ * (the bound scope recovers silently and never rejects), so this route is the
78
+ * one channel that can tell the card WHY a save would not land.
79
+ */
80
+ export declare const DIR_GUARD_PATH = "/token-usage/dir-guard";
81
+ /**
82
+ * The full-sync endpoint path: the card's manual "scan again" affordance.
83
+ * `POST` starts one full scan over every session log (the same scan the
84
+ * one-shot startup sync ran on first install — list + inspect + dedupe), and
85
+ * `GET` returns the live progress. The scan is fire-and-forget on the host
86
+ * side, so the card polls while it runs.
87
+ */
88
+ export declare const FULL_SYNC_PATH = "/token-usage/full-sync";
89
+ /** The guard's verdict for one would-be directory save. */
90
+ export interface DirectoryGuardView {
91
+ /** True when the Host's section validator would refuse the save right now. */
92
+ blocked: boolean;
93
+ /** Sessions mid-conversation (an open turn) at verdict time, for the notice's number. */
94
+ interactingSessions: number;
95
+ }
96
+ /**
97
+ * The view of one full-sync run: what the route returns to a poll, and what
98
+ * the card's section reads. `idle` means no run has been triggered (or the
99
+ * last one settled and the card cleared it); `running` carries the live
100
+ * counts the card renders as a progress bar; `done` and `failed` are the
101
+ * terminal states the card holds on screen until the next run.
102
+ */
103
+ export type FullSyncView = {
104
+ status: 'idle';
105
+ } | {
106
+ status: 'running';
107
+ processed: number;
108
+ total: number;
109
+ added: number;
110
+ skipped: number;
111
+ } | {
112
+ status: 'done';
113
+ processed: number;
114
+ total: number;
115
+ added: number;
116
+ skipped: number;
117
+ } | {
118
+ status: 'failed';
119
+ error: string;
120
+ };
121
+ /** Aggregated token counts over one group of records. */
122
+ export interface UsageTotals {
123
+ /** Number of recorded requests (records without provider usage count here). */
124
+ requests: number;
125
+ /** Uncached input tokens; billed input = input + cacheRead + cacheWrite. */
126
+ inputTokens: number;
127
+ /** Output tokens. */
128
+ outputTokens: number;
129
+ /** Cache-hit input tokens. */
130
+ cacheReadTokens: number;
131
+ /** Cache-write input tokens. */
132
+ cacheWriteTokens: number;
133
+ }
134
+ /** One per-day aggregation row, keyed by local date `YYYY-MM-DD`. */
135
+ export interface UsageDayRow {
136
+ day: string;
137
+ totals: UsageTotals;
138
+ }
139
+ /** One per-request token total in time order (session-scoped reads only).
140
+ * The usage tab's `fields=session` response is already time-bucketed: `count`
141
+ * and `end` are set, and the chart plots the points without folding again.
142
+ * A raw (unbucketed) point has only `time` + `tokens`. */
143
+ export interface RequestPoint {
144
+ /** Session-event wall time, or the bucket start when `count` is set. */
145
+ time: number;
146
+ /** Total tokens across the four buckets (0 for a request without usage). */
147
+ tokens: number;
148
+ /** Requests folded into this bucket; absent on a raw per-request point. */
149
+ count?: number;
150
+ /** Bucket end (exclusive), epoch ms; absent on a raw per-request point. */
151
+ end?: number;
152
+ }
153
+ /** Per-child row the usage tab's subagent table reads (no chart / pricing). */
154
+ export interface ChildUsageSummary {
155
+ total: UsageTotals;
156
+ totalCost: number;
157
+ unpricedModels: string[];
158
+ }
159
+ /** One per-hour × per-model aggregation row, keyed by local `YYYY-MM-DDTHH`. */
160
+ export interface UsageHourRow {
161
+ hour: string;
162
+ model: string;
163
+ totals: UsageTotals;
164
+ }
165
+ /** One per-model aggregation row (token counts only; see the cost layer below). */
166
+ export interface UsageModelRow {
167
+ model: string;
168
+ totals: UsageTotals;
169
+ }
170
+ /** Per-million-token prices of one rate node, in ¥ (RMB). */
171
+ export interface ModelPricing {
172
+ /** Uncached input price, ¥ per million tokens. */
173
+ inputPerMillion: number;
174
+ /** Output price, ¥ per million tokens. */
175
+ outputPerMillion: number;
176
+ /** Cache-hit input price, ¥ per million tokens. */
177
+ cacheReadPerMillion?: number;
178
+ /** Cache-write input price, ¥ per million tokens. */
179
+ cacheWritePerMillion?: number;
180
+ }
181
+ /** One peak window of a day, half-open [startMinute, endMinute) in local minutes. */
182
+ export interface RateWindow {
183
+ startMinute: number;
184
+ endMinute: number;
185
+ }
186
+ /** A peak-pricing slot: the rates that apply inside its windows. */
187
+ export interface DailySlot {
188
+ /** Optional display label. */
189
+ label?: string;
190
+ windows: RateWindow[];
191
+ rates: ModelPricing;
192
+ }
193
+ /** A context tier: the rates that apply once the context reaches the threshold. */
194
+ export interface ContextTier {
195
+ /** Context size (tokens) at and above which this tier applies. */
196
+ threshold: number;
197
+ rates: ModelPricing;
198
+ /** Tiers may carry their own peak slots (mirrors the analyzer's node chain). */
199
+ dailySlots?: DailySlot[];
200
+ }
201
+ /** A time rule: the container whose rates (and tiers/slots) apply inside its window. */
202
+ export interface TimeRule {
203
+ /** Optional display label. */
204
+ label?: string;
205
+ /** Inclusive window bounds, Unix seconds. */
206
+ startTime: number;
207
+ endTime: number;
208
+ rates: ModelPricing;
209
+ contextTiers?: ContextTier[];
210
+ dailySlots?: DailySlot[];
211
+ }
212
+ /**
213
+ * The full pricing of one model: the base rates plus the rule chain the
214
+ * analyzer resolves per request — time-rule container first, then context
215
+ * tier, then peak slot. A hand-edited entry contributes only `base` (manual
216
+ * overrides replace the model's cloud rules wholesale).
217
+ */
218
+ export interface ModelRates {
219
+ base: ModelPricing;
220
+ contextTiers: ContextTier[];
221
+ dailySlots: DailySlot[];
222
+ timeRules: TimeRule[];
223
+ }
224
+ /** True when any rule dimension exists beyond the flat base rates. */
225
+ export declare function hasRateRules(rates: ModelRates): boolean;
226
+ /**
227
+ * The identity of the rate one record was billed at: which time rule (by its
228
+ * window), which context tier (by its threshold), and which peak slot (by
229
+ * its index into the node's slots). Holds rule identity, never price
230
+ * numbers, so a price update re-prices history without a rollup rebuild.
231
+ */
232
+ export interface RateKey {
233
+ /** Time-rule window start (Unix seconds); 0 when no rule matched. */
234
+ ruleStart: number;
235
+ /** Time-rule window end (Unix seconds); 0 when no rule matched. */
236
+ ruleEnd: number;
237
+ /** Context-tier threshold; 0 when no tier matched. */
238
+ tier: number;
239
+ /** Peak-slot index into the resolved node's slots; -1 when off-peak. */
240
+ slot: number;
241
+ }
242
+ /** The neutral key of an unpriced model's rows. */
243
+ export declare const UNPRICED_KEY: RateKey;
244
+ /** Whether a key is the neutral unpriced one. */
245
+ export declare function isUnpricedKey(key: RateKey): boolean;
246
+ /**
247
+ * The merged pricing table: model id → full rule set, loaded from
248
+ * `<data dir>/pricing.ccsa.json` (cloud mirror, full rules) layered under
249
+ * `<data dir>/pricing.json` (hand-edited flat overrides; see pricing.ts).
250
+ * Models absent from the table are unpriced: their cost counts as 0 and they
251
+ * surface in {@link UsageSummary.unpricedModels}.
252
+ */
253
+ export type PricingTable = Record<string, ModelRates>;
254
+ /** One per-day × per-model × per-rate aggregation row. */
255
+ export interface UsageRateRow {
256
+ day: string;
257
+ model: string;
258
+ rate: RateKey;
259
+ totals: UsageTotals;
260
+ }
261
+ /**
262
+ * The token-only aggregation shape: what the aggregation functions produce
263
+ * and the rollup persists. No currency — cost is an additive layer computed
264
+ * from the pricing table when the route serves the summary (attachCosts),
265
+ * re-priced from the rate identities on every read.
266
+ */
267
+ export interface TokenSummary {
268
+ /** Totals over every recorded request. */
269
+ total: UsageTotals;
270
+ /** Per-local-day rows, ascending by day. */
271
+ byDay: UsageDayRow[];
272
+ /** Per-hour × per-model rows, ascending by hour then model; the web page
273
+ * folds them by hour to draw the single-day trend chart. */
274
+ byHour: UsageHourRow[];
275
+ /** Per-model rows, descending by request count. */
276
+ byModel: UsageModelRow[];
277
+ /** Per-day × per-model × per-rate rows, day then model then rate ascending;
278
+ * lets the route re-aggregate any day range × model filter without
279
+ * rereading files, and re-price history under the current table. */
280
+ rateRows: UsageRateRow[];
281
+ /** The most recent records, descending by time. */
282
+ recent: UsageRecord[];
283
+ }
284
+ /** A per-model row carrying its billed cost (¥); 0 when the model is unpriced. */
285
+ export type CostedModelRow = UsageModelRow & {
286
+ cost: number;
287
+ };
288
+ /** The currency the stats page renders cost figures in. The amounts on the
289
+ * wire stay RMB — this only names the display convention. */
290
+ export type DisplayCurrency = 'CNY' | 'USD';
291
+ /**
292
+ * The display currency a mirror region implies: `overseas` (GitHub) shows
293
+ * USD, `domestic` (Gitee) and the unset default show CNY. Only the region
294
+ * pick decides — an explicit `pricingUrl` never changes the display.
295
+ * @param region - the effective `pricingRegion` (undefined when unset).
296
+ * @returns the display currency of the stats page.
297
+ */
298
+ export declare function currencyOfRegion(region: 'domestic' | 'overseas' | undefined): DisplayCurrency;
299
+ /**
300
+ * The token aggregation plus the cost layer — what {@link attachCosts}
301
+ * produces before the route stamps the display-currency metadata.
302
+ */
303
+ export interface CostedSummary extends TokenSummary {
304
+ /** Absolute data directory the summary was computed from. */
305
+ dataDir: string;
306
+ /** Billed cost over every recorded request (¥); unpriced models count 0. */
307
+ totalCost: number;
308
+ /** Models with usage but no entry in the pricing table, byModel order. */
309
+ unpricedModels: string[];
310
+ /** The active pricing table (user-maintained; empty when none is configured). */
311
+ pricing: PricingTable;
312
+ /** Per-model rows with their billed cost attached. */
313
+ byModel: CostedModelRow[];
314
+ }
315
+ /** The full stats payload served at {@link STATS_PATH}. A discriminated
316
+ * union over the two scope modes the route serves:
317
+ * - `'whole'`: the settings page's whole-log read. The `requestSeries`
318
+ * field is absent (the page plots hours/days), so its `TrendChart`
319
+ * falls back to the `byDay` / `byHour` rows.
320
+ * - `'session'`: the conversation view tab's session-scoped read. The
321
+ * `sessionIds` field lists every requested id (the parent + its
322
+ * subagent children when the scope is "tree"), and `requestSeries`
323
+ * is the per-request series the chart plots at request granularity.
324
+ *
325
+ * Both branches share every {@link CostedSummary} field plus the
326
+ * display-currency metadata, so a consumer can read `total` /
327
+ * `totalCost` / `pricing` without narrowing first.
328
+ */
329
+ export type StatsPayload = (CostedSummary & {
330
+ scope: 'whole';
331
+ /** The display currency the page converts cost figures into. Amounts on
332
+ * the wire (totalCost, byModel[].cost, pricing rates) remain RMB. */
333
+ currency: DisplayCurrency;
334
+ /** Effective RMB-per-USD rate (feed value, else the built-in default);
335
+ * the divisor when `currency` is USD. */
336
+ usdExchangeRate: number;
337
+ }) | (CostedSummary & {
338
+ scope: 'session';
339
+ /** The session ids aggregated to produce this payload, in URL order. */
340
+ sessionIds: readonly string[];
341
+ /** Per-request token totals in time order; session-scoped reads always
342
+ * include this, so the trend chart can plot request granularity. */
343
+ requestSeries: readonly RequestPoint[];
344
+ /** The display currency the page converts cost figures into. */
345
+ currency: DisplayCurrency;
346
+ /** Effective RMB-per-USD rate (the divisor when `currency` is USD). */
347
+ usdExchangeRate: number;
348
+ /** Direct-child breakdown keyed by child id, when the request named `childId`. */
349
+ children?: Readonly<Record<string, ChildUsageSummary>>;
350
+ });
351
+ /**
352
+ * Default shape for code that doesn't need to discriminate the scope —
353
+ * mostly test fixtures and the `chip` and `section` summary readers.
354
+ * Adds `requestSeries?` as an optional field so legacy callers can read
355
+ * either branch without narrowing first. Uses a base cost layer plus the
356
+ * display metadata; for new code, narrow on `StatsPayload` instead.
357
+ */
358
+ export interface UsageSummary extends CostedSummary {
359
+ currency: DisplayCurrency;
360
+ usdExchangeRate: number;
361
+ requestSeries?: readonly RequestPoint[];
362
+ children?: Readonly<Record<string, ChildUsageSummary>>;
363
+ sessionIds?: readonly string[];
364
+ }
365
+ /** One normalized quota window tier, mirroring the tier vocabulary the
366
+ * cc-switch research normalized providers onto: time-boxed windows for
367
+ * coding-plan subscriptions, an open-ended balance tier for pay-as-you-go
368
+ * accounts. Display adapts by tier (progress bar vs amount). */
369
+ export type QuotaTier = 'five_hour' | 'weekly' | 'monthly' | 'balance';
370
+ /**
371
+ * One provider quota window as the panel renders it. Percent fields carry
372
+ * the two directions providers report (most coding plans report used,
373
+ * MiniMax reports remaining); the panel derives whichever is missing.
374
+ * Absolute amounts are balance semantics: `remainingValue` is what the
375
+ * user cares about, `maxValue` (when known) enables a spend-progress bar.
376
+ */
377
+ export interface QuotaWindow {
378
+ tier: QuotaTier;
379
+ /** Used share of the window, 0–100; preferred over `remainingPercent`. */
380
+ usedPercent?: number;
381
+ /** Remaining share of the window, 0–100. */
382
+ remainingPercent?: number;
383
+ /** When the window resets, epoch ms; absent for balances. */
384
+ resetAt?: number;
385
+ /** Remaining absolute amount (a balance, or a USD-metered quota). */
386
+ remainingValue?: number;
387
+ /** Total absolute amount, when the provider reports one. */
388
+ maxValue?: number;
389
+ /** Currency of the absolute fields. */
390
+ unit?: 'usd' | 'cny';
391
+ }
392
+ /** Why a quota query failed, normalized so the panel can pick friendly copy. */
393
+ export type QuotaErrorKind = 'auth' | 'no-credential' | 'http' | 'network' | 'parse';
394
+ /** The error face of a quota response. */
395
+ export interface QuotaError {
396
+ kind: QuotaErrorKind;
397
+ /** Technical detail (status code, thrown message); the panel wraps it in
398
+ * kind-specific locale copy. */
399
+ message: string;
400
+ }
401
+ /** The poll cadence the host asks the client to follow (seconds); stamped
402
+ * on every payload variant so the button adapts to the plugin config. */
403
+ interface QuotaCadence {
404
+ intervalSec: number;
405
+ }
406
+ /** A successful quota read: the normalized windows of the current
407
+ * provider, ready for the panel's adaptive grid. */
408
+ export interface QuotaSnapshot extends QuotaCadence {
409
+ status: 'ok';
410
+ /** Provider route key, exactly as session events carry it. */
411
+ provider: string;
412
+ /** Human-readable provider name when one is resolvable. */
413
+ providerName?: string;
414
+ /** Which adapter produced the windows (diagnostics). */
415
+ adapterId: string;
416
+ /** When the snapshot was fetched, epoch ms. */
417
+ fetchedAt: number;
418
+ /** Plan tier label when the provider reports one (e.g. Zhipu `data.level`). */
419
+ planTier?: string;
420
+ windows: QuotaWindow[];
421
+ }
422
+ /** A failed quota read: the provider matched an adapter but the query
423
+ * failed. The button stays visible (the provider IS supported) and the
424
+ * panel shows the error with a retry. */
425
+ export interface QuotaFailure extends QuotaCadence {
426
+ status: 'error';
427
+ provider: string;
428
+ providerName?: string;
429
+ adapterId: string;
430
+ fetchedAt: number;
431
+ error: QuotaError;
432
+ }
433
+ /** The full quota endpoint vocabulary. The hidden variants:
434
+ * - `no-provider` — no provider in use is determinable yet (no activity,
435
+ * no default selection); the button hides until one appears.
436
+ * - `unsupported` — the provider in use has no quota adapter; the button
437
+ * hides (switching providers brings it back).
438
+ * - `disabled` — the quota feature is off in plugin config.
439
+ */
440
+ export type QuotaPayload = QuotaSnapshot | QuotaFailure | (QuotaCadence & {
441
+ status: 'no-provider';
442
+ }) | (QuotaCadence & {
443
+ status: 'unsupported';
444
+ provider: string;
445
+ providerName?: string;
446
+ }) | (QuotaCadence & {
447
+ status: 'disabled';
448
+ });
449
+ /** The windows of a payload, empty for every non-ok variant — the helper
450
+ * the panel reuses for the trigger icon's color. */
451
+ export declare function quotaWindowsOf(payload: QuotaPayload): readonly QuotaWindow[];
452
+ //# sourceMappingURL=wire.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wire.d.ts","sourceRoot":"","sources":["../src/wire.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAA;AAEpD,YAAY,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAA;AAEjE,0EAA0E;AAC1E,eAAO,MAAM,UAAU,uBAAuB,CAAA;AAE9C;;wCAEwC;AACxC,MAAM,MAAM,WAAW,GAAG,MAAM,GAAG,SAAS,GAAG,MAAM,CAAA;AAErD,uFAAuF;AACvF,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,CAElF;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,GAAG,GAAG,eAAe,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,EAAE,CAUxF;AAED;;;;GAIG;AACH,MAAM,WAAW,UAAU;IACzB,EAAE,EAAE,MAAM,CAAA;IACV,UAAU,EAAE,SAAS,MAAM,EAAE,CAAA;CAC9B;AAED,2EAA2E;AAC3E,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,SAAS,CAAC,SAAS,MAAM,EAAE,CAAC,EAAE,GAAG,MAAM,CAKhF;AAED,8EAA8E;AAC9E,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,GAAG,GAAG,eAAe,GAAG,UAAU,EAAE,CAa7E;AAED;;;;GAIG;AACH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IAAE,MAAM,EAAE,aAAa,CAAA;CAAE,CAAC,GAC1C,CAAC,YAAY,GAAG;IAAE,MAAM,EAAE,aAAa,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,YAAY,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,GACnF,CAAC,YAAY,GAAG;IAAE,MAAM,EAAE,UAAU,CAAA;CAAE,CAAC,CAAA;AAE3C;oDACoD;AACpD,wBAAgB,cAAc,CAAC,OAAO,EAAE,YAAY,GAAG,SAAS,WAAW,EAAE,CAE5E"}
package/lib/wire.js ADDED
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Browser-safe wire vocabulary of the token-usage plugin: the stats endpoint
3
+ * path and the JSON shapes the web settings page consumes. No runtime imports
4
+ * and no I/O, so the host half (route handler) and the browser half (settings
5
+ * page) share one vocabulary, and the client bundle can inline this module.
6
+ *
7
+ * @module token-usage/wire
8
+ */
9
+ /** The stats endpoint path, served by the host half's webServer route. */
10
+ export const STATS_PATH = '/token-usage/stats';
11
+ /** Encode one repeated query key (`sessionId=a&sessionId=b`). Empty list yields ''. */
12
+ export function encodeRepeatedParam(key, values) {
13
+ return values.map(value => `${key}=${encodeURIComponent(value)}`).join('&');
14
+ }
15
+ /**
16
+ * Parse every occurrence of `key` off a URL or `URLSearchParams`, dropping
17
+ * blanks and duplicates, preserving first-seen order.
18
+ */
19
+ export function decodeRepeatedParam(source, key) {
20
+ const params = source instanceof URL ? source.searchParams : source;
21
+ const seen = new Set();
22
+ const out = [];
23
+ for (const value of params.getAll(key)) {
24
+ if (value === '' || seen.has(value))
25
+ continue;
26
+ seen.add(value);
27
+ out.push(value);
28
+ }
29
+ return out;
30
+ }
31
+ /** Encode child groups as repeated `childId=<id>[,member…]` parameters. */
32
+ export function encodeChildGroups(groups) {
33
+ return groups
34
+ .filter(group => group.length > 0 && group[0] !== '')
35
+ .map(group => `childId=${encodeURIComponent(group.join(','))}`)
36
+ .join('&');
37
+ }
38
+ /** Parse `childId=` groups; the first comma-separated token is the row id. */
39
+ export function decodeChildGroups(source) {
40
+ const params = source instanceof URL ? source.searchParams : source;
41
+ const seen = new Set();
42
+ const out = [];
43
+ for (const value of params.getAll('childId')) {
44
+ if (value === '')
45
+ continue;
46
+ const sessionIds = value.split(',').filter(id => id !== '');
47
+ const id = sessionIds[0];
48
+ if (id === undefined || seen.has(id))
49
+ continue;
50
+ seen.add(id);
51
+ out.push({ id, sessionIds });
52
+ }
53
+ return out;
54
+ }
55
+ /**
56
+ * Build the stats query string (including the leading `?`, or '' when
57
+ * unconstrained). `fields: 'full'` is omitted — that is the default the
58
+ * settings page already hits.
59
+ */
60
+ export function encodeStatsQuery(options) {
61
+ const parts = [];
62
+ if (options.sessionIds !== undefined && options.sessionIds.length > 0) {
63
+ parts.push(encodeRepeatedParam('sessionId', options.sessionIds));
64
+ }
65
+ const children = options.childGroups !== undefined ? encodeChildGroups(options.childGroups) : '';
66
+ if (children !== '')
67
+ parts.push(children);
68
+ if (options.fields !== undefined && options.fields !== 'full') {
69
+ parts.push(`fields=${options.fields}`);
70
+ }
71
+ return parts.length === 0 ? '' : `?${parts.join('&')}`;
72
+ }
73
+ /**
74
+ * Encode a session-scope id list as a `sessionId=` query fragment pair:
75
+ * every id becomes its own `sessionId=<encoded>` parameter (RFC-style
76
+ * `?a=1&a=2`), so a parent-and-children fetch aggregates the whole subtree
77
+ * in one request. The empty list yields '' (no query string at all).
78
+ * @param ids - the session ids to filter by.
79
+ */
80
+ export function encodeSessionScope(ids) {
81
+ return encodeStatsQuery({ sessionIds: ids });
82
+ }
83
+ /**
84
+ * Parse the `sessionId=` parameters off a URL or a parsed `URLSearchParams`:
85
+ * every occurrence of the key becomes one entry, in URL order (so a parent
86
+ * + children fetch preserves the caller-supplied order). Empty values are
87
+ * dropped (defensive: a `?sessionId=` blank yields no entry) and duplicates
88
+ * are deduped.
89
+ * @param source - the URL or its parsed params.
90
+ * @returns the deduplicated id list.
91
+ */
92
+ export function decodeSessionScope(source) {
93
+ return decodeRepeatedParam(source, 'sessionId');
94
+ }
95
+ /**
96
+ * The quota endpoint path: the input-bar quota button polls this for the
97
+ * current provider's rate-limit / balance snapshot. Served by the host
98
+ * half's quota route; the query carries `?session=<id>` so the host can
99
+ * resolve the provider the ACTIVE session is using.
100
+ */
101
+ export const QUOTA_PATH = '/token-usage/quota';
102
+ /** The migration-progress endpoint path, polled by the browser card. */
103
+ export const MIGRATION_PATH = '/token-usage/migration';
104
+ /**
105
+ * The directory-guard endpoint path, consulted by the browser card before a
106
+ * staged directory save commits. The settings wire swallows a refused write
107
+ * (the bound scope recovers silently and never rejects), so this route is the
108
+ * one channel that can tell the card WHY a save would not land.
109
+ */
110
+ export const DIR_GUARD_PATH = '/token-usage/dir-guard';
111
+ /**
112
+ * The full-sync endpoint path: the card's manual "scan again" affordance.
113
+ * `POST` starts one full scan over every session log (the same scan the
114
+ * one-shot startup sync ran on first install — list + inspect + dedupe), and
115
+ * `GET` returns the live progress. The scan is fire-and-forget on the host
116
+ * side, so the card polls while it runs.
117
+ */
118
+ export const FULL_SYNC_PATH = '/token-usage/full-sync';
119
+ /** True when any rule dimension exists beyond the flat base rates. */
120
+ export function hasRateRules(rates) {
121
+ return rates.contextTiers.length > 0 || rates.dailySlots.length > 0 || rates.timeRules.length > 0;
122
+ }
123
+ /** The neutral key of an unpriced model's rows. */
124
+ export const UNPRICED_KEY = { ruleStart: 0, ruleEnd: 0, tier: 0, slot: -1 };
125
+ /** Whether a key is the neutral unpriced one. */
126
+ export function isUnpricedKey(key) {
127
+ return key.ruleStart === 0 && key.ruleEnd === 0 && key.tier === 0 && key.slot === -1;
128
+ }
129
+ /**
130
+ * The display currency a mirror region implies: `overseas` (GitHub) shows
131
+ * USD, `domestic` (Gitee) and the unset default show CNY. Only the region
132
+ * pick decides — an explicit `pricingUrl` never changes the display.
133
+ * @param region - the effective `pricingRegion` (undefined when unset).
134
+ * @returns the display currency of the stats page.
135
+ */
136
+ export function currencyOfRegion(region) {
137
+ return region === 'overseas' ? 'USD' : 'CNY';
138
+ }
139
+ /** The windows of a payload, empty for every non-ok variant — the helper
140
+ * the panel reuses for the trigger icon's color. */
141
+ export function quotaWindowsOf(payload) {
142
+ return payload.status === 'ok' ? payload.windows : [];
143
+ }
144
+ //# sourceMappingURL=wire.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wire.js","sourceRoot":"","sources":["../src/wire.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAMH,0EAA0E;AAC1E,MAAM,CAAC,MAAM,UAAU,GAAG,oBAAoB,CAAA;AAO9C,uFAAuF;AACvF,MAAM,UAAU,mBAAmB,CAAC,GAAW,EAAE,MAAyB;IACxE,OAAO,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,GAAG,GAAG,IAAI,kBAAkB,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;AAC7E,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,mBAAmB,CAAC,MAA6B,EAAE,GAAW;IAC5E,MAAM,MAAM,GAAG,MAAM,YAAY,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC,CAAC,MAAM,CAAA;IACnE,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAA;IAC9B,MAAM,GAAG,GAAa,EAAE,CAAA;IACxB,KAAK,MAAM,KAAK,IAAI,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC;QACvC,IAAI,KAAK,KAAK,EAAE,IAAI,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC;YAAE,SAAQ;QAC7C,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAA;QACf,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;IACjB,CAAC;IACD,OAAO,GAAG,CAAA;AACZ,CAAC;AAYD,2EAA2E;AAC3E,MAAM,UAAU,iBAAiB,CAAC,MAAsC;IACtE,OAAO,MAAM;SACV,MAAM,CAAC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