@huaqiu/dsh-auth 0.6.21 → 0.6.22

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.
@@ -30,7 +30,7 @@
30
30
  import { memo, useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore, type CSSProperties } from 'react'
31
31
  import { createPortal } from 'react-dom'
32
32
  import { getAuth, getAuthState, getHqEdge, setProfile, subscribeAuth } from '../auth-state.js'
33
- import { buildProfileUrl, ERC_PRODUCT_CODE, GEN_PRODUCT_CODE, type AiTokenUsage, type SubscriptionQuota } from '../lib.js'
33
+ import { buildProfileUrl, ERC_PRODUCT_CODE, GEN_PRODUCT_CODE, type AiUsage, type SubscriptionQuota } from '../lib.js'
34
34
  import { useIsDark, useLocale } from '../ui-env.js'
35
35
  import { useT, type Translate } from '../i18n.js'
36
36
  import { HQ_ICON } from './hq-icon.jsx'
@@ -546,36 +546,19 @@ export function quotaReading(quota: SubscriptionQuota | null, t: Translate): Met
546
546
  }
547
547
 
548
548
  /**
549
- * AI token reading from `/user-rest/api/ai/usage`.
549
+ * AI reading from the subscription-balances AI Points group.
550
550
  *
551
- * The headline number is the AVAILABLE (remaining) balance, not the consumed
552
- * one — the same convention as the GEN/ERC cards beside it, which display
553
- * `currentQuota` (the REMAINING quota: hq-edge exposes it as
554
- * `availableQuota`/"Available Quota", hq-eda-ai as `remainingQuota`). Showing
555
- * `usedPoints` here made the AI card the only surface in the product that
556
- * reported consumption as the balance: an account that burned 77 of its 100
557
- * points read "77 / 100 pts" where the user expects "23 / 100 pts".
558
- *
559
- * The balance is reported as `usedPoints` + `availablePoints`, so the total is
560
- * their sum — there is no separate `totalPoints` field to read. Percent keeps
561
- * one decimal: a fresh account has well over 99% of its balance left, and
562
- * rounding 99.6% up to "100%" would read as an exhausted account.
551
+ * The percentage is the upstream `quotaRemainPercent` — the REMAINING share —
552
+ * passed through unchanged: no local ratio and no re-rounding, so `99.68`
553
+ * renders as `99.68%`. A missing / `null` / non-finite value is unavailable
554
+ * (the card shows「—」); the bar clamps to 0–100 while the label does not.
563
555
  */
