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,261 @@
1
+ import { createHash } from "crypto";
2
+ import { Hono } from "hono";
3
+ import { fetchQwenModels } from "../services/qwen.js";
4
+ import { loadAccounts } from "../core/accounts.ts";
5
+ import { getAccountCooldownInfo } from "../core/account-manager.ts";
6
+ import { getAccountsByPriority } from "../core/account-priority.ts";
7
+ import { NotFoundError } from "../core/errors.js";
8
+ import { sendOpenAIError } from "./error-helpers.js";
9
+ import {
10
+ getModelCapabilities,
11
+ getModelContextWindow,
12
+ syncModelMetadata,
13
+ } from "../core/model-registry.ts";
14
+ import { listMediaGenerationModels } from "../services/media-generation.ts";
15
+ import { isPlaywrightInitialized } from "../services/playwright.ts";
16
+
17
+ const app = new Hono();
18
+
19
+ /**
20
+ * Stable creation timestamp for synthetic media models.
21
+ * Uses a fixed value so the ETag remains stable across requests.
22
+ * 2025-01-01T00:00:00Z
23
+ */
24
+ const MEDIA_MODELS_CREATED_AT = 1735689600;
25
+
26
+ function getPreferredModelsAccountId(): string | undefined {
27
+ try {
28
+ const accounts = loadAccounts();
29
+ if (accounts.length === 0) return undefined;
30
+
31
+ // Prefer an account whose browser is already open so the models fetch
32
+ // reuses the running session instead of launching a new browser for a
33
+ // standby account. Among usable accounts, follow the same priority
34
+ // order as request routing.
35
+ const usable = getAccountsByPriority(accounts).filter(
36
+ (account) => !getAccountCooldownInfo(account.id),
37
+ );
38
+ const initialized = usable.find((account) =>
39
+ isPlaywrightInitialized(account.id),
40
+ );
41
+ return (initialized || usable[0] || accounts[0]).id;
42
+ } catch {
43
+ return undefined;
44
+ }
45
+ }
46
+
47
+ export type PublicModel = {
48
+ id: string;
49
+ object?: string;
50
+ created?: number;
51
+ owned_by?: string;
52
+ context_window?: number;
53
+ is_active?: boolean;
54
+ capabilities?: Record<string, unknown>;
55
+ [key: string]: unknown;
56
+ };
57
+
58
+ function baseModelId(modelId: string): string {
59
+ // Strip any reasoning suffix (-low, -medium, -high, -fast, -thinking) so the
60
+ // public /v1/models catalog returns strictly canonical unique base models without duplicates.
61
+ return modelId.replace(/-(?:low|medium|high|fast|no-thinking|thinking)$/, "");
62
+ }
63
+ /**
64
+ * Returns the public model catalog from the selected account's live
65
+ * catalog. Suffixes (-fast/-thinking) are not synthesized; reasoning
66
+ * is controlled via standard `reasoning_effort` (low/medium/high).
67
+ */
68
+ export function expandModelVariants(
69
+ models: PublicModel[],
70
+ accountId?: string,
71
+ ): PublicModel[] {
72
+ syncModelMetadata(
73
+ models as unknown as Array<Record<string, unknown> & { id: string }>,
74
+ accountId,
75
+ );
76
+ const baseModels = new Map<string, PublicModel>();
77
+
78
+ for (const model of models) {
79
+ if (!model?.id) continue;
80
+ const baseId = baseModelId(model.id);
81
+ if (!baseModels.has(baseId)) {
82
+ baseModels.set(baseId, {
83
+ ...model,
84
+ id: baseId,
85
+ object: "model",
86
+ });
87
+ }
88
+ }
89
+
90
+ return [...baseModels.values()];
91
+ }
92
+
93
+ function toAnthropicModel(model: PublicModel, accountId?: string) {
94
+ const capabilities = getModelCapabilities(model.id, accountId);
95
+ const isFastVariant = model.id.endsWith("-fast");
96
+ const contextWindow =
97
+ model.context_window ?? getModelContextWindow(model.id, accountId);
98
+
99
+ return {
100
+ id: model.id,
101
+ display_name:
102
+ typeof model.name === "string" && model.name ? model.name : model.id,
103
+ created_at: new Date(
104
+ typeof model.created === "number" ? model.created * 1000 : Date.now(),
105
+ ).toISOString(),
106
+ max_input_tokens: contextWindow,
107
+ max_tokens: capabilities.maxOutputTokens,
108
+ type: "model" as const,
109
+ capabilities: {
110
+ batch: { supported: false },
111
+ citations: { supported: capabilities.supportsCitations },
112
+ code_execution: { supported: capabilities.supportsCodeExecution },
113
+ image_input: { supported: capabilities.supportsVision },
114
+ pdf_input: { supported: capabilities.supportsDocument },
115
+ structured_outputs: {
116
+ supported: capabilities.supportsStructuredOutputs,
117
+ },
118
+ thinking: {
119
+ supported: capabilities.supportsThinking,
120
+ types: {
121
+ enabled: { supported: capabilities.supportsThinking },
122
+ disabled: {
123
+ supported: isFastVariant || capabilities.canSkipThinking,
124
+ },
125
+ },
126
+ },
127
+ audio_input: { supported: capabilities.supportsAudio },
128
+ video_input: { supported: capabilities.supportsVideo },
129
+ },
130
+ };
131
+ }
132
+
133
+ function wantsAnthropicModelsFormat(
134
+ anthropicVersion: string | undefined | null,
135
+ ): boolean {
136
+ return !!anthropicVersion;
137
+ }
138
+
139
+ async function loadModelsWithVariants(): Promise<{
140
+ models: PublicModel[];
141
+ accountId?: string;
142
+ }> {
143
+ const accountId = getPreferredModelsAccountId();
144
+ const models = (await fetchQwenModels(accountId)) as unknown as PublicModel[];
145
+ const expanded = expandModelVariants(models, accountId);
146
+
147
+ // Advertise media generation models so clients can discover them via
148
+ // /v1/models, including their supported generation modalities. Annotate a
149
+ // live model in place when Qwen already returned the same ID.
150
+ const mediaDefinitions = listMediaGenerationModels();
151
+ const mediaById = new Map(mediaDefinitions.map((definition) => [definition.id, definition]));
152
+ const expandedWithMedia = expanded.map((model) => {
153
+ const definition = mediaById.get(model.id);
154
+ if (!definition) return model;
155
+ return {
156
+ ...model,
157
+ media_generation: definition.kind,
158
+ media_modes: definition.modes,
159
+ media_reference_required: definition.modes.every(
160
+ (mode) => mode === "i2i" || mode === "i2v",
161
+ ),
162
+ };
163
+ });
164
+ const existing = new Set(expanded.map((model) => model.id));
165
+ const mediaModels: PublicModel[] = mediaDefinitions
166
+ .filter(({ id }) => !existing.has(id))
167
+ .map(({ id, kind, modes }) => ({
168
+ id,
169
+ object: "model",
170
+ created: MEDIA_MODELS_CREATED_AT,
171
+ owned_by: "qwen",
172
+ media_generation: kind,
173
+ media_modes: modes,
174
+ media_reference_required: modes.every(
175
+ (mode) => mode === "i2i" || mode === "i2v",
176
+ ),
177
+ }));
178
+
179
+ return {
180
+ models: [...expandedWithMedia, ...mediaModels],
181
+ accountId,
182
+ };
183
+ }
184
+
185
+ function findModel(
186
+ models: PublicModel[],
187
+ modelId: string,
188
+ ): PublicModel | undefined {
189
+ // Variants are materialized by expandModelVariants only when the live
190
+ // catalog says they are supported. Do not synthesize an invalid variant for
191
+ // a direct lookup.
192
+ return models.find((entry) => entry.id === modelId);
193
+ }
194
+
195
+ app.get("/v1/models", async (c) => {
196
+ try {
197
+ const { models: allModels, accountId } = await loadModelsWithVariants();
198
+ const anthropic = wantsAnthropicModelsFormat(c.req.header("anthropic-version"));
199
+
200
+ if (anthropic) {
201
+ return c.json({
202
+ data: allModels.map((model) => toAnthropicModel(model, accountId)),
203
+ has_more: false,
204
+ });
205
+ }
206
+
207
+ const etag = `"${createHash("md5").update(JSON.stringify(allModels)).digest("hex")}"`;
208
+
209
+ if (c.req.header("if-none-match") === etag) {
210
+ return c.body(null, 304);
211
+ }
212
+
213
+ c.header("Cache-Control", "public, max-age=3600");
214
+ c.header("ETag", etag);
215
+
216
+ return c.json({
217
+ object: "list",
218
+ data: allModels,
219
+ });
220
+ } catch (error) {
221
+ console.error("❌ [Models] Error fetching models:", error);
222
+ return sendOpenAIError(c, error);
223
+ }
224
+ });
225
+
226
+ app.get("/v1/models/:model", async (c) => {
227
+ try {
228
+ const modelId = c.req.param("model");
229
+ const { models: allModels, accountId } = await loadModelsWithVariants();
230
+ const model = findModel(allModels, modelId);
231
+ const anthropic = wantsAnthropicModelsFormat(c.req.header("anthropic-version"));
232
+
233
+ if (!model) {
234
+ if (anthropic) {
235
+ return c.json(
236
+ {
237
+ type: "error",
238
+ error: {
239
+ type: "not_found_error",
240
+ message: `Model '${modelId}' not found`,
241
+ },
242
+ },
243
+ 404,
244
+ );
245
+ }
246
+ return sendOpenAIError(c, new NotFoundError("Model not found"));
247
+ }
248
+
249
+ if (anthropic) {
250
+ return c.json(toAnthropicModel(model, accountId));
251
+ }
252
+
253
+ return c.json(model);
254
+ } catch (error) {
255
+ console.error("❌ [Models] Error fetching model:", error);
256
+ return sendOpenAIError(c, error);
257
+ }
258
+ });
259
+
260
+
261
+ export { app };