qwenproxy-cli 1.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 (109) hide show
  1. package/LICENSE +14 -0
  2. package/README.md +907 -0
  3. package/bin/qwenproxy.js +141 -0
  4. package/package.json +78 -0
  5. package/src/api/error-classifier.ts +159 -0
  6. package/src/api/error-helpers.ts +118 -0
  7. package/src/api/models.ts +261 -0
  8. package/src/api/server.ts +859 -0
  9. package/src/cache/memory-cache.ts +385 -0
  10. package/src/clean-cache.ts +204 -0
  11. package/src/core/account-concurrency.ts +671 -0
  12. package/src/core/account-manager.ts +297 -0
  13. package/src/core/account-priority.ts +163 -0
  14. package/src/core/accounts.ts +186 -0
  15. package/src/core/config.ts +383 -0
  16. package/src/core/crypto-utils.ts +79 -0
  17. package/src/core/database.ts +276 -0
  18. package/src/core/errors.ts +118 -0
  19. package/src/core/logger.ts +269 -0
  20. package/src/core/memory-usage.ts +84 -0
  21. package/src/core/metrics.ts +291 -0
  22. package/src/core/model-alias.ts +77 -0
  23. package/src/core/model-registry.ts +544 -0
  24. package/src/core/mutex.ts +119 -0
  25. package/src/core/paths.ts +199 -0
  26. package/src/core/prompt-limits.ts +214 -0
  27. package/src/core/reasoning-effort.ts +102 -0
  28. package/src/core/stream-registry.ts +96 -0
  29. package/src/core/waf-isolation.ts +117 -0
  30. package/src/core/watchdog.ts +195 -0
  31. package/src/delete-chats.ts +23 -0
  32. package/src/index.ts +64 -0
  33. package/src/login.ts +147 -0
  34. package/src/reset-cooldowns.ts +11 -0
  35. package/src/routes/anthropic/index.ts +355 -0
  36. package/src/routes/anthropic/translate.ts +522 -0
  37. package/src/routes/anthropic/types.ts +154 -0
  38. package/src/routes/anthropic/validation.ts +144 -0
  39. package/src/routes/chat/account.ts +1817 -0
  40. package/src/routes/chat/context.ts +241 -0
  41. package/src/routes/chat/errors.ts +85 -0
  42. package/src/routes/chat/helpers.ts +268 -0
  43. package/src/routes/chat/index.ts +618 -0
  44. package/src/routes/chat/media.ts +285 -0
  45. package/src/routes/chat/retry-policy.ts +754 -0
  46. package/src/routes/chat/stop.ts +98 -0
  47. package/src/routes/chat/streaming.ts +2710 -0
  48. package/src/routes/chat/validation.ts +526 -0
  49. package/src/routes/chat.ts +2 -0
  50. package/src/routes/completions.ts +290 -0
  51. package/src/routes/images.ts +139 -0
  52. package/src/routes/responses/adapter.ts +503 -0
  53. package/src/routes/responses/index.ts +405 -0
  54. package/src/routes/responses/state.ts +230 -0
  55. package/src/routes/responses/streaming.ts +528 -0
  56. package/src/routes/responses/types.ts +285 -0
  57. package/src/routes/responses/validation.ts +202 -0
  58. package/src/routes/upload.ts +731 -0
  59. package/src/routes/videos.ts +214 -0
  60. package/src/services/auth-playwright.ts +173 -0
  61. package/src/services/captcha-coordinator.ts +161 -0
  62. package/src/services/captcha-solver.ts +553 -0
  63. package/src/services/chat-cleanup.ts +80 -0
  64. package/src/services/context-meter.ts +317 -0
  65. package/src/services/fingerprint.ts +242 -0
  66. package/src/services/human-behavior.ts +173 -0
  67. package/src/services/media-generation.ts +1748 -0
  68. package/src/services/playwright.ts +2800 -0
  69. package/src/services/qwen-chat-pool.ts +345 -0
  70. package/src/services/qwen-errors.ts +133 -0
  71. package/src/services/qwen-headers.ts +79 -0
  72. package/src/services/qwen-thread-state.ts +393 -0
  73. package/src/services/qwen-url.ts +19 -0
  74. package/src/services/qwen.ts +3126 -0
  75. package/src/services/session-keeper.ts +88 -0
  76. package/src/services/token-estimation-metrics.ts +118 -0
  77. package/src/sync/claude-code.ts +75 -0
  78. package/src/sync/codex.ts +123 -0
  79. package/src/sync/index.ts +362 -0
  80. package/src/sync/omp.ts +105 -0
  81. package/src/sync/opencode.ts +214 -0
  82. package/src/sync/types.ts +53 -0
  83. package/src/sync/utils.ts +27 -0
  84. package/src/sync-clients.ts +189 -0
  85. package/src/tools/instructions.ts +137 -0
  86. package/src/tools/manifest.ts +81 -0
  87. package/src/tools/parser.ts +2989 -0
  88. package/src/tools/toolcall-tags.ts +142 -0
  89. package/src/tools/types.ts +53 -0
  90. package/src/tui/app.ts +264 -0
  91. package/src/tui/index.ts +61 -0
  92. package/src/tui/markdown.ts +258 -0
  93. package/src/tui/proxy-client.ts +326 -0
  94. package/src/tui/screen.ts +278 -0
  95. package/src/tui/server-manager.ts +270 -0
  96. package/src/tui/theme.ts +432 -0
  97. package/src/tui/types.ts +33 -0
  98. package/src/tui/views/accounts-view.ts +656 -0
  99. package/src/tui/views/chat-view.ts +823 -0
  100. package/src/tui/views/logs-view.ts +413 -0
  101. package/src/tui/views/status-view.ts +204 -0
  102. package/src/tui/views/storage-view.ts +291 -0
  103. package/src/tui/views/sync-view.ts +409 -0
  104. package/src/types/ali-oss.d.ts +32 -0
  105. package/src/utils/context-truncation.ts +84 -0
  106. package/src/utils/json.ts +380 -0
  107. package/src/utils/session-id.ts +37 -0
  108. package/src/utils/tool-call-guard.ts +85 -0
  109. package/src/utils/types.ts +109 -0
