mapigate 0.5.136 → 0.5.146

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 (102) hide show
  1. package/README.md +8 -8
  2. package/dist/cli/commands/logs.js +0 -1
  3. package/dist/core/adapters/anthropic/requestOpenAiToAnthropic.js +1 -1
  4. package/dist/core/adapters/helpers/toolCallRescue.js +1 -1
  5. package/dist/core/adapters/responsesAdapter.js +11 -0
  6. package/dist/core/capabilities/index.js +5 -4
  7. package/dist/core/capabilities/modelDictionary.js +1 -0
  8. package/dist/core/scanner/modelScanner.js +2 -1
  9. package/dist/core/scanner/payloadExtractor.js +1 -1
  10. package/dist/core/scanner/urlResolver.js +16 -0
  11. package/dist/core/tokenSaver/methods/rtk/autodetect.js +1 -1
  12. package/dist/core/tokenSaver/methods/rtk/filters/gitLog.js +1 -1
  13. package/dist/core/usage/pricing.js +98 -42
  14. package/dist/core/usage/tokenExtractor.js +59 -0
  15. package/dist/mitm/handlers/antigravity/config.js +22 -0
  16. package/dist/mitm/handlers/antigravity/modelInjector.js +2 -2
  17. package/dist/providers/catalog/coarena/index.js +3 -0
  18. package/dist/providers/catalog/coarena/metadata.js +104 -0
  19. package/dist/providers/catalog/coarena/provider.js +91 -0
  20. package/dist/providers/catalog/coarena/quota.js +119 -0
  21. package/dist/providers/catalog/iflow/provider.js +1 -1
  22. package/dist/providers/catalog/iteracompute/metadata.js +154 -13
  23. package/dist/providers/catalog/iteracompute/provider.js +111 -0
  24. package/dist/providers/catalog/opencode-go/responsesPayload.js +1 -1
  25. package/dist/providers/catalog/openrouter/metadata.js +1 -0
  26. package/dist/providers/core/base/baseProvider.js +5 -3
  27. package/dist/providers/generated/chunks/chunk1.js +2 -2
  28. package/dist/providers/generated/chunks/chunk2.js +2 -2
  29. package/dist/providers/generated/chunks/chunk3.js +2 -2
  30. package/dist/providers/generated/chunks/chunk4.js +2 -0
  31. package/dist/providers/generated/runtime/chunk1.js +2 -2
  32. package/dist/providers/generated/runtime/chunk2.js +2 -2
  33. package/dist/providers/generated/runtime/chunk3.js +2 -2
  34. package/dist/providers/generated/runtime/chunk4.js +2 -0
  35. package/dist/providers/runtime/antigravity/executor.js +2 -2
  36. package/dist/providers/runtime/antigravity/metadata.js +2 -2
  37. package/dist/providers/runtime/antigravity/models.js +9 -0
  38. package/dist/providers/runtime/antigravity/provider.js +2 -2
  39. package/dist/providers/runtime/antigravity/routes.js +2 -2
  40. package/dist/providers/runtime/antigravity/schema.js +1 -1
  41. package/dist/providers/runtime/antigravity/types.js +10 -2
  42. package/dist/providers/runtime/gemini/provider.js +77 -0
  43. package/dist/providers/runtime/gemini-cli/provider.js +2 -2
  44. package/dist/providers/runtime/github/routes.js +1 -1
  45. package/dist/providers/runtime/grok/provider.js +1 -1
  46. package/dist/providers/runtime/kiro/provider.js +1 -1
  47. package/dist/providers/runtime/minimax/routes.js +0 -1
  48. package/dist/providers/runtime/opencode/tools.js +1 -1
  49. package/dist/providers/runtime/trae/index.js +1 -0
  50. package/dist/providers/runtime/trae/metadata.js +1 -0
  51. package/dist/providers/runtime/trae/provider.js +7 -0
  52. package/dist/providers/runtime/trae/quota.js +99 -0
  53. package/dist/providers/runtime/windsurf/routes.js +0 -2
  54. package/dist/providers/runtime/xkiro/quota.js +4 -1
  55. package/dist/providers/runtime/zed/metadata.js +1 -1
  56. package/dist/providers/runtime/zed/models.js +68 -8
  57. package/dist/providers/runtime/zed/provider.js +60 -15
  58. package/dist/providers/runtime/zed/quota.js +69 -12
  59. package/dist/providers/runtime/zed/routes.js +7 -0
  60. package/dist/server/proxy/executorHelpers.js +1 -1
  61. package/dist/server/proxy/index.js +1 -1
  62. package/dist/server/proxy/pipeline.js +12 -6
  63. package/dist/server/proxy/responseHandlers.js +2 -18
  64. package/dist/server/proxy/singleModelExecutor.js +1 -1
  65. package/dist/server/proxy/streaming/sseStreamer.js +3 -10
  66. package/dist/server/routes/apiMitm.js +1 -1
  67. package/dist/server/routes/apiModels.js +17 -12
  68. package/dist/server/utils/consoleLogBuffer.js +3 -3
  69. package/dist/shared/constants/index.js +2 -2
  70. package/dist/shared/constants/quotaOrder.js +5 -0
  71. package/dist/shared/logger.js +2 -2
  72. package/dist/storage/repositories/logRepo.js +3 -23
  73. package/dist/storage/repositories/requestDetailsRepo.js +1 -1
  74. package/dist/storage/repositories/usageRepo.js +136 -74
  75. package/dist/web/assets/{CliToolsTab-CkzwuwaC.js → CliToolsTab-BYO-wJ7y.js} +1 -1
  76. package/dist/web/assets/CombosTab-CujUAbYQ.js +1 -0
  77. package/dist/web/assets/{ConfirmModal-DGvcf0gB.js → ConfirmModal-BS3mAUd5.js} +1 -1
  78. package/dist/web/assets/{ConsoleLogTab-84Ens8T5.js → ConsoleLogTab-CSgZxPGW.js} +1 -1
  79. package/dist/web/assets/{EditAccountModal-D-_omvev.js → EditAccountModal-BhPOk3Ya.js} +1 -1
  80. package/dist/web/assets/{EndpointTab-7nBfEdYE.js → EndpointTab-BRVjAng2.js} +1 -1
  81. package/dist/web/assets/{MitmTab-CqS6mXHZ.js → MitmTab-ZOoWyRnb.js} +5 -5
  82. package/dist/web/assets/{ModelAutocompleteInput-B9syrV1O.js → ModelAutocompleteInput-DJkxW2yD.js} +1 -1
  83. package/dist/web/assets/{ProviderDetailPage-DGZceQ2d.js → ProviderDetailPage-CnWjM-0J.js} +2 -2
  84. package/dist/web/assets/ProvidersTab-BFdg0gXr.js +1 -0
  85. package/dist/web/assets/QuotaTab-DXg3adeS.js +1 -0
  86. package/dist/web/assets/{SettingsTab-4c0ksNJa.js → SettingsTab-DoYGKtDn.js} +1 -1
  87. package/dist/web/assets/UsageTab-O6OK0i38.js +1 -0
  88. package/dist/web/assets/index-5TzViNxR.js +2 -0
  89. package/dist/web/assets/metadataRegistry-W75_wn57.js +1 -0
  90. package/dist/web/assets/providers/coarena/icon.png +0 -0
  91. package/dist/web/assets/providers/coarena/icon.svg +3 -0
  92. package/dist/web/assets/providers/openrouter/icon.png +0 -0
  93. package/dist/web/assets/{providersData-DkVCRBsJ.js → providersData-BI_7MaUL.js} +1 -1
  94. package/dist/web/index.html +1 -1
  95. package/package.json +9 -1
  96. package/dist/web/assets/CombosTab-C5RzRwwr.js +0 -1
  97. package/dist/web/assets/ProvidersTab-CiYbqRou.js +0 -1
  98. package/dist/web/assets/QuotaTab-DFr0DWAU.js +0 -1
  99. package/dist/web/assets/UsageTab-BQcPmvtQ.js +0 -1
  100. package/dist/web/assets/index-C4NTQZ40.js +0 -2
  101. package/dist/web/assets/metadataRegistry-B91sal4r.js +0 -1
  102. package/dist/web/assets/providers/openrouter/openrouter.png +0 -0
