bigmodelUsageQuotaProvider.ts 62 KB

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