commons-proxy 2.0.0

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 (99) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +757 -0
  3. package/bin/cli.js +146 -0
  4. package/package.json +97 -0
  5. package/public/Complaint Details.pdf +0 -0
  6. package/public/Cyber Crime Portal.pdf +0 -0
  7. package/public/app.js +229 -0
  8. package/public/css/src/input.css +523 -0
  9. package/public/css/style.css +1 -0
  10. package/public/favicon.png +0 -0
  11. package/public/index.html +549 -0
  12. package/public/js/components/account-manager.js +356 -0
  13. package/public/js/components/add-account-modal.js +414 -0
  14. package/public/js/components/claude-config.js +420 -0
  15. package/public/js/components/dashboard/charts.js +605 -0
  16. package/public/js/components/dashboard/filters.js +362 -0
  17. package/public/js/components/dashboard/stats.js +110 -0
  18. package/public/js/components/dashboard.js +236 -0
  19. package/public/js/components/logs-viewer.js +100 -0
  20. package/public/js/components/models.js +36 -0
  21. package/public/js/components/server-config.js +349 -0
  22. package/public/js/config/constants.js +102 -0
  23. package/public/js/data-store.js +375 -0
  24. package/public/js/settings-store.js +58 -0
  25. package/public/js/store.js +99 -0
  26. package/public/js/translations/en.js +367 -0
  27. package/public/js/translations/id.js +412 -0
  28. package/public/js/translations/pt.js +308 -0
  29. package/public/js/translations/tr.js +358 -0
  30. package/public/js/translations/zh.js +373 -0
  31. package/public/js/utils/account-actions.js +189 -0
  32. package/public/js/utils/error-handler.js +96 -0
  33. package/public/js/utils/model-config.js +42 -0
  34. package/public/js/utils/ui-logger.js +143 -0
  35. package/public/js/utils/validators.js +77 -0
  36. package/public/js/utils.js +69 -0
  37. package/public/proxy-server-64.png +0 -0
  38. package/public/views/accounts.html +361 -0
  39. package/public/views/dashboard.html +484 -0
  40. package/public/views/logs.html +97 -0
  41. package/public/views/models.html +331 -0
  42. package/public/views/settings.html +1327 -0
  43. package/src/account-manager/credentials.js +378 -0
  44. package/src/account-manager/index.js +462 -0
  45. package/src/account-manager/onboarding.js +112 -0
  46. package/src/account-manager/rate-limits.js +369 -0
  47. package/src/account-manager/storage.js +160 -0
  48. package/src/account-manager/strategies/base-strategy.js +109 -0
  49. package/src/account-manager/strategies/hybrid-strategy.js +339 -0
  50. package/src/account-manager/strategies/index.js +79 -0
  51. package/src/account-manager/strategies/round-robin-strategy.js +76 -0
  52. package/src/account-manager/strategies/sticky-strategy.js +138 -0
  53. package/src/account-manager/strategies/trackers/health-tracker.js +162 -0
  54. package/src/account-manager/strategies/trackers/index.js +9 -0
  55. package/src/account-manager/strategies/trackers/quota-tracker.js +120 -0
  56. package/src/account-manager/strategies/trackers/token-bucket-tracker.js +155 -0
  57. package/src/auth/database.js +169 -0
  58. package/src/auth/oauth.js +548 -0
  59. package/src/auth/token-extractor.js +117 -0
  60. package/src/cli/accounts.js +648 -0
  61. package/src/cloudcode/index.js +29 -0
  62. package/src/cloudcode/message-handler.js +510 -0
  63. package/src/cloudcode/model-api.js +248 -0
  64. package/src/cloudcode/rate-limit-parser.js +235 -0
  65. package/src/cloudcode/request-builder.js +93 -0
  66. package/src/cloudcode/session-manager.js +47 -0
  67. package/src/cloudcode/sse-parser.js +121 -0
  68. package/src/cloudcode/sse-streamer.js +293 -0
  69. package/src/cloudcode/streaming-handler.js +615 -0
  70. package/src/config.js +125 -0
  71. package/src/constants.js +407 -0
  72. package/src/errors.js +242 -0
  73. package/src/fallback-config.js +29 -0
  74. package/src/format/content-converter.js +193 -0
  75. package/src/format/index.js +20 -0
  76. package/src/format/request-converter.js +255 -0
  77. package/src/format/response-converter.js +120 -0
  78. package/src/format/schema-sanitizer.js +673 -0
  79. package/src/format/signature-cache.js +88 -0
  80. package/src/format/thinking-utils.js +648 -0
  81. package/src/index.js +148 -0
  82. package/src/modules/usage-stats.js +205 -0
  83. package/src/providers/anthropic-provider.js +258 -0
  84. package/src/providers/base-provider.js +157 -0
  85. package/src/providers/cloudcode.js +94 -0
  86. package/src/providers/copilot.js +399 -0
  87. package/src/providers/github-provider.js +287 -0
  88. package/src/providers/google-provider.js +192 -0
  89. package/src/providers/index.js +211 -0
  90. package/src/providers/openai-compatible.js +265 -0
  91. package/src/providers/openai-provider.js +271 -0
  92. package/src/providers/openrouter-provider.js +325 -0
  93. package/src/providers/setup.js +83 -0
  94. package/src/server.js +870 -0
  95. package/src/utils/claude-config.js +245 -0
  96. package/src/utils/helpers.js +51 -0
  97. package/src/utils/logger.js +142 -0
  98. package/src/utils/native-module-helper.js +162 -0
  99. package/src/webui/index.js +1134 -0
