aihezu 1.5.2 → 1.7.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.
package/README.md CHANGED
@@ -1,9 +1,10 @@
1
- # aihezu - Claude Code CLI 清理工具
1
+ # aihezu - Claude Code CLI 工具集
2
2
 
3
- 快速备份和清理 Claude Code CLI 的本地配置和缓存文件,同时修改 hosts 文件实现本地代理。
3
+ 快速配置或清理 Claude Code / Codex,本地修改 hosts 并提供企业独立域名支持。
4
4
 
5
5
  ## 功能特性
6
6
 
7
+ - 🔑 一键配置 Claude(默认)或 Codex,支持企业独立域名(`--api` / `--api-url`)
7
8
  - 🧹 一键清理 Claude Code CLI 的所有本地数据
8
9
  - 🌐 自动修改 hosts 文件,将 Anthropic 域名指向本地
9
10
  - 📦 自动备份配置文件和 hosts 文件(带时间戳)
@@ -11,6 +12,13 @@
11
12
  - 🚀 支持 npx 直接运行,无需安装
12
13
  - 🔄 自动刷新 DNS 缓存
13
14
 
15
+ ## 命令列表
16
+
17
+ - `ccinstall` / `install`:交互式配置 Claude(默认)或 Codex
18
+ - Claude:默认 `https://cc.aihezu.dev/api`,企业可用 `--api` / `--api-url` 指定独立域名
19
+ - Codex:写入 `~/.codex/config.toml` 和 `auth.json`,使用 `AIHEZU_OAI_KEY`
20
+ - `ccclear`:清理 Claude Code 缓存和配置
21
+
14
22
  ## 清理内容
15
23
 
16
24
  该工具会执行以下操作:
@@ -30,27 +38,48 @@
30
38
 
31
39
  ⚠️ **重要提示**:由于需要修改系统 hosts 文件,必须使用管理员权限运行!
32
40
 
33
- ### macOS/Linux
41
+ ### 配置 Claude Code(ccinstall / install)
34
42
 
35
- #### 方式一:使用 npx(推荐)
43
+ - 默认域名:
36
44
 
37
45
  ```bash
38
- sudo npx aihezu ccclear
46
+ sudo npx aihezu install
47
+ ```
48
+
49
+ - 企业独立域名(支持传入域名或完整 URL,自动补全为 `/api`):
50
+
51
+ ```bash
52
+ sudo npx aihezu install --api https://your-org.aihezu.dev
53
+ # 或
54
+ sudo npx aihezu install --api your-org.aihezu.dev
39
55
  ```
40
56
 
41
- #### 方式二:全局安装后运行
57
+ 也可以全局安装后运行:
42
58
 
43
59
  ```bash
44
60
  npm install -g aihezu
45
- sudo ccclear
61
+ sudo ccinstall --api your-company.aihezu.dev
46
62
  ```
47
63
 
48
- ### Windows
64
+ - 直接选择 Codex(可在交互中选择,也可用参数指定):
49
65
 
50
- 需要以管理员身份运行命令提示符或 PowerShell:
66
+ ```bash
67
+ sudo npx aihezu install --provider codex
68
+ ```
69
+
70
+ ### 清理 Claude Code(ccclear)
71
+
72
+ - 使用 npx(推荐):
51
73
 
52
74
  ```bash
53
- npx aihezu ccclear
75
+ sudo npx aihezu ccclear
76
+ ```
77
+
78
+ - 全局安装后运行:
79
+
80
+ ```bash
81
+ npm install -g aihezu
82
+ sudo ccclear
54
83
  ```
55
84
 
56
85
  ## 运行效果
package/bin/aihezu.js CHANGED
@@ -5,27 +5,30 @@ const path = require('path');
5
5
 
6
6
  const args = process.argv.slice(2);
7
7
  const command = args[0];
8
+ const commandArgs = args.slice(1);
8
9
 
9
10
  // 显示帮助信息
10
11
  function showHelp() {
11
- console.log('🌐 aihezu - Claude Code 工具集');
12
+ console.log('🌐 aihezu - Claude / Codex 工具集');
12
13
  console.log('Powered by https://aihezu.dev\n');
13
14
  console.log('使用方法:');
14
15
  console.log(' npx aihezu <command>\n');
15
16
  console.log('可用命令:');
16
- console.log(' ccinstall 配置 Claude Code API Key');
17
- console.log(' ccclear 清理 Claude Code 缓存和配置');
17
+ console.log(' ccinstall / install 配置 Claude (默认) Codex,支持企业自定义域名');
18
+ console.log(' ccclear 清理 Claude Code 缓存和配置');
18
19
  console.log(' help 显示帮助信息\n');
19
20
  console.log('示例:');
20
- console.log(' npx aihezu ccinstall # 配置 API Key');
21
+ console.log(' npx aihezu ccinstall # 配置 API Key (默认 Claude)');
22
+ console.log(' npx aihezu install --api your-org.aihezu.dev # 企业用户自定义域名');
23
+ console.log(' npx aihezu install --provider codex # 直接配置 Codex');
21
24
  console.log(' npx aihezu ccclear # 清理缓存');
22
25
  }
