@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
@@ -0,0 +1,246 @@
1
+ /**
2
+ * Zhipu GLM Coding Plan adapter (智谱 GLM 套餐): the 5-hour + weekly
3
+ * windows of the personal/international coding-plan subscriptions.
4
+ *
5
+ * Endpoint: `GET https://open.bigmodel.cn/api/monitor/usage/quota/limit`
6
+ * (international `https://api.z.ai/...`, same shape), authorized with the
7
+ * coding-plan API key in the `Authorization` header WITHOUT the `Bearer`
8
+ * prefix — a quirk cc-switch documented; adding the prefix authenticates
9
+ * as anonymous and answers an error envelope.
10
+ *
11
+ * Response (`data.limits[]`): the `unit`/`number` pair gives the window
12
+ * LENGTH (1 days, 3 hours, 5 minutes, 6 weeks — cc-switch and token-monitor
13
+ * read the same table), classifying the bucket: ≤ 6 hours is the 5-hour
14
+ * window, roughly-two-weeks-and-under is weekly, a billing month is
15
+ * monthly; a bare unit 6 stays the weekly bucket whatever its number
16
+ * (observed as 6/1 and 6/7 in the wild). Only when no length is
17
+ * computable does the reset-time-ascending heuristic apply — at a period's
18
+ * end the weekly bucket can reset BEFORE the 5-hour one, so pure time
19
+ * sorting swaps the two (cc-switch issue #3036). The entry `type` names
20
+ * the metered resource: `CREDIT_LIMIT` on the v3 coding plans
21
+ * (usage/currentValue/remaining credits), `TOKENS_LIMIT` on the older
22
+ * ones — the window fields and classification are identical either way.
23
+ * The used share comes from the credit totals when they are present —
24
+ * `max(usage - remaining, currentValue) / usage`, the console's own
25
+ * arithmetic — with `percentage` as the fallback; a share NEITHER source
26
+ * can produce is an unpaintable window, skipped rather than fabricated
27
+ * as 0% used. `nextResetTime` is epoch ms; `data.level` names the plan
28
+ * tier. Tolerances cc-switch learned in the wild: the `type` comparison
29
+ * is case-insensitive (upstream has been observed casing it differently),
30
+ * and an HTTP-200 `success: false` + `msg` envelope is a business error,
31
+ * not a payload to dig into.
32
+ *
33
+ * @module token-usage/quota/adapters/zhipu
34
+ */
35
+ import { fetchJson, hostOf, numberOf } from "../http.js";
36
+ import { QuotaQueryError } from "../types.js";
37
+ /** Domestic (open.bigmodel.cn) quota host; the international station mirrors the shape. */
38
+ const DOMESTIC_QUOTA_BASE = 'https://open.bigmodel.cn';
39
+ /** International (api.z.ai) quota host. */
40
+ const INTERNATIONAL_QUOTA_BASE = 'https://api.z.ai';
41
+ /** The quota monitor path, identical on both stations. */
42
+ const QUOTA_PATH = '/api/monitor/usage/quota/limit';
43
+ /** pi-ai catalog route of the domestic coding plan; the international one is `zai`. */
44
+ const ROUTE_CODING_CN = 'zai-coding-cn';
45
+ const ROUTE_ZAI = 'zai';
46
+ /** The `unit` vocabulary of `data.limits[]`: 3 is the 5-hour window, 6 the
47
+ * weekly one (observed as 6/7 and 6/1 in the wild; the primary value
48
+ * decides). */
49
+ const UNIT_FIVE_HOUR = 3;
50
+ const UNIT_WEEKLY = 6;
51
+ /** A billing month and longer: window lengths past this read monthly. */
52
+ const WEEKLY_MAX_MINUTES = 13 * 24 * 60;
53
+ /** Window length in minutes from the (unit, number) pair, or undefined
54
+ * when either side is missing/unusable. The table is shared with
55
+ * token-monitor's zai reader: 1 = days, 3 = hours, 5 = minutes, 6 = weeks. */
56
+ function windowMinutesOf(unit, count) {
57
+ if (unit === undefined || count === undefined || count <= 0)
58
+ return undefined;
59
+ if (unit === 5)
60
+ return count;
61
+ if (unit === UNIT_FIVE_HOUR)
62
+ return count * 60;
63
+ if (unit === 1)
64
+ return count * 24 * 60;
65
+ if (unit === UNIT_WEEKLY)
66
+ return count * 7 * 24 * 60;
67
+ return undefined;
68
+ }
69
+ /** Which window tier a limit entry belongs to, or undefined when the
70
+ * entry carries no computable classification (the reset-time heuristic
71
+ * takes those). */
72
+ function tierOf(unit, minutes) {
73
+ if (minutes !== undefined) {
74
+ if (minutes <= 360)
75
+ return 'five_hour';
76
+ // Unit 6 names the weekly bucket however its number reads — 6/7 was
77
+ // observed serving the weekly window, not seven weeks of it.
78
+ if (unit === UNIT_WEEKLY)
79
+ return 'weekly';
80
+ return minutes <= WEEKLY_MAX_MINUTES ? 'weekly' : 'monthly';
81
+ }
82
+ if (unit === UNIT_FIVE_HOUR)
83
+ return 'five_hour';
84
+ if (unit === UNIT_WEEKLY)
85
+ return 'weekly';
86
+ return undefined;
87
+ }
88
+ /** The used share of one limit entry. The credit totals are the primary
89
+ * source — `max(usage - remaining, currentValue) / usage`, the console's
90
+ * own arithmetic — and the explicit `percentage` is the fallback; a share
91
+ * neither source can produce reads as undefined (an unpaintable window),
92
+ * never as a fabricated 0%. */
93
+ function usedPercentOf(limit) {
94
+ const total = numberOf(limit.usage);
95
+ if (total !== undefined && total > 0) {
96
+ const remaining = numberOf(limit.remaining);
97
+ const current = numberOf(limit.currentValue);
98
+ let used;
99
+ if (remaining !== undefined) {
100
+ const fromRemaining = total - remaining;
101
+ used = current === undefined ? fromRemaining : Math.max(fromRemaining, current);
102
+ }
103
+ else if (current !== undefined) {
104
+ used = current;
105
+ }
106
+ if (used !== undefined) {
107
+ const clamped = Math.min(Math.max(used, 0), total);
108
+ return (clamped / total) * 100;
109
+ }
110
+ }
111
+ return numberOf(limit.percentage);
112
+ }
113
+ /** The limit-entry `type` vocabulary: which resource a window meters. The
114
+ * v3 coding plans answer `CREDIT_LIMIT` (usage/currentValue/remaining
115
+ * credits); the older TOKENS_LIMIT shape carries identical window fields,
116
+ * so both classify the same way. Cased variants land through the
117
+ * case-insensitive compare below. */
118
+ const KNOWN_LIMIT_TYPES = new Set(['TOKENS_LIMIT', 'CREDIT_LIMIT']);
119
+ /** Whether the base-URL host (or the route key) marks the international station. */
120
+ function isInternational(input) {
121
+ if (input.provider === ROUTE_ZAI)
122
+ return true;
123
+ const host = hostOf(input.baseUrl);
124
+ return host === 'api.z.ai' || (host?.endsWith('.z.ai') ?? false);
125
+ }
126
+ /** The quota host of the station this route resolves to. */
127
+ function quotaBase(input) {
128
+ return isInternational(input) ? INTERNATIONAL_QUOTA_BASE : DOMESTIC_QUOTA_BASE;
129
+ }
130
+ /** The Zhipu GLM coding-plan adapter: 5-hour + weekly windows. */
131
+ export const zhipuAdapter = {
132
+ id: 'zhipu-coding-plan',
133
+ label: 'Zhipu GLM Coding Plan',
134
+ routes: [ROUTE_CODING_CN, ROUTE_ZAI],
135
+ matches(input) {
136
+ if (input.provider === ROUTE_CODING_CN || input.provider === ROUTE_ZAI)
137
+ return true;
138
+ const host = hostOf(input.baseUrl);
139
+ // bigmodel.cn covers open.bigmodel.cn and the api subdomains; z.ai the
140
+ // international station. Host match is what catches user-declared
141
+ // routes pointing at the same endpoints under a custom name.
142
+ return host !== undefined
143
+ && (host === 'bigmodel.cn' || host.endsWith('.bigmodel.cn') || host === 'z.ai' || host.endsWith('.z.ai'));
144
+ },
145
+ async query(ctx) {
146
+ // No Bearer prefix — see the module note. The content-type and
147
+ // accept-language headers mirror cc-switch's request byte for byte.
148
+ const body = await fetchJson(ctx, quotaBase(ctx) + QUOTA_PATH, {
149
+ authorization: ctx.apiKey,
150
+ 'content-type': 'application/json',
151
+ 'accept-language': 'en-US,en',
152
+ });
153
+ if (typeof body !== 'object' || body === null) {
154
+ throw new QuotaQueryError('parse', 'missing "data" object');
155
+ }
156
+ const envelope = body;
157
+ // Business error: HTTP 200 with success:false carries the cause in
158
+ // "msg" (the anonymous-auth envelope has this shape, for one).
159
+ if (envelope.success === false) {
160
+ const msg = typeof envelope.msg === 'string' && envelope.msg !== '' ? envelope.msg : 'unknown error';
161
+ throw new QuotaQueryError('http', `API error: ${msg}`);
162
+ }
163
+ const data = envelope.data;
164
+ if (typeof data !== 'object' || data === null) {
165
+ throw new QuotaQueryError('parse', 'missing "data" object');
166
+ }
167
+ const record = data;
168
+ if (!Array.isArray(record.limits)) {
169
+ throw new QuotaQueryError('parse', 'missing "data.limits" array');
170
+ }
171
+ // Classify each limit to its window tier — by the (unit, number)
172
+ // length first, by the bare unit kind when the number is missing —
173
+ // with the first entry of a tier winning and later duplicates of a
174
+ // filled tier dropped (a surplus bucket never masquerades as another
175
+ // tier). Entries with no computable tier keep to the tail for the
176
+ // reset-time heuristic old plans need.
177
+ let fiveHour;
178
+ let weekly;
179
+ let monthly;
180
+ const unclassified = [];
181
+ const observedTypes = [];
182
+ for (const raw of record.limits) {
183
+ if (typeof raw !== 'object' || raw === null)
184
+ continue;
185
+ const limit = raw;
186
+ if (typeof limit.type === 'string')
187
+ observedTypes.push(limit.type);
188
+ // Case-insensitive across the known vocabulary (upstream has been
189
+ // observed casing it differently); a MISSING type still counts (old
190
+ // plans predate the field).
191
+ if (limit.type !== undefined && !KNOWN_LIMIT_TYPES.has(String(limit.type).toUpperCase()))
192
+ continue;
193
+ const usedPercent = usedPercentOf(limit);
194
+ // An unpaintable window — no totals to back-compute the share from,
195
+ // no `percentage` either — is skipped, not painted as 0% used.
196
+ if (usedPercent === undefined)
197
+ continue;
198
+ const resetAt = numberOf(limit.nextResetTime);
199
+ const window = {
200
+ tier: 'five_hour',
201
+ usedPercent,
202
+ ...(resetAt !== undefined ? { resetAt } : {}),
203
+ };
204
+ const unit = numberOf(limit.unit);
205
+ const tier = tierOf(unit, windowMinutesOf(unit, numberOf(limit.number)));
206
+ if (tier === 'five_hour' && fiveHour === undefined)
207
+ fiveHour = window;
208
+ else if (tier === 'weekly' && weekly === undefined)
209
+ weekly = { ...window, tier: 'weekly' };
210
+ else if (tier === 'monthly' && monthly === undefined)
211
+ monthly = { ...window, tier: 'monthly' };
212
+ else if (tier === undefined)
213
+ unclassified.push(window);
214
+ }
215
+ // Heuristic fallback for limits without a computable tier: entries
216
+ // without a reset first (a 0%-state 5-hour bucket may carry none),
217
+ // then ascending reset time filling whichever slot is still empty.
218
+ // The unit field exists precisely because time sorting alone swaps
219
+ // the two at a period's end; tier-less payloads are the single-window
220
+ // old plans, where the order is trivial.
221
+ unclassified.sort((a, b) => (a.resetAt ?? 0) - (b.resetAt ?? 0));
222
+ for (const window of unclassified) {
223
+ if (fiveHour === undefined)
224
+ fiveHour = window;
225
+ else if (weekly === undefined)
226
+ weekly = { ...window, tier: 'weekly' };
227
+ }
228
+ const windows = [];
229
+ if (fiveHour !== undefined)
230
+ windows.push(fiveHour);
231
+ if (weekly !== undefined)
232
+ windows.push(weekly);
233
+ if (monthly !== undefined)
234
+ windows.push(monthly);
235
+ if (windows.length === 0) {
236
+ const seen = observedTypes.length > 0 ? ` (types: ${observedTypes.join(', ')})` : '';
237
+ throw new QuotaQueryError('parse', `no TOKENS_LIMIT/CREDIT_LIMIT windows in "data.limits"${seen}`);
238
+ }
239
+ const level = record.level;
240
+ return {
241
+ windows,
242
+ ...(typeof level === 'string' && level !== '' ? { planTier: level } : {}),
243
+ };
244
+ },
245
+ };
246
+ //# sourceMappingURL=zhipu.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"zhipu.js","sourceRoot":"","sources":["../../../src/quota/adapters/zhipu.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AAGH,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAA;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAG7C,2FAA2F;AAC3F,MAAM,mBAAmB,GAAG,0BAA0B,CAAA;AACtD,2CAA2C;AAC3C,MAAM,wBAAwB,GAAG,kBAAkB,CAAA;AACnD,0DAA0D;AAC1D,MAAM,UAAU,GAAG,gCAAgC,CAAA;A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YACP,GAAG,CAAC,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC1E,CAAA;IACH,CAAC;CACF,CAAA"}
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Provider credential + base-URL resolution (node half): the chain that
3
+ * turns a provider ROUTE KEY into the material a quota adapter needs.
4
+ *
5
+ * The llm service never exposes keys or base URLs by design, so the chain
6
+ * reads them from where the adapters themselves read them:
7
+ * 1. the provider directory (`ctx.llm.listConfigurableProviders()`) maps a
8
+ * route to its settings namespace + path — with a built-in fallback for
9
+ * the two known shapes (pi-ai routes → `llm-pi-ai` `providers.<route>`;
10
+ * `deepseek-official` → the whole `llm-deepseek` section);
11
+ * 2. the settings section at that path carries the profile
12
+ * (`{ apiKeyEnv, baseURL, … }`) — `apiKeyEnv` is a credential
13
+ * REFERENCE (an environment-variable name), never a value;
14
+ * 3. the key resolves through the credentials seam (`credentials.resolve`),
15
+ * then a feature-detected `llm-pi-ai/<route>` record (newer hosts store
16
+ * the key the settings UI captured there), then the process env. The
17
+ * default env name comes from the profile, else pi-ai's per-route
18
+ * convention (`zai-coding-cn` → `ZAI_CODING_CN_API_KEY`, generic
19
+ * uppercase-dash-to-underscore otherwise).
20
+ *
21
+ * The base URL is the profile's `baseURL` override, else the built-in
22
+ * catalog default for the known coding-plan routes — enough for host
23
+ * matching (station choice) even though quota endpoints stay fixed.
24
+ *
25
+ * @module token-usage/quota/credentials
26
+ */
27
+ /** Where a provider's profile lives in the settings document. */
28
+ export interface ProviderDirectoryEntry {
29
+ settingsNs: string;
30
+ settingsPath: readonly string[];
31
+ displayName?: string;
32
+ }
33
+ /** The resolvable material of one provider route. */
34
+ export interface ResolvedQuotaCredentials {
35
+ /** The API key, or undefined when no configured source holds one. */
36
+ apiKey?: string;
37
+ /** The env-variable name the key was expected under (diagnostics). */
38
+ apiKeyEnv?: string;
39
+ /** Inference base URL when one is resolvable (override or catalog). */
40
+ baseUrl?: string;
41
+ /** Human-readable provider name when one is resolvable. */
42
+ displayName?: string;
43
+ }
44
+ /** Directory thunk: route key → its settings location (host llm service
45
+ * backed); undefined when the route is unknown to the directory. */
46
+ export type ProviderDirectory = (provider: string) => ProviderDirectoryEntry | undefined;
47
+ /** Settings read thunk: namespace → resolved section value (unknown shape). */
48
+ export type SettingsReader = (ns: string) => unknown;
49
+ /** Credential seam: an env-var reference → its value, if configured. */
50
+ export type CredentialResolver = (ref: string) => Promise<string | undefined>;
51
+ /** Record-store seam (feature-detected, newer hosts only): a
52
+ * `scope/provider` record key → its api-key material, if stored. */
53
+ export type CredentialRecordReader = (key: string) => Promise<{
54
+ key?: string;
55
+ } | undefined>;
56
+ /**
57
+ * Resolve one provider route's quota credentials.
58
+ * @param input - the route and the three seams (each optional; a missing
59
+ * seam simply shortens the chain).
60
+ * @returns the key material found and the resolvable base URL / name.
61
+ */
62
+ export declare function resolveQuotaCredentials(input: {
63
+ provider: string;
64
+ directory?: ProviderDirectory;
65
+ readSettings: SettingsReader;
66
+ resolveCredential?: CredentialResolver;
67
+ readRecord?: CredentialRecordReader;
68
+ }): Promise<ResolvedQuotaCredentials>;
69
+ /**
70
+ * Layer the catalog default base URL under a resolution that found none —
71
+ * the known coding-plan routes' catalog endpoints, so host-based adapter
72
+ * matching works even when the profile omits `baseURL` (the common case:
73
+ * pi-ai inherits the catalog silently).
74
+ * @param provider - the route key.
75
+ * @param resolved - the credential resolution (its `baseUrl` wins).
76
+ * @returns the resolution with a catalog fallback base URL filled in.
77
+ */
78
+ export declare function withCatalogBaseUrl(provider: string, resolved: ResolvedQuotaCredentials): ResolvedQuotaCredentials;
79
+ //# sourceMappingURL=credentials.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credentials.d.ts","sourceRoot":"","sources":["../../src/quota/credentials.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;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AQ,EAAE,wBAAwB,GACjC,wBAAwB,CAK1B"}
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Provider credential + base-URL resolution (node half): the chain that
3
+ * turns a provider ROUTE KEY into the material a quota adapter needs.
4
+ *
5
+ * The llm service never exposes keys or base URLs by design, so the chain
6
+ * reads them from where the adapters themselves read them:
7
+ * 1. the provider directory (`ctx.llm.listConfigurableProviders()`) maps a
8
+ * route to its settings namespace + path — with a built-in fallback for
9
+ * the two known shapes (pi-ai routes → `llm-pi-ai` `providers.<route>`;
10
+ * `deepseek-official` → the whole `llm-deepseek` section);
11
+ * 2. the settings section at that path carries the profile
12
+ * (`{ apiKeyEnv, baseURL, … }`) — `apiKeyEnv` is a credential
13
+ * REFERENCE (an environment-variable name), never a value;
14
+ * 3. the key resolves through the credentials seam (`credentials.resolve`),
15
+ * then a feature-detected `llm-pi-ai/<route>` record (newer hosts store
16
+ * the key the settings UI captured there), then the process env. The
17
+ * default env name comes from the profile, else pi-ai's per-route
18
+ * convention (`zai-coding-cn` → `ZAI_CODING_CN_API_KEY`, generic
19
+ * uppercase-dash-to-underscore otherwise).
20
+ *
21
+ * The base URL is the profile's `baseURL` override, else the built-in
22
+ * catalog default for the known coding-plan routes — enough for host
23
+ * matching (station choice) even though quota endpoints stay fixed.
24
+ *
25
+ * @module token-usage/quota/credentials
26
+ */
27
+ /** The built-in directory fallback for the two known settings shapes. */
28
+ const BUILTIN_DIRECTORY = {
29
+ 'deepseek-official': { settingsNs: 'llm-deepseek', settingsPath: [] },
30
+ };
31
+ /** pi-ai route → default credential record key (`llm-pi-ai/<route>`). */
32
+ function recordKeyOf(provider) {
33
+ return `llm-pi-ai/${provider}`;
34
+ }
35
+ /** pi-ai's per-route env-var convention for the routes we ship adapters
36
+ * for; the generic mangling below covers everything else. */
37
+ const KNOWN_ENV_NAMES = {
38
+ 'zai-coding-cn': 'ZAI_CODING_CN_API_KEY',
39
+ zai: 'ZAI_API_KEY',
40
+ 'kimi-coding': 'KIMI_API_KEY',
41
+ 'opencode-go': 'OPENCODE_API_KEY',
42
+ openrouter: 'OPENROUTER_API_KEY',
43
+ };
44
+ /** The generic env-name convention pi-ai applies: uppercase, every
45
+ * non-alphanumeric run → `_` (`my-gateway` → `MY_GATEWAY_API_KEY`). */
46
+ function defaultEnvNameOf(provider) {
47
+ return `${provider.toUpperCase().replace(/[^A-Z0-9]+/gu, '_')}_API_KEY`;
48
+ }
49
+ /** The catalog base URLs of routes whose profiles carry no `baseURL` —
50
+ * the inference endpoints the pi-ai catalog ships; quota adapters only
51
+ * ever read the HOST off these. */
52
+ const CATALOG_BASE_URLS = {
53
+ 'zai-coding-cn': 'https://open.bigmodel.cn/api/coding/paas/v4',
54
+ zai: 'https://api.z.ai/api/paas/v4',
55
+ 'kimi-coding': 'https://api.kimi.com/coding/v1',
56
+ minimax: 'https://api.minimax.io/v1',
57
+ 'minimax-cn': 'https://api.minimaxi.com/v1',
58
+ 'opencode-go': 'https://opencode.ai/zen/go/v1',
59
+ };
60
+ /** Walk a settings section along a path; undefined as soon as a hop is
61
+ * not an object holding the next key. */
62
+ function walkPath(section, path) {
63
+ let current = section;
64
+ for (const key of path) {
65
+ if (typeof current !== 'object' || current === null)
66
+ return undefined;
67
+ current = current[key];
68
+ }
69
+ return current;
70
+ }
71
+ /** A string field off an unknown-shaped profile. */
72
+ function stringField(value) {
73
+ return typeof value === 'string' && value !== '' ? value : undefined;
74
+ }
75
+ /**
76
+ * Resolve one provider route's quota credentials.
77
+ * @param input - the route and the three seams (each optional; a missing
78
+ * seam simply shortens the chain).
79
+ * @returns the key material found and the resolvable base URL / name.
80
+ */
81
+ export async function resolveQuotaCredentials(input) {
82
+ const { provider } = input;
83
+ // Directory entry: the host's llm service when injected, else the
84
+ // built-in shapes (every non-deepseek route is a pi-ai settings dict key).
85
+ const entry = input.directory?.(provider)
86
+ ?? BUILTIN_DIRECTORY[provider]
87
+ ?? { settingsNs: 'llm-pi-ai', settingsPath: ['providers', provider] };
88
+ const profile = walkPath(input.readSettings(entry.settingsNs), entry.settingsPath);
89
+ const record = typeof profile === 'object' && profile !== null ? profile : {};
90
+ const apiKeyEnv = stringField(record.apiKeyEnv);
91
+ const baseURL = stringField(record.baseURL);
92
+ const ref = apiKeyEnv ?? KNOWN_ENV_NAMES[provider] ?? defaultEnvNameOf(provider);
93
+ // Chain: credentials seam → pi-ai record store → process env. Each
94
+ // layer is per-call by contract; no layer caches across queries.
95
+ let apiKey;
96
+ if (input.resolveCredential !== undefined) {
97
+ apiKey = await input.resolveCredential(ref);
98
+ }
99
+ if (apiKey === undefined && input.readRecord !== undefined) {
100
+ const stored = await input.readRecord(recordKeyOf(provider));
101
+ apiKey = stringField(stored?.key);
102
+ }
103
+ if (apiKey === undefined) {
104
+ apiKey = stringField(process.env[ref]);
105
+ }
106
+ return {
107
+ ...(apiKey !== undefined ? { apiKey } : {}),
108
+ apiKeyEnv: ref,
109
+ ...(baseURL !== undefined ? { baseUrl: baseURL } : {}),
110
+ ...(entry.displayName !== undefined ? { displayName: entry.displayName } : {}),
111
+ };
112
+ }
113
+ /**
114
+ * Layer the catalog default base URL under a resolution that found none —
115
+ * the known coding-plan routes' catalog endpoints, so host-based adapter
116
+ * matching works even when the profile omits `baseURL` (the common case:
117
+ * pi-ai inherits the catalog silently).
118
+ * @param provider - the route key.
119
+ * @param resolved - the credential resolution (its `baseUrl` wins).
120
+ * @returns the resolution with a catalog fallback base URL filled in.
121
+ */
122
+ export function withCatalogBaseUrl(provider, resolved) {
123
+ if (resolved.baseUrl !== undefined)
124
+ return resolved;
125
+ const fallback = CATALOG_BASE_URLS[provider];
126
+ if (fallback === undefined)
127
+ return resolved;
128
+ return { ...resolved, baseUrl: fallback };
129
+ }
130
+ //# sourceMappingURL=credentials.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credentials.js","sourceRoot":"","sources":["../../src/quota/credentials.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAmCH,yEAAyE;AACz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G,WAAW,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IACnC,CAAC;IACD,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;QACzB,MAAM,GAAG,WAAW,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAA;IACxC,CAAC;IAED,OAAO;QACL,GAAG,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC3C,SAAS,EAAE,GAAG;QACd,GAAG,CAAC,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACtD,GAAG,CAAC,KAAK,CAAC,WAAW,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,KAAK,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAC/E,CAAA;AACH,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,kBAAkB,CAChC,QAAgB,EAChB,QAAkC;IAElC,IAAI,QAAQ,CAAC,OAAO,KAAK,SAAS;QAAE,OAAO,QAAQ,CAAA;IACnD,MAAM,QAAQ,GAAG,iBAAiB,CAAC,QAAQ,CAAC,CAAA;IAC5C,IAAI,QAAQ,KAAK,SAAS;QAAE,OAAO,QAAQ,CAAA;IAC3C,OAAO,EAAE,GAAG,QAAQ,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAA;AAC3C,CAAC"}
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Shared transport helpers of the quota adapters (node half): one JSON GET
3
+ * that normalizes every failure mode into {@link QuotaQueryError} with the
4
+ * wire's error kind, plus small parsing utilities (host extraction,
5
+ * epoch-ms normalization) every adapter repeats.
6
+ *
7
+ * @module token-usage/quota/http
8
+ */
9
+ import type { QuotaQueryContext } from './types.ts';
10
+ /**
11
+ * GET one URL and parse the JSON body, normalizing failures: 401/403 →
12
+ * `auth`, other non-2xx → `http`, transport errors (DNS, timeout, abort)
13
+ * → `network`, a body that is not JSON → `parse`. Adapters therefore only
14
+ * throw shape-validation errors of their own.
15
+ * @param ctx - the query context (transport, auth header material, signal).
16
+ * @param url - the absolute quota endpoint.
17
+ * @param headers - extra request headers (most adapters pass Authorization).
18
+ * @returns the parsed body.
19
+ */
20
+ export declare function fetchJson(ctx: QuotaQueryContext, url: string, headers?: Record<string, string>): Promise<unknown>;
21
+ /** Read a required object field or fail with the normalized parse error. */
22
+ export declare function requireObject(value: unknown, field: string): Record<string, unknown>;
23
+ /** Read a required array field or fail with the normalized parse error. */
24
+ export declare function requireArray(value: unknown, field: string): unknown[];
25
+ /** A finite non-negative number off a JSON value, else undefined. */
26
+ export declare function numberOf(value: unknown): number | undefined;
27
+ /**
28
+ * A money/credit amount off a JSON value: a finite number, or the string
29
+ * form providers actually serialize (DeepSeek and OpenRouter ship `"110.00"`
30
+ * strings), with EITHER sign — a pay-as-you-go account can overdraft
31
+ * (DeepSeek answers `total_balance: "-0.01"`). Everything else, including
32
+ * blank strings, reads undefined.
33
+ */
34
+ export declare function amountOf(value: unknown): number | undefined;
35
+ /**
36
+ * Normalize a provider timestamp to epoch ms. Providers mix units (MiniMax
37
+ * documents ms, some hand-rolled gateways answer seconds); an absolute
38
+ * epoch in seconds is ≤ ~1.1e10 while the ms form is ≥ 1e12, so anything
39
+ * below the seconds ceiling is re-scaled. Values that fit neither an
40
+ * absolute epoch shape pass through unchanged (the caller clamps).
41
+ */
42
+ export declare function toEpochMs(value: unknown): number | undefined;
43
+ /**
44
+ * The lowercase hostname of a base URL, or undefined when the string is
45
+ * blank or unparseable — adapters match hosts, never full URLs, because
46
+ * the path spelling differs between the inference and quota endpoints.
47
+ */
48
+ export declare function hostOf(baseUrl: string | undefined): string | undefined;
49
+ //# sourceMappingURL=http.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../../src/quota/http.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AAGnD;;;;;;;;;GASG;AACH,wBAAsB,SAAS,CAAC,GAAG,EAAE,iBAAiB,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,GAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAwB3H;AAED,4EAA4E;AAC5E,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAMpF;AAED,2EAA2E;AAC3E,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,EAAE,CAMrE;AAED,qEAAqE;AACrE,wBAAgB,QAAQ,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAG3D;AAED;;;;;;GAMG;AACH,wBAAgB,QAAQ,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAO3D;AAED;;;;;;GAMG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAI5D;AAED;;;;GAIG;AACH,wBAAgB,MAAM,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAQtE"}
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Shared transport helpers of the quota adapters (node half): one JSON GET
3
+ * that normalizes every failure mode into {@link QuotaQueryError} with the
4
+ * wire's error kind, plus small parsing utilities (host extraction,
5
+ * epoch-ms normalization) every adapter repeats.
6
+ *
7
+ * @module token-usage/quota/http
8
+ */
9
+ import { QuotaQueryError } from "./types.js";
10
+ /**
11
+ * GET one URL and parse the JSON body, normalizing failures: 401/403 →
12
+ * `auth`, other non-2xx → `http`, transport errors (DNS, timeout, abort)
13
+ * → `network`, a body that is not JSON → `parse`. Adapters therefore only
14
+ * throw shape-validation errors of their own.
15
+ * @param ctx - the query context (transport, auth header material, signal).
16
+ * @param url - the absolute quota endpoint.
17
+ * @param headers - extra request headers (most adapters pass Authorization).
18
+ * @returns the parsed body.
19
+ */
20
+ export async function fetchJson(ctx, url, headers = {}) {
21
+ let response;
22
+ try {
23
+ response = await ctx.fetchFn(url, {
24
+ method: 'GET',
25
+ headers: { accept: 'application/json', ...headers },
26
+ ...(ctx.signal !== undefined ? { signal: ctx.signal } : {}),
27
+ });
28
+ }
29
+ catch (error) {
30
+ // Abort/timeout arrives here too — the query is dead either way, and
31
+ // the message is the only distinguishing detail worth keeping.
32
+ throw new QuotaQueryError('network', error instanceof Error ? error.message : String(error));
33
+ }
34
+ if (response.status === 401 || response.status === 403) {
35
+ throw new QuotaQueryError('auth', `HTTP ${String(response.status)}`);
36
+ }
37
+ if (!response.ok) {
38
+ throw new QuotaQueryError('http', `HTTP ${String(response.status)}`);
39
+ }
40
+ try {
41
+ return await response.json();
42
+ }
43
+ catch (error) {
44
+ throw new QuotaQueryError('parse', error instanceof Error ? error.message : String(error));
45
+ }
46
+ }
47
+ /** Read a required object field or fail with the normalized parse error. */
48
+ export function requireObject(value, field) {
49
+ const inner = value instanceof Object ? value[field] : undefined;
50
+ if (typeof inner !== 'object' || inner === null) {
51
+ throw new QuotaQueryError('parse', `missing "${field}" object`);
52
+ }
53
+ return inner;
54
+ }
55
+ /** Read a required array field or fail with the normalized parse error. */
56
+ export function requireArray(value, field) {
57
+ const inner = value instanceof Object ? value[field] : undefined;
58
+ if (!Array.isArray(inner)) {
59
+ throw new QuotaQueryError('parse', `missing "${field}" array`);
60
+ }
61
+ return inner;
62
+ }
63
+ /** A finite non-negative number off a JSON value, else undefined. */
64
+ export function numberOf(value) {
65
+ if (typeof value === 'number' && Number.isFinite(value) && value >= 0)
66
+ return value;
67
+ return undefined;
68
+ }
69
+ /**
70
+ * A money/credit amount off a JSON value: a finite number, or the string
71
+ * form providers actually serialize (DeepSeek and OpenRouter ship `"110.00"`
72
+ * strings), with EITHER sign — a pay-as-you-go account can overdraft
73
+ * (DeepSeek answers `total_balance: "-0.01"`). Everything else, including
74
+ * blank strings, reads undefined.
75
+ */
76
+ export function amountOf(value) {
77
+ if (typeof value === 'number')
78
+ return Number.isFinite(value) ? value : undefined;
79
+ if (typeof value === 'string' && value.trim() !== '') {
80
+ const parsed = Number(value);
81
+ return Number.isFinite(parsed) ? parsed : undefined;
82
+ }
83
+ return undefined;
84
+ }
85
+ /**
86
+ * Normalize a provider timestamp to epoch ms. Providers mix units (MiniMax
87
+ * documents ms, some hand-rolled gateways answer seconds); an absolute
88
+ * epoch in seconds is ≤ ~1.1e10 while the ms form is ≥ 1e12, so anything
89
+ * below the seconds ceiling is re-scaled. Values that fit neither an
90
+ * absolute epoch shape pass through unchanged (the caller clamps).
91
+ */
92
+ export function toEpochMs(value) {
93
+ const n = numberOf(value);
94
+ if (n === undefined || n <= 0)
95
+ return undefined;
96
+ return n < 1e11 ? n * 1000 : n;
97
+ }
98
+ /**
99
+ * The lowercase hostname of a base URL, or undefined when the string is
100
+ * blank or unparseable — adapters match hosts, never full URLs, because
101
+ * the path spelling differs between the inference and quota endpoints.
102
+ */
103
+ export function hostOf(baseUrl) {
104
+ if (baseUrl === undefined || baseUrl === '')
105
+ return undefined;
106
+ try {
107
+ const host = new URL(baseUrl).hostname.toLowerCase();
108
+ return host === '' ? undefined : host;
109
+ }
110
+ catch {
111
+ return undefined;
112
+ }
113
+ }
114
+ //# sourceMappingURL=http.js.map