coding-tool-x 3.4.10 → 3.4.11

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.
@@ -34,6 +34,43 @@ function getChannelsFilePath() {
34
34
  return PATHS.channels.gemini;
35
35
  }
36
36
 
37
+ function readExistingGeminiEnv() {
38
+ const envPath = path.join(getGeminiDir(), '.env');
39
+ if (!fs.existsSync(envPath)) {
40
+ return {};
41
+ }
42
+
43
+ const env = {};
44
+ try {
45
+ const content = fs.readFileSync(envPath, 'utf8');
46
+ content.split('\n').forEach((line) => {
47
+ const trimmed = line.trim();
48
+ if (!trimmed || trimmed.startsWith('#')) return;
49
+
50
+ const match = trimmed.match(/^([^=]+)=(.*)$/);
51
+ if (match) {
52
+ env[match[1].trim()] = match[2].trim();
53
+ }
54
+ });
55
+ } catch (err) {
56
+ return {};
57
+ }
58
+
59
+ return env;
60
+ }
61
+
62
+ function writeGeminiEnv(env = {}) {
63
+ const envPath = path.join(getGeminiDir(), '.env');
64
+ const content = Object.entries(env)
65
+ .map(([key, value]) => `${key}=${value}`)
66
+ .join('\n');
67
+
68
+ fs.writeFileSync(envPath, content ? `${content}\n` : '', 'utf8');
69
+ if (process.platform !== 'win32') {
70
+ fs.chmodSync(envPath, 0o600);
71
+ }
72
+ }
73
+
37
74
  // 检查是否在代理模式
38
75
  function isProxyConfig() {
39
76
  const envPath = path.join(getGeminiDir(), '.env');
@@ -295,21 +332,12 @@ function applyChannelToSettings(channelId, channels = null) {
295
332
  fs.mkdirSync(geminiDir, { recursive: true });
296
333
  }
297
334
 
298
- const envPath = path.join(geminiDir, '.env');
299
-
300
- // 构建 .env 内容
335
+ const env = readExistingGeminiEnv();
301
336
  const effectiveApiKey = getEffectiveApiKey(channel) || '';
302
- const envContent = `GOOGLE_GEMINI_BASE_URL=${channel.baseUrl}
303
- GEMINI_API_KEY=${effectiveApiKey}
304
- GEMINI_MODEL=${channel.model}
305
- `;
306
-
307
- fs.writeFileSync(envPath, envContent, 'utf8');
308
-
309
- // 设置 .env 文件权限为 600 (仅所有者可读写)
310
- if (process.platform !== 'win32') {
311
- fs.chmodSync(envPath, 0o600);
312
- }
337
+ env.GOOGLE_GEMINI_BASE_URL = channel.baseUrl;
338
+ env.GEMINI_API_KEY = effectiveApiKey;
339
+ env.GEMINI_MODEL = channel.model;
340
+ writeGeminiEnv(env);
313
341
 
314
342
  // 确保 settings.json 存在并配置正确的认证模式
315
343
  const settingsPath = path.join(geminiDir, 'settings.json');
@@ -364,32 +392,25 @@ function writeGeminiConfigForMultiChannel(allChannels) {
364
392
  fs.mkdirSync(geminiDir, { recursive: true });
365
393
  }
366
394
 
367
- const envPath = path.join(geminiDir, '.env');
368
-
369
395
  // 获取第一个启用的渠道作为默认配置
370
396
  const enabledChannels = allChannels.filter(c => c.enabled !== false);
371
397
  const defaultChannel = enabledChannels[0] || allChannels[0];
372
398
 
399
+ const env = readExistingGeminiEnv();
400
+
373
401
  if (!defaultChannel) {
374
- // 没有渠道,写入空配置
375
- const envContent = `# Gemini Configuration\n# No channels configured\n`;
376
- fs.writeFileSync(envPath, envContent, 'utf8');
402
+ delete env.GOOGLE_GEMINI_BASE_URL;
403
+ delete env.GEMINI_API_KEY;
404
+ delete env.GEMINI_MODEL;
405
+ writeGeminiEnv(env);
377
406
  return;
378
407
  }
379
408
 
380
- // 构建 .env 内容
381
409
  const effectiveApiKey = getEffectiveApiKey(defaultChannel) || '';
382
- const envContent = `GOOGLE_GEMINI_BASE_URL=${defaultChannel.baseUrl}
383
- GEMINI_API_KEY=${effectiveApiKey}
384
- GEMINI_MODEL=${defaultChannel.model}
385
- `;
386
-
387
- fs.writeFileSync(envPath, envContent, 'utf8');
388
-
389
- // 设置 .env 文件权限为 600 (仅所有者可读写)
390
- if (process.platform !== 'win32') {
391
- fs.chmodSync(envPath, 0o600);
392
- }
410
+ env.GOOGLE_GEMINI_BASE_URL = defaultChannel.baseUrl;
411
+ env.GEMINI_API_KEY = effectiveApiKey;
412
+ env.GEMINI_MODEL = defaultChannel.model;
413
+ writeGeminiEnv(env);
393
414
 
394
415
  // 确保 settings.json 存在并配置正确的认证模式
395
416
  const settingsPath = path.join(geminiDir, 'settings.json');
@@ -723,18 +723,21 @@ function clearOpenCodeOAuth() {
723
723
  return;
724
724
  }
725
725
 
726
+ const removedProviderIds = [];
726
727
  Object.keys(payload).forEach((providerId) => {
727
728
  if (payload[providerId]?.type === 'oauth') {
729
+ removedProviderIds.push(providerId);
728
730
  delete payload[providerId];
729
731
  }
730
732
  });
731
733
 
732
734
  if (Object.keys(payload).length === 0) {
733
735
  removeFileIfExists(NATIVE_PATHS.opencode.auth);
734
- return;
736
+ } else {
737
+ writeJsonFile(NATIVE_PATHS.opencode.auth, payload);
735
738
  }
736
739
 
737
- writeJsonFile(NATIVE_PATHS.opencode.auth, payload);
740
+ syncOpenCodeConfigAfterOAuthRemoval(removedProviderIds);
738
741
  }