@@ -0,0 +1,355 @@
1
+ import crypto from "crypto";
2
+ import { Hono, type Context } from "hono";
3
+ import { stream as honoStream } from "hono/streaming";
4
+ import { config } from "../../core/config.ts";
5
+ import { validateAnthropicRequest } from "./validation.ts";
6
+ import {
7
+ translateAnthropicToOpenAI,
8
+ translateOpenAIToAnthropic,
9
+ translateStreamChunk,
10
+ generateMessageId,
11
+ type AnthropicStreamState,
12
+ } from "./translate.ts";
13
+ import type { AnthropicRequest, OpenAIResponse } from "./types.ts";
14
+ import { estimateTokenCount } from "../../utils/context-truncation.ts";
15
+
16
+ const app = new Hono();
17
+
18
+ function generateRequestId(): string {
19
+ return `req_${crypto.randomBytes(12).toString("hex")}`;
20
+ }
21
+
22
+ export function anthropicError(
23
+ c: Context,
24
+ type: string,
25
+ message: string,
26
+ statusCode: number,
27
+ ) {
28
+ c.header("anthropic-version", c.req.header("anthropic-version") || "2023-06-01");
29
+ return c.json(
30
+ {
31
+ type: "error",
32
+ error: { type, message },
33
+ request_id: generateRequestId(),
34
+ },
35
+ statusCode as any,
36
+ );
37
+ }
38
+
39
+ function constantTimeStringEqual(provided: string, expected: string): boolean {
40
+ const providedBuf = Buffer.from(provided);
41
+ const expectedBuf = Buffer.from(expected);
42
+ const providedHash = crypto.createHash("sha256").update(providedBuf).digest();
43
+ const expectedHash = crypto.createHash("sha256").update(expectedBuf).digest();
44
+
45
+ return (
46
+ crypto.timingSafeEqual(providedHash, expectedHash) &&
47
+ providedBuf.length === expectedBuf.length
48
+ );
49
+ }
50
+
51
+ export function verifyAnthropicApiKey(c: Context): boolean {
52
+ const apiKey = process.env.API_KEY || config.apiKey;
53
+ if (!apiKey) return true; // No key configured = open access
54
+
55
+ const candidates: string[] = [];
56
+ const auth = c.req.header("Authorization");
57
+ if (auth?.startsWith("Bearer ")) {
58
+ const token = auth.slice(7).trim();
59
+ if (token) candidates.push(token);
60
+ }
61
+ const xApiKey = c.req.header("x-api-key")?.trim();
62
+ if (xApiKey) candidates.push(xApiKey);
63
+
64
+ if (candidates.length === 0) return false;
65
+ return candidates.some((key) => constantTimeStringEqual(key, apiKey));
66
+ }
67
+
68
+ /**
69
+ * POST /v1/messages - Anthropic Messages API compatible endpoint.
70
+ */
71
+ app.post("/v1/messages", async (c) => {
72
+ const requestId = generateRequestId();
73
+ const anthropicVersion = c.req.header("anthropic-version") || "2023-06-01";
74
+
75
+ // 1. Verify API key
76
+ if (!verifyAnthropicApiKey(c)) {
77
+ return anthropicError(c, "authentication_error", "Invalid API key", 401);
78
+ }
79
+
80
+ // 2. Parse & Validate body
81
+ let body: AnthropicRequest;
82
+ try {
83
+ body = await c.req.json();
84
+ } catch {
85
+ return anthropicError(c, "invalid_request_error", "Invalid JSON body", 400);
86
+ }
87
+
88
+ const validation = validateAnthropicRequest(body);
89
+ if (!validation.valid) {
90
+ return anthropicError(c, "invalid_request_error", validation.error!, 400);
91
+ }
92
+
93
+ const isStream = body.stream ?? false;
94
+ const requestModel = body.model;
95
+
96
+
97
+ try {
98
+ // 3. Translate Anthropic request to internal OpenAI format
99
+ const openaiRequest = translateAnthropicToOpenAI(body);
100
+
101
+ const dispatchToChat = (streamMode: boolean) =>
102
+ fetch(`http://127.0.0.1:${config.server.port}/v1/chat/completions`, {
103
+ method: "POST",
104
+ headers: {
105
+ "Content-Type": "application/json",
106
+ Authorization: `Bearer ${process.env.API_KEY || config.apiKey || ""}`,
107
+ "x-qwenproxy-route": "Anthropic",
108
+ },
109
+ body: JSON.stringify({
110
+ ...openaiRequest,
111
+ stream: streamMode,
112
+ ...(streamMode ? { stream_options: { include_usage: true } } : {}),
113
+ }),
114
+ signal: c.req.raw.signal,
115
+ });
116
+
117
+ if (isStream) {
118
+ // ============ STREAMING MODE ============
119
+ const socket =
120
+ (c.env as any)?.incoming?.socket || (c.req.raw as any)?.socket;
121
+ if (socket && typeof socket.setNoDelay === "function") {
122
+ socket.setNoDelay(true);
123
+ }
124
+
125
+ c.header("Content-Type", "text/event-stream; charset=utf-8");
126
+ c.header("Cache-Control", "no-cache, no-transform");
127
+ c.header("Connection", "keep-alive");
128
+ c.header("X-Accel-Buffering", "no");
129
+ c.header("anthropic-version", anthropicVersion);
130
+ c.header("request-id", requestId);
131
+ return honoStream(c, async (stream) => {
132
+ const encoder = new TextEncoder();
133
+ const write = async (data: string) => {
134
+ await stream.write(encoder.encode(data));
135
+ };
136
+
137
+ const messageId = generateMessageId();
138
+ const state: AnthropicStreamState = {
139
+ contentBlockIndex: 0,
140
+ currentBlockType: null,
141
+ currentToolId: null,
142
+ currentToolIndex: null,
143
+ requestModel,
144
+ inputTokens: 0,
145
+ outputTokens: 0,
146
+ hasEmittedToolUse: false,
147
+ };
148
+
149
+ // Emit initial message_start event
150
+ const messageStart = {
151
+ type: "message_start",
152
+ message: {
153
+ id: messageId,
154
+ type: "message",
155
+ role: "assistant",
156
+ content: [],
157
+ model: requestModel,
158
+ stop_reason: null,
159
+ stop_sequence: null,
160
+ usage: { input_tokens: 0, output_tokens: 1 },
161
+ },
162
+ };
163
+ await write(
164
+ `event: message_start\ndata: ${JSON.stringify(messageStart)}\n\n`,
165
+ );
166
+
167
+ // Keep-alive heartbeat
168
+ const heartbeatInterval = setInterval(() => {
169
+ write(": keep-alive\n\n").catch(() => clearInterval(heartbeatInterval));
170
+ }, 15000);
171
+
172
+ try {
173
+ const response = await dispatchToChat(true);
174
+
175
+ if (!response.ok) {
176
+ clearInterval(heartbeatInterval);
177
+ const errText = await response.text().catch(() => "");
178
+ console.error(`[Anthropic] Upstream error: ${response.status} ${errText}`);
179
+ await write(
180
+ `event: error\ndata: ${JSON.stringify({
181
+ type: "error",
182
+ error: {
183
+ type: response.status === 429 ? "rate_limit_error" : "api_error",
184
+ message: `Upstream error: ${response.status}`,
185
+ },
186
+ })}\n\n`,
187
+ );
188
+ return;
189
+ }
190
+
191
+ const reader = response.body?.getReader();
192
+ if (!reader) {
193
+ throw new Error("No response body from internal chat stream");
194
+ }
195
+
196
+ const decoder = new TextDecoder();
197
+ let buffer = "";
198
+
199
+ try {
200
+ while (true) {
201
+ const { done, value } = await reader.read();
202
+ if (done) break;
203
+
204
+ buffer += decoder.decode(value, { stream: true });
205
+ const lines = buffer.split("\n");
206
+ buffer = lines.pop() || "";
207
+
208
+ for (const line of lines) {
209
+ const trimmed = line.trim();
210
+ if (!trimmed.startsWith("data: ")) continue;
211
+ const dataStr = trimmed.slice(6);
212
+ if (dataStr === "[DONE]") continue;
213
+
214
+ try {
215
+ const chunk = JSON.parse(dataStr);
216
+ const events = translateStreamChunk(chunk, state);
217
+ for (const event of events) {
218
+ const parsed = JSON.parse(event);
219
+ await write(`event: ${parsed.type}\ndata: ${event}\n\n`);
220
+ }
221
+ } catch {
222
+ // Skip invalid JSON lines
223
+ }
224
+ }
225
+ }
226
+ } finally {
227
+ reader.releaseLock();
228
+ }
229
+
230
+ // Close any remaining open content block before ending message
231
+ if (state.currentBlockType !== null) {
232
+ await write(
233
+ `event: content_block_stop\ndata: ${JSON.stringify({
234
+ type: "content_block_stop",
235
+ index: state.contentBlockIndex,
236
+ })}\n\n`,
237
+ );
238
+ state.contentBlockIndex++;
239
+ state.currentBlockType = null;
240
+ }
241
+
242
+ // Emit final message_stop
243
+ await write(
244
+ `event: message_stop\ndata: ${JSON.stringify({ type: "message_stop" })}\n\n`,
245
+ );
246
+ } catch (error: any) {
247
+ console.error("❌ [Anthropic] Stream error:", error?.message || error);
248
+ try {
249
+ await write(
250
+ `event: error\ndata: ${JSON.stringify({
251
+ type: "error",
252
+ error: { type: "api_error", message: error?.message || "Stream error" },
253
+ })}\n\n`,
254
+ );
255
+ } catch {
256
+ // Client closed connection
257
+ }
258
+ } finally {
259
+ clearInterval(heartbeatInterval);
260
+ }
261
+ });
262
+ } else {
263
+ // ============ NON-STREAMING MODE ============
264
+ const response = await dispatchToChat(false);
265
+
266
+ if (!response.ok) {
267
+ const errorJson = await response.json().catch(() => null);
268
+ const errorText = errorJson?.error?.message || `HTTP ${response.status}`;
269
+ console.error(`[Anthropic] Upstream error: ${response.status} ${errorText}`);
270
+
271
+ const errorType =
272
+ response.status === 429
273
+ ? "rate_limit_error"
274
+ : response.status === 404
275
+ ? "not_found_error"
276
+ : response.status === 400
277
+ ? "invalid_request_error"
278
+ : "api_error";
279
+
280
+ return anthropicError(c, errorType, errorText, response.status);
281
+ }
282
+
283
+ const openaiResponse: OpenAIResponse = await response.json();
284
+ const anthropicResponse = translateOpenAIToAnthropic(
285
+ openaiResponse,
286
+ requestModel,
287
+ );
288
+
289
+
290
+ c.header("anthropic-version", anthropicVersion);
291
+ c.header("request-id", requestId);
292
+
293
+ return c.json(anthropicResponse);
294
+ }
295
+ } catch (error: any) {
296
+ console.error("❌ [Anthropic] Error:", error);
297
+ return anthropicError(
298
+ c,
299
+ "api_error",
300
+ error?.message || "Internal server error",
301
+ 500,
302
+ );
303
+ }
304
+ });
305
+
306
+ /**
307
+ * POST /v1/messages/count_tokens - Anthropic Token Counting API.
308
+ */
309
+ app.post("/v1/messages/count_tokens", async (c) => {
310
+ if (!verifyAnthropicApiKey(c)) {
311
+ return anthropicError(c, "authentication_error", "Invalid API key", 401);
312
+ }
313
+
314
+ try {
315
+ const body = await c.req.json();
316
+ if (!body || typeof body !== "object") {
317
+ return anthropicError(c, "invalid_request_error", "Request body must be a JSON object", 400);
318
+ }
319
+
320
+ let textToCount = "";
321
+ if (typeof body.system === "string") {
322
+ textToCount += body.system + " ";
323
+ } else if (Array.isArray(body.system)) {
324
+ textToCount += body.system.map((s: any) => s?.text || "").join(" ") + " ";
325
+ }
326
+
327
+ if (Array.isArray(body.messages)) {
328
+ for (const m of body.messages) {
329
+ if (typeof m.content === "string") {
330
+ textToCount += m.content + " ";
331
+ } else if (Array.isArray(m.content)) {
332
+ for (const b of m.content) {
333
+ if (b?.text) textToCount += b.text + " ";
334
+ if (b?.content) textToCount += (typeof b.content === "string" ? b.content : JSON.stringify(b.content)) + " ";
335
+ }
336
+ }
337
+ }
338
+ }
339
+
340
+ if (Array.isArray(body.tools)) {
341
+ textToCount += JSON.stringify(body.tools);
342
+ }
343
+
344
+ const inputTokens = Math.max(1, estimateTokenCount(textToCount));
345
+
346
+ c.header("anthropic-version", c.req.header("anthropic-version") || "2023-06-01");
347
+ return c.json({
348
+ input_tokens: inputTokens,
349
+ });
350
+ } catch {
351
+ return anthropicError(c, "invalid_request_error", "Invalid request body", 400);
352
+ }
353
+ });
354
+
355
+ export { app as anthropicApp };