@@ -0,0 +1,121 @@
1
+ /**
2
+ * SSE Parser for Cloud Code
3
+ *
4
+ * Parses SSE responses for non-streaming thinking models.
5
+ * Accumulates all parts and returns a single response.
6
+ */
7
+
8
+ import { convertGoogleToAnthropic } from '../format/index.js';
9
+ import { logger } from '../utils/logger.js';
10
+
11
+ /**
12
+ * Parse SSE response for thinking models and accumulate all parts
13
+ *
14
+ * @param {Response} response - The HTTP response with SSE body
15
+ * @param {string} originalModel - The original model name
16
+ * @returns {Promise<Object>} Anthropic-format response object
17
+ */
18
+ export async function parseThinkingSSEResponse(response, originalModel) {
19
+ let accumulatedThinkingText = '';
20
+ let accumulatedThinkingSignature = '';
21
+ let accumulatedText = '';
22
+ const finalParts = [];
23
+ let usageMetadata = {};
24
+ let finishReason = 'STOP';
25
+
26
+ const flushThinking = () => {
27
+ if (accumulatedThinkingText) {
28
+ finalParts.push({
29
+ thought: true,
30
+ text: accumulatedThinkingText,
31
+ thoughtSignature: accumulatedThinkingSignature
32
+ });
33
+ accumulatedThinkingText = '';
34
+ accumulatedThinkingSignature = '';
35
+ }
36
+ };
37
+
38
+ const flushText = () => {
39
+ if (accumulatedText) {
40
+ finalParts.push({ text: accumulatedText });
41
+ accumulatedText = '';
42
+ }
43
+ };
44
+
45
+ const reader = response.body.getReader();
46
+ const decoder = new TextDecoder();
47
+ let buffer = '';
48
+
49
+ while (true) {
50
+ const { done, value } = await reader.read();
51
+ if (done) break;
52
+
53
+ buffer += decoder.decode(value, { stream: true });
54
+ const lines = buffer.split('\n');
55
+ buffer = lines.pop() || '';
56
+
57
+ for (const line of lines) {
58
+ if (!line.startsWith('data:')) continue;
59
+ const jsonText = line.slice(5).trim();
60
+ if (!jsonText) continue;
61
+
62
+ try {
63
+ const data = JSON.parse(jsonText);
64
+ const innerResponse = data.response || data;
65
+
66
+ if (innerResponse.usageMetadata) {
67
+ usageMetadata = innerResponse.usageMetadata;
68
+ }
69
+
70
+ const candidates = innerResponse.candidates || [];
71
+ const firstCandidate = candidates[0] || {};
72
+ if (firstCandidate.finishReason) {
73
+ finishReason = firstCandidate.finishReason;
74
+ }
75
+
76
+ const parts = firstCandidate.content?.parts || [];
77
+ for (const part of parts) {
78
+ if (part.thought === true) {
79
+ flushText();
80
+ accumulatedThinkingText += (part.text || '');
81
+ if (part.thoughtSignature) {
82
+ accumulatedThinkingSignature = part.thoughtSignature;
83
+ }
84
+ } else if (part.functionCall) {
85
+ flushThinking();
86
+ flushText();
87
+ finalParts.push(part);
88
+ } else if (part.text !== undefined) {
89
+ if (!part.text) continue;
90
+ flushThinking();
91
+ accumulatedText += part.text;
92
+ } else if (part.inlineData) {
93
+ // Handle image content
94
+ flushThinking();
95
+ flushText();
96
+ finalParts.push(part);
97
+ }
98
+ }
99
+ } catch (e) {
100
+ logger.debug('[CloudCode] SSE parse warning:', e.message, 'Raw:', jsonText.slice(0, 100));
101
+ }
102
+ }
103
+ }
104
+
105
+ flushThinking();
106
+ flushText();
107
+
108
+ const accumulatedResponse = {
109
+ candidates: [{ content: { parts: finalParts }, finishReason }],
110
+ usageMetadata
111
+ };
112
+
113
+ const partTypes = finalParts.map(p => p.thought ? 'thought' : (p.functionCall ? 'functionCall' : (p.inlineData ? 'inlineData' : 'text')));
114
+ logger.debug('[CloudCode] Response received (SSE), part types:', partTypes);
115
+ if (finalParts.some(p => p.thought)) {
116
+ const thinkingPart = finalParts.find(p => p.thought);
117
+ logger.debug('[CloudCode] Thinking signature length:', thinkingPart?.thoughtSignature?.length || 0);
118
+ }
119
+
120
+ return convertGoogleToAnthropic(accumulatedResponse, originalModel);
121
+ }
@@ -0,0 +1,293 @@
1
+ /**
2
+ * SSE Streamer for Cloud Code
3
+ *
4
+ * Streams SSE events in real-time, converting Google format to Anthropic format.
5
+ * Handles thinking blocks, text blocks, and tool use blocks.
6
+ */
7
+
8
+ import crypto from 'crypto';
9
+ import { MIN_SIGNATURE_LENGTH, getModelFamily } from '../constants.js';
10
+ import { EmptyResponseError } from '../errors.js';
11
+ import { cacheSignature, cacheThinkingSignature } from '../format/signature-cache.js';
12
+ import { logger } from '../utils/logger.js';
13
+
14
+ /**
15
+ * Stream SSE response and yield Anthropic-format events
16
+ *
17
+ * @param {Response} response - The HTTP response with SSE body
18
+ * @param {string} originalModel - The original model name
19
+ * @yields {Object} Anthropic-format SSE events
20
+ */
21
+ export async function* streamSSEResponse(response, originalModel) {
22
+ const messageId = `msg_${crypto.randomBytes(16).toString('hex')}`;
23
+ let hasEmittedStart = false;
24
+ let blockIndex = 0;
25
+ let currentBlockType = null;
26
+ let currentThinkingSignature = '';
27
+ let inputTokens = 0;
28
+ let outputTokens = 0;
29
+ let cacheReadTokens = 0;
30
+ let stopReason = null;
31
+
32
+ const reader = response.body.getReader();
33
+ const decoder = new TextDecoder();
34
+ let buffer = '';
35
+
36
+ while (true) {
37
+ const { done, value } = await reader.read();
38
+ if (done) break;
39
+
40
+ buffer += decoder.decode(value, { stream: true });
41
+ const lines = buffer.split('\n');
42
+ buffer = lines.pop() || '';
43
+
44
+ for (const line of lines) {
45
+ if (!line.startsWith('data:')) continue;
46
+
47
+ const jsonText = line.slice(5).trim();
48
+ if (!jsonText) continue;
49
+
50
+ try {
51
+ const data = JSON.parse(jsonText);
52
+ const innerResponse = data.response || data;
53
+
54
+ // Extract usage metadata (including cache tokens)
55
+ const usage = innerResponse.usageMetadata;
56
+ if (usage) {
57
+ inputTokens = usage.promptTokenCount || inputTokens;
58
+ outputTokens = usage.candidatesTokenCount || outputTokens;
59
+ cacheReadTokens = usage.cachedContentTokenCount || cacheReadTokens;
60
+ }
61
+
62
+ const candidates = innerResponse.candidates || [];
63
+ const firstCandidate = candidates[0] || {};
64
+ const content = firstCandidate.content || {};
65
+ const parts = content.parts || [];
66
+
67
+ // Emit message_start on first data
68
+ // Note: input_tokens = promptTokenCount - cachedContentTokenCount (Antigravity includes cached in total)
69
+ if (!hasEmittedStart && parts.length > 0) {
70
+ hasEmittedStart = true;
71
+ yield {
72
+ type: 'message_start',
73
+ message: {
74
+ id: messageId,
75
+ type: 'message',
76
+ role: 'assistant',
77
+ content: [],
78
+ model: originalModel,
79
+ stop_reason: null,
80
+ stop_sequence: null,
81
+ usage: {
82
+ input_tokens: inputTokens - cacheReadTokens,
83
+ output_tokens: 0,
84
+ cache_read_input_tokens: cacheReadTokens,
85
+ cache_creation_input_tokens: 0
86
+ }
87
+ }
88
+ };
89
+ }
90
+
91
+ // Process each part
92
+ for (const part of parts) {
93
+ if (part.thought === true) {
94
+ // Handle thinking block
95
+ const text = part.text || '';
96
+ const signature = part.thoughtSignature || '';
97
+
98
+ if (currentBlockType !== 'thinking') {
99
+ if (currentBlockType !== null) {
100
+ yield { type: 'content_block_stop', index: blockIndex };
101
+ blockIndex++;
102
+ }
103
+ currentBlockType = 'thinking';
104
+ currentThinkingSignature = '';
105
+ yield {
106
+ type: 'content_block_start',
107
+ index: blockIndex,
108
+ content_block: { type: 'thinking', thinking: '' }
109
+ };
110
+ }
111
+
112
+ if (signature && signature.length >= MIN_SIGNATURE_LENGTH) {
113
+ currentThinkingSignature = signature;
114
+ // Cache thinking signature with model family for cross-model compatibility
115
+ const modelFamily = getModelFamily(originalModel);
116
+ cacheThinkingSignature(signature, modelFamily);
117
+ }
118
+
119
+ yield {
120
+ type: 'content_block_delta',
121
+ index: blockIndex,
122
+ delta: { type: 'thinking_delta', thinking: text }
123
+ };
124
+
125
+ } else if (part.text !== undefined) {
126
+ // Skip empty text parts (but preserve whitespace-only chunks for proper spacing)
127
+ if (part.text === '') {
128
+ continue;
129
+ }
130
+
131
+ // Handle regular text
132
+ if (currentBlockType !== 'text') {
133
+ if (currentBlockType === 'thinking' && currentThinkingSignature) {
134
+ yield {
135
+ type: 'content_block_delta',
136
+ index: blockIndex,
137
+ delta: { type: 'signature_delta', signature: currentThinkingSignature }
138
+ };
139
+ currentThinkingSignature = '';
140
+ }
141
+ if (currentBlockType !== null) {
142
+ yield { type: 'content_block_stop', index: blockIndex };
143
+ blockIndex++;
144
+ }
145
+ currentBlockType = 'text';
146
+ yield {
147
+ type: 'content_block_start',
148
+ index: blockIndex,
149
+ content_block: { type: 'text', text: '' }
150
+ };
151
+ }
152
+
153
+ yield {
154
+ type: 'content_block_delta',
155
+ index: blockIndex,
156
+ delta: { type: 'text_delta', text: part.text }
157
+ };
158
+
159
+ } else if (part.functionCall) {
160
+ // Handle tool use
161
+ // For Gemini 3+, capture thoughtSignature from the functionCall part
162
+ // The signature is a sibling to functionCall, not inside it
163
+ const functionCallSignature = part.thoughtSignature || '';
164
+
165
+ if (currentBlockType === 'thinking' && currentThinkingSignature) {
166
+ yield {
167
+ type: 'content_block_delta',
168
+ index: blockIndex,
169
+ delta: { type: 'signature_delta', signature: currentThinkingSignature }
170
+ };
171
+ currentThinkingSignature = '';
172
+ }
173
+ if (currentBlockType !== null) {
174
+ yield { type: 'content_block_stop', index: blockIndex };
175
+ blockIndex++;
176
+ }
177
+ currentBlockType = 'tool_use';
178
+ stopReason = 'tool_use';
179
+
180
+ const toolId = part.functionCall.id || `toolu_${crypto.randomBytes(12).toString('hex')}`;
181
+
182
+ // For Gemini, include the thoughtSignature in the tool_use block
183
+ // so it can be sent back in subsequent requests
184
+ const toolUseBlock = {
185
+ type: 'tool_use',
186
+ id: toolId,
187
+ name: part.functionCall.name,
188
+ input: {}
189
+ };
190
+
191
+ // Store the signature in the tool_use block for later retrieval
192
+ if (functionCallSignature && functionCallSignature.length >= MIN_SIGNATURE_LENGTH) {
193
+ toolUseBlock.thoughtSignature = functionCallSignature;
194
+ // Cache for future requests (Claude Code may strip this field)
195
+ cacheSignature(toolId, functionCallSignature);
196
+ }
197
+
198
+ yield {
199
+ type: 'content_block_start',
200
+ index: blockIndex,
201
+ content_block: toolUseBlock
202
+ };
203
+
204
+ yield {
205
+ type: 'content_block_delta',
206
+ index: blockIndex,
207
+ delta: {
208
+ type: 'input_json_delta',
209
+ partial_json: JSON.stringify(part.functionCall.args || {})
210
+ }
211
+ };
212
+ } else if (part.inlineData) {
213
+ // Handle image content from Google format
214
+ if (currentBlockType === 'thinking' && currentThinkingSignature) {
215
+ yield {
216
+ type: 'content_block_delta',
217
+ index: blockIndex,
218
+ delta: { type: 'signature_delta', signature: currentThinkingSignature }
219
+ };
220
+ currentThinkingSignature = '';
221
+ }
222
+ if (currentBlockType !== null) {
223
+ yield { type: 'content_block_stop', index: blockIndex };
224
+ blockIndex++;
225
+ }
226
+ currentBlockType = 'image';
227
+
228
+ // Emit image block as a complete block
229
+ yield {
230
+ type: 'content_block_start',
231
+ index: blockIndex,
232
+ content_block: {
233
+ type: 'image',
234
+ source: {
235
+ type: 'base64',
236
+ media_type: part.inlineData.mimeType,
237
+ data: part.inlineData.data
238
+ }
239
+ }
240
+ };
241
+
242
+ yield { type: 'content_block_stop', index: blockIndex };
243
+ blockIndex++;
244
+ currentBlockType = null;
245
+ }
246
+ }
247
+
248
+ // Check finish reason (only if not already set by tool_use)
249
+ if (firstCandidate.finishReason && !stopReason) {
250
+ if (firstCandidate.finishReason === 'MAX_TOKENS') {
251
+ stopReason = 'max_tokens';
252
+ } else if (firstCandidate.finishReason === 'STOP') {
253
+ stopReason = 'end_turn';
254
+ }
255
+ }
256
+
257
+ } catch (parseError) {
258
+ logger.warn('[CloudCode] SSE parse error:', parseError.message);
259
+ }
260
+ }
261
+ }
262
+
263
+ // Handle no content received - throw error to trigger retry in streaming-handler
264
+ if (!hasEmittedStart) {
265
+ logger.warn('[CloudCode] No content parts received, throwing for retry');
266
+ throw new EmptyResponseError('No content parts received from API');
267
+ } else {
268
+ // Close any open block
269
+ if (currentBlockType !== null) {
270
+ if (currentBlockType === 'thinking' && currentThinkingSignature) {
271
+ yield {
272
+ type: 'content_block_delta',
273
+ index: blockIndex,
274
+ delta: { type: 'signature_delta', signature: currentThinkingSignature }
275
+ };
276
+ }
277
+ yield { type: 'content_block_stop', index: blockIndex };
278
+ }
279
+ }
280
+
281
+ // Emit message_delta and message_stop
282
+ yield {
283
+ type: 'message_delta',
284
+ delta: { stop_reason: stopReason || 'end_turn', stop_sequence: null },
285
+ usage: {
286
+ output_tokens: outputTokens,
287
+ cache_read_input_tokens: cacheReadTokens,
288
+ cache_creation_input_tokens: 0
289
+ }
290
+ };
291
+
292
+ yield { type: 'message_stop' };
293
+ }