mapigate 0.5.141 → 0.5.150

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +8 -8
  2. package/dist/cli/commands/restart.js +9 -1
  3. package/dist/cli/commands/start.js +15 -2
  4. package/dist/core/capabilities/index.js +13 -6
  5. package/dist/core/capabilities/modelDictionary.js +23 -7
  6. package/dist/core/router/ruleEngine.js +11 -1
  7. package/dist/core/usage/pricing.js +52 -24
  8. package/dist/mitm/handlers/antigravity/config.js +6 -0
  9. package/dist/mitm/handlers/base.js +18 -8
  10. package/dist/mitm/server.js +19 -4
  11. package/dist/mitm/toolsHelper.js +2 -0
  12. package/dist/providers/catalog/coarena/index.js +3 -0
  13. package/dist/providers/catalog/coarena/metadata.js +104 -0
  14. package/dist/providers/catalog/coarena/provider.js +91 -0
  15. package/dist/providers/catalog/coarena/quota.js +119 -0
  16. package/dist/providers/generated/chunks/chunk1.js +2 -2
  17. package/dist/providers/generated/chunks/chunk2.js +2 -2
  18. package/dist/providers/generated/chunks/chunk3.js +2 -2
  19. package/dist/providers/generated/chunks/chunk4.js +2 -0
  20. package/dist/providers/generated/runtime/chunk1.js +2 -2
  21. package/dist/providers/generated/runtime/chunk2.js +2 -2
  22. package/dist/providers/generated/runtime/chunk3.js +2 -2
  23. package/dist/providers/generated/runtime/chunk4.js +2 -0
  24. package/dist/providers/runtime/antigravity/executor.js +1 -1
  25. package/dist/providers/runtime/antigravity/metadata.js +2 -2
  26. package/dist/providers/runtime/antigravity/models.js +2 -0
  27. package/dist/providers/runtime/antigravity/provider.js +2 -2
  28. package/dist/providers/runtime/antigravity/routes.js +2 -2
  29. package/dist/providers/runtime/antigravity/types.js +4 -2
  30. package/dist/providers/runtime/gemini/metadata.js +1 -1
  31. package/dist/providers/runtime/gemini/provider.js +2 -2
  32. package/dist/providers/runtime/gemini-cli/provider.js +2 -2
  33. package/dist/providers/runtime/trae/index.js +1 -0
  34. package/dist/providers/runtime/trae/metadata.js +1 -0
  35. package/dist/providers/runtime/trae/provider.js +7 -0
  36. package/dist/providers/runtime/trae/quota.js +99 -0
  37. package/dist/providers/runtime/zed/metadata.js +1 -1
  38. package/dist/providers/runtime/zed/models.js +68 -8
  39. package/dist/providers/runtime/zed/provider.js +60 -15
  40. package/dist/providers/runtime/zed/quota.js +69 -12
  41. package/dist/providers/runtime/zed/routes.js +7 -0
  42. package/dist/server/lifecycle.js +2 -2
  43. package/dist/server/proxy/executorHelpers.js +52 -4
  44. package/dist/server/routes/apiModels.js +141 -8
  45. package/dist/server/routes/apiProviders.js +21 -14
  46. package/dist/server/routes/mitmRouterTargetHelper.js +14 -1
  47. package/dist/shared/constants/quotaOrder.js +5 -0
  48. package/dist/shared/utils/modelUtils.js +64 -0
  49. package/dist/storage/database.js +14 -0
  50. package/dist/storage/repositories/accountModelRepo.js +14 -1
  51. package/dist/storage/repositories/providerRepo.js +66 -38
  52. package/dist/storage/repositories/settingsRepo.js +41 -0
  53. package/dist/storage/repositories/toolMappingRepo.js +29 -0
  54. package/dist/web/assets/{CliToolsTab-rKSWLJC3.js → CliToolsTab-D_MUwimj.js} +1 -1
  55. package/dist/web/assets/CombosTab-EWUYC3TU.js +1 -0
  56. package/dist/web/assets/{ConfirmModal-OWeauwYv.js → ConfirmModal-CMfDss7P.js} +1 -1
  57. package/dist/web/assets/{ConsoleLogTab-rZe8zCb_.js → ConsoleLogTab-BSMXSYrR.js} +1 -1
  58. package/dist/web/assets/{EditAccountModal-CAg-yIOn.js → EditAccountModal-OrvqLLBP.js} +1 -1
  59. package/dist/web/assets/{EndpointTab-B-Jb4wAG.js → EndpointTab-BwtzqXUN.js} +1 -1
  60. package/dist/web/assets/MitmTab-C7g7GUXW.js +14 -0
  61. package/dist/web/assets/ModelAutocompleteInput-DEb_clZC.js +1 -0
  62. package/dist/web/assets/ProviderDetailPage-BIfOQupC.js +6 -0
  63. package/dist/web/assets/{ProvidersTab-yzmb4w0D.js → ProvidersTab-CwJo_EUX.js} +1 -1
  64. package/dist/web/assets/QuotaTab-PFvP6yAb.js +1 -0
  65. package/dist/web/assets/{SettingsTab-LkByv4Sg.js → SettingsTab-DwAbjIW3.js} +1 -1
  66. package/dist/web/assets/{UsageTab-Hr8XPZD4.js → UsageTab-85tTb2_C.js} +1 -1
  67. package/dist/web/assets/{index-CKuvklEr.js → index-CWkEEbms.js} +2 -2
  68. package/dist/web/assets/metadataRegistry-FuJXbCt4.js +1 -0
  69. package/dist/web/assets/providers/coarena/icon.png +0 -0
  70. package/dist/web/assets/providers/coarena/icon.svg +3 -0
  71. package/dist/web/assets/{providersData-DS1-ETBi.js → providersData-Y57rBt5o.js} +1 -1
  72. package/dist/web/index.html +1 -1
  73. package/package.json +1 -1
  74. package/dist/web/assets/CombosTab-D1_cfssh.js +0 -1
  75. package/dist/web/assets/MitmTab-5dKeNi4T.js +0 -14
  76. package/dist/web/assets/ModelAutocompleteInput-CoinzdsW.js +0 -1
  77. package/dist/web/assets/ProviderDetailPage-D-fodBhz.js +0 -6
  78. package/dist/web/assets/QuotaTab-BXevQzen.js +0 -1
  79. package/dist/web/assets/metadataRegistry-NuDSSkP9.js +0 -1
