qwenproxy-cli 1.0.0 → 1.0.2

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 -14
  2. package/README.md +906 -906
  3. package/bin/qwenproxy.js +5 -1
  4. package/package.json +77 -78
  5. package/src/api/error-classifier.ts +159 -159
  6. package/src/api/error-helpers.ts +118 -118
  7. package/src/api/models.ts +261 -261
  8. package/src/api/server.ts +860 -859
  9. package/src/cache/memory-cache.ts +385 -385
  10. package/src/clean-cache.ts +204 -204
  11. package/src/core/account-concurrency.ts +671 -671
  12. package/src/core/account-manager.ts +301 -297
  13. package/src/core/account-priority.ts +163 -163
  14. package/src/core/accounts.ts +186 -186
  15. package/src/core/config.ts +383 -383
  16. package/src/core/crypto-utils.ts +79 -79
  17. package/src/core/database.ts +276 -276
  18. package/src/core/errors.ts +118 -118
  19. package/src/core/logger.ts +269 -269
  20. package/src/core/memory-usage.ts +84 -84
  21. package/src/core/metrics.ts +291 -291
  22. package/src/core/model-alias.ts +77 -77
  23. package/src/core/model-registry.ts +544 -544
  24. package/src/core/mutex.ts +119 -119
  25. package/src/core/paths.ts +199 -199
  26. package/src/core/prompt-limits.ts +214 -214
  27. package/src/core/reasoning-effort.ts +102 -102
  28. package/src/core/stream-registry.ts +96 -96
  29. package/src/core/waf-isolation.ts +117 -117
  30. package/src/core/watchdog.ts +195 -195
  31. package/src/delete-chats.ts +23 -23
  32. package/src/index.ts +65 -64
  33. package/src/login.ts +147 -147
  34. package/src/reset-cooldowns.ts +11 -11
  35. package/src/routes/anthropic/index.ts +355 -355
  36. package/src/routes/anthropic/translate.ts +522 -522
  37. package/src/routes/anthropic/types.ts +154 -154
  38. package/src/routes/anthropic/validation.ts +144 -144
  39. package/src/routes/chat/account.ts +1817 -1817
  40. package/src/routes/chat/context.ts +241 -241
  41. package/src/routes/chat/errors.ts +85 -85
  42. package/src/routes/chat/helpers.ts +268 -268
  43. package/src/routes/chat/index.ts +618 -618
  44. package/src/routes/chat/media.ts +285 -285
  45. package/src/routes/chat/retry-policy.ts +754 -754
  46. package/src/routes/chat/stop.ts +98 -98
  47. package/src/routes/chat/streaming.ts +2710 -2710
  48. package/src/routes/chat/validation.ts +526 -526
  49. package/src/routes/chat.ts +2 -2
  50. package/src/routes/completions.ts +290 -290
  51. package/src/routes/images.ts +139 -139
  52. package/src/routes/responses/adapter.ts +503 -503
  53. package/src/routes/responses/index.ts +405 -405
  54. package/src/routes/responses/state.ts +230 -230
  55. package/src/routes/responses/streaming.ts +528 -528
  56. package/src/routes/responses/types.ts +285 -285
  57. package/src/routes/responses/validation.ts +202 -202
  58. package/src/routes/upload.ts +731 -731
  59. package/src/routes/videos.ts +214 -214
  60. package/src/services/auth-playwright.ts +173 -173
  61. package/src/services/captcha-coordinator.ts +161 -161
  62. package/src/services/captcha-solver.ts +553 -553
  63. package/src/services/chat-cleanup.ts +80 -80
  64. package/src/services/context-meter.ts +317 -317
  65. package/src/services/fingerprint.ts +242 -242
  66. package/src/services/human-behavior.ts +173 -173
  67. package/src/services/media-generation.ts +1748 -1748
  68. package/src/services/playwright.ts +2878 -2800
  69. package/src/services/qwen-chat-pool.ts +345 -345
  70. package/src/services/qwen-errors.ts +133 -133
  71. package/src/services/qwen-headers.ts +79 -79
  72. package/src/services/qwen-thread-state.ts +393 -393
  73. package/src/services/qwen-url.ts +19 -19
  74. package/src/services/qwen.ts +3126 -3126
  75. package/src/services/session-keeper.ts +88 -88
  76. package/src/services/token-estimation-metrics.ts +118 -118
  77. package/src/sync/claude-code.ts +75 -75
  78. package/src/sync/codex.ts +123 -123
  79. package/src/sync/index.ts +362 -362
  80. package/src/sync/omp.ts +105 -105
  81. package/src/sync/opencode.ts +214 -214
  82. package/src/sync/types.ts +53 -53
  83. package/src/sync/utils.ts +27 -27
  84. package/src/sync-clients.ts +189 -189
  85. package/src/tools/instructions.ts +137 -137
  86. package/src/tools/manifest.ts +81 -81
  87. package/src/tools/parser.ts +2989 -2989
  88. package/src/tools/toolcall-tags.ts +142 -142
  89. package/src/tui/app.ts +259 -264
  90. package/src/tui/index.ts +61 -61
  91. package/src/tui/markdown.ts +258 -258
  92. package/src/tui/proxy-client.ts +331 -326
  93. package/src/tui/screen.ts +294 -278
  94. package/src/tui/server-manager.ts +270 -270
  95. package/src/tui/theme.ts +432 -432
  96. package/src/tui/types.ts +33 -33
  97. package/src/tui/views/accounts-view.ts +656 -656
  98. package/src/tui/views/chat-view.ts +1018 -823
  99. package/src/tui/views/logs-view.ts +479 -413
  100. package/src/tui/views/status-view.ts +204 -204
  101. package/src/tui/views/storage-view.ts +304 -291
  102. package/src/tui/views/sync-view.ts +409 -409
  103. package/src/types/ali-oss.d.ts +32 -32
  104. package/src/update-cli.ts +121 -0
  105. package/src/utils/context-truncation.ts +84 -84
  106. package/src/utils/json.ts +380 -380
  107. package/src/utils/session-id.ts +37 -37
  108. package/src/utils/tool-call-guard.ts +84 -84
  109. package/src/utils/types.ts +109 -109
package/src/sync/omp.ts CHANGED
@@ -1,105 +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
- }
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
+ }
@@ -1,214 +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
- }
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
+ }