bigmodelUsageQuotaProvider.ts 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708
  1. /* eslint-disable max-lines -- quota、entitlement 与 monitor 请求共用同一套 provider 鉴权逻辑,拆文件会让 Coding Plan strict key 边界更难追踪。 */
  2. import { z } from "zod";
  3. import {
  4. isSameOAuthAccountMaterial,
  5. type OAuthAccountMaterial,
  6. } from "#src/oauth/repo/oauthCredentialRepo.js";
  7. import type {
  8. ApiClient,
  9. ApiRequestInit,
  10. CodingPlanRegularTpsRequest,
  11. CodingPlanUsageRequest,
  12. CodingPlanUsageSnapshot,
  13. CodingPlanResetOpportunityRequest,
  14. CodingPlanResetOpportunityResult,
  15. CodingPlanResetScopeRequest,
  16. CodingPlanResetStatusSnapshot,
  17. CodingPlanResetUseRequest,
  18. CodingPlanResetUseResult,
  19. UsageEntitlementRequest,
  20. UsageEntitlementSnapshot,
  21. UsageMcpQuotaSnapshot,
  22. UsageQuotaLimit,
  23. UsageStatsRequest,
  24. UsageStatsSnapshot,
  25. ZCodeAccountAccess,
  26. } from "@zcode/shared";
  27. import {
  28. ApiError,
  29. BUILTIN_MODEL_PROVIDER_IDS,
  30. isCodingPlanModelProviderId,
  31. isStartPlanModelProviderId,
  32. isZaiCodingPlanProviderId,
  33. buildBigModelApiUrl,
  34. buildRuntimeZaiBusinessUrl,
  35. buildRuntimeZCodeApiUrl,
  36. } from "@zcode/shared";
  37. import type { ProviderFamilyDomain } from "@zcode/shared";
  38. import { createServiceLogger } from "#src/logger/serviceLogger.js";
  39. import type { IAccountRequestAuthService } from "../../model-provider/accountRequestAuthService.js";
  40. import { readApiJson } from "../../providers/api/apiJson.js";
  41. import { readEnv } from "../../oauth/providers/configUtils.js";
  42. import {
  43. buildZaiStartPlanBalanceUrl,
  44. fetchZaiStartPlanBalanceEnvelope,
  45. type ZaiStartPlanBalanceEnvelope,
  46. type ZaiStartPlanPlan,
  47. } from "../../model-provider/zaiStartPlanBilling.js";
  48. import type {
  49. BigModelUsageModelUsagePayload,
  50. BigModelUsageModelUsageEnvelope,
  51. BigModelUsageToolUsagePayload,
  52. BigModelUsageToolUsageEnvelope,
  53. BigModelCreditUsageActivityPayload,
  54. BigModelCreditUsageActivityEnvelope,
  55. BigModelCreditUsageDetailPayload,
  56. BigModelCreditUsageDetailEnvelope,
  57. BigModelUsageModelPerformancePayload,
  58. BigModelUsageModelPerformanceEnvelope,
  59. } from "./bigmodelUsageMonitorMapper.js";
  60. import {
  61. buildCodingPlanUsageSnapshotFromMonitor,
  62. buildUsageStatsSnapshotFromMonitor,
  63. } from "./bigmodelUsageMonitorMapper.js";
  64. import {
  65. resolveCodingPlanUsageTimeRange,
  66. resolveUsageTimeRange,
  67. } from "./bigmodelUsageMonitorRange.js";
  68. import { fetchBigModelSubscriptionSummary } from "./bigmodelSubscriptionProvider.js";
  69. import {
  70. fetchMcpQuotaSnapshot,
  71. type OfficialMcpCredentialSource,
  72. } from "./zcodeMcpQuotaProvider.js";
  73. import type { BigModelUsageQuotaEnvelope } from "./bigmodelUsageQuotaMapper.js";
  74. import { normalizeLimits, pickPrimaryLimit } from "./bigmodelUsageQuotaMapper.js";
  75. const BIGMODEL_QUOTA_PATH = "/api/monitor/usage/quota/limit";
  76. const CODING_PLAN_RESET_BASE_PATH = "/api/v1/coding-plan/reset";
  77. const REQUEST_TIMEOUT_MS = 15_000;
  78. const log = createServiceLogger("usage-stats");
  79. const EMPTY_MODEL_USAGE_PAYLOAD = {} satisfies BigModelUsageModelUsagePayload;
  80. const EMPTY_TOOL_USAGE_PAYLOAD = {} satisfies BigModelUsageToolUsagePayload;
  81. const EMPTY_CREDIT_ACTIVITY_PAYLOAD = {} satisfies BigModelCreditUsageActivityPayload;
  82. const EMPTY_CREDIT_DETAIL_PAYLOAD = {} satisfies BigModelCreditUsageDetailPayload;
  83. const EMPTY_MODEL_PERFORMANCE_PAYLOAD = {} satisfies BigModelUsageModelPerformancePayload;
  84. const codingPlanResetEnvelopeSchema = z.object({
  85. code: z.number(),
  86. msg: z.string().optional(),
  87. data: z.unknown().optional(),
  88. });
  89. const codingPlanResetOpportunitySchema = z.object({
  90. expire_at: z.number().finite().positive(),
  91. });
  92. const codingPlanResetHistorySchema = z.object({
  93. used_at: z.number().finite().positive(),
  94. });
  95. const codingPlanResetStatusDataSchema = z.object({
  96. available_five_hour_resets: z.array(codingPlanResetOpportunitySchema),
  97. available_week_resets: z.array(codingPlanResetOpportunitySchema),
  98. latest_five_hour_reset_history: codingPlanResetHistorySchema.nullable(),
  99. latest_week_reset_history: codingPlanResetHistorySchema.nullable(),
  100. has_unread_history: z.boolean(),
  101. });
  102. const codingPlanResetUseDataSchema = z.object({
  103. used: z.literal(true),
  104. });
  105. const codingPlanResetOpportunityGrantedDataSchema = z.object({
  106. granted: z.literal(true),
  107. });
  108. const codingPlanResetOpportunityDeniedDataSchema = z.object({
  109. granted: z.literal(false),
  110. next_try_at: z.number().int().positive(),
  111. });
  112. export interface UsageApiAuthorizationRequest {
  113. readonly preferredProviderId?: string;
  114. readonly requirePreferredProvider: boolean;
  115. }
  116. export interface UsageApiAuthorization {
  117. readonly authorization: string;
  118. readonly quotaUrl: string;
  119. readonly provider: ResolvedQuotaAuthorization["provider"];
  120. }
  121. interface BigModelUsageQuotaProviderOptions {
  122. apiClient: ApiClient;
  123. loadOAuthAccountMaterial(family: "zai" | "bigmodel"): Promise<OAuthAccountMaterial | null>;
  124. accountRequestAuthService: Pick<
  125. IAccountRequestAuthService,
  126. "resolveAccessCurrent" | "resolveCurrent"
  127. >;
  128. resolveApiAuthorization?: (
  129. request: UsageApiAuthorizationRequest,
  130. ) => Promise<UsageApiAuthorization | null>;
  131. env?: NodeJS.ProcessEnv;
  132. /**
  133. * 官方 Server MCP 的凭证来源。缺省时 entitlement 快照的 mcpQuota 恒为 null,
  134. * 既有装配(含单测)无需改动即可保持原行为。
  135. */
  136. officialMcpCredentialSource?: OfficialMcpCredentialSource;
  137. }
  138. interface ResolvedQuotaAuthorization {
  139. authorization: string;
  140. quotaUrl: string;
  141. teamContext: TeamPlanContext | null;
  142. provider: {
  143. id: string;
  144. name: string;
  145. };
  146. }
  147. interface TeamPlanContext {
  148. organizationId: string;
  149. projectId: string;
  150. // Team Plan 用量查询在 zai/bigmodel 两个 family 上对称存在,
  151. // 但复制团队项目 API Key 的 host、OAuth token key、鉴权 header 都按 family 分离。
  152. // 这里必须带上 family,下游 resolveTeamPlanProjectApiKey 才能选对 zai/bigmodel 的业务域名和 token。
  153. family: ProviderFamilyDomain;
  154. }
  155. interface CodingPlanResetAuthorization {
  156. zcodeAuthorization: string;
  157. codingPlanAuthorization: string;
  158. teamContext: TeamPlanContext | null;
  159. }
  160. // 直接复用响应类型,避免本地副本遗漏新 bucket/周期字段。
  161. type ZaiStartPlanBalance = NonNullable<
  162. NonNullable<ZaiStartPlanBalanceEnvelope["data"]>["balances"]
  163. >[number];
  164. export class BigModelUsageQuotaProvider {
  165. private readonly apiClient: ApiClient;
  166. private readonly loadOAuthAccountMaterial: BigModelUsageQuotaProviderOptions["loadOAuthAccountMaterial"];
  167. private readonly accountRequestAuthService: Pick<
  168. IAccountRequestAuthService,
  169. "resolveAccessCurrent" | "resolveCurrent"
  170. >;
  171. private readonly resolveApiAuthorization?: BigModelUsageQuotaProviderOptions["resolveApiAuthorization"];
  172. private readonly env: NodeJS.ProcessEnv;
  173. private readonly officialMcpCredentialSource?: OfficialMcpCredentialSource;
  174. constructor(options: BigModelUsageQuotaProviderOptions) {
  175. this.apiClient = options.apiClient;
  176. this.loadOAuthAccountMaterial = options.loadOAuthAccountMaterial;
  177. this.accountRequestAuthService = options.accountRequestAuthService;
  178. this.resolveApiAuthorization = options.resolveApiAuthorization;
  179. this.env = options.env ?? process.env;
  180. this.officialMcpCredentialSource = options.officialMcpCredentialSource;
  181. }
  182. async getSnapshot(): Promise<UsageEntitlementSnapshot> {
  183. return this.getSnapshotForRequest({});
  184. }
  185. async getSnapshotForRequest(
  186. request: UsageEntitlementRequest = {},
  187. ): Promise<UsageEntitlementSnapshot> {
  188. // 设置页只能从 Registry 取得静态 family/mode。动态 planKind 与 Team scope
  189. // 必须在服务边界读取当前账号连接;不能要求 UI 从 Effective Config 伪造动态权益事实。
  190. const accountAccess = await this.resolveRequestAccountAccess(request.accountAccess);
  191. const resolvedRequest: UsageEntitlementRequest = {
  192. ...request,
  193. accountAccess,
  194. };
  195. if (request.preferredProviderId && isStartPlanModelProviderId(request.preferredProviderId)) {
  196. return this.getStartPlanSnapshot(
  197. request.preferredProviderId,
  198. accountAccess,
  199. request.invalidateBalanceCache,
  200. );
  201. }
  202. const generatedAt = Date.now();
  203. const teamContext = accountAccess ? resolveTeamPlanContext(accountAccess) : null;
  204. const providerId = request.preferredProviderId?.trim() ?? "";
  205. const account = accountAccess
  206. ? await this.loadOAuthAccountMaterial(accountAccess.family)
  207. : null;
  208. if (teamContext && !account) throw new Error("coding_plan_account_required");
  209. // 团队权益不以调用 Key 为前置条件;即使 Key 创建/复制失败也保留已确认的订阅。
  210. const teamEntitlement = teamContext
  211. ? await fetchBigModelSubscriptionSummary({
  212. apiClient: this.apiClient,
  213. authorization: "",
  214. quotaUrl:
  215. resolveQuotaUrlFromEnv(this.env) ??
  216. (teamContext.family === "zai"
  217. ? buildZaiQuotaUrl(this.env)
  218. : buildBigModelQuotaUrl(this.env)),
  219. teamContext,
  220. businessToken: account?.accessToken,
  221. timeoutMs: REQUEST_TIMEOUT_MS,
  222. })
  223. : null;
  224. let resolved: ResolvedQuotaAuthorization | null = null;
  225. try {
  226. resolved = await this.resolveAuthorization({
  227. preferredProviderId: request.preferredProviderId,
  228. accountAccess,
  229. requirePreferredProvider: request.requirePreferredProvider === true,
  230. allowEnvApiKey: request.allowEnvApiKey,
  231. });
  232. } catch (error) {
  233. log.warn(undefined, "读取用量凭据失败,保留独立订阅判定", {
  234. error: error instanceof Error ? error.message : String(error),
  235. preferredProviderId: providerId,
  236. });
  237. }
  238. const entitlement =
  239. teamEntitlement ??
  240. (resolved
  241. ? await fetchBigModelSubscriptionSummary({
  242. apiClient: this.apiClient,
  243. authorization: resolved.authorization,
  244. quotaUrl: resolved.quotaUrl,
  245. timeoutMs: REQUEST_TIMEOUT_MS,
  246. })
  247. : { kind: "unknown" as const });
  248. // 订阅未知不能发布为成功空快照,否则 hook 会覆盖同身份已确认权益并清除失败退避。
  249. // 无凭据的未配置状态仍正常返回;已有查询身份时让统一失败路径保留快照。
  250. if (entitlement.kind === "unknown" && (resolved || teamContext)) {
  251. throw new Error("Coding Plan entitlement refresh failed");
  252. }
  253. const subscription =
  254. entitlement.kind !== "available" ? null : buildSubscriptionSnapshot(entitlement.subscription);
  255. const [payload, mcpQuota] = resolved
  256. ? await Promise.all([
  257. this.fetchQuota(resolved).catch(() => null),
  258. this.fetchMcpQuota(resolved).catch(() => null),
  259. ])
  260. : [null, null];
  261. // quota 失败或 level 存在都不改变权益;额度耗尽也只影响用量显示。
  262. const quotaData = payload && isSuccessfulBigModelEnvelope(payload) ? payload.data : null;
  263. const limits = normalizeLimits(quotaData?.limits);
  264. const primaryLimit = pickPrimaryLimit(limits);
  265. if (accountAccess && providerId) {
  266. await this.assertUnchangedRequestAccess(request.accountAccess, accountAccess);
  267. }
  268. if (
  269. account &&
  270. !isSameOAuthAccountMaterial(account, await this.loadOAuthAccountMaterial(account.family))
  271. )
  272. throw new Error("coding_plan_account_changed");
  273. return {
  274. generatedAt,
  275. authenticated: true,
  276. ...(entitlement.kind === "available"
  277. ? {}
  278. : {
  279. unavailableReason:
  280. entitlement.kind === "unavailable"
  281. ? ("no_plan" as const)
  282. : resolved || teamContext
  283. ? ("unavailable" as const)
  284. : ("not_configured" as const),
  285. }),
  286. ...(teamEntitlement?.kind === "unavailable" && teamEntitlement.reason
  287. ? { teamPlanUnavailableReason: teamEntitlement.reason }
  288. : {}),
  289. context: resolved
  290. ? buildUsageEntitlementContext(resolved, subscription)
  291. : buildUsageEntitlementContextFromRequest(resolvedRequest),
  292. provider: resolved?.provider ?? null,
  293. remaining: primaryLimit
  294. ? {
  295. count: primaryLimit.remaining ?? 0,
  296. isShow: true,
  297. percentage: primaryLimit.percentage,
  298. nextResetTime: primaryLimit.nextResetTime ?? null,
  299. }
  300. : null,
  301. subscription,
  302. quota: quotaData ? { level: quotaData.level?.trim() || null, limits } : null,
  303. mcpQuota,
  304. };
  305. }
  306. private async resolveRequestAccountAccess(
  307. accountAccess: UsageEntitlementRequest["accountAccess"],
  308. ): Promise<ZCodeAccountAccess | undefined> {
  309. if (!accountAccess) return undefined;
  310. if (!("mode" in accountAccess)) return accountAccess;
  311. return (await this.accountRequestAuthService.resolveAccessCurrent(accountAccess)) ?? undefined;
  312. }
  313. private async assertUnchangedRequestAccess(
  314. requested: UsageEntitlementRequest["accountAccess"],
  315. expected: ZCodeAccountAccess,
  316. ): Promise<void> {
  317. // 静态请求表示当前连接,须重解析原请求;具体 access 是浏览指定套餐,不能强绑当前选择。
  318. if (!requested || !("mode" in requested)) return;
  319. const current = await this.resolveRequestAccountAccess(requested);
  320. const scope = (access: ZCodeAccountAccess | undefined) =>
  321. access
  322. ? [
  323. access.family,
  324. access.planKind,
  325. access.planKind === "team-coding-plan"
  326. ? [access.organizationId, access.projectId, access.productId]
  327. : null,
  328. ]
  329. : null;
  330. if (JSON.stringify(scope(current)) !== JSON.stringify(scope(expected)))
  331. throw new Error("coding_plan_account_changed");
  332. }
  333. /**
  334. * 读取官方 Server MCP 额度。仅 Coding Plan provider 会发起:
  335. * 环境变量 key、普通 API Key provider 与 Start Plan 都没有该权益。
  336. */
  337. private async fetchMcpQuota(
  338. resolved: ResolvedQuotaAuthorization,
  339. ): Promise<UsageMcpQuotaSnapshot | null> {
  340. if (!this.officialMcpCredentialSource) {
  341. return null;
  342. }
  343. if (!isCodingPlanModelProviderId(resolved.provider.id)) {
  344. return null;
  345. }
  346. return fetchMcpQuotaSnapshot({
  347. apiClient: this.apiClient,
  348. credentialSource: this.officialMcpCredentialSource,
  349. env: this.env,
  350. requestScope: {
  351. providerFamily:
  352. resolved.teamContext?.family ??
  353. (isZaiCodingPlanProviderId(resolved.provider.id) ? "zai" : "bigmodel"),
  354. organizationId: resolved.teamContext?.organizationId ?? null,
  355. projectId: resolved.teamContext?.projectId ?? null,
  356. },
  357. });
  358. }
  359. private async getStartPlanSnapshot(
  360. providerId: string,
  361. accountAccess: ZCodeAccountAccess | undefined,
  362. invalidateBalanceCache = false,
  363. ): Promise<UsageEntitlementSnapshot> {
  364. const generatedAt = Date.now();
  365. const resolved = await this.resolveStartPlanAuthorization(providerId, accountAccess);
  366. if (!resolved) {
  367. return {
  368. generatedAt,
  369. authenticated: true,
  370. unavailableReason: "not_configured",
  371. context: { scope: "personal" },
  372. provider: null,
  373. remaining: null,
  374. subscription: null,
  375. quota: null,
  376. };
  377. }
  378. let balancePayload: ZaiStartPlanBalanceEnvelope;
  379. try {
  380. const balanceUrl = buildZaiStartPlanBalanceUrl();
  381. const balanceStartedAt = Date.now();
  382. // billing/current 已废弃,balance 会同时返回 plans 与 balances。
  383. // Start Plan 快照必须只发起一次 balance 请求,避免冷启动重复请求并继续依赖旧接口。
  384. balancePayload = await fetchZaiStartPlanBalanceEnvelope(
  385. this.apiClient,
  386. resolved.authorization,
  387. invalidateBalanceCache,
  388. );
  389. log.info(undefined, "billing/balance 请求完成", {
  390. balanceCount: balancePayload.data?.balances?.length ?? 0,
  391. balances: summarizeStartPlanBalances(balancePayload.data?.balances),
  392. code: balancePayload.code ?? null,
  393. durationMs: Date.now() - balanceStartedAt,
  394. msg: balancePayload.msg ?? null,
  395. payload: balancePayload,
  396. planCount: balancePayload.data?.plans?.length ?? 0,
  397. plans: summarizeStartPlans(balancePayload.data?.plans),
  398. providerId,
  399. success: balancePayload.code === 0,
  400. url: balanceUrl,
  401. });
  402. } catch (error) {
  403. log.warn(undefined, "billing/balance 请求失败", {
  404. error: error instanceof Error ? error.message : String(error),
  405. providerId,
  406. responseHeaders: error instanceof ApiError ? (error.responseHeaders ?? null) : null,
  407. status: error instanceof ApiError ? error.status : null,
  408. url: buildZaiStartPlanBalanceUrl(),
  409. });
  410. // 保留 HTTP 429 等错误信息,让调用方退避并保留已确认的权益。
  411. throw error;
  412. }
  413. if (balancePayload.code !== 0) {
  414. throw new Error(balancePayload.msg || `Start Plan balance failed: ${balancePayload.code}`);
  415. }
  416. const currentPlan = pickCurrentZaiStartPlan(balancePayload.data?.plans);
  417. if (!currentPlan) {
  418. return {
  419. generatedAt,
  420. authenticated: true,
  421. unavailableReason: "no_plan",
  422. startPlanExpired:
  423. balancePayload.data?.plans?.some((plan) => plan.status?.toLowerCase() === "expired") ??
  424. false,
  425. context: { scope: "personal" },
  426. provider: resolved.provider,
  427. remaining: null,
  428. subscription: null,
  429. quota: null,
  430. };
  431. }
  432. warnOnUnattributedStartPlanBuckets(
  433. balancePayload.data?.plans,
  434. readZaiStartPlanBalances(balancePayload),
  435. );
  436. return {
  437. generatedAt,
  438. authenticated: true,
  439. context: { scope: "personal" },
  440. provider: resolved.provider,
  441. // balance 的服务端时间与本响应的 effective_at 配对,不能用本机时钟覆盖。
  442. ...(typeof balancePayload.data?.server_time === "number" &&
  443. Number.isFinite(balancePayload.data.server_time) &&
  444. balancePayload.data.server_time >= 0
  445. ? { serverTime: balancePayload.data.server_time * 1_000 }
  446. : {}),
  447. remaining: buildZaiStartPlanRemaining(readZaiStartPlanBalances(balancePayload)),
  448. subscription: buildZaiStartPlanSubscription(balancePayload.data?.plans),
  449. quota: buildZaiStartPlanQuota(
  450. readZaiStartPlanBalances(balancePayload),
  451. balancePayload.data?.plans,
  452. ),
  453. };
  454. }
  455. private async resolveStartPlanAuthorization(
  456. providerId: string,
  457. accountAccess: ZCodeAccountAccess | undefined,
  458. ): Promise<{
  459. authorization: string;
  460. provider: ResolvedQuotaAuthorization["provider"];
  461. } | null> {
  462. if (!accountAccess || accountAccess.planKind !== "start-plan") {
  463. return null;
  464. }
  465. let auth;
  466. try {
  467. auth = await this.accountRequestAuthService.resolveCurrent({
  468. providerId,
  469. accountAccess,
  470. reason: "usage",
  471. });
  472. } catch {
  473. return null;
  474. }
  475. const apiKey = auth.apiKey?.trim() ?? "";
  476. if (!apiKey) return null;
  477. return {
  478. authorization: /^Bearer\s/i.test(apiKey) ? apiKey : `Bearer ${apiKey}`,
  479. provider: {
  480. id: providerId,
  481. name: resolveAccountProviderLabel(providerId),
  482. },
  483. };
  484. }
  485. async getUsageStatsSnapshot(request: UsageStatsRequest): Promise<UsageStatsSnapshot> {
  486. const resolved = await this.resolveAuthorization({
  487. preferredProviderId: request.preferredProviderId,
  488. accountAccess: request.accountAccess,
  489. requirePreferredProvider: request.requirePreferredProvider === true,
  490. allowEnvApiKey: request.allowEnvApiKey,
  491. });
  492. if (!resolved) {
  493. // 设置页使用统计可被显式收口到 Coding Plan provider。
  494. // 严格指定 provider 时不允许回退到普通 API Key、环境变量或本地 session 聚合。
  495. throw new Error("no_bigmodel_api_key");
  496. }
  497. const { startTime, endTime } = resolveUsageTimeRange(request);
  498. const [modelPayload, toolPayload] = await Promise.all([
  499. this.fetchModelUsage(resolved, startTime, endTime),
  500. this.fetchToolUsage(resolved, startTime, endTime),
  501. ]);
  502. const modelData = readSuccessfulBigModelMonitorData(
  503. modelPayload,
  504. "BigModel model usage failed",
  505. EMPTY_MODEL_USAGE_PAYLOAD,
  506. );
  507. const toolData = readSuccessfulBigModelMonitorData(
  508. toolPayload,
  509. "BigModel tool usage failed",
  510. EMPTY_TOOL_USAGE_PAYLOAD,
  511. { allowMissingData: true },
  512. );
  513. return {
  514. ...buildUsageStatsSnapshotFromMonitor(request, modelData, toolData),
  515. sourceProvider: resolved.provider,
  516. };
  517. }
  518. async getCodingPlanResetStatus(
  519. request: CodingPlanResetScopeRequest,
  520. ): Promise<CodingPlanResetStatusSnapshot> {
  521. const authorization = await this.resolveCodingPlanResetAuthorization(request);
  522. const payload = await readCodingPlanResetApiJson(
  523. this.apiClient,
  524. buildRuntimeZCodeApiUrl(this.env, `${CODING_PLAN_RESET_BASE_PATH}/status`),
  525. {
  526. method: "GET",
  527. timeoutMs: REQUEST_TIMEOUT_MS,
  528. headers: createCodingPlanResetHeaders(authorization, true),
  529. },
  530. );
  531. const data = readCodingPlanResetEnvelopeData(payload, codingPlanResetStatusDataSchema);
  532. return {
  533. availableFiveHourResets: data.available_five_hour_resets.map((item) => ({
  534. expireAt: item.expire_at,
  535. })),
  536. availableWeekResets: data.available_week_resets.map((item) => ({
  537. expireAt: item.expire_at,
  538. })),
  539. latestFiveHourResetHistory: data.latest_five_hour_reset_history
  540. ? { usedAt: data.latest_five_hour_reset_history.used_at }
  541. : null,
  542. latestWeekResetHistory: data.latest_week_reset_history
  543. ? { usedAt: data.latest_week_reset_history.used_at }
  544. : null,
  545. hasUnreadHistory: data.has_unread_history,
  546. };
  547. }
  548. async useCodingPlanReset(request: CodingPlanResetUseRequest): Promise<CodingPlanResetUseResult> {
  549. const idempotencyKey = request.idempotencyKey.trim();
  550. if (!idempotencyKey || idempotencyKey.length > 64) {
  551. throw new Error("coding_plan_reset_invalid_idempotency_key");
  552. }
  553. const authorization = await this.resolveCodingPlanResetAuthorization(request);
  554. const payload = await readCodingPlanResetApiJson(
  555. this.apiClient,
  556. buildRuntimeZCodeApiUrl(this.env, `${CODING_PLAN_RESET_BASE_PATH}/use`),
  557. {
  558. method: "POST",
  559. timeoutMs: REQUEST_TIMEOUT_MS,
  560. headers: {
  561. ...createCodingPlanResetHeaders(authorization, true),
  562. "content-type": "application/json",
  563. },
  564. body: JSON.stringify({
  565. idempotency_key: idempotencyKey,
  566. reset_type: request.resetType,
  567. }),
  568. },
  569. );
  570. const data = readCodingPlanResetEnvelopeData(payload, codingPlanResetUseDataSchema);
  571. return { used: data.used };
  572. }
  573. async requestCodingPlanResetOpportunity(
  574. request: CodingPlanResetOpportunityRequest,
  575. ): Promise<CodingPlanResetOpportunityResult> {
  576. const idempotencyKey = request.idempotencyKey.trim();
  577. if (!idempotencyKey || idempotencyKey.length > 64) {
  578. throw new Error("coding_plan_reset_invalid_idempotency_key");
  579. }
  580. const authorization = await this.resolveCodingPlanResetAuthorization(request);
  581. let payload: unknown;
  582. try {
  583. payload = await readCodingPlanResetApiJson(
  584. this.apiClient,
  585. buildRuntimeZCodeApiUrl(this.env, `${CODING_PLAN_RESET_BASE_PATH}/opportunity`),
  586. {
  587. method: "POST",
  588. timeoutMs: REQUEST_TIMEOUT_MS,
  589. headers: {
  590. ...createCodingPlanResetHeaders(authorization, true),
  591. "content-type": "application/json",
  592. },
  593. body: JSON.stringify({ idempotency_key: idempotencyKey }),
  594. },
  595. { acceptedBusinessCodes: [3301] },
  596. );
  597. } catch (error) {
  598. // 后端在请求过快/发卡锁竞争时直接回 HTTP 429,不带 3301 信封和 next_try_at。
  599. // 映射成稳定错误码,客户端据此写兜底冷却,避免 30 秒轮询持续撞限流。
  600. if (error instanceof ApiError && error.status === 429) {
  601. throw new Error("coding_plan_reset_opportunity_throttled", {
  602. cause: error,
  603. });
  604. }
  605. throw error;
  606. }
  607. const envelope = codingPlanResetEnvelopeSchema.safeParse(payload);
  608. if (!envelope.success) {
  609. throw new Error("coding_plan_reset_invalid_response");
  610. }
  611. // 3301 的 next_try_at 是服务端限流边界,必须完整透传给客户端;
  612. // 丢弃该字段会让 30 秒轮询持续触发资格判断,绕过后端要求的重试间隔。
  613. if (envelope.data.code === 3301) {
  614. const denied = codingPlanResetOpportunityDeniedDataSchema.safeParse(envelope.data.data);
  615. if (!denied.success) {
  616. throw new Error("coding_plan_reset_invalid_response");
  617. }
  618. return { granted: false, nextTryAt: denied.data.next_try_at };
  619. }
  620. const data = readCodingPlanResetEnvelopeData(
  621. payload,
  622. codingPlanResetOpportunityGrantedDataSchema,
  623. );
  624. return { granted: data.granted, nextTryAt: null };
  625. }
  626. async markCodingPlanResetHistoryRead(request: CodingPlanResetScopeRequest): Promise<void> {
  627. const authorization = await this.resolveCodingPlanResetAuthorization(request);
  628. const payload = await readCodingPlanResetApiJson(
  629. this.apiClient,
  630. buildRuntimeZCodeApiUrl(this.env, `${CODING_PLAN_RESET_BASE_PATH}/history/read`),
  631. {
  632. method: "POST",
  633. timeoutMs: REQUEST_TIMEOUT_MS,
  634. // history/read 使用当前 Coding Plan credential 校验身份,但按用户共享已读游标,不带 target scope。
  635. headers: createCodingPlanResetHeaders(authorization, false),
  636. },
  637. );
  638. readCodingPlanResetEnvelope(payload);
  639. }
  640. private async resolveCodingPlanResetAuthorization(
  641. request: CodingPlanResetScopeRequest,
  642. ): Promise<CodingPlanResetAuthorization> {
  643. const accountAccess = await this.resolveRequestAccountAccess(request.accountAccess);
  644. if (!accountAccess) {
  645. throw new Error("coding_plan_reset_account_access_required");
  646. }
  647. const account = await this.loadOAuthAccountMaterial(accountAccess.family);
  648. if (!account?.zcodeJwtToken) throw new Error("coding_plan_reset_zcode_jwt_required");
  649. if (!account.accessToken.trim()) throw new Error("coding_plan_reset_maas_jwt_required");
  650. await this.assertUnchangedRequestAccess(request.accountAccess, accountAccess);
  651. // 关联套餐未必与主登录渠道同名。两种 JWT 必须来自同一会话快照,防止换号时拼接。
  652. if (
  653. !isSameOAuthAccountMaterial(
  654. account,
  655. await this.loadOAuthAccountMaterial(accountAccess.family),
  656. )
  657. )
  658. throw new Error("coding_plan_reset_account_changed");
  659. const zcodeJwt = account.zcodeJwtToken;
  660. return {
  661. zcodeAuthorization: /^Bearer\s/i.test(zcodeJwt) ? zcodeJwt : `Bearer ${zcodeJwt}`,
  662. codingPlanAuthorization: account.accessToken.trim(),
  663. teamContext: resolveTeamPlanContext(accountAccess),
  664. };
  665. }
  666. async getCodingPlanUsageSnapshot(
  667. request: CodingPlanUsageRequest,
  668. ): Promise<CodingPlanUsageSnapshot> {
  669. const resolved = await this.resolveAuthorization({
  670. preferredProviderId: request.preferredProviderId,
  671. accountAccess: request.accountAccess,
  672. requirePreferredProvider: true,
  673. allowEnvApiKey: false,
  674. });
  675. if (!resolved) {
  676. // Coding Plan 用量现在直接使用对应 Coding Plan provider 的 API Key。
  677. // 缺少 key 时不能回退普通 API Key、环境变量、OAuth 或本地 App Usage。
  678. throw new Error(resolveCodingPlanApiKeyError(request.preferredProviderId));
  679. }
  680. const usageRange = resolveCodingPlanUsageTimeRange(request);
  681. // monitor 请求不能全有全无。quota 保持原有必须成功语义
  682. // (传输失败时整体失败,业务失败降级为 quota: null);activity / detail / health
  683. // 是可选数据面,传输失败只清空对应区域并记 warn,任一路故障不能拖垮整张面板。
  684. const [quotaPayload, activityData, modelDetailData, toolDetailData, health7dData] =
  685. await Promise.all([
  686. this.fetchQuota(resolved),
  687. readBestEffortBigModelMonitorData(
  688. this.fetchCreditUsageActivity(resolved, request.timeZone),
  689. "BigModel activity usage failed",
  690. EMPTY_CREDIT_ACTIVITY_PAYLOAD,
  691. ),
  692. readBestEffortBigModelMonitorData(
  693. this.fetchCreditUsageDetail(resolved, usageRange.startTime, usageRange.endTime, "MODEL"),
  694. "BigModel model usage detail failed",
  695. EMPTY_CREDIT_DETAIL_PAYLOAD,
  696. ),
  697. readBestEffortBigModelMonitorData(
  698. this.fetchCreditUsageDetail(resolved, usageRange.startTime, usageRange.endTime, "MCP"),
  699. "BigModel tool usage detail failed",
  700. EMPTY_CREDIT_DETAIL_PAYLOAD,
  701. ),
  702. readBestEffortBigModelMonitorData(
  703. this.fetchModelPerformanceDay(resolved, request.timeZone, "7d"),
  704. "BigModel model performance failed",
  705. EMPTY_MODEL_PERFORMANCE_PAYLOAD,
  706. ),
  707. ]);
  708. const quota =
  709. isSuccessfulBigModelEnvelope(quotaPayload) && quotaPayload.data
  710. ? {
  711. level: quotaPayload.data.level?.trim() || null,
  712. limits: normalizeLimits(quotaPayload.data.limits),
  713. }
  714. : null;
  715. return buildCodingPlanUsageSnapshotFromMonitor({
  716. request,
  717. provider: resolved.provider,
  718. quota,
  719. granularity: usageRange.granularity,
  720. xTime: usageRange.xTime,
  721. startDateKey: usageRange.startDateKey,
  722. endDateKey: usageRange.endDateKey,
  723. activityData,
  724. modelDetailData,
  725. toolDetailData,
  726. healthData: health7dData,
  727. });
  728. }
  729. async getCodingPlanRegularTps(request: CodingPlanRegularTpsRequest): Promise<number | undefined> {
  730. const startedAt = Date.now();
  731. let requestUrl: string | undefined;
  732. let responseHeaders: Record<string, string> = {};
  733. let responseStatus: number | undefined;
  734. let responseStatusText: string | undefined;
  735. let responseCode: number | undefined;
  736. try {
  737. const resolved = await this.resolveAuthorization({
  738. preferredProviderId: request.preferredProviderId,
  739. accountAccess: request.accountAccess,
  740. requirePreferredProvider: true,
  741. allowEnvApiKey: false,
  742. });
  743. if (!resolved) throw new Error(resolveCodingPlanApiKeyError(request.preferredProviderId));
  744. const timeRange = resolveModelPerformanceTimeRange(request.timeZone, "7d");
  745. requestUrl = buildModelPerformanceMonitorUrl(
  746. resolved,
  747. timeRange.startTime,
  748. timeRange.endTime,
  749. );
  750. const response = await this.apiClient.request(requestUrl, {
  751. method: "GET",
  752. timeoutMs: REQUEST_TIMEOUT_MS,
  753. headers: createBigModelUsageHeaders(resolved),
  754. });
  755. responseStatus = response.status;
  756. responseStatusText = response.statusText;
  757. responseHeaders = readApiDiagnosticHeaders(response.headers) ?? {};
  758. let payload: BigModelUsageModelPerformanceEnvelope | undefined;
  759. let parseError: unknown;
  760. try {
  761. payload = JSON.parse(await response.text()) as BigModelUsageModelPerformanceEnvelope;
  762. responseCode = typeof payload.code === "number" ? payload.code : undefined;
  763. } catch (error) {
  764. parseError = error;
  765. }
  766. if (!response.ok) {
  767. throw new ApiError({
  768. message: readApiErrorMessage(payload, `HTTP ${response.status}`),
  769. url: requestUrl,
  770. method: "GET",
  771. status: response.status,
  772. responseHeaders,
  773. cause: parseError,
  774. });
  775. }
  776. if (parseError !== undefined || payload === undefined) {
  777. throw new ApiError({
  778. message: parseError instanceof Error ? parseError.message : "Invalid JSON response",
  779. url: requestUrl,
  780. method: "GET",
  781. status: response.status,
  782. responseHeaders,
  783. cause: parseError,
  784. });
  785. }
  786. const data = readSuccessfulBigModelMonitorData<BigModelUsageModelPerformancePayload>(
  787. payload,
  788. "BigModel model performance failed",
  789. EMPTY_MODEL_PERFORMANCE_PAYLOAD,
  790. { allowMissingData: true },
  791. );
  792. return data.proMaxDecodeSpeed?.findLast((value) => Number.isFinite(value) && value > 0);
  793. } catch (error) {
  794. // Bug 原因:Highspeed 仅在 Renderer 记录了 TPS 读取失败文案,Host 层丢失了
  795. // monitor 的 HTTP status 和 request id,无法与后端日志对账。只输出 ApiError 中的安全诊断头。
  796. log.warn(undefined, "Highspeed 普通 TPS 健康检查失败", {
  797. error: error instanceof Error ? error.message : String(error),
  798. providerId: request.preferredProviderId,
  799. durationMs: Date.now() - startedAt,
  800. status: error instanceof ApiError ? error.status : (responseStatus ?? null),
  801. statusText: responseStatusText ?? null,
  802. responseCode: responseCode ?? null,
  803. responseHeaders:
  804. error instanceof ApiError ? (error.responseHeaders ?? responseHeaders) : responseHeaders,
  805. url: sanitizeMonitorDiagnosticUrl(error instanceof ApiError ? error.url : requestUrl),
  806. });
  807. throw error;
  808. }
  809. }
  810. private async resolveAuthorization(
  811. request: {
  812. preferredProviderId?: string;
  813. accountAccess?: UsageEntitlementRequest["accountAccess"];
  814. requirePreferredProvider?: boolean;
  815. allowEnvApiKey?: boolean;
  816. } = {},
  817. ): Promise<ResolvedQuotaAuthorization | null> {
  818. if (request.allowEnvApiKey !== false && request.requirePreferredProvider !== true) {
  819. const envApiKey =
  820. readEnv(this.env, "ZCODE_BIGMODEL_USAGE_API_KEY") ??
  821. readEnv(this.env, "BIGMODEL_USAGE_API_KEY");
  822. if (envApiKey) {
  823. return {
  824. authorization: envApiKey,
  825. quotaUrl: resolveQuotaUrlFromEnv(this.env) ?? buildBigModelQuotaUrl(this.env),
  826. teamContext: null,
  827. provider: {
  828. id: "env:bigmodel-usage",
  829. name: "BigModel",
  830. },
  831. };
  832. }
  833. }
  834. const providerId = request.preferredProviderId?.trim() ?? "";
  835. const accountAccess = await this.resolveRequestAccountAccess(request.accountAccess);
  836. if (providerId && isCodingPlanModelProviderId(providerId)) {
  837. if (!accountAccess) return null;
  838. const auth = await this.accountRequestAuthService.resolveCurrent({
  839. providerId,
  840. accountAccess,
  841. reason: "usage",
  842. });
  843. const authorization = auth.apiKey?.trim() ?? "";
  844. if (!authorization) return null;
  845. return {
  846. authorization,
  847. quotaUrl:
  848. resolveQuotaUrlFromEnv(this.env) ?? resolveAccountProviderQuotaUrl(providerId, this.env),
  849. teamContext: resolveTeamPlanContext(accountAccess),
  850. provider: {
  851. id: providerId,
  852. name: resolveAccountProviderLabel(providerId),
  853. },
  854. };
  855. }
  856. const apiAuthorization = await this.resolveApiAuthorization?.({
  857. preferredProviderId: providerId || undefined,
  858. requirePreferredProvider: request.requirePreferredProvider === true,
  859. });
  860. return apiAuthorization ? { ...apiAuthorization, teamContext: null } : null;
  861. }
  862. private async fetchQuota(
  863. resolved: ResolvedQuotaAuthorization,
  864. ): Promise<BigModelUsageQuotaEnvelope> {
  865. return readApiJson<BigModelUsageQuotaEnvelope>(this.apiClient, buildQuotaLimitUrl(resolved), {
  866. method: "GET",
  867. timeoutMs: REQUEST_TIMEOUT_MS,
  868. headers: createBigModelUsageHeaders(resolved),
  869. });
  870. }
  871. private async fetchModelUsage(
  872. resolved: ResolvedQuotaAuthorization,
  873. startTime: string,
  874. endTime: string,
  875. ): Promise<BigModelUsageModelUsageEnvelope> {
  876. return readApiJson<BigModelUsageModelUsageEnvelope>(
  877. this.apiClient,
  878. buildUsageMonitorUrl(resolved, "model-usage", startTime, endTime),
  879. {
  880. method: "GET",
  881. timeoutMs: REQUEST_TIMEOUT_MS,
  882. headers: createBigModelUsageHeaders(resolved),
  883. },
  884. );
  885. }
  886. private async fetchToolUsage(
  887. resolved: ResolvedQuotaAuthorization,
  888. startTime: string,
  889. endTime: string,
  890. ): Promise<BigModelUsageToolUsageEnvelope> {
  891. return readApiJson<BigModelUsageToolUsageEnvelope>(
  892. this.apiClient,
  893. buildUsageMonitorUrl(resolved, "tool-usage", startTime, endTime),
  894. {
  895. method: "GET",
  896. timeoutMs: REQUEST_TIMEOUT_MS,
  897. headers: createBigModelUsageHeaders(resolved),
  898. },
  899. );
  900. }
  901. private async fetchCreditUsageActivity(
  902. resolved: ResolvedQuotaAuthorization,
  903. timeZone: string | undefined,
  904. ): Promise<BigModelCreditUsageActivityEnvelope> {
  905. const range = resolveCreditUsageActivityTimeRange(timeZone);
  906. return readApiJson<BigModelCreditUsageActivityEnvelope>(
  907. this.apiClient,
  908. buildCreditUsageMonitorUrl(resolved, "activity", range.startTime, range.endTime),
  909. {
  910. method: "GET",
  911. timeoutMs: REQUEST_TIMEOUT_MS,
  912. headers: createBigModelUsageHeaders(resolved),
  913. },
  914. );
  915. }
  916. private async fetchCreditUsageDetail(
  917. resolved: ResolvedQuotaAuthorization,
  918. startTime: string,
  919. endTime: string,
  920. usageType: "MODEL" | "MCP",
  921. ): Promise<BigModelCreditUsageDetailEnvelope> {
  922. return readApiJson<BigModelCreditUsageDetailEnvelope>(
  923. this.apiClient,
  924. buildCreditUsageMonitorUrl(resolved, "usage-detail", startTime, endTime, usageType),
  925. {
  926. method: "GET",
  927. timeoutMs: REQUEST_TIMEOUT_MS,
  928. headers: createBigModelUsageHeaders(resolved),
  929. },
  930. );
  931. }
  932. private async fetchModelPerformanceDay(
  933. resolved: ResolvedQuotaAuthorization,
  934. timeZone: string | undefined,
  935. range: "7d" | "30d",
  936. ): Promise<BigModelUsageModelPerformanceEnvelope> {
  937. const timeRange = resolveModelPerformanceTimeRange(timeZone, range);
  938. return readApiJson<BigModelUsageModelPerformanceEnvelope>(
  939. this.apiClient,
  940. buildModelPerformanceMonitorUrl(resolved, timeRange.startTime, timeRange.endTime),
  941. {
  942. method: "GET",
  943. timeoutMs: REQUEST_TIMEOUT_MS,
  944. headers: createBigModelUsageHeaders(resolved),
  945. },
  946. );
  947. }
  948. }
  949. function createCodingPlanResetHeaders(
  950. authorization: CodingPlanResetAuthorization,
  951. includeTargetScope: boolean,
  952. ): Record<string, string> {
  953. const headers: Record<string, string> = {
  954. Authorization: authorization.zcodeAuthorization,
  955. "X-Bigmodel-Authorization": authorization.codingPlanAuthorization,
  956. };
  957. if (!includeTargetScope) {
  958. return headers;
  959. }
  960. headers["Bigmodel-Target-Type"] = authorization.teamContext ? "TEAM" : "PERSONAL";
  961. if (authorization.teamContext) {
  962. headers["Bigmodel-Organization"] = authorization.teamContext.organizationId;
  963. headers["Bigmodel-Project"] = authorization.teamContext.projectId;
  964. }
  965. return headers;
  966. }
  967. function readApiErrorMessage(payload: unknown, fallback: string): string {
  968. if (!payload || typeof payload !== "object") {
  969. return fallback;
  970. }
  971. const record = payload as Record<string, unknown>;
  972. for (const key of ["error", "message", "msg", "detail"] as const) {
  973. const value = record[key];
  974. if (typeof value === "string" && value.trim()) {
  975. return value.trim();
  976. }
  977. }
  978. return fallback;
  979. }
  980. function readApiDiagnosticHeaders(headers: Headers): Record<string, string> | undefined {
  981. const result: Record<string, string> = {};
  982. for (const name of ["x-request-id", "x-trace-id", "x-span-id"] as const) {
  983. const value = headers.get(name)?.trim();
  984. if (value) {
  985. result[name] = value;
  986. }
  987. }
  988. return Object.keys(result).length > 0 ? result : undefined;
  989. }
  990. // 联调对账后缀:envelope 业务错误(如 2007 依赖失败)需要把后端 x-request-id
  991. // 带进错误 message,RPC 日志和 UI warn 才能与后端日志按请求 id 精确对上。
  992. // 仅用于日志定位,客户端不做分支;缺失时返回空串保持原 message 契约。
  993. function readCodingPlanResetErrorDiagnostics(headers: Headers): string {
  994. const requestId = headers.get("x-request-id")?.trim();
  995. return requestId ? ` (x-request-id:${requestId})` : "";
  996. }
  997. async function readCodingPlanResetApiJson(
  998. apiClient: ApiClient,
  999. input: string,
  1000. init: ApiRequestInit,
  1001. options: { acceptedBusinessCodes?: readonly number[] } = {},
  1002. ): Promise<unknown> {
  1003. const response = await apiClient.request(input, init);
  1004. let payload: unknown;
  1005. let parseError: unknown;
  1006. try {
  1007. payload = JSON.parse(await response.text()) as unknown;
  1008. } catch (error) {
  1009. parseError = error;
  1010. }
  1011. // reset 后端在 HTTP 4xx 时仍通过统一 envelope 返回稳定业务 code。
  1012. // 必须先读取 code,不能把易变的 msg 当成客户端分支依据。
  1013. const envelope = codingPlanResetEnvelopeSchema.safeParse(payload);
  1014. if (envelope.success && envelope.data.code !== 0) {
  1015. if (options.acceptedBusinessCodes?.includes(envelope.data.code)) {
  1016. return payload;
  1017. }
  1018. throw new Error(
  1019. `coding_plan_reset_api_error:${envelope.data.code}${readCodingPlanResetErrorDiagnostics(response.headers)}`,
  1020. );
  1021. }
  1022. if (!response.ok) {
  1023. throw new ApiError({
  1024. message: readApiErrorMessage(payload, `HTTP ${response.status}`),
  1025. url: input,
  1026. method: init.method,
  1027. status: response.status,
  1028. responseHeaders: readApiDiagnosticHeaders(response.headers),
  1029. cause: parseError,
  1030. });
  1031. }
  1032. if (parseError !== undefined) {
  1033. throw new Error("coding_plan_reset_invalid_response", {
  1034. cause: parseError,
  1035. });
  1036. }
  1037. return payload;
  1038. }
  1039. function readCodingPlanResetEnvelope(
  1040. payload: unknown,
  1041. ): z.infer<typeof codingPlanResetEnvelopeSchema> {
  1042. const result = codingPlanResetEnvelopeSchema.safeParse(payload);
  1043. if (!result.success) {
  1044. throw new Error("coding_plan_reset_invalid_response");
  1045. }
  1046. if (result.data.code !== 0) {
  1047. throw new Error(`coding_plan_reset_api_error:${result.data.code}`);
  1048. }
  1049. return result.data;
  1050. }
  1051. function readCodingPlanResetEnvelopeData<TSchema extends z.ZodType>(
  1052. payload: unknown,
  1053. schema: TSchema,
  1054. ): z.infer<TSchema> {
  1055. const envelope = readCodingPlanResetEnvelope(payload);
  1056. const result = schema.safeParse(envelope.data);
  1057. if (!result.success) {
  1058. throw new Error("coding_plan_reset_invalid_response");
  1059. }
  1060. return result.data;
  1061. }
  1062. function resolveTeamPlanContext(accountAccess: ZCodeAccountAccess): TeamPlanContext | null {
  1063. return accountAccess.planKind === "team-coding-plan"
  1064. ? {
  1065. organizationId: accountAccess.organizationId,
  1066. projectId: accountAccess.projectId,
  1067. family: accountAccess.family,
  1068. }
  1069. : null;
  1070. }
  1071. function buildUsageEntitlementContextFromRequest(
  1072. request: Pick<UsageEntitlementRequest, "accountAccess">,
  1073. ): UsageEntitlementSnapshot["context"] {
  1074. if (
  1075. !request.accountAccess ||
  1076. !("planKind" in request.accountAccess) ||
  1077. request.accountAccess.planKind !== "team-coding-plan"
  1078. ) {
  1079. return { scope: "personal" };
  1080. }
  1081. return {
  1082. scope: "team",
  1083. organizationId: request.accountAccess.organizationId,
  1084. projectId: request.accountAccess.projectId,
  1085. };
  1086. }
  1087. function buildUsageEntitlementContext(
  1088. resolved: ResolvedQuotaAuthorization,
  1089. subscription: UsageEntitlementSnapshot["subscription"],
  1090. ): UsageEntitlementSnapshot["context"] {
  1091. if (!resolved.teamContext) {
  1092. return {
  1093. scope: "personal",
  1094. productId: subscription?.details[0]?.productId || null,
  1095. displayName: subscription?.details[0]?.productName || null,
  1096. };
  1097. }
  1098. return {
  1099. scope: "team",
  1100. organizationId: resolved.teamContext.organizationId,
  1101. projectId: resolved.teamContext.projectId,
  1102. productId: subscription?.details[0]?.productId || null,
  1103. displayName: subscription?.details[0]?.productName || null,
  1104. };
  1105. }
  1106. function createBigModelUsageHeaders(resolved: ResolvedQuotaAuthorization): Record<string, string> {
  1107. const headers: Record<string, string> = {
  1108. // monitor 接口要求 authorization 直接传完整凭据。
  1109. // 普通用量和 Coding Plan 用量都走 API Key,不能额外加 Bearer 前缀。
  1110. authorization: resolved.authorization,
  1111. };
  1112. if (resolved.teamContext) {
  1113. // Team Plan 的 quota / usage 按组织和项目隔离。
  1114. // 只用 provider id 会固定读取默认项目,多个团队时余额会和当前选择不一致。
  1115. headers["bigmodel-organization"] = resolved.teamContext.organizationId;
  1116. headers["bigmodel-project"] = resolved.teamContext.projectId;
  1117. }
  1118. return headers;
  1119. }
  1120. function buildQuotaLimitUrl(resolved: ResolvedQuotaAuthorization): string {
  1121. if (!resolved.teamContext) {
  1122. return resolved.quotaUrl;
  1123. }
  1124. // BigModel Team Plan 的 quota/limit 后端按 type=2 路由到团队套餐。
  1125. // 只切换团队项目 key/header 仍会走个人 Coding Plan 分支并返回“当前用户不存在 coding plan”。
  1126. const url = new URL(resolved.quotaUrl);
  1127. url.searchParams.set("type", "2");
  1128. return url.toString();
  1129. }
  1130. function readSuccessfulBigModelMonitorData<TData extends object>(
  1131. payload: {
  1132. code?: number;
  1133. message?: string;
  1134. msg?: string;
  1135. success?: boolean;
  1136. data?: TData | null;
  1137. },
  1138. fallbackMessage: string,
  1139. emptyData: TData,
  1140. options: { allowMissingData?: boolean } = {},
  1141. ): TData {
  1142. if (!isSuccessfulBigModelEnvelope(payload)) {
  1143. throw new Error(readBigModelEnvelopeMessage(payload) || fallbackMessage);
  1144. }
  1145. if (payload.data) {
  1146. return payload.data;
  1147. }
  1148. if (options.allowMissingData === true && hasExplicitBigModelSuccessSignal(payload)) {
  1149. // BigModel monitor 的 tool-usage 在团队项目无工具调用时会返回
  1150. // code=200、msg=“操作成功”但省略 data。空用量应显示为空统计,不能中断整个统计页。
  1151. return emptyData;
  1152. }
  1153. throw new Error(readBigModelEnvelopeMessage(payload) || fallbackMessage);
  1154. }
  1155. // credit-usage/activity、usage-detail、model-performance-day 是可选数据面。
  1156. // 传输层失败(HTTP 非 2xx、超时、断网)时只清空对应区域并记 warn,不能让
  1157. // Promise.all 提前 reject 拖垮整张 Coding Plan Usage 面板。HTTP 200 但业务信封失败
  1158. // (如 token expired)仍由 readSuccessfulBigModelMonitorData 抛错:鉴权/后端错误必须
  1159. // 显式暴露给用户,不能伪装成空用量(既有测试已锁定该语义)。
  1160. async function readBestEffortBigModelMonitorData<TData extends object>(
  1161. request: Promise<{
  1162. code?: number;
  1163. message?: string;
  1164. msg?: string;
  1165. success?: boolean;
  1166. data?: TData | null;
  1167. }>,
  1168. fallbackMessage: string,
  1169. emptyData: TData,
  1170. ): Promise<TData> {
  1171. let payload: Awaited<typeof request> | null = null;
  1172. try {
  1173. payload = await request;
  1174. } catch (error) {
  1175. log.warn(undefined, `${fallbackMessage},该区域降级为空统计`, {
  1176. error: error instanceof Error ? error.message : String(error),
  1177. status: error instanceof ApiError ? error.status : null,
  1178. });
  1179. return emptyData;
  1180. }
  1181. return readSuccessfulBigModelMonitorData(payload, fallbackMessage, emptyData, {
  1182. allowMissingData: true,
  1183. });
  1184. }
  1185. function readBigModelEnvelopeMessage(payload: { message?: string; msg?: string }): string {
  1186. return payload.msg?.trim() || payload.message?.trim() || "";
  1187. }
  1188. function sanitizeMonitorDiagnosticUrl(url: string | undefined): string {
  1189. if (!url) return "<unknown-monitor-url>";
  1190. try {
  1191. const parsed = new URL(url);
  1192. return `${parsed.origin}${parsed.pathname}`;
  1193. } catch {
  1194. return "<invalid-monitor-url>";
  1195. }
  1196. }
  1197. function hasExplicitBigModelSuccessSignal(payload: { code?: number; success?: boolean }): boolean {
  1198. return payload.success === true || payload.code === 0 || payload.code === 200;
  1199. }
  1200. function isSuccessfulBigModelEnvelope(payload: { code?: number; success?: boolean }): boolean {
  1201. const code = payload.code;
  1202. // BigModel monitor/quota 后端存在 code=0 且 msg=“操作成功”的成功响应。
  1203. // 只按 code=200 判断会把团队用量统计的成功包误抛成错误,导致设置页显示无法读取统计。
  1204. return (
  1205. payload.success !== false && (code === undefined || code === null || code === 0 || code === 200)
  1206. );
  1207. }
  1208. function buildSubscriptionSnapshot(summary: {
  1209. productId: string;
  1210. productName: string;
  1211. billingCycle: string | null;
  1212. renewTime: string | null;
  1213. expireTime: string | null;
  1214. }): UsageEntitlementSnapshot["subscription"] {
  1215. return {
  1216. identityType: "unknown",
  1217. identityMasked: null,
  1218. details: [{ ...summary, purchaseTime: null, beginTime: null }],
  1219. };
  1220. }
  1221. function buildZaiStartPlanSubscription(
  1222. plans: ZaiStartPlanPlan[] | undefined,
  1223. ): UsageEntitlementSnapshot["subscription"] {
  1224. const activePlans = (plans ?? []).filter(
  1225. (plan) => readNonEmptyString(plan.status)?.toLowerCase() === "active",
  1226. );
  1227. return {
  1228. identityType: "unknown",
  1229. identityMasked: null,
  1230. details: activePlans.map((plan) => ({
  1231. productId: readNonEmptyString(plan.plan_id) ?? "",
  1232. productName: readNonEmptyString(plan.name) ?? "编程套餐",
  1233. purchaseTime: null,
  1234. beginTime: formatUnixSecondsAsIso(plan.starts_at),
  1235. billingCycle: pickZaiStartPlanBillingCycle(plan),
  1236. // Start Plan 卡片不展示套餐级续期时间:额度桶刷新时间由每个 limit 的
  1237. // nextResetTime(balance.expires_at)表达,套餐到期由 expireTime(ends_at)表达。
  1238. renewTime: null,
  1239. expireTime: formatUnixSecondsAsIso(plan.ends_at),
  1240. entitlements: (plan.entitlements ?? []).flatMap((entitlement) => {
  1241. const entitlementId = readNonEmptyString(entitlement.entitlement_id);
  1242. if (!entitlementId) return [];
  1243. return [
  1244. {
  1245. entitlementId,
  1246. showName: readNonEmptyString(entitlement.show_name),
  1247. effectiveTime: formatUnixSecondsAsIso(entitlement.effective_at),
  1248. },
  1249. ];
  1250. }),
  1251. })),
  1252. };
  1253. }
  1254. /**
  1255. * tripwire:服务端契约保证 balances 只属于 active plans、每个桶都能按
  1256. * plan_id 归属到套餐卡。出现无归属桶(含缺失 plan_id 的桶)说明契约被破坏——
  1257. * 设置页多卡路径会静默丢弃这些桶,必须在 provider 层显式暴露,避免「额度去哪了」
  1258. * 类问题无迹可查。正常数据下此日志零输出,用 warn 保证生产环境可见。
  1259. */
  1260. function warnOnUnattributedStartPlanBuckets(
  1261. plans: ZaiStartPlanPlan[] | undefined,
  1262. balances: ZaiStartPlanBalance[] | undefined,
  1263. ): void {
  1264. const activePlanIds = new Set(
  1265. (plans ?? [])
  1266. .filter((plan) => readNonEmptyString(plan.status)?.toLowerCase() === "active")
  1267. .map((plan) => readNonEmptyString(plan.plan_id))
  1268. .filter((planId): planId is string => Boolean(planId)),
  1269. );
  1270. const orphanBuckets = (balances ?? []).filter((balance) => {
  1271. const planId = readNonEmptyString(balance.plan_id);
  1272. return !planId || !activePlanIds.has(planId);
  1273. });
  1274. if (orphanBuckets.length === 0) {
  1275. return;
  1276. }
  1277. log.warn(undefined, "billing/balance 返回无法归属到 active 套餐的额度桶", {
  1278. orphanCount: orphanBuckets.length,
  1279. orphanPlanIds: orphanBuckets.map((balance) => balance.plan_id ?? null),
  1280. activePlanIds: [...activePlanIds],
  1281. });
  1282. }
  1283. function buildZaiStartPlanRemaining(
  1284. balances: ZaiStartPlanBalance[] | undefined,
  1285. ): UsageEntitlementSnapshot["remaining"] {
  1286. const limits = normalizeZaiStartPlanBalanceLimits(balances);
  1287. if (limits.length === 0) {
  1288. return null;
  1289. }
  1290. const total = limits.reduce((sum, limit) => sum + (limit.number ?? 0), 0);
  1291. const remaining = limits.reduce((sum, limit) => sum + (limit.remaining ?? 0), 0);
  1292. return {
  1293. count: remaining,
  1294. isShow: true,
  1295. percentage: total > 0 ? remaining / total : undefined,
  1296. nextResetTime:
  1297. limits
  1298. .map((limit) => limit.nextResetTime)
  1299. .filter((value): value is number => typeof value === "number")
  1300. .sort((left, right) => left - right)[0] ?? null,
  1301. };
  1302. }
  1303. function buildZaiStartPlanQuota(
  1304. balances: ZaiStartPlanBalance[] | undefined,
  1305. plans?: ZaiStartPlanPlan[],
  1306. ): UsageEntitlementSnapshot["quota"] {
  1307. const limits = normalizeZaiStartPlanBalanceLimits(balances, plans);
  1308. if (limits.length === 0) {
  1309. return null;
  1310. }
  1311. return {
  1312. level: "Start",
  1313. limits,
  1314. };
  1315. }
  1316. function normalizeZaiStartPlanBalanceLimits(
  1317. balances: ZaiStartPlanBalance[] | undefined,
  1318. plans?: ZaiStartPlanPlan[],
  1319. ): UsageQuotaLimit[] {
  1320. if (!Array.isArray(balances)) {
  1321. return [];
  1322. }
  1323. return balances
  1324. .map((balance) => {
  1325. const total = parseNumber(balance.total_units);
  1326. const used = parseNumber(balance.used_units);
  1327. // Start Plan 余额卡必须展示后端给出的 remaining_units。
  1328. // available_units 会再扣除进行中请求的 reserved_units,不能作为“剩余”兜底。
  1329. const remaining = parseNumber(balance.remaining_units);
  1330. if (total === null && used === null && remaining === null) {
  1331. return null;
  1332. }
  1333. // 额度桶的真实重置边界由 balance.expires_at 表达;服务端契约保证每个桶都带该字段。
  1334. const nextResetSeconds = parseUnixSeconds(balance.expires_at);
  1335. const capabilityLabels = normalizeZaiStartPlanCapabilities(balance.capabilities);
  1336. const capabilityType = readNonEmptyString(capabilityLabels.join(", "));
  1337. const displayName = readNonEmptyString(balance.show_name);
  1338. const planId = readNonEmptyString(balance.plan_id);
  1339. const userPlanId = readNonEmptyString(balance.user_plan_id);
  1340. const plan = plans?.find((candidate) =>
  1341. userPlanId && candidate.user_plan_id
  1342. ? candidate.user_plan_id === userPlanId
  1343. : candidate.plan_id === planId,
  1344. );
  1345. const period = plan?.entitlements?.find(
  1346. (entry) => entry.entitlement_id === balance.entitlement_id,
  1347. )?.period;
  1348. const periodStart = parseUnixSeconds(balance.period_start);
  1349. const periodEnd = parseUnixSeconds(balance.period_end);
  1350. return {
  1351. // 旧映射丢弃 bucket 和周期字段,Renderer 只能用变化的余额去重,导致反复提醒。
  1352. bucketId: readNonEmptyString(balance.bucket_id) ?? undefined,
  1353. userPlanId: userPlanId ?? undefined,
  1354. periodStart: periodStart === null ? undefined : periodStart * 1000,
  1355. periodEnd: periodEnd === null ? undefined : periodEnd * 1000,
  1356. period: readNonEmptyString(period) ?? undefined,
  1357. meter: readNonEmptyString(balance.meter) ?? undefined,
  1358. unitType: readNonEmptyString(balance.unit_type) ?? undefined,
  1359. type:
  1360. readNonEmptyString(balance.entitlement_id) ??
  1361. capabilityType ??
  1362. readNonEmptyString(balance.meter) ??
  1363. "model_usage",
  1364. // planId 用于设置页按套餐卡片分组额度桶;服务端契约保证每个桶都携带 plan_id。
  1365. ...(planId ? { planId } : {}),
  1366. unit: total ?? undefined,
  1367. number: total ?? undefined,
  1368. usage: used ?? undefined,
  1369. currentValue: used ?? undefined,
  1370. remaining: remaining ?? undefined,
  1371. percentage:
  1372. total !== null && remaining !== null && total > 0 ? remaining / total : undefined,
  1373. nextResetTime: nextResetSeconds === null ? undefined : nextResetSeconds * 1000,
  1374. usageDetails: capabilityLabels.map((modelCode) => ({
  1375. modelCode,
  1376. // 两个 Start Plan 的 Today's balance 接口已经返回面向用户的 show_name。
  1377. // 继续从 capabilities 推导会把 GLM-5-Turbo 显示成 GLM-5Turbo,并且丢失服务端名称语义。
  1378. ...(displayName ? { displayName } : {}),
  1379. usage: used ?? 0,
  1380. })),
  1381. };
  1382. })
  1383. .filter((limit): limit is NonNullable<typeof limit> => limit !== null);
  1384. }
  1385. function normalizeZaiStartPlanCapabilities(capabilities: string[] | undefined): string[] {
  1386. if (!Array.isArray(capabilities)) {
  1387. return [];
  1388. }
  1389. return capabilities
  1390. .map((capability) =>
  1391. capability.startsWith("model:") ? capability.slice("model:".length) : capability,
  1392. )
  1393. .filter((capability) => capability.trim().length > 0);
  1394. }
  1395. function parseNumber(value: number | string | null | undefined): number | null {
  1396. const numericValue =
  1397. typeof value === "number"
  1398. ? value
  1399. : typeof value === "string" && value.trim().length > 0
  1400. ? Number(value)
  1401. : Number.NaN;
  1402. return Number.isFinite(numericValue) ? numericValue : null;
  1403. }
  1404. function pickCurrentZaiStartPlan(plans: ZaiStartPlanPlan[] | undefined): ZaiStartPlanPlan | null {
  1405. return (
  1406. plans?.find((plan) => {
  1407. const status = readNonEmptyString(plan.status)?.toLowerCase();
  1408. const planId = readNonEmptyString(plan.plan_id)?.toLowerCase();
  1409. const name = readNonEmptyString(plan.name)?.toLowerCase();
  1410. return (
  1411. status === "active" && (isZaiStartPlanIdentity(planId) || isZaiStartPlanIdentity(name))
  1412. );
  1413. }) ?? null
  1414. );
  1415. }
  1416. function readZaiStartPlanBalances(
  1417. payload: ZaiStartPlanBalanceEnvelope,
  1418. ): ZaiStartPlanBalance[] | undefined {
  1419. return payload.data?.balances as ZaiStartPlanBalance[] | undefined;
  1420. }
  1421. function summarizeStartPlans(plans: ZaiStartPlanPlan[] | undefined): Array<{
  1422. name: string | null;
  1423. plan_id: string | null;
  1424. status: string | null;
  1425. }> {
  1426. return (plans ?? []).map((plan) => ({
  1427. name: plan.name ?? null,
  1428. plan_id: plan.plan_id ?? null,
  1429. status: plan.status ?? null,
  1430. }));
  1431. }
  1432. function summarizeStartPlanBalances(balances: ZaiStartPlanBalance[] | undefined): Array<{
  1433. entitlement_id: string | null;
  1434. show_name: string | null;
  1435. total_units: number | string | null;
  1436. used_units: number | string | null;
  1437. remaining_units: number | string | null;
  1438. available_units: number | string | null;
  1439. reserved_units: number | string | null;
  1440. }> {
  1441. return (balances ?? []).map((balance) => ({
  1442. entitlement_id: balance.entitlement_id ?? null,
  1443. show_name: balance.show_name ?? null,
  1444. total_units: balance.total_units ?? null,
  1445. used_units: balance.used_units ?? null,
  1446. remaining_units: balance.remaining_units ?? null,
  1447. available_units: balance.available_units ?? null,
  1448. reserved_units: balance.reserved_units ?? null,
  1449. }));
  1450. }
  1451. function isZaiStartPlanIdentity(value: string | null | undefined): boolean {
  1452. if (!value) {
  1453. return false;
  1454. }
  1455. return value.includes("start-plan") || value.includes("start plan");
  1456. }
  1457. function pickZaiStartPlanBillingCycle(plan: ZaiStartPlanPlan): string | null {
  1458. return (
  1459. plan.entitlements
  1460. ?.map((item) => readNonEmptyString(item.period))
  1461. .find((period): period is string => Boolean(period)) ?? null
  1462. );
  1463. }
  1464. function readNonEmptyString(value: unknown): string | null {
  1465. return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
  1466. }
  1467. function formatUnixSecondsAsIso(value: number | string | null | undefined): string | null {
  1468. const numericValue = parseUnixSeconds(value);
  1469. if (numericValue === null) {
  1470. return null;
  1471. }
  1472. return new Date(numericValue * 1000).toISOString();
  1473. }
  1474. function parseUnixSeconds(value: number | string | null | undefined): number | null {
  1475. const numericValue =
  1476. typeof value === "number"
  1477. ? value
  1478. : typeof value === "string" && value.trim().length > 0
  1479. ? Number(value)
  1480. : Number.NaN;
  1481. if (!Number.isFinite(numericValue) || numericValue <= 0) {
  1482. return null;
  1483. }
  1484. return numericValue;
  1485. }
  1486. function buildUsageMonitorUrl(
  1487. resolved: ResolvedQuotaAuthorization,
  1488. endpoint: "model-usage" | "tool-usage",
  1489. startTime: string,
  1490. endTime: string,
  1491. ): string {
  1492. const url = new URL(resolved.quotaUrl);
  1493. url.pathname = url.pathname.replace(/\/quota\/limit$/, `/${endpoint}`);
  1494. if (resolved.teamContext) {
  1495. // BigModel Team Plan 的 monitor 用量接口和 quota/limit 一样按 type=2 路由。
  1496. // 只带团队项目 key/header 时仍会落到个人 Coding Plan 分支并返回不存在套餐。
  1497. url.searchParams.set("type", "2");
  1498. }
  1499. url.searchParams.set("startTime", startTime);
  1500. url.searchParams.set("endTime", endTime);
  1501. return url.toString();
  1502. }
  1503. function buildCreditUsageMonitorUrl(
  1504. resolved: ResolvedQuotaAuthorization,
  1505. endpoint: "activity" | "usage-detail",
  1506. startTime: string,
  1507. endTime: string,
  1508. usageType?: "MODEL" | "MCP",
  1509. ): string {
  1510. const url = new URL(resolved.quotaUrl);
  1511. url.pathname = url.pathname.replace(/\/usage\/quota\/limit$/, `/credit-usage/${endpoint}`);
  1512. // Team Plan 的 quota/limit 仍用 type=2,但 credit-usage 使用 type=3;
  1513. // 继续沿用 type=2 会触发后端“仅企业主账号可查询企业汇总数据”分支。
  1514. url.searchParams.set("type", resolved.teamContext ? "3" : "1");
  1515. url.searchParams.set("startTime", startTime);
  1516. url.searchParams.set("endTime", endTime);
  1517. if (usageType) {
  1518. url.searchParams.set("usageType", usageType);
  1519. }
  1520. return url.toString();
  1521. }
  1522. function buildModelPerformanceMonitorUrl(
  1523. resolved: ResolvedQuotaAuthorization,
  1524. startTime: string,
  1525. endTime: string,
  1526. ): string {
  1527. const url = new URL(resolved.quotaUrl);
  1528. url.pathname = url.pathname.replace(/\/quota\/limit$/, "/model-performance-day");
  1529. url.searchParams.set("startTime", startTime);
  1530. url.searchParams.set("endTime", endTime);
  1531. return url.toString();
  1532. }
  1533. function resolveCreditUsageActivityTimeRange(timeZone: string | undefined): {
  1534. startTime: string;
  1535. endTime: string;
  1536. } {
  1537. const endDateKey = formatDateInTimeZone(new Date(), timeZone);
  1538. const startDateKey = addDaysToDateKey(endDateKey, -365);
  1539. return {
  1540. startTime: `${startDateKey} 00:00:00`,
  1541. endTime: `${endDateKey} 23:59:59`,
  1542. };
  1543. }
  1544. function resolveModelPerformanceTimeRange(
  1545. timeZone: string | undefined,
  1546. range: "7d" | "30d",
  1547. ): {
  1548. startTime: string;
  1549. endTime: string;
  1550. } {
  1551. const endDateKey = formatDateInTimeZone(new Date(), timeZone);
  1552. const startDateKey = addDaysToDateKey(endDateKey, range === "7d" ? -6 : -29);
  1553. return {
  1554. startTime: `${startDateKey} 00:00:00`,
  1555. endTime: `${endDateKey} 23:59:59`,
  1556. };
  1557. }
  1558. function formatDateInTimeZone(date: Date, timeZone: string | undefined): string {
  1559. const parts = new Intl.DateTimeFormat("en-CA", {
  1560. timeZone: timeZone || undefined,
  1561. year: "numeric",
  1562. month: "2-digit",
  1563. day: "2-digit",
  1564. }).formatToParts(date);
  1565. const year = parts.find((part) => part.type === "year")?.value ?? "1970";
  1566. const month = parts.find((part) => part.type === "month")?.value ?? "01";
  1567. const day = parts.find((part) => part.type === "day")?.value ?? "01";
  1568. return `${year}-${month}-${day}`;
  1569. }
  1570. function addDaysToDateKey(dateKey: string, days: number): string {
  1571. const [year = "1970", month = "01", day = "01"] = dateKey.split("-");
  1572. const date = new Date(Date.UTC(Number(year), Number(month) - 1, Number(day) + days));
  1573. const pad = (value: number) => String(value).padStart(2, "0");
  1574. return `${date.getUTCFullYear()}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())}`;
  1575. }
  1576. function resolveQuotaUrlFromEnv(env: NodeJS.ProcessEnv): string | undefined {
  1577. return readEnv(env, "ZCODE_BIGMODEL_USAGE_QUOTA_URL") ?? readEnv(env, "BIGMODEL_USAGE_QUOTA_URL");
  1578. }
  1579. function resolveCodingPlanApiKeyError(providerId: string | undefined): string {
  1580. if (providerId && isZaiCodingPlanProviderId(providerId)) {
  1581. return "zai_coding_plan_api_key_required";
  1582. }
  1583. return "bigmodel_coding_plan_api_key_required";
  1584. }
  1585. function resolveAccountProviderQuotaUrl(providerId: string, env: NodeJS.ProcessEnv): string {
  1586. return isZaiCodingPlanProviderId(providerId) ? buildZaiQuotaUrl(env) : buildBigModelQuotaUrl(env);
  1587. }
  1588. function resolveAccountProviderLabel(providerId: string): string {
  1589. return providerId === BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan ||
  1590. providerId === BUILTIN_MODEL_PROVIDER_IDS.zaiStartPlan
  1591. ? "Z.ai - Coding Plan"
  1592. : "BigModel - Coding Plan";
  1593. }
  1594. function buildBigModelQuotaUrl(env: NodeJS.ProcessEnv = process.env): string {
  1595. return buildBigModelApiUrl(env, BIGMODEL_QUOTA_PATH);
  1596. }
  1597. function buildZaiQuotaUrl(env: NodeJS.ProcessEnv = process.env): string {
  1598. // ZAI usage/quota 与 business login 共用业务域名。
  1599. // 测试环境必须请求 配置的 ZAI Business origin,不能把测试 token 发送到生产 api.z.ai。
  1600. return buildRuntimeZaiBusinessUrl(env, "/api/monitor/usage/quota/limit");
  1601. }