@@ -1,5 +1,6 @@
1
1
  import { OpenAiCompatibleProvider } from "../../core/base/openAiProvider.js";
2
2
  import { metadata } from "./metadata.js";
3
+ import { getTraeUsage } from "./quota.js";
3
4
  import { AnthropicAdapter } from "../../../core/adapters/anthropicAdapter.js";
4
5
  import { createResponsesStreamState, openAiChunkToResponsesEvents, finalizeResponsesStream, } from "../../../core/adapters/responsesAdapter.js";
5
6
  import { ResponseLogger } from "../../../server/proxy/responseLogger.js";
@@ -34,6 +35,12 @@ export class TraeProvider extends OpenAiCompatibleProvider {
34
35
  id = metadata.id;
35
36
  name = metadata.name;
36
37
  defaultFormat = metadata.format || "openai";
38
+ supportsQuota() {
39
+ return true;
40
+ }
41
+ async fetchQuota(context) {
42
+ return await getTraeUsage(context.account.rawApiKey, context.account.providerSpecificData);
43
+ }
37
44
  async probeModels(context) {
38
45
  const token = (context.account?.rawApiKey || context.apiKey || "").trim();
39
46
  if (!token) {
@@ -0,0 +1,99 @@
1
+ import { parseResetTime, toFiniteNumber } from "../../../core/usage/utils.js";
2
+ export const TRAE_ENTITLEMENT_URL = "https://ug-normal.trae.ai/trae/api/v1/pay/user_current_entitlement_list";
3
+ export async function getTraeUsage(accessToken, _providerSpecificData) {
4
+ const token = (accessToken || "").trim();
5
+ if (!token) {
6
+ return { plan: "Trae", message: "Trae access token not available." };
7
+ }
8
+ const authHeader = token.startsWith("Cloud-IDE-JWT ") ? token : `Cloud-IDE-JWT ${token}`;
9
+ try {
10
+ const res = await fetch(TRAE_ENTITLEMENT_URL, {
11
+ method: "POST",
12
+ headers: {
13
+ Accept: "application/json, text/plain, */*",
14
+ "Content-Type": "application/json",
15
+ Authorization: authHeader,
16
+ "x-cloudide-token": token,
17
+ Origin: "https://www.trae.ai",
18
+ Referer: "https://www.trae.ai/",
19
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.0.0 Safari/537.36",
20
+ },
21
+ body: JSON.stringify({ require_usage: true }),
22
+ signal: AbortSignal.timeout(8000),
23
+ });
24
+ if (!res.ok) {
25
+ return { plan: "Trae", message: `Trae quota API error (HTTP ${res.status})` };
26
+ }
27
+ const data = await res.json().catch(() => ({}));
28
+ return parseTraeEntitlementResponse(data);
29
+ }
30
+ catch (err) {
31
+ const message = err instanceof Error ? err.message : String(err);
32
+ return { plan: "Trae", message: `Failed to fetch Trae quota: ${message}` };
33
+ }
34
+ }
35
+ export function parseTraeEntitlementResponse(data) {
36
+ const packList = Array.isArray(data?.user_entitlement_pack_list)
37
+ ? data.user_entitlement_pack_list
38
+ : [];
39
+ if (packList.length === 0) {
40
+ return { plan: "Trae", message: "Connected. No entitlement package found." };
41
+ }
42
+ const primaryPack = packList.find((p) => !p.is_hide) || packList[0];
43
+ const plan = primaryPack.display_desc || "Free plan";
44
+ const baseInfo = primaryPack.entitlement_base_info || {};
45
+ const quota = baseInfo.quota ||
46
+ baseInfo.product_extra?.subscription_extra?.quota ||
47
+ {};
48
+ const usage = primaryPack.usage || {};
49
+ const endTime = baseInfo.end_time;
50
+ const resetAt = parseResetTime(endTime);
51
+ const quotas = {};
52
+ // 1. Dollar Usage
53
+ const basicLimit = toFiniteNumber(quota.basic_usage_limit, 0);
54
+ const bonusLimit = toFiniteNumber(quota.bonus_usage_limit, 0);
55
+ const totalDollarLimit = basicLimit + bonusLimit;
56
+ const basicUsage = toFiniteNumber(usage.basic_usage_amount, 0);
57
+ const bonusUsage = toFiniteNumber(usage.bonus_usage_amount, 0);
58
+ const totalDollarUsage = basicUsage + bonusUsage;
59
+ if (totalDollarLimit > 0) {
60
+ quotas["Dollar Usage"] = {
61
+ used: totalDollarUsage,
62
+ total: totalDollarLimit,
63
+ remaining: Math.max(0, totalDollarLimit - totalDollarUsage),
64
+ resetAt,
65
+ displayName: "Dollar Usage ($)",
66
+ recurring: true,
67
+ };
68
+ }
69
+ // 2. Autocomplete
70
+ const autoLimit = toFiniteNumber(quota.auto_completion_limit, 0);
71
+ if (autoLimit > 0) {
72
+ const autoUsed = toFiniteNumber(usage.auto_completion_amount ?? usage.autocomplete_amount ?? 0);
73
+ quotas["Autocomplete"] = {
74
+ used: autoUsed,
75
+ total: autoLimit,
76
+ remaining: Math.max(0, autoLimit - autoUsed),
77
+ resetAt,
78
+ displayName: "Autocomplete",
79
+ recurring: true,
80
+ };
81
+ }
82
+ // 3. Fast Requests (Premium Model Fast Requests if configured)
83
+ const fastLimit = toFiniteNumber(quota.premium_model_fast_request_limit, 0);
84
+ if (fastLimit > 0) {
85
+ const fastUsed = toFiniteNumber(usage.premium_model_fast_request_amount ?? usage.fast_request_amount ?? 0);
86
+ quotas["Fast Requests"] = {
87
+ used: fastUsed,
88
+ total: fastLimit,
89
+ remaining: Math.max(0, fastLimit - fastUsed),
90
+ resetAt,
91
+ displayName: "Fast Requests",
92
+ recurring: true,
93
+ };
94
+ }
95
+ return {
96
+ plan,
97
+ quotas,
98
+ };
99
+ }
@@ -8,7 +8,7 @@ export const metadata = {
8
8
  image: "/assets/providers/zed/icon.png",
9
9
  website: "https://zed.dev",
10
10
  notice: {
11
- signupUrl: "https://zed.dev/native_app_signin",
11
+ signupUrl: "https://dashboard.zed.dev",
12
12
  },
13
13
  category: "oauth",
14
14
  authType: "oauth",
@@ -1,10 +1,70 @@
1
1
  export const models = [
2
- { id: "claude-3-7-sonnet", name: "Claude 3.7 Sonnet" },
3
- { id: "claude-3-5-sonnet", name: "Claude 3.5 Sonnet" },
4
- { id: "claude-3-5-haiku", name: "Claude 3.5 Haiku" },
5
- { id: "gpt-4o", name: "GPT-4o" },
6
- { id: "gpt-4o-mini", name: "GPT-4o Mini" },
7
- { id: "gemini-2.0-flash", name: "Gemini 2.0 Flash" },
8
- { id: "gemini-2.0-pro-exp-02-05", name: "Gemini 2.0 Pro Exp" },
9
- { id: "grok-2", name: "Grok 2" },
2
+ // OpenAI Hosted Models
3
+ { id: "gpt-6-luna", name: "GPT-6 Luna", contextLength: 400000 },
4
+ { id: "gpt-6-sol", name: "GPT-6 Sol", contextLength: 400000 },
5
+ { id: "gpt-6.1-sol", name: "GPT-6.1 Sol", contextLength: 400000 },
6
+ { id: "gpt-6-astra", name: "GPT-6 Astra", contextLength: 400000 },
7
+ { id: "gpt-5.6-luna", name: "GPT-5.6 Luna", contextLength: 400000 },
8
+ { id: "gpt-5.6-terra", name: "GPT-5.6 Terra", contextLength: 400000 },
9
+ { id: "gpt-5.6-sol", name: "GPT-5.6 Sol", contextLength: 400000 },
10
+ { id: "gpt-5.5-pro", name: "GPT-5.5 pro", contextLength: 400000 },
11
+ { id: "gpt-5.5", name: "GPT-5.5", contextLength: 400000 },
12
+ { id: "gpt-5.4-pro", name: "GPT-5.4 pro", contextLength: 400000 },
13
+ { id: "gpt-5.4", name: "GPT-5.4", contextLength: 400000 },
14
+ { id: "gpt-5.3-codex", name: "GPT-5.3-Codex", contextLength: 400000 },
15
+ { id: "gpt-5.2-codex", name: "GPT-5.2-Codex", contextLength: 400000 },
16
+ { id: "gpt-5.2", name: "GPT-5.2", contextLength: 400000 },
17
+ { id: "gpt-5-mini", name: "GPT-5 mini", contextLength: 400000 },
18
+ { id: "gpt-5-nano", name: "GPT-5 nano", contextLength: 400000 },
19
+ { id: "gpt-4o", name: "GPT-4o", contextLength: 128000 },
20
+ { id: "gpt-4o-mini", name: "GPT-4o Mini", contextLength: 128000 },
21
+ // Anthropic Hosted Models
22
+ { id: "claude-fable-5.1", name: "Claude Fable 5.1", contextLength: 1000000 },
23
+ { id: "claude-fable-5", name: "Claude Fable 5", contextLength: 1000000 },
24
+ { id: "claude-opus-5.5", name: "Claude Opus 5.5", contextLength: 1000000 },
25
+ { id: "claude-opus-5", name: "Claude Opus 5", contextLength: 1000000 },
26
+ { id: "claude-opus-4.8", name: "Claude Opus 4.8", contextLength: 1000000 },
27
+ { id: "claude-opus-4.7", name: "Claude Opus 4.7", contextLength: 1000000 },
28
+ { id: "claude-opus-4.6", name: "Claude Opus 4.6", contextLength: 1000000 },
29
+ { id: "claude-opus-4.5", name: "Claude Opus 4.5", contextLength: 200000 },
30
+ { id: "claude-sonnet-5.5", name: "Claude Sonnet 5.5", contextLength: 1000000 },
31
+ { id: "claude-sonnet-5", name: "Claude Sonnet 5", contextLength: 1000000 },
32
+ { id: "claude-sonnet-4.6", name: "Claude Sonnet 4.6", contextLength: 1000000 },
33
+ { id: "claude-sonnet-4.5", name: "Claude Sonnet 4.5", contextLength: 200000 },
34
+ { id: "claude-haiku-4.5", name: "Claude Haiku 4.5", contextLength: 200000 },
35
+ { id: "claude-3-7-sonnet", name: "Claude 3.7 Sonnet", contextLength: 200000 },
36
+ { id: "claude-3-5-sonnet", name: "Claude 3.5 Sonnet", contextLength: 200000 },
37
+ { id: "claude-3-5-haiku", name: "Claude 3.5 Haiku", contextLength: 200000 },
38
+ // Google Hosted Models
39
+ { id: "gemini-4-argon", name: "Gemini 4 Argon", contextLength: 1000000 },
40
+ { id: "gemini-3.1-pro", name: "Gemini 3.1 Pro", contextLength: 200000 },
41
+ { id: "gemini-3.5-flash", name: "Gemini 3.5 Flash", contextLength: 1000000 },
42
+ { id: "gemini-3-flash", name: "Gemini 3 Flash", contextLength: 1000000 },
43
+ { id: "gemini-2.0-flash", name: "Gemini 2.0 Flash", contextLength: 1000000 },
44
+ { id: "gemini-2.0-pro-exp-02-05", name: "Gemini 2.0 Pro Exp", contextLength: 1000000 },
45
+ // Legacy / Other
46
+ { id: "grok-2", name: "Grok 2", contextLength: 128000 },
10
47
  ];
48
+ export function getModelsForZedPlan(rawPlan) {
49
+ const plan = String(rawPlan || "").toLowerCase().trim();
50
+ if (plan === "zed_free" || plan === "free") {
51
+ return [];
52
+ }
53
+ if (plan === "zed_pro_trial" || plan === "pro_trial" || plan === "trial") {
54
+ // Zed Pro Trial strictly includes GPT-6 Luna only
55
+ return models.filter((m) => m.id === "gpt-6-luna");
56
+ }
57
+ if (plan === "zed_student" || plan === "student") {
58
+ // Student plan excludes Claude Fable, Claude Opus, GPT-6 Astra, GPT-5.5 pro, GPT-5.4 pro
59
+ return models.filter((m) => {
60
+ const id = m.id.toLowerCase();
61
+ if (id.includes("fable") || id.includes("opus"))
62
+ return false;
63
+ if (id === "gpt-6-astra" || id === "gpt-5.5-pro" || id === "gpt-5.4-pro")
64
+ return false;
65
+ return true;
66
+ });
67
+ }
68
+ // Zed Pro, Zed Business, Zed VIP, or general access
69
+ return models;
70
+ }
@@ -1,14 +1,20 @@
1
1
  import { OpenAiCompatibleProvider } from "../../core/base/openAiProvider.js";
2
2
  import { metadata } from "./metadata.js";
3
3
  import { getZedUsage } from "./quota.js";
4
+ import { getModelsForZedPlan } from "./models.js";
4
5
  import { AnthropicAdapter } from "../../../core/adapters/anthropicAdapter.js";
5
6
  import { createResponsesStreamState, openAiChunkToResponsesEvents, finalizeResponsesStream, } from "../../../core/adapters/responsesAdapter.js";
6
7
  import { ResponseLogger } from "../../../server/proxy/responseLogger.js";
7
8
  const llmTokenCache = new Map();
8
9
  function normalizeZedProvider(model) {
9
10
  const m = String(model || "").toLowerCase();
10
- if (m.includes("claude"))
11
+ if (m.includes("claude") ||
12
+ m.includes("fable") ||
13
+ m.includes("opus") ||
14
+ m.includes("sonnet") ||
15
+ m.includes("haiku")) {
11
16
  return "anthropic";
17
+ }
12
18
  if (m.includes("gemini"))
13
19
  return "google";
14
20
  if (m.includes("grok") || m.includes("xai"))
@@ -75,25 +81,64 @@ export class ZedProvider extends OpenAiCompatibleProvider {
75
81
  headers,
76
82
  signal: AbortSignal.timeout(timeoutMs),
77
83
  });
78
- if (res.ok || res.status === 200) {
79
- return {
80
- success: true,
81
- endpointUrl: "https://cloud.zed.dev",
82
- models: metadata.models.map((m) => ({ id: m.id, name: m.name, contextLength: m.contextLength })),
83
- count: metadata.models.length,
84
- };
85
- }
86
- if (res.status === 401 || res.status === 403) {
84
+ if (!res.ok && res.status !== 200) {
85
+ if (res.status === 401 || res.status === 403) {
86
+ return {
87
+ success: false,
88
+ error: `Authentication failed (HTTP ${res.status}): Invalid or expired Zed token`,
89
+ authError: "Invalid or expired Zed token",
90
+ };
91
+ }
92
+ const errText = await res.text().catch(() => "");
87
93
  return {
88
94
  success: false,
89
- error: `Authentication failed (HTTP ${res.status}): Invalid or expired Zed token`,
90
- authError: "Invalid or expired Zed token",
95
+ error: `Endpoint returned HTTP ${res.status}: ${errText.slice(0, 100)}`,
91
96
  };
92
97
  }
93
- const errText = await res.text().catch(() => "");
98
+ // Query dynamic models from Zed Cloud using LLM token (same mechanism as Zed editor)
99
+ try {
100
+ const llmToken = await fetchZedLlmToken({
101
+ userId,
102
+ accessToken: token,
103
+ systemId: psd.systemId,
104
+ organizationId: psd.organizationId,
105
+ });
106
+ const modelsRes = await fetch("https://cloud.zed.dev/models", {
107
+ headers: {
108
+ Accept: "application/json",
109
+ Authorization: `Bearer ${llmToken}`,
110
+ "x-zed-client-supports-x-ai": "true",
111
+ },
112
+ signal: AbortSignal.timeout(timeoutMs),
113
+ });
114
+ if (modelsRes.ok) {
115
+ const data = await modelsRes.json().catch(() => ({}));
116
+ if (Array.isArray(data.models) && data.models.length > 0) {
117
+ const dynamicModels = data.models.map((m) => ({
118
+ id: m.id,
119
+ name: m.display_name || m.name || m.id,
120
+ contextLength: m.max_token_count || 200000,
121
+ }));
122
+ return {
123
+ success: true,
124
+ endpointUrl: "https://cloud.zed.dev/models",
125
+ models: dynamicModels,
126
+ count: dynamicModels.length,
127
+ };
128
+ }
129
+ }
130
+ }
131
+ catch { }
132
+ // Fallback: If /models query fails or returns empty, use plan-aware model resolution
133
+ const data = await res.json().catch(() => ({}));
134
+ const orgId = psd.organizationId || data?.default_organization_id;
135
+ const orgPlan = (orgId && data?.plans_by_organization?.[orgId]) || data?.plan?.plan_v3 || data?.plan?.plan;
136
+ const availableModels = getModelsForZedPlan(orgPlan);
94
137
  return {
95
- success: false,
96
- error: `Endpoint returned HTTP ${res.status}: ${errText.slice(0, 100)}`,
138
+ success: true,
139
+ endpointUrl: "https://cloud.zed.dev",
140
+ models: availableModels.map((m) => ({ id: m.id, name: m.name, contextLength: m.contextLength })),
141
+ count: availableModels.length,
97
142
  };
98
143
  }
99
144
  catch (err) {
@@ -101,26 +101,83 @@ export async function getZedUsage(accessToken, providerSpecificData) {
101
101
  }
102
102
  const data = await res.json().catch(() => ({}));
103
103
  const plan = data?.plan || {};
104
- const planId = plan.plan_v3 || plan.plan_v2 || plan.plan || data?.plan_v3;
104
+ const orgs = Array.isArray(data?.organizations) ? data.organizations : [];
105
+ const targetOrgId = providerSpecificData?.organizationId || data?.default_organization_id;
106
+ const currentOrg = orgs.find((o) => o?.id === targetOrgId) || orgs[0];
107
+ const planId = (currentOrg?.id && data?.plans_by_organization?.[currentOrg.id]) ||
108
+ plan.plan_v3 ||
109
+ plan.plan_v2 ||
110
+ plan.plan ||
111
+ data?.plan_v3;
105
112
  const resetAt = parseResetTime(plan.subscription_period?.ended_at) ||
106
113
  parseResetTime(plan.subscriptionPeriod?.endedAt) ||
107
114
  null;
108
115
  const quotas = {};
109
- const usage = plan.usage || {};
110
- const editPredictions = usage.edit_predictions || usage.editPredictions;
111
- if (editPredictions) {
112
- quotas["Edit Predictions"] = makeZedQuotaRow(editPredictions.used, editPredictions.limit, resetAt);
116
+ // Fetch Organization Billing Usage for Token Spend ($ used of $)
117
+ if (currentOrg?.id) {
118
+ try {
119
+ const billingRes = await fetch(`https://cloud.zed.dev/client/organizations/${currentOrg.id}/billing/usage`, { headers });
120
+ if (billingRes.ok) {
121
+ const billingData = await billingRes.json().catch(() => ({}));
122
+ const tokenSpend = billingData?.token_spend || billingData?.tokenSpend;
123
+ if (tokenSpend) {
124
+ const usedCents = Math.max(0, toFiniteNumber(tokenSpend.spend_in_cents ?? tokenSpend.spendInCents, 0));
125
+ const limitCentsRaw = tokenSpend.limit_in_cents ?? tokenSpend.limitInCents;
126
+ const usedUsd = Math.round((usedCents / 100) * 100) / 100;
127
+ if (limitCentsRaw != null) {
128
+ const limitCents = Math.max(0, toFiniteNumber(limitCentsRaw, 0));
129
+ const totalUsd = Math.round((limitCents / 100) * 100) / 100;
130
+ if (totalUsd > 0) {
131
+ const remaining = Math.max(0, totalUsd - usedUsd);
132
+ quotas["Token Spend"] = {
133
+ used: usedUsd,
134
+ total: totalUsd,
135
+ remainingPercentage: (remaining / totalUsd) * 100,
136
+ resetAt: resetAt !== null ? resetAt : undefined,
137
+ unlimited: false,
138
+ recurring: true,
139
+ unit: "USD",
140
+ };
141
+ }
142
+ else {
143
+ quotas["Token Spend"] = {
144
+ used: usedUsd,
145
+ total: 0,
146
+ remainingPercentage: 100,
147
+ resetAt: resetAt !== null ? resetAt : undefined,
148
+ unlimited: true,
149
+ recurring: true,
150
+ unit: "USD",
151
+ };
152
+ }
153
+ }
154
+ }
155
+ }
156
+ }
157
+ catch { }
113
158
  }
114
- const modelRequests = usage.model_requests || usage.modelRequests;
115
- if (modelRequests) {
116
- const limitRaw = modelRequests.limit != null ? modelRequests.limit : modelRequests?.limit;
117
- const limitInfo = parseZedUsageLimit(limitRaw);
118
- if (limitInfo.unlimited || limitInfo.total > 0) {
119
- quotas["Hosted Model Requests"] = makeZedQuotaRow(modelRequests.used, limitRaw, resetAt);
159
+ // Fallback: If billing endpoint didn't provide token spend, check hosted model requests
160
+ if (Object.keys(quotas).length === 0) {
161
+ const usage = plan.usage || {};
162
+ const modelRequests = usage.model_requests || usage.modelRequests;
163
+ if (modelRequests) {
164
+ const limitRaw = modelRequests.limit != null ? modelRequests.limit : modelRequests?.limit;
165
+ const limitInfo = parseZedUsageLimit(limitRaw);
166
+ if (limitInfo.unlimited || limitInfo.total > 0) {
167
+ quotas["Hosted Model Requests"] = makeZedQuotaRow(modelRequests.used, limitRaw, resetAt);
168
+ }
169
+ }
170
+ // Always include Edit Predictions as secondary quota so the card always has active progress
171
+ const editPredictions = usage.edit_predictions || usage.editPredictions;
172
+ if (editPredictions) {
173
+ quotas["Edit Predictions"] = makeZedQuotaRow(editPredictions.used, editPredictions.limit, resetAt);
120
174
  }
121
175
  }
176
+ const basePlanLabel = formatZedPlanLabel(planId);
177
+ const orgSuffix = currentOrg?.name ? ` (${currentOrg.name})` : "";
178
+ const displayPlan = `${basePlanLabel}${orgSuffix}`;
122
179
  return {
123
- plan: formatZedPlanLabel(planId),
180
+ plan: displayPlan,
124
181
  quotas,
125
182
  };
126
183
  }
@@ -107,6 +107,7 @@ export const zedOAuthHandler = {
107
107
  let accountName = "Zed User";
108
108
  let email;
109
109
  let organizationId = "";
110
+ let orgList = [];
110
111
  try {
111
112
  const userRes = await fetch("https://cloud.zed.dev/client/users/me", {
112
113
  headers: {
@@ -122,6 +123,11 @@ export const zedOAuthHandler = {
122
123
  const orgs = u?.organizations || [];
123
124
  const personalOrg = orgs.find((o) => o?.is_personal) || orgs[0];
124
125
  organizationId = personalOrg?.id || u?.default_organization_id || "";
126
+ orgList = orgs.map((o) => ({
127
+ id: String(o?.id || ""),
128
+ name: String(o?.name || ""),
129
+ isPersonal: Boolean(o?.is_personal),
130
+ }));
125
131
  }
126
132
  }
127
133
  catch { }
@@ -137,6 +143,7 @@ export const zedOAuthHandler = {
137
143
  userId,
138
144
  systemId,
139
145
  organizationId,
146
+ organizations: orgList,
140
147
  email,
141
148
  },
142
149
  });
@@ -181,8 +181,8 @@ export class ServerLifecycle {
181
181
  dbSettings = SettingsRepository.getEndpointSettings();
182
182
  }
183
183
  catch { }
184
- const port = Number(process.env.PORT) || dbSettings?.port || DEFAULT_PORT;
185
- const host = process.env.HOST || dbSettings?.host || DEFAULT_HOST;
184
+ const port = dbSettings?.port || Number(process.env.PORT) || DEFAULT_PORT;
185
+ const host = dbSettings?.host || process.env.HOST || DEFAULT_HOST;
186
186
  const { cmd, args, shell } = ProcessManager.resolveSpawnCommand();
187
187
  const dataDir = getDefaultDataDir();
188
188
  if (!fs.existsSync(dataDir)) {
@@ -2,7 +2,9 @@ import { stripModelContextMarker, RuleEngine } from "../../core/router/ruleEngin
2
2
  import { LoadBalancer } from "../../core/router/loadBalancer.js";
3
3
  import { ModelRepository } from "../../storage/repositories/modelRepo.js";
4
4
  import { ProviderRepository } from "../../storage/repositories/providerRepo.js";
5
+ import { PROVIDER_REGISTRY, getRegistryProvider } from "../../shared/constants/providerRegistry.js";
5
6
  import { logger, LogSymbol } from "../../shared/logger.js";
7
+ import { normalizeModelCompareKey } from "../../shared/utils/modelUtils.js";
6
8
  export function tryFailover(providerId, account, status, cooldownMs, triedAccountIds, targetModel, reqTag, isCustom = false, prefixHash, sessionId) {
7
9
  const next = LoadBalancer.pickAccount(providerId, {
8
10
  excludeAccountIds: triedAccountIds,
@@ -37,6 +39,17 @@ export function extractSessionId(req, body) {
37
39
  }
38
40
  return undefined;
39
41
  }
42
+ function isKnownProviderOrAlias(pName) {
43
+ if (!pName)
44
+ return false;
45
+ const pLower = pName.toLowerCase().trim();
46
+ if (PROVIDER_REGISTRY[pLower] || getRegistryProvider(pLower))
47
+ return true;
48
+ const dbProv = ProviderRepository.getProviderById(pLower);
49
+ if (dbProv)
50
+ return true;
51
+ return false;
52
+ }
40
53
  export function resolveTargetModelAndProvider(modelStr) {
41
54
  const { model: cleanModelStr, is1mContext } = stripModelContextMarker(modelStr);
42
55
  const effective = cleanModelStr || modelStr;
@@ -46,15 +59,25 @@ export function resolveTargetModelAndProvider(modelStr) {
46
59
  if (effective.includes("/")) {
47
60
  const slash = effective.indexOf("/");
48
61
  const rawProvider = effective.slice(0, slash);
49
- targetModel = effective.slice(slash + 1);
62
+ const candidateModel = effective.slice(slash + 1);
50
63
  // Parse provider[tag] syntax, e.g. claude[pro] -> provider: claude, tag: pro
64
+ let candidateProviderId = rawProvider;
65
+ let candidateTag;
51
66
  const tagMatch = rawProvider.match(/^([^[\]]+)\[([^[\]]+)\]$/);
52
67
  if (tagMatch) {
53
- providerId = tagMatch[1];
54
- targetTag = tagMatch[2];
68
+ candidateProviderId = tagMatch[1];
69
+ candidateTag = tagMatch[2];
70
+ }
71
+ // Only treat the prefix as a provider if candidateProviderId matches a known registered or DB provider
72
+ if (isKnownProviderOrAlias(candidateProviderId)) {
73
+ providerId = candidateProviderId;
74
+ targetTag = candidateTag;
75
+ targetModel = candidateModel;
55
76
  }
56
77
  else {
57
- providerId = rawProvider;
78
+ // The slash is part of the model name itself (e.g. "coarena/gpt-6-luna", "z-ai/glm-5.3-flash")
79
+ targetModel = effective;
80
+ providerId = undefined;
58
81
  }
59
82
  }
60
83
  else {
@@ -74,6 +97,17 @@ export function resolveTargetModelAndProvider(modelStr) {
74
97
  if (exactMatch) {
75
98
  providerId = exactMatch.id;
76
99
  }
100
+ else {
101
+ const targetCompareKey = normalizeModelCompareKey(targetLower);
102
+ const normalizedMatch = activeProviders.find((p) => Array.isArray(p.models) && p.models.some((m) => normalizeModelCompareKey(m) === targetCompareKey));
103
+ if (normalizedMatch) {
104
+ providerId = normalizedMatch.id;
105
+ const canonical = normalizedMatch.models?.find((m) => normalizeModelCompareKey(m) === targetCompareKey);
106
+ if (canonical) {
107
+ targetModel = canonical;
108
+ }
109
+ }
110
+ }
77
111
  // 2. Try matching by well-known model prefix patterns to active providers
78
112
  if (!providerId) {
79
113
  const isClaude = targetLower.startsWith("claude");
@@ -111,5 +145,19 @@ export function resolveTargetModelAndProvider(modelStr) {
111
145
  providerId = activeProviders[0]?.id;
112
146
  }
113
147
  }
148
+ // Canonical targetModel resolution for known provider (Strict exact first, then dot/dash canonical)
149
+ if (providerId) {
150
+ const prov = ProviderRepository.getProviderById(providerId);
151
+ if (prov && Array.isArray(prov.models) && prov.models.length > 0) {
152
+ const hasExact = prov.models.some((m) => m.toLowerCase() === targetModel.toLowerCase());
153
+ if (!hasExact) {
154
+ const targetCompareKey = normalizeModelCompareKey(targetModel);
155
+ const canonical = prov.models.find((m) => normalizeModelCompareKey(m) === targetCompareKey);
156
+ if (canonical) {
157
+ targetModel = canonical;
158
+ }
159
+ }
160
+ }
161
+ }
114
162
  return { targetModel, providerId, targetTag, is1mContext: Boolean(is1mContext) };
115
163
  }