-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathclaude-code-router-config.js
More file actions
executable file
·291 lines (260 loc) · 9.81 KB
/
claude-code-router-config.js
File metadata and controls
executable file
·291 lines (260 loc) · 9.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
#!/usr/bin/env node
const fs = require("fs-extra");
const path = require("path");
const os = require("os");
const readline = require("readline");
class ClaudeCodeRouterConfig {
constructor() {
this.homeDir = os.homedir();
this.configDir = path.join(this.homeDir, ".claude-code-router");
this.configFile = path.join(this.configDir, "config.json");
this.pluginsDir = path.join(this.configDir, "plugins");
this.transformerFile = path.join(
this.pluginsDir,
"dashscope-transformer.js"
);
this.language = this.detectLanguage();
this.messages = this.getMessages();
}
detectLanguage() {
// 检测系统语言
const locale = process.env.LANG || process.env.LANGUAGE || process.env.LC_ALL || "en_US.UTF-8";
return locale.toLowerCase().includes('zh') ? 'zh' : 'en';
}
async promptForRegion() {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
return new Promise((resolve) => {
const askForRegion = () => {
const prompt = `${this.messages.regionPrompt}\n${this.messages.regionOption1}\n${this.messages.regionOption2}\n${this.messages.regionInput}`;
rl.question(prompt, (answer) => {
const choice = answer.trim();
if (choice === '1') {
console.log(this.messages.regionSelected1);
rl.close();
resolve('cn');
} else if (choice === '2') {
console.log(this.messages.regionSelected2);
rl.close();
resolve('intl');
} else {
console.log(this.messages.regionInvalid);
askForRegion();
}
});
};
askForRegion();
});
}
getApiBaseUrl(region) {
return region === 'intl'
? "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions"
: "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";
}
getMessages() {
const messages = {
zh: {
configuring: "🚀 正在配置 claude-code-router...",
envKeyDetected: "🔑 检测到环境变量 DASHSCOPE_API_KEY,将使用环境变量中的 API Key",
envKeyNotFound: "⚠️ 未检测到环境变量 DASHSCOPE_API_KEY,将使用默认配置",
configComplete: "✅ claude-code-router 配置完成!",
configLocation: "📁 配置文件位置:",
usage: "📝 使用说明:",
step1: "1. 请确保已安装 @anthropic-ai/claude-code",
step2: "2. 请确保已安装 @musistudio/claude-code-router",
step3Warning: "3. ⚠️ 请手动配置环境变量DASHSCOPE_API_KEY:",
step3Success: "3. ✅ API Key 已从环境变量自动配置",
regionPrompt: "请选择服务区域 (Please select service region):",
regionOption1: "1. 阿里云 (Alibaba Cloud China)",
regionOption2: "2. 阿里云国际站 (Alibaba Cloud International)",
regionInput: "请输入 1 或 2 (Enter 1 or 2): ",
regionSelected1: "✅ 已选择阿里云中国站",
regionSelected2: "✅ 已选择阿里云国际站",
regionInvalid: "❌ 请输入 1 或 2",
promptApiKey: "请输入您的 DashScope API Key:",
apiKeyPrompt: "DashScope API Key",
apiKeyConfigured: "✅ API Key 已配置完成",
invalidApiKey: "❌ API Key 不能为空,请重新输入",
step4: "4. 运行 ccr code 开始使用",
configFailed: "❌ 配置失败:",
createDir: "📁 创建目录:",
createConfig: "📄 创建配置文件:",
createPlugin: "🔧 创建插件文件:",
editConfigInstructions: [
` cd `,
` open config.json # macOS`,
` # 或者用你喜欢的编辑器打开 config.json`,
` # 将 "api_key" 字段替换为你的 DashScope API Key`
]
},
en: {
configuring: "🚀 Configuring claude-code-router...",
envKeyDetected: "🔑 DASHSCOPE_API_KEY environment variable detected, will use API Key from environment",
envKeyNotFound: "⚠️ DASHSCOPE_API_KEY environment variable not found, will use default configuration",
configComplete: "✅ claude-code-router configuration completed!",
configLocation: "📁 Configuration file location:",
usage: "📝 Usage instructions:",
step1: "1. Please ensure @anthropic-ai/claude-code is installed",
step2: "2. Please ensure @musistudio/claude-code-router is installed",
step3Warning: "3. ⚠️ Please manually set your DASHSCOPE_API_KEY environment variable:",
step3Success: "3. ✅ API Key automatically configured from environment variable",
regionPrompt: "Please select service region:",
regionOption1: "1. Alibaba Cloud China",
regionOption2: "2. Alibaba Cloud International",
regionInput: "Enter 1 or 2: ",
regionSelected1: "✅ Selected Alibaba Cloud China",
regionSelected2: "✅ Selected Alibaba Cloud International",
regionInvalid: "❌ Please enter 1 or 2",
promptApiKey: "Please enter your DashScope API Key:",
apiKeyPrompt: "DashScope API Key",
apiKeyConfigured: "✅ API Key configured successfully",
invalidApiKey: "❌ API Key cannot be empty, please try again",
step4: "4. Run ccr code to start using",
configFailed: "❌ Configuration failed:",
createDir: "📁 Creating directory:",
createConfig: "📄 Creating configuration file:",
createPlugin: "🔧 Creating plugin file:",
editConfigInstructions: [
` cd `,
` open config.json # macOS`,
` # Or open config.json with your preferred editor`,
` # Replace the "api_key" field with your DashScope API Key`
]
}
};
return messages[this.language];
}
async promptForApiKey() {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
return new Promise((resolve) => {
const askForKey = () => {
rl.question(`${this.messages.promptApiKey} `, (apiKey) => {
const trimmedKey = apiKey.trim();
if (trimmedKey) {
console.log(this.messages.apiKeyConfigured);
rl.close();
resolve(trimmedKey);
} else {
console.log(this.messages.invalidApiKey);
askForKey();
}
});
};
askForKey();
});
}
async setup() {
try {
console.log(this.messages.configuring);
// 询问用户选择服务区域
const region = await this.promptForRegion();
// 检查环境变量
let apiKey = process.env.DASHSCOPE_API_KEY;
const hasEnvApiKey = !!apiKey;
if (hasEnvApiKey) {
console.log(this.messages.envKeyDetected);
} else {
console.log(this.messages.envKeyNotFound);
// 提示用户输入 API Key
apiKey = await this.promptForApiKey();
}
// 创建配置目录
await this.createDirectories();
// 创建配置文件
await this.createConfigFile(apiKey, region);
// 创建插件文件
await this.createTransformerFile();
console.log(this.messages.configComplete);
console.log(this.messages.configLocation, this.configDir);
console.log("");
console.log(this.messages.usage);
console.log(this.messages.step1);
console.log(this.messages.step2);
console.log(this.messages.step3Success);
console.log(this.messages.step4);
} catch (error) {
console.error(this.messages.configFailed, error.message);
process.exit(1);
}
}
async createDirectories() {
// 创建主配置目录
await fs.ensureDir(this.configDir);
// 创建插件目录
await fs.ensureDir(this.pluginsDir);
console.log(this.messages.createDir, this.configDir);
}
async createConfigFile(apiKey, region) {
// 使用传入的 API Key(可能来自环境变量或用户输入)
const dashscopeApiKey = apiKey;
const apiBaseUrl = this.getApiBaseUrl(region);
const configContent = {
LOG: true,
OPENAI_API_KEY: "",
OPENAI_BASE_URL: "",
OPENAI_MODEL: "",
transformers: [
{
path: path.join(
this.configDir,
"plugins",
"dashscope-transformer.js"
),
options: {
enable_thinking: false,
stream: true,
},
},
],
Providers: [
{
name: "dashscope",
api_base_url: apiBaseUrl,
api_key: dashscopeApiKey,
models: ["qwen3-coder-plus"],
transformer: {
use: ["dashscope"],
},
},
],
Router: {
default: "dashscope,qwen3-coder-plus",
think: "dashscope,qwen3-coder-plus",
background: "dashscope,qwen3-coder-plus",
longContext: "dashscope,qwen3-coder-plus",
},
};
await fs.writeJson(this.configFile, configContent, { spaces: 2 });
console.log(this.messages.createConfig, this.configFile);
}
async createTransformerFile() {
const transformerContent = `class DashScopeTransformer {
name = "dashscope";
constructor(options) {
this.max_tokens = options.max_tokens || 8192;
this.enable_thinking = options.enable_thinking || false;
this.stream = options.stream || true;
}
async transformRequestIn(request, provider) {
request.max_tokens = this.max_tokens;
request.enable_thinking = this.enable_thinking;
request.stream = this.stream;
return request;
}
}
module.exports = DashScopeTransformer;`;
await fs.writeFile(this.transformerFile, transformerContent);
console.log(this.messages.createPlugin, this.transformerFile);
}
}
// 如果直接运行此脚本
if (require.main === module) {
const config = new ClaudeCodeRouterConfig();
config.setup();
}
module.exports = ClaudeCodeRouterConfig;