564
- export function aiUsageReading(usage: AiTokenUsage | null, t: Translate): MetricReading | null {
565
- if (!usage) return null
566
- const used = Math.max(0, usage.usedPoints)
567
- const available = Math.max(0, usage.availablePoints)
568
- const total = used + available
569
- const percent = total > 0
570
- ? Math.min(100, Math.round((available / total) * 1000) / 10)
571
- : 0
572
- // Headline shows the usage percent (e.g. "65%"); the exact
573
- // "{available} / {total} pts" balance is preserved as the hover title.
574
- const displayPercent = Math.round(percent)
556
+ export function aiUsageReading(usage: AiUsage | null, t: Translate): MetricReading | null {
557
+ const percent = usage?.quotaRemainPercent
558
+ if (typeof percent !== 'number' || !Number.isFinite(percent)) return null
575
559
  return {
576
- value: t('subscription.aiUsagePercent', { percent: displayPercent }),
577
- title: t('subscription.aiUsageCount', { available, total }),
578
- percent,
560
+ value: t('subscription.aiUsagePercent', { percent }),
561
+ percent: Math.max(0, Math.min(100, percent)),
579
562
  ok: true,
580
563
  }
581
564
  }
@@ -739,7 +722,7 @@ export const HuaqiuAuthSidebarAction = memo(function HuaqiuAuthSidebarAction({ w
739
722
  const [menuStyle, setMenuStyle] = useState<CSSProperties | null>(null)
740
723
  const [avatarBroken, setAvatarBroken] = useState(false)
741
724
  const [hovered, setHovered] = useState(false)
742
- const [quota, setQuota] = useState<{ gen: SubscriptionQuota | null; erc: SubscriptionQuota | null; ai: AiTokenUsage | null } | null>(null)
725
+ const [quota, setQuota] = useState<{ gen: SubscriptionQuota | null; erc: SubscriptionQuota | null; ai: AiUsage | null } | null>(null)
743
726
  const [subscribing, setSubscribing] = useState(false)
744
727
  const triggerRef = useRef<HTMLButtonElement | null>(null)
745
728
  const menuRef = useRef<HTMLDivElement | null>(null)
@@ -796,10 +779,9 @@ export const HuaqiuAuthSidebarAction = memo(function HuaqiuAuthSidebarAction({ w
796
779
 
797
780
  // Live quota: EVERY time the menu opens (and every time the auth state
798
781
  // flips to authenticated) re-fetch the active subscription for GEN and ERC
799
- // DIRECTLY from eda.cn — the sidebar must never show a stale count. The AI
800
- // token balance rides the same pass (`/user-rest/api/ai/usage`, one GET, no
801
- // hq-edge hop), so all three metrics share one loading window instead of
802
- // three staggered ones.
782
+ // from the environment's subscription API, and the AI percentage from the
783
+ // node-proxied subscription balances. All three share one loading window
784
+ // instead of three staggered ones.
803
785
  useEffect(() => {
804
786
  if (!menuOpen || !authenticated) {
805
787
  if (!menuOpen) setQuota(null)
package/src/host.ts CHANGED
@@ -46,11 +46,11 @@ export interface HuaqiuAuthConfig {
46
46
  /** Seconds remote token-validation results are cached. Default 60. */
47
47
  validationTtlSeconds?: number
48
48
  /**
49
- * AI token-usage endpoint resolved by HQ Edge from `HQ_AI_ENV` (task
50
- * ai-env-swithcing-for-internal-test.md). Absent → `/ai-usage` returns null
51
- * instead of calling a stale/default endpoint.
49
+ * Subscription balances endpoint resolved by HQ Edge from `HQ_AI_ENV`
50
+ * (`GET /sub-api/subscriptions/balances/current`). Absent → `/ai-usage`
51
+ * returns null instead of calling a stale/default endpoint.
52
52
  */
53
- aiUsageUrl?: string
53
+ subscriptionBalancesUrl?: string
54
54
  /**
55
55
  * Subscription landing-page origin resolved by HQ Edge from the SAME
56
56
  * `HQ_AI_ENV`. Absent → the browser half keeps its standalone PROD default.
@@ -104,7 +104,11 @@ export function resolveHostConfig(
104
104
  // Resolved AI endpoints: overlay config (what HQ Edge injects) wins; explicit
105
105
  // env URLs are the standalone escape hatch. HQ_AI_ENV itself is NOT read here
106
106
  // — the prod/test mapping lives only in HQ Edge's central config.
107
- const aiUsageUrl = (config?.aiUsageUrl ?? env.HQ_AI_USAGE_URL ?? '').trim()
107
+ const subscriptionBalancesUrl = (
108
+ config?.subscriptionBalancesUrl
109
+ ?? env.HQ_AI_SUBSCRIPTION_BALANCES_URL
110
+ ?? ''
111
+ ).trim()
108
112
  const subscriptionOrigin = (config?.subscriptionOrigin ?? env.HQ_AI_SUBSCRIPTION_ORIGIN ?? '')
109
113
  .trim()
110
114
  .replace(/\/+$/, '')
@@ -115,7 +119,7 @@ export function resolveHostConfig(
115
119
  hostLogoutPath,
116
120
  hostSessionTtlSeconds: ttl,
117
121
  validationTtlSeconds,
118
- aiUsageUrl,
122
+ subscriptionBalancesUrl,
119
123
  subscriptionOrigin,
120
124
  }
121
125
  }
package/src/routes.ts CHANGED
@@ -5,9 +5,9 @@
5
5
  * POST /api/v1/huaqiu/auth/session body { token, userId, nickname?, expiresAt? } → cache set
6
6
  * POST /api/v1/huaqiu/auth/logout → cache cleared
7
7
  * GET /api/v1/huaqiu/auth/session → { authenticated, user }
8
- * GET /api/v1/huaqiu/auth/config → { hostMode }
8
+ * GET /api/v1/huaqiu/auth/config → { hostMode, subscriptionOrigin, subscriptionApiBaseUrl }
9
9
  * GET /api/v1/huaqiu/auth/user-info → { userInfo } (node-side eda.cn call)
10
- * GET /api/v1/huaqiu/auth/ai-usage → { usage } (node-side AI balance call)
10
+ * GET /api/v1/huaqiu/auth/ai-usage → { usage } (node-side subscription-balances call)
11
11
  *
12
12
  * `config` tells the browser half whether it is running under an HQ Edge host
13
13
  * (hq-edge passes the operator credential to hq-edge itself, so the sidebar
@@ -19,6 +19,7 @@
19
19
  import type { IncomingMessage, ServerResponse } from 'node:http'
20
20
  import { getLogger, type PluginLogger } from '@huaqiu/dsh-plugin-log'
21
21
  import type { HuaqiuAuthService, HuaqiuUserInfo } from './service.js'
22
+ import { aiUsageFromPayload, type AiUsage } from './subscription-balances.js'
22
23
 
23
24
  // Lazy so test suites that `vi.mock('@deepseek-ai/dsh-home-paths', …)` before
24
25
  // their TMP constant is initialised don't trigger `dshHomePath('logs')` at
@@ -75,82 +76,84 @@ export async function fetchEdaUserProfile(
75
76
 
76
77
  export const AUTH_ROUTE_PREFIX = '/api/v1/huaqiu/auth'
77
78
 
78
- // ── AI token usage (proxied by the node half) ────────────────────────────────
79
+ // ── Subscription balances / AI usage (proxied by the node half) ──────────────
79
80
 
80
81
  /**
81
- * The account's AI balance endpoint.
82
+ * The authoritative subscription-balances endpoint
83
+ * (`GET /sub-api/subscriptions/balances/current`).
82
84
  *
83
- * It is served over PLAIN `http`, which is why the node half must be the one to
84
- * call it: a WebView fetch is refused by App Transport Security ("the resource
85
- * could not be loaded because the App Transport Security policy requires the
86
- * use of a secure connection") and, independently, by CORS (the response sends
87
- * no `Access-Control-Allow-Origin`). Node's fetch is subject to neither, and
88
- * this process already talks to the same AI host for the Huaqiu gateway — so
89
- * the call is known to work from here. The endpoint is injected as resolved
90
- * config by HQ Edge (`HQ_AI_ENV`); this module has no hardcoded env URL.
85
+ * It may be served over PLAIN `http`, which is why the node half must be the one
86
+ * to call it: a WebView fetch is refused by App Transport Security ("the
87
+ * resource could not be loaded because the App Transport Security policy
88
+ * requires the use of a secure connection") and, independently, by CORS (the
89
+ * response sends no `Access-Control-Allow-Origin`). Node's fetch is subject to
90
+ * neither. The URL is injected as resolved config by HQ Edge (`HQ_AI_ENV`);
91
+ * this module has no hardcoded environment URL, and every payload is validated
92
+ * against the single schema in `./subscription-balances.js`.
91
93
  */
92
94
 
93
- /**
94
- * Normalized AI token usage — the `/user-rest/api/ai/usage` result.
95
- *
96
- * `points` is the account-level token balance (what the user thinks of as
97
- * "tokens"); `quota` is the same figure in the gateway's internal unit
98
- * (points × 50) and `usd` its money equivalent. All three pairs are reported
99
- * because the endpoint reports all three; the UI reads `points`.
100
- *
101
- * (Mirrored as a type-only declaration in `client/lib.ts` — the browser half
102
- * must not import node modules, and the two halves are built as separate
103
- * bundles.)
104
- */
105
- export interface AiTokenUsage {
106
- availablePoints: number
107
- availableQuota: number
108
- availableUsd: number
109
- usedPoints: number
110
- usedQuota: number
111
- usedUsd: number
95
+ /** Upstream budget for one balances call. */
96
+ export const AI_USAGE_TIMEOUT_MS = 10_000
97
+
98
+ /** Host-only label for diagnostics (never log the full URL or the token). */
99
+ function safeHost(url: string): string {
100
+ try {
101
+ return new URL(url).host
102
+ } catch {
103
+ return '<invalid-url>'
104
+ }
112
105
  }
113
106
 
114
107
  /**
115
- * Fetch the account's AI token usage for a token. Null on any failure (the UI
116
- * degrades to「—」) — never throws.
108
+ * Fetch and normalize AI usage for a token.
109
+ *
110
+ * `quotaRemainPercent` comes straight from the AI Points group — no local ratio
111
+ * is derived. `null` on any failure (invalid payload, timeout, network, non-2xx)
112
+ * so the UI degrades to「—」; never throws.
117
113
  *
118
- * The header is `X-Token` (capital T), which is what this endpoint expects; the
119
- * subscription endpoint next door uses `x-token` + `X-User-Id`.
114
+ * The upstream header is `X-Token` (capital T).
120
115
  */
121
- export async function fetchAiTokenUsage(
116
+ export async function fetchAiUsage(
122
117
  token: string,
123
- usageUrl: string,
118
+ subscriptionBalancesUrl: string,
124
119
  doFetch: typeof fetch = globalThis.fetch.bind(globalThis),
125
- ): Promise<AiTokenUsage | null> {
120
+ options: { signal?: AbortSignal; timeoutMs?: number } = {},
121
+ ): Promise<AiUsage | null> {
122
+ const timeoutMs = options.timeoutMs ?? AI_USAGE_TIMEOUT_MS
123
+ const controller = new AbortController()
124
+ const onAbort = () => controller.abort(options.signal?.reason)
125
+ if (options.signal) {
126
+ if (options.signal.aborted) controller.abort(options.signal.reason)
127
+ else options.signal.addEventListener('abort', onAbort, { once: true })
128
+ }
129
+ const timer = setTimeout(() => controller.abort(new Error('timeout')), timeoutMs)
130
+ const host = safeHost(subscriptionBalancesUrl)
126
131
  try {
127
- const res = await doFetch(usageUrl, {
132
+ const res = await doFetch(subscriptionBalancesUrl, {
128
133
  method: 'GET',
129
134
  headers: {
130
- Accept: 'application/json, text/plain, */*',
131
- 'Content-Type': 'application/json',
135
+ Accept: 'application/json',
136
+ 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
132
137
  'X-Token': token,
133
138
  },
139
+ signal: controller.signal,
134
140
  })
135
- if (!res.ok) return null
136
- const body = (await res.json()) as { code?: number; result?: Record<string, unknown> }
137
- if (body.code !== 200000 || !body.result) return null
138
- const result = body.result
139
- const num = (key: string): number => {
140
- const v = Number(result[key])
141
- return Number.isFinite(v) ? v : 0
142
- }
143
- return {
144
- availablePoints: num('availablePoints'),
145
- availableQuota: num('availableQuota'),
146
- availableUsd: num('availableUsd'),
147
- usedPoints: num('usedPoints'),
148
- usedQuota: num('usedQuota'),
149
- usedUsd: num('usedUsd'),
141
+ if (!res.ok) {
142
+ log().warn('subscription balances request failed', { host, status: res.status })
143
+ return null
150
144
  }
145
+ const usage = aiUsageFromPayload(await res.json())
146
+ if (!usage) log().warn('subscription balances payload unusable', { host })
147
+ return usage
151
148
  } catch (err) {
152
- log().warn('fetchAiTokenUsage failed', { error: String((err as Error)?.message || err) })
149
+ log().warn('subscription balances request failed', {
150
+ host,
151
+ error: String((err as Error)?.message || err),
152
+ })
153
153
  return null
154
+ } finally {
155
+ clearTimeout(timer)
156
+ options.signal?.removeEventListener('abort', onAbort)
154
157
  }
155
158
  }
156
159
 
@@ -234,6 +237,9 @@ export function createAuthHandler(service: HuaqiuAuthService): AuthHandler {
234
237
  sendJson(res, 200, {
235
238
  hostMode: service.hostMode,
236
239
  subscriptionOrigin: service.subscriptionOrigin,
240
+ // Origin of the resolved balances API — lets the browser build the
241
+ // GEN/ERC active-subscription calls without hardcoding eda.cn.
242
+ subscriptionApiBaseUrl: service.subscriptionApiBaseUrl,
237
243
  })
238
244
  return
239
245
  }
@@ -258,11 +264,25 @@ export function createAuthHandler(service: HuaqiuAuthService): AuthHandler {
258
264
  // resolved (host → pushed → persisted) — the same shape as /user-info
259
265
  // above. The URL itself is resolved by HQ Edge; absent → no call.
260
266
  const token = await service.auth.getAccessToken()
261
- if (!token || !service.aiUsageUrl) {
267
+ if (!token || !service.subscriptionBalancesUrl) {
262
268
  sendJson(res, 200, { usage: null })
263
269
  return
264
270
  }
265
- sendJson(res, 200, { usage: await fetchAiTokenUsage(token, service.aiUsageUrl) })
271
+ const controller = new AbortController()
272
+ const onClose = () => controller.abort()
273
+ res.on('close', onClose)
274
+ let usage: AiUsage | null
275
+ try {
276
+ usage = await fetchAiUsage(
277
+ token,
278
+ service.subscriptionBalancesUrl,
279
+ globalThis.fetch.bind(globalThis),
280
+ { signal: controller.signal },
281
+ )
282
+ } finally {
283
+ res.off('close', onClose)
284
+ }
285
+ sendJson(res, 200, { usage })
266
286
  return
267
287
  }
268
288
 
package/src/service.ts CHANGED
@@ -96,11 +96,17 @@ export interface HuaqiuAuthService {
96
96
  */
97
97
  readonly hostMode: boolean
98
98
  /**
99
- * Resolved AI token-usage endpoint injected by HQ Edge (`config.aiUsageUrl`),
100
- * or null when none was configured. `/ai-usage` never falls back to a stale
101
- * hardcoded environment endpoint.
99
+ * Resolved subscription balances endpoint injected by HQ Edge
100
+ * (`config.subscriptionBalancesUrl`), or null when none was configured.
101
+ * `/ai-usage` never falls back to a stale hardcoded environment endpoint.
102
102
  */
103
- readonly aiUsageUrl: string | null
103
+ readonly subscriptionBalancesUrl: string | null
104
+ /**
105
+ * Origin of {@link subscriptionBalancesUrl} (e.g. `https://www.eda.cn`), used
106
+ * by the browser half for the GEN/ERC active-subscription calls. Null when no
107
+ * endpoint was configured — DSH Auth never hardcodes a production host.
108
+ */
109
+ readonly subscriptionApiBaseUrl: string | null
104
110
  /**
105
111
  * Resolved subscription origin injected by HQ Edge (`config.subscriptionOrigin`),
106
112
  * or null when none was configured (standalone keeps its PROD default).
@@ -120,6 +126,15 @@ function safeHost(url: string): string {
120
126
  }
121
127
  }
122
128
 
129
+ /** Scheme + host origin of a URL, or null when it does not parse. */
130
+ function originOf(url: string): string | null {
131
+ try {
132
+ return new URL(url).origin
133
+ } catch {
134
+ return null
135
+ }
136
+ }
137
+
123
138
  /**
124
139
  * Bounded wait for the host to confirm a logout. Shorter than the login wait
125
140
  * (which must cover a human completing the EDA dialog): logout is a host-side
@@ -222,7 +237,12 @@ export class InMemoryHuaqiuAuthService implements HuaqiuAuthService {
222
237
  fetchImpl: this.doFetch,
223
238
  })
224
239
  this.hostMode = this.host.enabled
225
- this.aiUsageUrl = resolved.aiUsageUrl?.length ? resolved.aiUsageUrl : null
240
+ this.subscriptionBalancesUrl = resolved.subscriptionBalancesUrl?.length
241
+ ? resolved.subscriptionBalancesUrl
242
+ : null
243
+ this.subscriptionApiBaseUrl = this.subscriptionBalancesUrl
244
+ ? originOf(this.subscriptionBalancesUrl)
245
+ : null
226
246
  this.subscriptionOrigin = resolved.subscriptionOrigin?.length
227
247
  ? resolved.subscriptionOrigin
228
248
  : null
@@ -231,15 +251,19 @@ export class InMemoryHuaqiuAuthService implements HuaqiuAuthService {
231
251
  hostAuthPath: resolved.hostAuthPath,
232
252
  hostSessionTtlSeconds: resolved.hostSessionTtlSeconds,
233
253
  // Hosts only — never a complete URL that could carry a credential.
234
- aiUsageHost: this.aiUsageUrl ? safeHost(this.aiUsageUrl) : null,
254
+ subscriptionBalancesHost: this.subscriptionBalancesUrl
255
+ ? safeHost(this.subscriptionBalancesUrl)
256
+ : null,
235
257
  subscriptionOrigin: this.subscriptionOrigin,
236
258
  })
237
259
  }
238
260
 
239
261
  /** Host mode is active iff a host base URL was configured (see HostSessionResolver.enabled). */
240
262
  readonly hostMode: boolean
241
- /** AI usage endpoint resolved by HQ Edge (`HQ_AI_ENV`); null → no call. */
242
- readonly aiUsageUrl: string | null
263
+ /** Subscription balances endpoint resolved by HQ Edge (`HQ_AI_ENV`); null → no call. */
264
+ readonly subscriptionBalancesUrl: string | null
265
+ /** Origin used for GEN/ERC active-subscription calls; null → unavailable. */
266
+ readonly subscriptionApiBaseUrl: string | null
243
267
  /** Subscription origin resolved by HQ Edge (`HQ_AI_ENV`); null → standalone. */
244
268
  readonly subscriptionOrigin: string | null
245
269
 
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Single authoritative contract for the subscription-balances API
3
+ * (`GET /sub-api/subscriptions/balances/current`).
4
+ *
5
+ * Both halves import these types (the browser half type-only), and the node
6
+ * half's parser is the ONE place an upstream payload is turned into usage data.
7
+ * There must be no second response shape, no second parser and no locally
8
+ * derived percentage: `quotaRemainPercent` is the only source of truth.
9
+ *
10
+ * This module is intentionally dependency-free so the browser bundle can import
11
+ * the types without pulling node modules in.
12
+ */
13
+
14
+ /** One quota group in `result[]` (AI and non-AI groups share this shape). */
15
+ export interface SubscriptionBalanceGroup {
16
+ id: number
17
+ groupCode: string
18
+ groupName: string
19
+ quotaTotal: number | null
20
+ quotaUsed: number | null
21
+ quotaRemain: number | null
22
+ /** Remaining percentage. `null` for groups that do not report one. */
23
+ quotaRemainPercent: number | null
24
+ /** `true` ONLY for the AI Points group — the discriminator. */
25
+ aiPoints: boolean
26
+ status: number
27
+ }
28
+
29
+ /** The upstream envelope. */
30
+ export interface SubscriptionBalancesResponse {
31
+ code: number
32
+ message: string
33
+ result: SubscriptionBalanceGroup[]
34
+ }
35
+
36
+ /** Client-facing view: only the authoritative remaining percentage. */
37
+ export interface AiUsage {
38
+ quotaRemainPercent: number | null
39
+ }
40
+
41
+ /** The only success code accepted from the subscription balances API. */
42
+ export const SUBSCRIPTION_BALANCES_SUCCESS_CODE = 200000
43
+
44
+ function asRecord(value: unknown): Record<string, unknown> | null {
45
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
46
+ ? (value as Record<string, unknown>)
47
+ : null
48
+ }
49
+
50
+ /** `null`/missing/non-numeric → `null` (never a coerced 0). */
51
+ function numberOrNull(value: unknown): number | null {
52
+ return typeof value === 'number' && Number.isFinite(value) ? value : null
53
+ }
54
+
55
+ function numberOf(value: unknown): number {
56
+ return typeof value === 'number' && Number.isFinite(value) ? value : 0
57
+ }
58
+
59
+ function stringOf(value: unknown): string {
60
+ return typeof value === 'string' ? value : ''
61
+ }
62
+
63
+ function parseGroup(raw: unknown): SubscriptionBalanceGroup | null {
64
+ const group = asRecord(raw)
65
+ if (!group) return null
66
+ // `aiPoints` is the ONLY AI-group discriminator. A non-boolean value makes
67
+ // the payload unusable: guessing would risk showing a non-AI group.
68
+ if (typeof group.aiPoints !== 'boolean') return null
69
+ return {
70
+ id: numberOf(group.id),
71
+ groupCode: stringOf(group.groupCode),
72
+ groupName: stringOf(group.groupName),
73
+ quotaTotal: numberOrNull(group.quotaTotal),
74
+ quotaUsed: numberOrNull(group.quotaUsed),
75
+ quotaRemain: numberOrNull(group.quotaRemain),
76
+ quotaRemainPercent: numberOrNull(group.quotaRemainPercent),
77
+ aiPoints: group.aiPoints,
78
+ status: numberOf(group.status),
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Validate an upstream payload against the authoritative schema.
84
+ * Returns `null` for a non-2xx-style envelope, a non-array `result`, or any
85
+ * malformed group — callers degrade to "unavailable" rather than guessing.
86
+ */
87
+ export function parseSubscriptionBalancesResponse(
88
+ payload: unknown,
89
+ ): SubscriptionBalancesResponse | null {
90
+ const body = asRecord(payload)
91
+ if (!body) return null
92
+ if (body.code !== SUBSCRIPTION_BALANCES_SUCCESS_CODE) return null
93
+ if (!Array.isArray(body.result)) return null
94
+ const result = body.result.map(parseGroup)
95
+ if (result.some((group) => group === null)) return null
96
+ return {
97
+ code: body.code,
98
+ message: typeof body.message === 'string' ? body.message : '',
99
+ result: result as SubscriptionBalanceGroup[],
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Select the AI Points group and read its remaining percentage.
105
+ *
106
+ * No AI group → `null`; a missing/`null`/non-finite `quotaRemainPercent` →
107
+ * `null` (unavailable). `0` is preserved as a valid exhausted balance.
108
+ */
109
+ export function selectAiUsage(
110
+ response: SubscriptionBalancesResponse | null,
111
+ ): AiUsage | null {
112
+ const group = response?.result.find((entry) => entry.aiPoints === true)
113
+ if (!group) return null
114
+ const percent = group.quotaRemainPercent
115
+ if (percent === null || !Number.isFinite(percent)) return null
116
+ return { quotaRemainPercent: percent }
117
+ }
118
+
119
+ /** Parse + select in one step — the single upstream→usage normalization. */
120
+ export function aiUsageFromPayload(payload: unknown): AiUsage | null {
121
+ return selectAiUsage(parseSubscriptionBalancesResponse(payload))
122
+ }