23
26
 
24
27
  // 执行子命令
25
- function runCommand(scriptName) {
28
+ function runCommand(scriptName, extraArgs = []) {
26
29
  const scriptPath = path.join(__dirname, scriptName);
27
30
 
28
- const child = spawn('node', [scriptPath], {
31
+ const child = spawn('node', [scriptPath, ...extraArgs], {
29
32
  stdio: 'inherit',
30
33
  env: process.env
31
34
  });
@@ -43,11 +46,12 @@ function runCommand(scriptName) {
43
46
  // 路由命令
44
47
  switch (command) {
45
48
  case 'ccinstall':
46
- runCommand('ccinstall.js');
49
+ case 'install':
50
+ runCommand('ccinstall.js', commandArgs);
47
51
  break;
48
52
 
49
53
  case 'ccclear':
50
- runCommand('ccclear.js');
54
+ runCommand('ccclear.js', commandArgs);
51
55
  break;
52
56
 
53
57
  case 'help':
package/bin/ccinstall.js CHANGED
@@ -8,99 +8,291 @@ const { modifyHostsFile } = require('../lib/hosts');
8
8
  const { cleanCache } = require('../lib/cache');
9
9
 
10
10
  const homeDir = os.homedir();
11
- const settingsPath = path.join(homeDir, '.claude', 'settings.json');
11
+ const claudeSettingsPath = path.join(homeDir, '.claude', 'settings.json');
12
12
  const claudeDir = path.join(homeDir, '.claude');
13
+ const codexDir = path.join(homeDir, '.codex');
14
+ const codexConfigPath = path.join(codexDir, 'config.toml');
15
+ const codexAuthPath = path.join(codexDir, 'auth.json');
16
+ const DEFAULT_CLAUDE_API_BASE = 'https://cc.aihezu.dev/api';
17
+ const DEFAULT_CODEX_BASE_URL = 'https://cc.aihezu.dev/openai';
18
+ const PROVIDERS = {
19
+ CLAUDE: 'claude',
20
+ CODEX: 'codex'
21
+ };
22
+ const cliArgs = process.argv.slice(2);
13
23
 
14
- console.log('🔧 Claude Code API 配置工具');
15
- console.log('🌐 Powered by https://aihezu.dev\n');
24
+ function askQuestion(rl, question) {
25
+ return new Promise(resolve => rl.question(question, answer => resolve(answer.trim())));
26
+ }
16
27
 
17
- // 创建 readline 接口
18
- const rl = readline.createInterface({
19
- input: process.stdin,
20
- output: process.stdout
21
- });
28
+ function getArgValue(argv, keys) {
29
+ for (let i = 0; i < argv.length; i++) {
30
+ const arg = argv[i];
31
+ const [key, inlineValue] = arg.split('=');
32
+ if (keys.includes(key)) {
33
+ return (inlineValue || argv[i + 1] || '').trim();
34
+ }
35
+ }
36
+ return '';
37
+ }
38
+
39
+ function parseProviderArg(argv) {
40
+ const value = getArgValue(argv, ['--provider', '--product', '--service', '--mode']);
41
+ return value.toLowerCase();
42
+ }
43
+
44
+ function parseApiBaseInput(argv) {
45
+ let apiBaseInput = '';
46
+
47
+ for (let i = 0; i < argv.length; i++) {
48
+ const arg = argv[i];
49
+
50
+ if (['--api', '--api-url', '--api-base', '--domain'].includes(arg)) {
51
+ apiBaseInput = argv[i + 1] || '';
52
+ i++;
53
+ continue;
54
+ }
55
+
56
+ if (!arg.startsWith('-') && !apiBaseInput) {
57
+ apiBaseInput = arg;
58
+ }
59
+ }
60
+
61
+ return apiBaseInput.trim();
62
+ }
63
+
64
+ function normalizeApiBaseUrl(input) {
65
+ if (!input) return DEFAULT_CLAUDE_API_BASE;
66
+
67
+ let normalized = input;
68
+
69
+ if (!/^https?:\/\//i.test(normalized)) {
70
+ normalized = `https://${normalized}`;
71
+ }
22
72
 
73
+ let url;
74
+ try {
75
+ url = new URL(normalized);
76
+ } catch (error) {
77
+ throw new Error('无效的域名或 URL,请输入类似 your-org.aihezu.dev 或 https://your-org.aihezu.dev');
78
+ }
79
+
80
+ let pathname = url.pathname.replace(/\/+$/, '');
81
+ if (!pathname || pathname === '/') {
82
+ pathname = '/api';
83
+ }
84
+
85
+ url.pathname = pathname;
86
+ url.search = '';
87
+ url.hash = '';
88
+
89
+ return `${url.origin}${url.pathname}`;
90
+ }
91
+
92
+ function resolveProvider(input) {
93
+ const value = (input || '').toLowerCase();
94
+ if (['2', 'codex', 'c'].includes(value)) return PROVIDERS.CODEX;
95
+ return PROVIDERS.CLAUDE;
96
+ }
23
97
 
24
- // 询问是否需要清理缓存
25
- rl.question('您是从其他服务切换过来的吗?(y/n,如果是首次使用请输入 n): ', (answer) => {
26
- const needClean = answer.toLowerCase() === 'y' || answer.toLowerCase() === 'yes';
98
+ function backupFile(filePath) {
99
+ if (!fs.existsSync(filePath)) return null;
100
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
101
+ const backupPath = `${filePath}.backup-${timestamp}`;
102
+ fs.copyFileSync(filePath, backupPath);
103
+ return backupPath;
104
+ }
27
105
 
28
- if (needClean) {
106
+ function writeClaudeSettings(apiKey, apiBaseUrl) {
107
+ // 确保 .claude 目录存在
108
+ if (!fs.existsSync(claudeDir)) {
109
+ console.log('📁 创建 ~/.claude 目录...');
110
+ fs.mkdirSync(claudeDir, { recursive: true });
111
+ }
112
+
113
+ // 读取或创建 settings.json
114
+ let settings = {};
115
+ if (fs.existsSync(claudeSettingsPath)) {
116
+ console.log('📖 读取现有配置文件...');
117
+ const content = fs.readFileSync(claudeSettingsPath, 'utf8');
29
118
  try {
30
- console.log('\n=== 清理旧缓存 ===');
31
- const count = cleanCache({ showHeader: false });
32
- console.log(`\n✅ 缓存清理完成!(共处理 ${count} 项)`);
33
- console.log('💡 配置文件已保留,即将配置新的 API Key\n');
34
- } catch (error) {
35
- console.error('⚠️ 清理缓存时出错:', error.message);
36
- console.log('继续配置流程...\n');
119
+ settings = JSON.parse(content);
120
+ } catch (e) {
121
+ console.log('⚠️ 现有配置文件格式错误,将创建新的配置');
122
+ // 备份错误的配置文件
123
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
124
+ const backupPath = `${claudeSettingsPath}.backup-${timestamp}`;
125
+ fs.writeFileSync(backupPath, content);
126
+ console.log(`📦 已备份原配置文件到: ${path.basename(backupPath)}`);
37
127
  }
38
128
  }
39
129
 
40
- // 提示用户输入 API Key
41
- rl.question('请输入您的 API Key: ', (apiKey) => {
42
- if (!apiKey || apiKey.trim() === '') {
43
- console.error('❌ API Key 不能为空');
44
- rl.close();
45
- process.exit(1);
130
+ // 完全替换 env 对象,清除所有旧的环境变量配置
131
+ settings.env = {
132
+ ANTHROPIC_AUTH_TOKEN: apiKey,
133
+ ANTHROPIC_BASE_URL: apiBaseUrl
134
+ };
135
+
136
+ // 写入配置文件
137
+ fs.writeFileSync(claudeSettingsPath, JSON.stringify(settings, null, 2), 'utf8');
138
+
139
+ console.log('\n=== API 配置 (Claude) ===\n');
140
+ console.log('✅ 配置成功!');
141
+ console.log('📝 已更新配置文件:', claudeSettingsPath);
142
+ console.log('\n配置内容:');
143
+ console.log(' ANTHROPIC_AUTH_TOKEN:', apiKey);
144
+ console.log(' ANTHROPIC_BASE_URL:', apiBaseUrl);
145
+ }
146
+
147
+ function writeCodexConfig(apiKey) {
148
+ if (!fs.existsSync(codexDir)) {
149
+ console.log('📁 创建 ~/.codex 目录...');
150
+ fs.mkdirSync(codexDir, { recursive: true });
46
151
  }
47
152
 
48
- apiKey = apiKey.trim();
153
+ const configBackup = backupFile(codexConfigPath);
154
+ if (configBackup) {
155
+ console.log(`📦 已备份原配置文件到: ${path.basename(configBackup)}`);
156
+ }
157
+
158
+ const configContent = [
159
+ 'model_provider = "aihezu"',
160
+ 'model = "gpt-5-codex"',
161
+ 'model_reasoning_effort = "high"',
162
+ 'disable_response_storage = true',
163
+ 'preferred_auth_method = "apikey"',
164
+ '',
165
+ '[model_providers.aihezu]',
166
+ 'name = "aihezu"',
167
+ `base_url = "${DEFAULT_CODEX_BASE_URL}"`,
168
+ 'wire_api = "responses"',
169
+ 'requires_openai_auth = true',
170
+ 'env_key = "AIHEZU_OAI_KEY"',
171
+ ''
172
+ ].join('\n');
173
+
174
+ fs.writeFileSync(codexConfigPath, configContent, 'utf8');
175
+
176
+ let authData = {};
177
+ if (fs.existsSync(codexAuthPath)) {
178
+ try {
179
+ const content = fs.readFileSync(codexAuthPath, 'utf8');
180
+ authData = JSON.parse(content);
181
+ } catch (e) {
182
+ const backupPath = backupFile(codexAuthPath);
183
+ console.log('⚠️ 现有 auth.json 解析失败,已备份旧文件:', backupPath ? path.basename(backupPath) : '未备份');
184
+ authData = {};
185
+ }
186
+ }
187
+
188
+ authData.OPENAI_API_KEY = null;
189
+ authData.AIHEZU_OAI_KEY = apiKey;
190
+
191
+ fs.writeFileSync(codexAuthPath, JSON.stringify(authData, null, 2), 'utf8');
192
+
193
+ console.log('\n=== API 配置 (Codex) ===\n');
194
+ console.log('✅ 配置成功!');
195
+ console.log('📝 已更新配置文件:');
196
+ console.log(' -', codexConfigPath);
197
+ console.log(' -', codexAuthPath);
198
+ console.log('\n配置内容:');
199
+ console.log(' AIHEZU_OAI_KEY:', apiKey);
200
+ console.log(' base_url:', DEFAULT_CODEX_BASE_URL);
201
+ console.log('\n💡 已在 auth.json 中写入密钥,并在 config.toml 中指定 env_key = "AIHEZU_OAI_KEY"');
202
+ console.log(' 如需在 shell 中直接使用,可运行: export AIHEZU_OAI_KEY="<你的密钥>"');
203
+ }
204
+
205
+ async function main() {
206
+ console.log('🔧 Claude / Codex API 配置工具');
207
+ console.log('🌐 Powered by https://aihezu.dev\n');
208
+
209
+ const rl = readline.createInterface({
210
+ input: process.stdin,
211
+ output: process.stdout
212
+ });
49
213
 
50
214
  try {
51
- // 确保 .claude 目录存在
52
- if (!fs.existsSync(claudeDir)) {
53
- console.log('📁 创建 ~/.claude 目录...');
54
- fs.mkdirSync(claudeDir, { recursive: true });
215
+ const cliProviderInput = parseProviderArg(cliArgs);
216
+ let provider = resolveProvider(cliProviderInput);
217
+
218
+ if (!cliProviderInput) {
219
+ const providerAnswer = await askQuestion(rl, '请选择服务类型 [1] Claude (默认) / [2] Codex: ');
220
+ provider = resolveProvider(providerAnswer);
55
221
  }
56
222
 
57
- // 读取或创建 settings.json
58
- let settings = {};
59
- if (fs.existsSync(settingsPath)) {
60
- console.log('📖 读取现有配置文件...');
61
- const content = fs.readFileSync(settingsPath, 'utf8');
223
+ const apiBaseInput = provider === PROVIDERS.CLAUDE ? parseApiBaseInput(cliArgs) : '';
224
+ let apiBaseUrl = DEFAULT_CLAUDE_API_BASE;
225
+ if (provider === PROVIDERS.CLAUDE) {
62
226
  try {
63
- settings = JSON.parse(content);
64
- } catch (e) {
65
- console.log('⚠️ 现有配置文件格式错误,将创建新的配置');
66
- // 备份错误的配置文件
67
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
68
- const backupPath = `${settingsPath}.backup-${timestamp}`;
69
- fs.writeFileSync(backupPath, content);
70
- console.log(`📦 已备份原配置文件到: ${path.basename(backupPath)}`);
227
+ apiBaseUrl = normalizeApiBaseUrl(apiBaseInput);
228
+ } catch (error) {
229
+ console.error(`❌ ${error.message}`);
230
+ process.exit(1);
71
231
  }
72
232
  }
73
233
 
74
- // 完全替换 env 对象,清除所有旧的环境变量配置
75
- // 这样可以避免旧配置(如 ANTHROPIC_MODEL 等)干扰新配置
76
- settings.env = {
77
- ANTHROPIC_AUTH_TOKEN: apiKey,
78
- ANTHROPIC_BASE_URL: 'https://cc.aihezu.dev/api'
79
- };
234
+ const usingCustomDomain = provider === PROVIDERS.CLAUDE && !!apiBaseInput;
80
235
 
81
- // 写入配置文件
82
- fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2), 'utf8');
236
+ if (provider === PROVIDERS.CLAUDE) {
237
+ if (usingCustomDomain) {
238
+ console.log(`🏢 已启用企业独立域名: ${apiBaseUrl}\n`);
239
+ } else {
240
+ console.log(`ℹ️ 未指定域名,将使用默认地址: ${DEFAULT_CLAUDE_API_BASE}`);
241
+ console.log(' 企业用户可使用 --api 或 --api-url 指定独立域名,例如:');
242
+ console.log(' sudo npx aihezu install --api your-org.aihezu.dev\n');
243
+ }
244
+ } else {
245
+ console.log(`🤖 已选择 Codex,默认网关: ${DEFAULT_CODEX_BASE_URL}\n`);
246
+ }
247
+
248
+ const needCleanAnswer = await askQuestion(
249
+ rl,
250
+ '您是从其他服务切换过来的吗?(y/n,如果是首次使用请输入 n): '
251
+ );
252
+ const needClean = ['y', 'yes'].includes(needCleanAnswer.toLowerCase());
253
+
254
+ if (needClean) {
255
+ try {
256
+ console.log('\n=== 清理旧缓存 ===');
257
+ const count = cleanCache({ showHeader: false });
258
+ console.log(`\n✅ 缓存清理完成!(共处理 ${count} 项)`);
259
+ console.log('💡 配置文件已保留,即将配置新的 API Key\n');
260
+ } catch (error) {
261
+ console.error('⚠️ 清理缓存时出错:', error.message);
262
+ console.log('继续配置流程...\n');
263
+ }
264
+ }
265
+
266
+ const apiKey = await askQuestion(rl, '请输入您的 API Key: ');
267
+ if (!apiKey) {
268
+ console.error('❌ API Key 不能为空');
269
+ process.exit(1);
270
+ }
83
271
 
84
- console.log('\n=== API 配置 ===\n');
85
- console.log('✅ 配置成功!');
86
- console.log('📝 已更新配置文件:', settingsPath);
87
- console.log('\n配置内容:');
88
- console.log(' ANTHROPIC_AUTH_TOKEN:', apiKey);
89
- console.log(' ANTHROPIC_BASE_URL:', 'https://cc.aihezu.dev/api');
272
+ if (provider === PROVIDERS.CLAUDE) {
273
+ writeClaudeSettings(apiKey.trim(), apiBaseUrl);
274
+ } else {
275
+ writeCodexConfig(apiKey.trim());
276
+ }
90
277
 
91
- // 修改 hosts 文件
92
- console.log('\n=== 修改 hosts 文件 ===\n');
93
- modifyHostsFile();
278
+ if (provider === PROVIDERS.CLAUDE) {
279
+ console.log('\n=== 修改 hosts 文件 ===\n');
280
+ modifyHostsFile();
281
+ }
94
282
 
95
283
  console.log('\n=== 全部完成 ===');
96
- console.log('💡 您现在可以开始使用 Claude Code 了!');
284
+ if (provider === PROVIDERS.CLAUDE) {
285
+ console.log('💡 您现在可以开始使用 Claude Code 了!');
286
+ } else {
287
+ console.log('💡 您现在可以开始使用 Codex 了!');
288
+ }
97
289
  console.log('🌐 更多服务请访问: https://aihezu.dev');
98
-
99
290
  } catch (error) {
100
291
  console.error('❌ 配置失败:', error.message);
101
292
  process.exit(1);
102
293
  } finally {
103
294
  rl.close();
104
295
  }
105
- });
106
- });
296
+ }
297
+
298
+ main();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aihezu",
3
- "version": "1.5.2",
3
+ "version": "1.7.0",
4
4
  "description": "Claude Code CLI 清理工具 - 快速备份和清理 Claude Code 的本地配置和缓存,同时修改 hosts 文件实现本地代理",
5
5
  "main": "bin/ccclear.js",
6
6
  "bin": {