@@ -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
  });
@@ -48,7 +48,7 @@ export function resolveTargetModelAndProvider(modelStr) {
48
48
  const rawProvider = effective.slice(0, slash);
49
49
  targetModel = effective.slice(slash + 1);
50
50
  // Parse provider[tag] syntax, e.g. claude[pro] -> provider: claude, tag: pro
51
- const tagMatch = rawProvider.match(/^([^\[\]]+)\[([^\[\]]+)\]$/);
51
+ const tagMatch = rawProvider.match(/^([^[\]]+)\[([^[\]]+)\]$/);
52
52
  if (tagMatch) {
53
53
  providerId = tagMatch[1];
54
54
  targetTag = tagMatch[2];
@@ -32,7 +32,7 @@ export async function handleProxyRequest(req, res, clientFormat) {
32
32
  providedKey = apiKeyHeader.trim();
33
33
  }
34
34
  // Resolve client gateway API key if provided
35
- let matchedKey = providedKey ? allKeys.find((k) => safeCompareKeys(k.key, providedKey)) : undefined;
35
+ const matchedKey = providedKey ? allKeys.find((k) => safeCompareKeys(k.key, providedKey)) : undefined;
36
36
  if (endpointSettings.requireApiKey) {
37
37
  const activeKeys = allKeys.filter((k) => k.isActive);
38
38
  if (activeKeys.length === 0 || !matchedKey || !matchedKey.isActive) {
@@ -14,6 +14,7 @@ import { AnthropicAdapter } from "../../core/adapters/anthropicAdapter.js";
14
14
  import { convertOpenAiResponseToResponsesApi } from "../../core/adapters/responsesAdapter.js";
15
15
  import { sanitizeErrorMessage } from "../../shared/utils/errorSanitizer.js";
16
16
  import { resolveTargetModelAndProvider } from "./executorHelpers.js";
17
+ import { extractUsageTokens } from "../../core/usage/tokenExtractor.js";
17
18
  import crypto from "node:crypto";
18
19
  export function formatProxyErrorResponse(status, message, clientFormat) {
19
20
  if (clientFormat === "anthropic") {
@@ -255,10 +256,15 @@ export async function runProxyPipeline(req, res, clientFormat) {
255
256
  let promptTokens = 0;
256
257
  let completionTokens = 0;
257
258
  let cachedTokens = 0;
258
- if (typeof respData === "object" && respData !== null && respData.usage) {
259
- promptTokens = respData.usage.prompt_tokens ?? respData.usage.input_tokens ?? 0;
260
- completionTokens = respData.usage.completion_tokens ?? respData.usage.output_tokens ?? 0;
261
- cachedTokens = respData.usage.prompt_tokens_details?.cached_tokens ?? 0;
259
+ let cacheCreationTokens = 0;
260
+ let reasoningTokens = 0;
261
+ if (typeof respData === "object" && respData !== null && (respData.usage || respData.usageMetadata)) {
262
+ const extracted = extractUsageTokens(respData);
263
+ promptTokens = extracted.promptTokens;
264
+ completionTokens = extracted.completionTokens;
265
+ cachedTokens = extracted.cachedTokens;
266
+ cacheCreationTokens = extracted.cacheCreationTokens;
267
+ reasoningTokens = extracted.reasoningTokens;
262
268
  }
263
269
  ResponseLogger.logSuccess({
264
270
  requestId,
@@ -273,8 +279,8 @@ export async function runProxyPipeline(req, res, clientFormat) {
273
279
  promptTokens,
274
280
  completionTokens,
275
281
  cachedTokens,
276
- cacheCreationTokens: 0,
277
- reasoningTokens: 0,
282
+ cacheCreationTokens,
283
+ reasoningTokens,
278
284
  tokensSavedByRtk: rtkStats.tokensSaved,
279
285
  is1mContext,
280
286
  requestHeaders: req.headers,
@@ -7,6 +7,7 @@ import { reasoningCache } from "../../core/caching/reasoningCache.js";
7
7
  import { OpenAiAdapter } from "../../core/adapters/openAiAdapter.js";
8
8
  import { AnthropicAdapter } from "../../core/adapters/anthropicAdapter.js";
9
9
  import { convertOpenAiResponseToResponsesApi } from "../../core/adapters/responsesAdapter.js";
10
+ import { extractUsageTokens } from "../../core/usage/tokenExtractor.js";
10
11
  export async function handleNonStreamingResponse(upstreamRes, res, context, provider, meta) {
11
12
  const { startTime, targetModel, rawModel, clientTool, rtkStats, is1mContext, req, account } = context;
12
13
  const durationMs = Date.now() - startTime;
@@ -42,24 +43,7 @@ export async function handleNonStreamingResponse(upstreamRes, res, context, prov
42
43
  else {
43
44
  res.status(200).send(responseBody);
44
45
  }
45
- const usage = responseBody?.usage || {};
46
- let promptTokens = usage.prompt_tokens ?? usage.input_tokens ?? usage.prompt_eval_count ?? rtkStats.compressedTokens ?? 0;
47
- const completionTokens = usage.completion_tokens ?? usage.output_tokens ?? usage.eval_count ?? 0;
48
- const cachedTokens = usage.prompt_tokens_details?.cached_tokens ??
49
- usage.input_tokens_details?.cached_tokens ??
50
- usage.prompt_cache_hit_tokens ??
51
- usage.cache_read_input_tokens ??
52
- usage.cachedContentTokenCount ??
53
- usage.cached_tokens ??
54
- 0;
55
- const cacheCreationTokens = usage.cache_creation_input_tokens ?? 0;
56
- const reasoningTokens = usage.completion_tokens_details?.reasoning_tokens ??
57
- usage.output_tokens_details?.reasoning_tokens ??
58
- usage.reasoning_tokens ??
59
- 0;
60
- if (usage.input_tokens !== undefined && usage.prompt_tokens === undefined) {
61
- promptTokens = (usage.input_tokens || 0) + cachedTokens + cacheCreationTokens;
62
- }
46
+ const { promptTokens, completionTokens, cachedTokens, cacheCreationTokens, reasoningTokens, } = extractUsageTokens(responseBody, rtkStats.compressedTokens ?? 0);
63
47
  const calculatedCost = ResponseLogger.logSuccess({
64
48
  requestId: context.requestId,
65
49
  startTime,
@@ -54,7 +54,7 @@ function cloneBodyForUpstream(body) {
54
54
  export async function executeSingleModel(options) {
55
55
  const { req, res, body, modelStr, clientFormat, isPanel = false, requestId, startTime, clientTool, rawModel, rtkStats, is1mContext: optionIs1m, reqTag = options.req.reqTag || tagForSession(options.requestId), apiKeyId, apiKeyName, } = options;
56
56
  const resolved = resolveTargetModelAndProvider(modelStr);
57
- let targetModel = resolved.targetModel;
57
+ const targetModel = resolved.targetModel;
58
58
  const providerId = resolved.providerId;
59
59
  const targetTag = resolved.targetTag;
60
60
  const is1mContext = Boolean(optionIs1m || resolved.is1mContext);
@@ -84,16 +84,9 @@ export async function pipeSseStream(upstreamRes, clientRes, context, provider) {
84
84
  }
85
85
  };
86
86
  // 1. Read and verify initial chunk before committing HTTP headers to client
87
- let firstReadDone = false;
88
- let firstReadValue;
89
- try {
90
- const firstRead = await reader.read();
91
- firstReadDone = firstRead.done;
92
- firstReadValue = firstRead.value;
93
- }
94
- catch (err) {
95
- throw err;
96
- }
87
+ const firstRead = await reader.read();
88
+ const firstReadDone = firstRead.done;
89
+ const firstReadValue = firstRead.value;
97
90
  if (firstReadDone && !firstReadValue) {
98
91
  throw new Error("Upstream stream ended immediately without sending any data");
99
92
  }
@@ -69,7 +69,7 @@ mitmRouter.get("/status", async (_req, res) => {
69
69
  augmentModels: MitmRepository.getAllToolAugmentModels(),
70
70
  });
71
71
  }
72
- catch (error) {
72
+ catch {
73
73
  res.json({
74
74
  running: MitmRepository.getMitmServerRunning(),
75
75
  certExists: true,
@@ -92,28 +92,33 @@ modelRouter.get("/available", (req, res) => {
92
92
  pId = m.slice(0, slash);
93
93
  }
94
94
  else {
95
+ // Check static PROVIDER_REGISTRY presets
95
96
  for (const prov of Object.values(PROVIDER_REGISTRY)) {
96
97
  if (prov?.models?.some((pm) => pm.id === m)) {
97
98
  pId = prov.id;
98
99
  break;
99
100
  }
100
101
  }
101
- }
102
- if (pId) {
103
- let count = activeCounts.get(pId) || 0;
104
- const regProv = PROVIDER_REGISTRY[pId];
105
- if (regProv) {
106
- if (regProv.alias && regProv.alias !== regProv.id) {
107
- count += activeCounts.get(regProv.alias) || 0;
108
- }
109
- if (regProv.aliases) {
110
- for (const a of regProv.aliases) {
111
- if (a !== regProv.id && a !== regProv.alias) {
112
- count += activeCounts.get(a) || 0;
102
+ // Check configured dbProviders if not in static registry
103
+ if (!pId) {
104
+ for (const dbP of dbProviders) {
105
+ if (Array.isArray(dbP.models)) {
106
+ const hasModel = dbP.models.some((dm) => {
107
+ const id = typeof dm === "string" ? dm : dm?.id;
108
+ return id === m || id === `${dbP.id}/${m}`;
109
+ });
110
+ if (hasModel) {
111
+ pId = dbP.id;
112
+ break;
113
113
  }
114
114
  }
115
115
  }
116
116
  }
117
+ }
118
+ // Strip account tag if present (e.g. claude[pro] -> claude)
119
+ const cleanPId = pId.replace(/\[.*\]$/, "");
120
+ if (cleanPId) {
121
+ const count = getProviderAccountsCount(cleanPId);
117
122
  if (count > 0) {
118
123
  comboHasConnected = true;
119
124
  comboAccountsCount += count;
@@ -43,8 +43,8 @@ export function stripAnsi(str) {
43
43
  export function maskSecretsInText(text) {
44
44
  if (!text || typeof text !== "string")
45
45
  return text;
46
- let result = text.replace(/Bearer\s+([A-Za-z0-9_\-\.]{8,})/gi, (_m, t) => `Bearer ${maskKey(t)}`);
47
- result = result.replace(/sk-[A-Za-z0-9_\-]{8,}/g, (m) => maskKey(m));
46
+ let result = text.replace(/Bearer\s+([A-Za-z0-9_.-]{8,})/gi, (_m, t) => `Bearer ${maskKey(t)}`);
47
+ result = result.replace(/sk-[A-Za-z0-9_-]{8,}/g, (m) => maskKey(m));
48
48
  return result.replace(/"(password|secret|rawApiKey|client_secret|apiKey)"\s*:\s*"([^"]+)"/gi, (_m, f, val) => `"${f}":"${maskKey(val)}"`);
49
49
  }
50
50
  function formatArg(arg) {
@@ -65,7 +65,7 @@ export function parseRawLineToStructured(line, fallbackLevel = "info") {
65
65
  const cleanLine = maskSecretsInText(stripAnsi(line));
66
66
  const timeMatch = cleanLine.match(/^\[(\d{2}:\d{2}:\d{2})\]\s*/);
67
67
  let rest = timeMatch ? cleanLine.slice(timeMatch[0].length) : cleanLine;
68
- const tagMatch = rest.match(/^([🟢🔵🟣🟡🟠🔴⚪🟤📥▶⚙🔀🔑🔄🌊📊❌✔⚠️💥📤🛠️])\s*/u);
68
+ const tagMatch = rest.match(/^(🟢|🔵|🟣|🟡|🟠|🔴|⚪|🟤|📥|▶|⚙|🔀|🔑|🔄|🌊|📊|❌|✔|⚠️|💥|📤|🛠️)\s*/u);
69
69
  const reqTag = tagMatch ? tagMatch[1] : undefined;
70
70
  if (tagMatch)
71
71
  rest = rest.slice(tagMatch[0].length);
@@ -36,10 +36,10 @@ export function isTestEnvironment() {
36
36
  process.env.npm_lifecycle_event === "pretest") {
37
37
  return true;
38
38
  }
39
- if (Boolean(process.env.NODE_TEST_CONTEXT)) {
39
+ if (process.env.NODE_TEST_CONTEXT) {
40
40
  return true;
41
41
  }
42
- if (Boolean(process.env.MAPIGATE_DATA_DIR?.includes("test"))) {
42
+ if (process.env.MAPIGATE_DATA_DIR?.includes("test")) {
43
43
  return true;
44
44
  }
45
45
  const args = [...(process.execArgv || []), ...(process.argv || [])];
@@ -132,6 +132,11 @@ const FALLBACK_QUOTA_ORDER_MAP = {
132
132
  "Monthly Tokens",
133
133
  "Weekly Quota",
134
134
  ],
135
+ trae: [
136
+ "Dollar Usage",
137
+ "Autocomplete",
138
+ "Fast Requests",
139
+ ],
135
140
  };
136
141
  /**
137
142
  * Proxy that pulls quotaOrder dynamically from provider metadata in metadataRegistry,
@@ -140,10 +140,10 @@ export function sanitizeMetadata(data, depth = 0, seen = new WeakSet()) {
140
140
  if (data === null || data === undefined)
141
141
  return data;
142
142
  if (typeof data === "string") {
143
- if (/^Bearer\s+[A-Za-z0-9_\-\.]{8,}$/i.test(data)) {
143
+ if (/^Bearer\s+[A-Za-z0-9_.-]{8,}$/i.test(data)) {
144
144
  return `Bearer ${maskKey(data.slice(7).trim())}`;
145
145
  }
146
- if (/^sk-[A-Za-z0-9_\-]{8,}$/i.test(data)) {
146
+ if (/^sk-[A-Za-z0-9_-]{8,}$/i.test(data)) {
147
147
  return maskKey(data);
148
148
  }
149
149
  return data;
@@ -1,17 +1,16 @@
1
1
  import { getDatabase } from "../database.js";
2
- import { SettingsRepository } from "./settingsRepo.js";
3
2
  export class LogRepository {
4
3
  static saveLog(log) {
5
4
  const db = getDatabase();
6
- db.run(`INSERT OR REPLACE INTO request_logs (
5
+ const insertResult = db.run(`INSERT OR IGNORE INTO request_logs (
7
6
  id, timestamp, client_tool, requested_model, actual_model,
8
7
  provider_id, prompt_tokens, completion_tokens, tokens_saved_by_rtk,
9
8
  cached_tokens, cache_creation_tokens, cost, account_id, account_name,
10
9
  api_key_id, api_key_name, duration_ms, status, error_message
11
10
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, log.id, log.timestamp, log.clientTool, log.requestedModel, log.actualModel, log.providerId, log.promptTokens || 0, log.completionTokens || 0, log.tokensSavedByRtk || 0, log.cachedTokens || 0, log.cacheCreationTokens || 0, log.cost || 0, log.accountId || null, log.accountName || null, log.apiKeyId || null, log.apiKeyName || null, log.durationMs || 0, log.status, log.errorMessage || null);
12
- // Roll up into daily_usage_stats for perpetual history (only for requests with actual token usage)
11
+ // Roll up into daily_usage_stats only when this log ID was newly inserted (prevents double-counting on duplicate calls)
13
12
  const hasTokens = (log.promptTokens || 0) + (log.completionTokens || 0) > 0;
14
- if (hasTokens) {
13
+ if (insertResult.changes > 0 && hasTokens) {
15
14
  try {
16
15
  const d = new Date(log.timestamp);
17
16
  const dateStr = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
@@ -41,25 +40,6 @@ export class LogRepository {
41
40
  // Best effort rollup
42
41
  }
43
42
  }
44
- // Periodic retention prune (1 in 50 writes) to keep database lean and prevent unbounded table growth
45
- if (Math.random() < 0.02) {
46
- try {
47
- const retentionDays = SettingsRepository.getLogRetentionDays();
48
- if (retentionDays > 0) {
49
- const cutoffTs = Date.now() - retentionDays * 24 * 60 * 60 * 1000;
50
- db.run("DELETE FROM request_logs WHERE timestamp < ?", cutoffTs);
51
- }
52
- const maxLogs = Number(process.env.MAPIGATE_MAX_LOGS) || 20000;
53
- const countRow = db.get("SELECT COUNT(*) as count FROM request_logs");
54
- if (countRow && countRow.count > maxLogs) {
55
- const excess = countRow.count - maxLogs;
56
- db.run("DELETE FROM request_logs WHERE id IN (SELECT id FROM request_logs ORDER BY timestamp ASC LIMIT ?)", excess);
57
- }
58
- }
59
- catch {
60
- // Best effort
61
- }
62
- }
63
43
  }
64
44
  static getRecentLogs(limit = 100) {
65
45
  const db = getDatabase();
@@ -15,7 +15,7 @@ export function getMaxRecords() {
15
15
  const DEFAULT_BATCH_SIZE = 10;
16
16
  const DEFAULT_FLUSH_INTERVAL_MS = 3000;
17
17
  const MAX_JSON_SIZE = 1024 * 1024; // 1MB max per json payload to preserve full coding assistant payloads
18
- let writeBuffer = [];
18
+ const writeBuffer = [];
19
19
  let flushTimer = null;
20
20
  let isFlushing = false;
21
21
  function sanitizeHeaders(headers) {