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,362 @@
1
+ import "dotenv/config";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import os from "node:os";
5
+
6
+ import { config } from "../core/config.ts";
7
+ import { getSyncStatePath } from "../core/paths.ts";
8
+ import type {
9
+ ClientSyncResult,
10
+ SyncAllOptions,
11
+ SyncRecord,
12
+ SyncStateFile,
13
+ } from "./types.ts";
14
+ import { syncClaudeCode, restoreClaudeCode } from "./claude-code.ts";
15
+ import { syncCodex, restoreCodex } from "./codex.ts";
16
+ import { syncOpenCode, restoreOpenCode } from "./opencode.ts";
17
+ import { syncOmp, restoreOmp } from "./omp.ts";
18
+
19
+ export function resolveApiKey(overrideKey?: string, configKey?: string): string {
20
+ if (overrideKey && overrideKey.trim().length > 0) {
21
+ return overrideKey.trim();
22
+ }
23
+ const envKey = process.env.API_KEY || process.env.ADMIN_PASSWORD || configKey;
24
+ if (envKey && envKey.trim().length > 0) {
25
+ return envKey.trim();
26
+ }
27
+ return "sk-qwenproxy-local";
28
+ }
29
+ export function normalizeClientName(name: string): "claude-code" | "codex" | "opencode" | "omp" | null {
30
+ const clean = name.trim().toLowerCase().replace(/[-_ ]/g, "");
31
+ if (clean === "claude" || clean === "claudecode" || clean === "anthropic") return "claude-code";
32
+ if (clean === "codex" || clean === "codexcli" || clean === "openai") return "codex";
33
+ if (clean === "opencode") return "opencode";
34
+ if (clean === "omp" || clean === "ohmypi") return "omp";
35
+ return null;
36
+ }
37
+
38
+ export function resolveBaseUrls(port = 7936, host = "127.0.0.1"): {
39
+ anthropicBaseUrl: string;
40
+ openaiBaseUrl: string;
41
+ } {
42
+ const cleanHost = host === "0.0.0.0" ? "127.0.0.1" : host;
43
+ return {
44
+ anthropicBaseUrl: `http://${cleanHost}:${port}`,
45
+ openaiBaseUrl: `http://${cleanHost}:${port}/v1`,
46
+ };
47
+ }
48
+
49
+ export function getDefaultPaths(): {
50
+ claudeCode: string;
51
+ codex: string;
52
+ openCode: string;
53
+ omp: string;
54
+ } {
55
+ const home = os.homedir();
56
+
57
+ // OpenCode can be ~/.config/opencode/opencode.jsonc or ~/.opencode/opencode.jsonc
58
+ const openCodeCandidates = [
59
+ path.join(home, ".config", "opencode", "opencode.jsonc"),
60
+ path.join(home, ".config", "opencode", "opencode.json"),
61
+ path.join(home, ".opencode", "opencode.jsonc"),
62
+ path.join(home, ".opencode", "opencode.json"),
63
+ ];
64
+ const existingOpenCode = openCodeCandidates.find((p) => fs.existsSync(p));
65
+
66
+ return {
67
+ claudeCode: path.join(home, ".claude", "settings.json"),
68
+ codex: process.env.CODEX_HOME
69
+ ? path.join(process.env.CODEX_HOME, "config.toml")
70
+ : path.join(home, ".codex", "config.toml"),
71
+ openCode: existingOpenCode || openCodeCandidates[0],
72
+ omp: path.join(home, ".omp", "agent", "models.yml"),
73
+ };
74
+ }
75
+
76
+ export function getDefaultStateFilePath(): string {
77
+ return getSyncStatePath();
78
+ }
79
+ export interface ClientDetectionStatus {
80
+ id: "claude-code" | "codex" | "opencode" | "omp";
81
+ installed: boolean;
82
+ synced: boolean;
83
+ model?: string;
84
+ url?: string;
85
+ }
86
+
87
+ /**
88
+ * Inspects a client configuration file to determine whether the client is installed
89
+ * and whether it is actively configured to route to QwenProxy.
90
+ */
91
+ export function inspectClientSyncStatus(
92
+ id: "claude-code" | "codex" | "opencode" | "omp",
93
+ filePath?: string,
94
+ port = 7936,
95
+ ): ClientDetectionStatus {
96
+ const defaultPaths = getDefaultPaths();
97
+ const targetPath =
98
+ filePath ||
99
+ (id === "claude-code"
100
+ ? defaultPaths.claudeCode
101
+ : id === "codex"
102
+ ? defaultPaths.codex
103
+ : id === "opencode"
104
+ ? defaultPaths.openCode
105
+ : defaultPaths.omp);
106
+
107
+ if (!fs.existsSync(targetPath)) {
108
+ return { id, installed: false, synced: false };
109
+ }
110
+
111
+ try {
112
+ const raw = fs.readFileSync(targetPath, "utf-8");
113
+
114
+ if (id === "claude-code") {
115
+ const data = JSON.parse(raw);
116
+ const url = data?.env?.ANTHROPIC_BASE_URL || "";
117
+ const model = data?.env?.ANTHROPIC_MODEL || data?.model || "";
118
+ const isSynced =
119
+ (url.includes(String(port)) || url.includes("qwenproxy")) &&
120
+ (model.toLowerCase().includes("qwen") || Boolean(data?.env?.ANTHROPIC_AUTH_TOKEN));
121
+ return {
122
+ id,
123
+ installed: true,
124
+ synced: isSynced,
125
+ model: model || undefined,
126
+ url: url || undefined,
127
+ };
128
+ }
129
+
130
+ if (id === "codex") {
131
+ const hasProvider = raw.includes("[model_providers.qwenproxy]");
132
+ const isProviderActive = /^model_provider\s*=\s*["']qwenproxy["']/m.test(raw);
133
+ const modelMatch = raw.match(/^model\s*=\s*["']([^"']+)["']/m);
134
+ const model = modelMatch ? modelMatch[1] : undefined;
135
+ return {
136
+ id,
137
+ installed: true,
138
+ synced: hasProvider && isProviderActive,
139
+ model,
140
+ };
141
+ }
142
+
143
+ if (id === "opencode") {
144
+ const hasQwen =
145
+ raw.includes('"qwenproxy"') &&
146
+ (raw.includes(String(port)) || raw.includes("QwenProxy") || raw.includes("qwen3"));
147
+ return {
148
+ id,
149
+ installed: true,
150
+ synced: hasQwen,
151
+ };
152
+ }
153
+
154
+ if (id === "omp") {
155
+ const hasQwen =
156
+ /^ {2}qwenproxy:\s*$/m.test(raw) ||
157
+ raw.includes("qwenproxy:") ||
158
+ (raw.includes(String(port)) && raw.includes("qwen3"));
159
+ return {
160
+ id,
161
+ installed: true,
162
+ synced: hasQwen,
163
+ };
164
+ }
165
+ } catch {
166
+ return { id, installed: true, synced: false };
167
+ }
168
+
169
+ return { id, installed: true, synced: false };
170
+ }
171
+
172
+ export interface SyncAllResult {
173
+ apiKey: string;
174
+ port: number;
175
+ host: string;
176
+ clients: {
177
+ claudeCode?: ClientSyncResult;
178
+ codex?: ClientSyncResult;
179
+ openCode?: ClientSyncResult;
180
+ omp?: ClientSyncResult;
181
+ };
182
+ }
183
+
184
+ export function syncAllClients(options: SyncAllOptions = {}): SyncAllResult {
185
+ const defaultPaths = getDefaultPaths();
186
+ const paths = {
187
+ claudeCode: options.customPaths?.claudeCode || defaultPaths.claudeCode,
188
+ codex: options.customPaths?.codex || defaultPaths.codex,
189
+ openCode: options.customPaths?.openCode || defaultPaths.openCode,
190
+ omp: options.customPaths?.omp || defaultPaths.omp,
191
+ };
192
+
193
+ const port = options.port ?? (config.server?.port || 7936);
194
+ const configuredHost = config.server?.host;
195
+ const host = options.host ?? (configuredHost && configuredHost !== "0.0.0.0" ? configuredHost : "127.0.0.1");
196
+ const apiKey = resolveApiKey(options.apiKey, config.apiKey);
197
+ const { anthropicBaseUrl, openaiBaseUrl } = resolveBaseUrls(port, host);
198
+ const stateFilePath = options.stateFilePath || getDefaultStateFilePath();
199
+
200
+ const results: SyncAllResult = {
201
+ apiKey,
202
+ port,
203
+ host,
204
+ clients: {},
205
+ };
206
+
207
+ const stateRecords: SyncStateFile["clients"] = {};
208
+ const shouldSync = (client: "claude-code" | "codex" | "opencode" | "omp") => {
209
+ if (!options.targets || options.targets.length === 0) return true;
210
+ return options.targets.includes(client);
211
+ };
212
+
213
+ // 1. Claude Code
214
+ if (shouldSync("claude-code")) {
215
+ const claudeExisted = fs.existsSync(paths.claudeCode);
216
+ const claudeRes = syncClaudeCode({
217
+ filePath: paths.claudeCode,
218
+ apiKey,
219
+ baseUrl: anthropicBaseUrl,
220
+ });
221
+ results.clients.claudeCode = claudeRes;
222
+ if (claudeRes.success && claudeRes.backupPath) {
223
+ stateRecords.claudeCode = {
224
+ filePath: paths.claudeCode,
225
+ backupPath: claudeRes.backupPath,
226
+ existedBefore: claudeExisted,
227
+ syncedAt: Date.now(),
228
+ };
229
+ }
230
+ }
231
+
232
+ // 2. Codex
233
+ if (shouldSync("codex")) {
234
+ const codexExisted = fs.existsSync(paths.codex);
235
+ const codexRes = syncCodex({
236
+ filePath: paths.codex,
237
+ apiKey,
238
+ baseUrl: openaiBaseUrl,
239
+ setActive: options.setActive ?? true,
240
+ });
241
+ results.clients.codex = codexRes;
242
+ if (codexRes.success && codexRes.backupPath) {
243
+ stateRecords.codex = {
244
+ filePath: paths.codex,
245
+ backupPath: codexRes.backupPath,
246
+ existedBefore: codexExisted,
247
+ syncedAt: Date.now(),
248
+ };
249
+ }
250
+ }
251
+
252
+ // 3. OpenCode
253
+ if (shouldSync("opencode")) {
254
+ const openCodeExisted = fs.existsSync(paths.openCode);
255
+ const openCodeRes = syncOpenCode({
256
+ filePath: paths.openCode,
257
+ apiKey,
258
+ baseUrl: openaiBaseUrl,
259
+ });
260
+ results.clients.openCode = openCodeRes;
261
+ if (openCodeRes.success && openCodeRes.backupPath) {
262
+ stateRecords.openCode = {
263
+ filePath: paths.openCode,
264
+ backupPath: openCodeRes.backupPath,
265
+ existedBefore: openCodeExisted,
266
+ syncedAt: Date.now(),
267
+ };
268
+ }
269
+ }
270
+
271
+ // 4. OMP
272
+ if (shouldSync("omp")) {
273
+ const ompExisted = fs.existsSync(paths.omp);
274
+ const ompRes = syncOmp({
275
+ filePath: paths.omp,
276
+ apiKey,
277
+ baseUrl: openaiBaseUrl,
278
+ });
279
+ results.clients.omp = ompRes;
280
+ if (ompRes.success && ompRes.backupPath) {
281
+ stateRecords.omp = {
282
+ filePath: paths.omp,
283
+ backupPath: ompRes.backupPath,
284
+ existedBefore: ompExisted,
285
+ syncedAt: Date.now(),
286
+ };
287
+ }
288
+ }
289
+
290
+ // Persist sync state
291
+ try {
292
+ fs.mkdirSync(path.dirname(stateFilePath), { recursive: true });
293
+ const stateContent: SyncStateFile = {
294
+ version: 1,
295
+ updatedAt: new Date().toISOString(),
296
+ apiKey,
297
+ port,
298
+ host,
299
+ clients: stateRecords,
300
+ };
301
+ fs.writeFileSync(stateFilePath, JSON.stringify(stateContent, null, 2) + "\n", "utf-8");
302
+ } catch (err) {
303
+ console.error("Warning: could not write sync state file:", err);
304
+ }
305
+
306
+ return results;
307
+ }
308
+
309
+ export interface RestoreAllResult {
310
+ restoredCount: number;
311
+ details: ClientSyncResult[];
312
+ }
313
+
314
+ export function restoreAllClients(options: { stateFilePath?: string } = {}): RestoreAllResult {
315
+ const stateFilePath = options.stateFilePath || getDefaultStateFilePath();
316
+ const details: ClientSyncResult[] = [];
317
+ let restoredCount = 0;
318
+
319
+ if (!fs.existsSync(stateFilePath)) {
320
+ return { restoredCount: 0, details };
321
+ }
322
+
323
+ try {
324
+ const raw = fs.readFileSync(stateFilePath, "utf-8");
325
+ const state: SyncStateFile = JSON.parse(raw);
326
+
327
+ if (state.clients.claudeCode?.backupPath) {
328
+ const res = restoreClaudeCode(state.clients.claudeCode.filePath, state.clients.claudeCode.backupPath);
329
+ details.push(res);
330
+ if (res.success) restoredCount++;
331
+ }
332
+
333
+ if (state.clients.codex?.backupPath) {
334
+ const res = restoreCodex(state.clients.codex.filePath, state.clients.codex.backupPath);
335
+ details.push(res);
336
+ if (res.success) restoredCount++;
337
+ }
338
+
339
+ if (state.clients.openCode?.backupPath) {
340
+ const res = restoreOpenCode(state.clients.openCode.filePath, state.clients.openCode.backupPath);
341
+ details.push(res);
342
+ if (res.success) restoredCount++;
343
+ }
344
+
345
+ if (state.clients.omp?.backupPath) {
346
+ const res = restoreOmp(state.clients.omp.filePath, state.clients.omp.backupPath);
347
+ details.push(res);
348
+ if (res.success) restoredCount++;
349
+ }
350
+
351
+ // Remove state file after successful restoration
352
+ try {
353
+ fs.unlinkSync(stateFilePath);
354
+ } catch {
355
+ // Ignore
356
+ }
357
+ } catch (err) {
358
+ console.error("Error reading sync state file:", err);
359
+ }
360
+
361
+ return { restoredCount, details };
362
+ }
@@ -0,0 +1,105 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import type { ClientSyncResult, SyncOptions } from "./types.ts";
4
+ import { createTimestampBackup, restoreFromBackup } from "./utils.ts";
5
+
6
+ function buildOmpProviderYaml(baseUrl: string, apiKey: string): string {
7
+ return ` qwenproxy:
8
+ baseUrl: ${baseUrl}
9
+ api: openai-completions
10
+ apiKey: "${apiKey}"
11
+ compat:
12
+ supportsStore: true
13
+ supportsReasoningEffort: true
14
+ maxTokensField: max_completion_tokens
15
+ models:
16
+ - id: qwen3.8-max
17
+ name: Qwen3.8-Max
18
+ input: [text, image]
19
+ contextWindow: 1000000
20
+ maxTokens: 131072
21
+ reasoning: true
22
+ thinking:
23
+ mode: effort
24
+ efforts: [low, medium, high]
25
+ - id: qwen3.7-plus
26
+ name: Qwen3.7-Plus
27
+ input: [text, image]
28
+ contextWindow: 1000000
29
+ maxTokens: 131072
30
+ reasoning: true
31
+ thinking:
32
+ mode: effort
33
+ efforts: [low, medium, high]
34
+ `;
35
+ }
36
+
37
+ export function syncOmp(options: SyncOptions): ClientSyncResult {
38
+ const { filePath, apiKey, baseUrl } = options;
39
+ try {
40
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
41
+
42
+ let backupPath: string | undefined;
43
+ let content = "";
44
+
45
+ if (fs.existsSync(filePath)) {
46
+ backupPath = createTimestampBackup(filePath);
47
+ content = fs.readFileSync(filePath, "utf-8");
48
+ }
49
+
50
+ const providerBlock = buildOmpProviderYaml(baseUrl, apiKey);
51
+
52
+ if (!content.trim()) {
53
+ content = `providers:\n${providerBlock}`;
54
+ } else {
55
+ // Check if "qwenproxy:" already exists under "providers:"
56
+ const existingQwenRegex = /^ {2}qwenproxy:[\s\S]*?(?=(?:^ {2}[a-zA-Z0-9_-]+:|\Z))/m;
57
+ if (existingQwenRegex.test(content)) {
58
+ content = content.replace(existingQwenRegex, providerBlock);
59
+ } else {
60
+ const providersMatch = content.match(/^providers:\s*$/m);
61
+ if (providersMatch && providersMatch.index !== undefined) {
62
+ const insertIdx = providersMatch.index + providersMatch[0].length;
63
+ content =
64
+ content.slice(0, insertIdx) +
65
+ "\n" +
66
+ providerBlock +
67
+ content.slice(insertIdx);
68
+ } else {
69
+ content = content.trimEnd() + "\n\nproviders:\n" + providerBlock;
70
+ }
71
+ }
72
+ }
73
+
74
+ fs.writeFileSync(filePath, content.trimEnd() + "\n", "utf-8");
75
+
76
+ return {
77
+ client: "omp",
78
+ filePath,
79
+ backupPath,
80
+ success: true,
81
+ action: backupPath ? "updated" : "created",
82
+ message: `Configured OMP with provider qwenproxy (${baseUrl})`,
83
+ };
84
+ } catch (err: any) {
85
+ return {
86
+ client: "omp",
87
+ filePath,
88
+ success: false,
89
+ action: "failed",
90
+ error: err?.message || String(err),
91
+ };
92
+ }
93
+ }
94
+
95
+ export function restoreOmp(filePath: string, backupPath?: string): ClientSyncResult {
96
+ const restored = restoreFromBackup(filePath, backupPath);
97
+ return {
98
+ client: "omp",
99
+ filePath,
100
+ backupPath,
101
+ success: restored,
102
+ action: restored ? "restored" : "failed",
103
+ message: restored ? "Restored OMP models config from backup" : "Backup file not found",
104
+ };
105
+ }
@@ -0,0 +1,214 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import type { ClientSyncResult, SyncOptions } from "./types.ts";
4
+ import { createTimestampBackup, restoreFromBackup } from "./utils.ts";
5
+
6
+ function buildOpenCodeProviderObject(baseUrl: string, apiKey: string): Record<string, any> {
7
+ return {
8
+ npm: "@ai-sdk/openai-compatible",
9
+ name: "QwenProxy",
10
+ options: {
11
+ baseURL: baseUrl,
12
+ apiKey: apiKey,
13
+ },
14
+ models: {
15
+ "qwen3.8-max": {
16
+ name: "Qwen 3.8 Max",
17
+ limit: { context: 1048576, output: 65536 },
18
+ modalities: { input: ["text", "image"], output: ["text"] },
19
+ reasoning: true,
20
+ variants: {
21
+ low: { effort: "low" },
22
+ medium: { effort: "medium" },
23
+ high: { effort: "high" },
24
+ },
25
+ },
26
+ "qwen3.7-plus": {
27
+ name: "Qwen 3.7 Plus",
28
+ limit: { context: 1048576, output: 65536 },
29
+ modalities: { input: ["text", "image"], output: ["text"] },
30
+ reasoning: true,
31
+ variants: {
32
+ low: { effort: "low" },
33
+ medium: { effort: "medium" },
34
+ high: { effort: "high" },
35
+ },
36
+ },
37
+ },
38
+ };
39
+ }
40
+ function findKeyObjectSpan(content: string, key: string): { start: number; end: number; hasTrailingComma: boolean } | null {
41
+ const regex = new RegExp(`"${key}"\\s*:\\s*\\{`);
42
+ const match = content.match(regex);
43
+ if (!match || match.index === undefined) return null;
44
+
45
+ const startIndex = match.index;
46
+ const braceIndex = content.indexOf("{", startIndex + match[0].length - 1);
47
+ if (braceIndex === -1) return null;
48
+
49
+ let depth = 0;
50
+ let inString = false;
51
+ let inLineComment = false;
52
+ let inBlockComment = false;
53
+ let escape = false;
54
+
55
+ for (let i = braceIndex; i < content.length; i++) {
56
+ const ch = content[i];
57
+ const nextCh = content[i + 1] || "";
58
+
59
+ if (inLineComment) {
60
+ if (ch === "\n") inLineComment = false;
61
+ continue;
62
+ }
63
+ if (inBlockComment) {
64
+ if (ch === "*" && nextCh === "/") {
65
+ inBlockComment = false;
66
+ i++;
67
+ }
68
+ continue;
69
+ }
70
+ if (inString) {
71
+ if (escape) {
72
+ escape = false;
73
+ } else if (ch === "\\") {
74
+ escape = true;
75
+ } else if (ch === '"') {
76
+ inString = false;
77
+ }
78
+ continue;
79
+ }
80
+
81
+ if (ch === "/" && nextCh === "/") {
82
+ inLineComment = true;
83
+ i++;
84
+ continue;
85
+ }
86
+ if (ch === "/" && nextCh === "*") {
87
+ inBlockComment = true;
88
+ i++;
89
+ continue;
90
+ }
91
+
92
+ if (ch === '"') {
93
+ inString = true;
94
+ continue;
95
+ }
96
+
97
+ if (ch === "{") {
98
+ depth++;
99
+ } else if (ch === "}") {
100
+ depth--;
101
+ if (depth === 0) {
102
+ let endIndex = i + 1;
103
+ let hasTrailingComma = false;
104
+ while (endIndex < content.length && /[\s,]/.test(content[endIndex])) {
105
+ if (content[endIndex] === ",") {
106
+ hasTrailingComma = true;
107
+ endIndex++;
108
+ break;
109
+ }
110
+ if (content[endIndex] === "\n") {
111
+ break;
112
+ }
113
+ endIndex++;
114
+ }
115
+ return { start: startIndex, end: endIndex, hasTrailingComma };
116
+ }
117
+ }
118
+ }
119
+
120
+ return null;
121
+ }
122
+
123
+ export function syncOpenCode(options: SyncOptions): ClientSyncResult {
124
+ const { filePath, apiKey, baseUrl } = options;
125
+ try {
126
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
127
+
128
+ let backupPath: string | undefined;
129
+ let content = "";
130
+
131
+ if (fs.existsSync(filePath)) {
132
+ backupPath = createTimestampBackup(filePath);
133
+ content = fs.readFileSync(filePath, "utf-8");
134
+ }
135
+
136
+ const providerObj = buildOpenCodeProviderObject(baseUrl, apiKey);
137
+ const providerJson = JSON.stringify(providerObj, null, 6)
138
+ .split("\n")
139
+ .map((line, idx) => (idx === 0 ? line : " " + line))
140
+ .join("\n");
141
+
142
+ const qwenEntry = ` "qwenproxy": ${providerJson}`;
143
+
144
+ if (!content.trim()) {
145
+ const initial = {
146
+ $schema: "https://opencode.ai/config.json",
147
+ provider: {
148
+ qwenproxy: providerObj,
149
+ },
150
+ };
151
+ fs.writeFileSync(filePath, JSON.stringify(initial, null, 2) + "\n", "utf-8");
152
+ } else {
153
+ // Check if "qwenproxy" already exists under "provider" with balanced braces
154
+ const existingSpan = findKeyObjectSpan(content, "qwenproxy");
155
+ if (existingSpan) {
156
+ const comma = existingSpan.hasTrailingComma ? "," : "";
157
+ content =
158
+ content.slice(0, existingSpan.start) +
159
+ `"qwenproxy": ${providerJson}${comma}` +
160
+ content.slice(existingSpan.end);
161
+ } else {
162
+ const providerMatch = content.match(/"provider"\s*:\s*\{/);
163
+ if (providerMatch && providerMatch.index !== undefined) {
164
+ const insertIdx = providerMatch.index + providerMatch[0].length;
165
+ content =
166
+ content.slice(0, insertIdx) +
167
+ "\n" +
168
+ qwenEntry +
169
+ "," +
170
+ content.slice(insertIdx);
171
+ } else {
172
+ // If no "provider" object exists, add it before the final closing brace
173
+ const lastBraceIdx = content.lastIndexOf("}");
174
+ if (lastBraceIdx !== -1) {
175
+ const comma = content.slice(0, lastBraceIdx).trimEnd().endsWith("{") ? "" : ",";
176
+ content =
177
+ content.slice(0, lastBraceIdx).trimEnd() +
178
+ `${comma}\n "provider": {\n${qwenEntry}\n }\n}\n`;
179
+ }
180
+ }
181
+ }
182
+ fs.writeFileSync(filePath, content, "utf-8");
183
+ }
184
+
185
+ return {
186
+ client: "opencode",
187
+ filePath,
188
+ backupPath,
189
+ success: true,
190
+ action: backupPath ? "updated" : "created",
191
+ message: `Configured OpenCode with provider qwenproxy (${baseUrl})`,
192
+ };
193
+ } catch (err: any) {
194
+ return {
195
+ client: "opencode",
196
+ filePath,
197
+ success: false,
198
+ action: "failed",
199
+ error: err?.message || String(err),
200
+ };
201
+ }
202
+ }
203
+
204
+ export function restoreOpenCode(filePath: string, backupPath?: string): ClientSyncResult {
205
+ const restored = restoreFromBackup(filePath, backupPath);
206
+ return {
207
+ client: "opencode",
208
+ filePath,
209
+ backupPath,
210
+ success: restored,
211
+ action: restored ? "restored" : "failed",
212
+ message: restored ? "Restored OpenCode config from backup" : "Backup file not found",
213
+ };
214
+ }