739
742
 
740
743
  function disableOpenCodeOAuthCredential(credential = {}) {
@@ -745,6 +748,7 @@ function disableOpenCodeOAuthCredential(credential = {}) {
745
748
  return;
746
749
  }
747
750
 
751
+ const removedProviderIds = [];
748
752
  Object.keys(payload).forEach((key) => {
749
753
  const target = payload[key];
750
754
  if (!target || target.type !== 'oauth') {
@@ -754,16 +758,18 @@ function disableOpenCodeOAuthCredential(credential = {}) {
754
758
  const providerMatched = providerId && key === providerId;
755
759
  const tokenMatched = accessToken && String(target.access || '').trim() === accessToken;
756
760
  if (providerMatched || tokenMatched) {
761
+ removedProviderIds.push(key);
757
762
  delete payload[key];
758
763
  }
759
764
  });
760
765
 
761
766
  if (Object.keys(payload).length === 0) {
762
767
  removeFileIfExists(NATIVE_PATHS.opencode.auth);
763
- return;
768
+ } else {
769
+ writeJsonFile(NATIVE_PATHS.opencode.auth, payload);
764
770
  }
765
771
 
766
- writeJsonFile(NATIVE_PATHS.opencode.auth, payload);
772
+ syncOpenCodeConfigAfterOAuthRemoval(removedProviderIds);
767
773
  }
768
774
 
769
775
  function isManagedOpenCodeProvider(provider) {
@@ -780,6 +786,44 @@ function isManagedOpenCodeProvider(provider) {
780
786
  return apiKey === 'PROXY_KEY' && (baseUrl.includes('127.0.0.1') || baseUrl.includes('localhost'));
781
787
  }
782
788
 
789
+ function isProxyBackedOpenCodeProvider(provider) {
790
+ if (!provider || typeof provider !== 'object') {
791
+ return false;
792
+ }
793
+
794
+ const apiKey = String(provider?.options?.apiKey || '').trim();
795
+ const baseUrl = String(provider?.options?.baseURL || '').trim();
796
+ return apiKey === 'PROXY_KEY' && (baseUrl.includes('127.0.0.1') || baseUrl.includes('localhost'));
797
+ }
798
+
799
+ function isMeaningfulOpenCodeProvider(provider) {
800
+ if (!provider || typeof provider !== 'object') {
801
+ return false;
802
+ }
803
+
804
+ if (provider.__ctx_managed__ === true) {
805
+ return true;
806
+ }
807
+
808
+ if (typeof provider.npm === 'string' && provider.npm.trim()) {
809
+ return true;
810
+ }
811
+
812
+ if (typeof provider.name === 'string' && provider.name.trim()) {
813
+ return true;
814
+ }
815
+
816
+ if (provider.options && typeof provider.options === 'object' && Object.keys(provider.options).length > 0) {
817
+ return true;
818
+ }
819
+
820
+ if (provider.models && typeof provider.models === 'object' && Object.keys(provider.models).length > 0) {
821
+ return true;
822
+ }
823
+
824
+ return false;
825
+ }
826
+
783
827
  function clearOpenCodeManagedModelSelection(config) {
784
828
  const modelRef = String(config?.model || '').trim();
785
829
  if (!modelRef || !modelRef.includes('/')) {
@@ -797,6 +841,107 @@ function clearOpenCodeManagedModelSelection(config) {
797
841
  }
798
842
  }
799
843
 
844
+ function getConfiguredOpenCodeProviderId(config) {
845
+ const modelRef = String(config?.model || '').trim();
846
+ if (modelRef.includes('/')) {
847
+ return modelRef.split('/')[0].trim();
848
+ }
849
+
850
+ const providerIds = config?.provider && typeof config.provider === 'object'
851
+ ? Object.keys(config.provider).filter(Boolean)
852
+ : [];
853
+ return providerIds.length === 1 ? providerIds[0] : '';
854
+ }
855
+
856
+ function buildOpenCodeModelRef(providerId, provider) {
857
+ if (!providerId || !provider || typeof provider !== 'object') {
858
+ return '';
859
+ }
860
+
861
+ const modelIds = provider.models && typeof provider.models === 'object'
862
+ ? Object.keys(provider.models).filter(Boolean)
863
+ : [];
864
+
865
+ if (modelIds.length === 0) {
866
+ return '';
867
+ }
868
+
869
+ return `${providerId}/${modelIds[0]}`;
870
+ }
871
+
872
+ function pickFallbackOpenCodeModel(config, excludedProviderIds = new Set()) {
873
+ const providers = config?.provider && typeof config.provider === 'object'
874
+ ? Object.entries(config.provider)
875
+ : [];
876
+
877
+ for (const [providerId, provider] of providers) {
878
+ if (excludedProviderIds.has(providerId)) {
879
+ continue;
880
+ }
881
+
882
+ const modelRef = buildOpenCodeModelRef(providerId, provider);
883
+ if (modelRef) {
884
+ return modelRef;
885
+ }
886
+ }
887
+
888
+ return '';
889
+ }
890
+
891
+ function syncOpenCodeConfigAfterOAuthRemoval(removedProviderIds = []) {
892
+ const removedIds = new Set((removedProviderIds || []).filter(Boolean));
893
+ if (removedIds.size === 0) {
894
+ return;
895
+ }
896
+
897
+ const configPath = opencodeSettingsManager.selectConfigPath();
898
+ if (!configPath || !fs.existsSync(configPath)) {
899
+ return;
900
+ }
901
+
902
+ let config = {};
903
+ try {
904
+ config = opencodeSettingsManager.readConfig(configPath);
905
+ } catch {
906
+ return;
907
+ }
908
+
909
+ config = config && typeof config === 'object' ? config : {};
910
+ config.provider = config.provider && typeof config.provider === 'object' ? config.provider : {};
911
+
912
+ let changed = false;
913
+ for (const providerId of removedIds) {
914
+ const provider = config.provider[providerId];
915
+ if (provider && !isMeaningfulOpenCodeProvider(provider)) {
916
+ delete config.provider[providerId];
917
+ changed = true;
918
+ }
919
+ }
920
+
921
+ const activeProviderId = getConfiguredOpenCodeProviderId(config);
922
+ if (activeProviderId && removedIds.has(activeProviderId)) {
923
+ const activeProvider = config.provider[activeProviderId];
924
+ if (!isMeaningfulOpenCodeProvider(activeProvider)) {
925
+ const fallbackModel = pickFallbackOpenCodeModel(config, removedIds);
926
+ if (fallbackModel) {
927
+ config.model = fallbackModel;
928
+ } else {
929
+ delete config.model;
930
+ }
931
+ changed = true;
932
+ }
933
+ }
934
+
935
+ if (Object.keys(config.provider).length === 0) {
936
+ delete config.provider;
937
+ changed = true;
938
+ }
939
+
940
+ if (changed) {
941
+ opencodeSettingsManager.writeConfig(configPath, config);
942
+ }
943
+ }
944
+
800
945
  function applyOpenCodeOAuth(credential) {
801
946
  const providerId = String(credential.providerId || 'openai').trim() || 'openai';
802
947
  const payload = readJsonFile(NATIVE_PATHS.opencode.auth, {});
@@ -840,7 +985,9 @@ function inspectOpenCodeState() {
840
985
  const providers = config?.provider && typeof config.provider === 'object'
841
986
  ? Object.values(config.provider)
842
987
  : [];
843
- channelConfigured = providers.some(provider => provider?.__ctx_managed__ === true);
988
+ channelConfigured = providers.some(provider => (
989
+ isMeaningfulOpenCodeProvider(provider) && !isProxyBackedOpenCodeProvider(provider)
990
+ ));
844
991
  } catch {
845
992
  channelConfigured = false;
846
993
  }
@@ -238,7 +238,41 @@ function escapeForXml(value) {
238
238
  }
239
239
 
240
240
  function buildWindowsPopupCommand(title, message) {
241
- return `powershell -NoProfile -Command "$wshell = New-Object -ComObject Wscript.Shell; $wshell.Popup('${escapeForPowerShellSingleQuote(message)}', 5, '${escapeForPowerShellSingleQuote(title)}', 0x40)"`;
241
+ const script = [
242
+ 'Add-Type -AssemblyName System.Windows.Forms',
243
+ 'Add-Type -AssemblyName System.Drawing',
244
+ '$form = New-Object System.Windows.Forms.Form',
245
+ `$form.Text = '${escapeForPowerShellSingleQuote(title)}'`,
246
+ '$form.Width = 360',
247
+ '$form.Height = 120',
248
+ '$form.StartPosition = [System.Windows.Forms.FormStartPosition]::Manual',
249
+ '$form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedToolWindow',
250
+ '$form.ShowInTaskbar = $false',
251
+ '$form.TopMost = $true',
252
+ '$form.MaximizeBox = $false',
253
+ '$form.MinimizeBox = $false',
254
+ '$workingArea = [System.Windows.Forms.Screen]::PrimaryScreen.WorkingArea',
255
+ '$form.Location = New-Object System.Drawing.Point(($workingArea.Right - $form.Width - 16), ($workingArea.Top + 16))',
256
+ '$titleLabel = New-Object System.Windows.Forms.Label',
257
+ `$titleLabel.Text = '${escapeForPowerShellSingleQuote(title)}'`,
258
+ "$titleLabel.Font = New-Object System.Drawing.Font('Segoe UI', 10, [System.Drawing.FontStyle]::Bold)",
259
+ '$titleLabel.AutoSize = $true',
260
+ '$titleLabel.Location = New-Object System.Drawing.Point(14, 12)',
261
+ '$messageLabel = New-Object System.Windows.Forms.Label',
262
+ `$messageLabel.Text = '${escapeForPowerShellSingleQuote(message)}'`,
263
+ "$messageLabel.Font = New-Object System.Drawing.Font('Segoe UI', 9)",
264
+ '$messageLabel.MaximumSize = New-Object System.Drawing.Size(332, 0)',
265
+ '$messageLabel.AutoSize = $true',
266
+ '$messageLabel.Location = New-Object System.Drawing.Point(14, 40)',
267
+ '$form.Controls.Add($titleLabel)',
268
+ '$form.Controls.Add($messageLabel)',
269
+ '$timer = New-Object System.Windows.Forms.Timer',
270
+ '$timer.Interval = 5000',
271
+ '$timer.Add_Tick({ $timer.Stop(); $form.Close() })',
272
+ '$timer.Start()',
273
+ '[void]$form.ShowDialog()'
274
+ ].join('; ');
275
+ return `powershell -NoProfile -Command ${JSON.stringify(script)}`;
242
276
  }
243
277
 
244
278
  function generateNotifyScript(feishu = {}) {
@@ -464,7 +498,41 @@ function escapeForXml(value) {
464
498
  }
465
499
 
466
500
  function buildWindowsPopupCommand(title, message) {
467
- return \`powershell -NoProfile -Command "$wshell = New-Object -ComObject Wscript.Shell; $wshell.Popup('\${escapeForPowerShellSingleQuote(message)}', 5, '\${escapeForPowerShellSingleQuote(title)}', 0x40)"\`
501
+ const script = [
502
+ 'Add-Type -AssemblyName System.Windows.Forms',
503
+ 'Add-Type -AssemblyName System.Drawing',
504
+ '$form = New-Object System.Windows.Forms.Form',
505
+ \`$form.Text = '\${escapeForPowerShellSingleQuote(title)}'\`,
506
+ '$form.Width = 360',
507
+ '$form.Height = 120',
508
+ '$form.StartPosition = [System.Windows.Forms.FormStartPosition]::Manual',
509
+ '$form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedToolWindow',
510
+ '$form.ShowInTaskbar = $false',
511
+ '$form.TopMost = $true',
512
+ '$form.MaximizeBox = $false',
513
+ '$form.MinimizeBox = $false',
514
+ '$workingArea = [System.Windows.Forms.Screen]::PrimaryScreen.WorkingArea',
515
+ '$form.Location = New-Object System.Drawing.Point(($workingArea.Right - $form.Width - 16), ($workingArea.Top + 16))',
516
+ '$titleLabel = New-Object System.Windows.Forms.Label',
517
+ \`$titleLabel.Text = '\${escapeForPowerShellSingleQuote(title)}'\`,
518
+ " $titleLabel.Font = New-Object System.Drawing.Font('Segoe UI', 10, [System.Drawing.FontStyle]::Bold)".trim(),
519
+ '$titleLabel.AutoSize = $true',
520
+ '$titleLabel.Location = New-Object System.Drawing.Point(14, 12)',
521
+ '$messageLabel = New-Object System.Windows.Forms.Label',
522
+ \`$messageLabel.Text = '\${escapeForPowerShellSingleQuote(message)}'\`,
523
+ " $messageLabel.Font = New-Object System.Drawing.Font('Segoe UI', 9)".trim(),
524
+ '$messageLabel.MaximumSize = New-Object System.Drawing.Size(332, 0)',
525
+ '$messageLabel.AutoSize = $true',
526
+ '$messageLabel.Location = New-Object System.Drawing.Point(14, 40)',
527
+ '$form.Controls.Add($titleLabel)',
528
+ '$form.Controls.Add($messageLabel)',
529
+ '$timer = New-Object System.Windows.Forms.Timer',
530
+ '$timer.Interval = 5000',
531
+ '$timer.Add_Tick({ $timer.Stop(); $form.Close() })',
532
+ '$timer.Start()',
533
+ '[void]$form.ShowDialog()'
534
+ ].join('; ')
535
+ return 'powershell -NoProfile -Command ' + JSON.stringify(script)
468
536
  }
469
537
  `;
470
538
  }
@@ -117,7 +117,7 @@ function syncManagedChannelConfig(channels = [], preferredChannel = null) {
117
117
  : resolveCurrentManagedChannel(channels);
118
118
 
119
119
  if (targetChannel) {
120
- setChannelConfig(targetChannel);
120
+ setChannelConfig(buildNativeConfigChannel(targetChannel));
121
121
  return targetChannel;
122
122
  }
123
123
 
@@ -305,11 +305,20 @@ function applyChannelToSettings(channelId) {
305
305
  });
306
306
  saveChannels(data);
307
307
 
308
- setChannelConfig(channel);
308
+ setChannelConfig(buildNativeConfigChannel(channel));
309
309
 
310
310
  return channel;
311
311
  }
312
312
 
313
+ function buildNativeConfigChannel(channel = {}) {
314
+ const candidates = getEffectiveApiKeyCandidates(channel);
315
+ const effectiveApiKey = candidates[0] || normalizeApiKey(channel.apiKey || channel.key || '');
316
+ return {
317
+ ...channel,
318
+ apiKey: effectiveApiKey
319
+ };
320
+ }
321
+
313
322
  function loadCodexChannels() {
314
323
  const filePath = getCodexChannelsFilePath();
315
324
  if (!fs.existsSync(filePath)) {