-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
executable file
·1175 lines (994 loc) · 37 KB
/
index.js
File metadata and controls
executable file
·1175 lines (994 loc) · 37 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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
// Load environment variables from ~/.j/.env
const dotenv = require('dotenv');
const fs = require('fs');
const path = require('path');
const os = require('os');
// Define paths early for dotenv configuration
const J_DIR_PATH = path.join(os.homedir(), '.j');
const ENV_FILE_PATH = path.join(J_DIR_PATH, '.env');
// Configure dotenv to use the custom path
dotenv.config({ path: ENV_FILE_PATH });
const { OpenAI } = require('openai');
const { GoogleGenerativeAI } = require('@google/generative-ai');
const Anthropic = require('@anthropic-ai/sdk');
const inquirer = require('inquirer');
const { intro, outro, text, select, confirm, spinner, isCancel, cancel, note, log, password } = require('@clack/prompts');
const chalk = require('chalk');
const ora = require('ora');
let colorize;
const { exec, spawn } = require('child_process');
const { determineToolType, runTool, TOOLS } = require('./tools');
const { checkForUpdates } = require('./utils/update-checker');
// Setup colorize function (defined early for error handling)
colorize = {
blue: text => chalk.blue(text),
green: text => chalk.green(text),
yellow: text => chalk.yellow(text),
red: text => chalk.red(text),
cyan: text => chalk.cyan(text)
};
// Paths for configuration files
const LOCAL_PREFERENCES_FILE_PATH = path.join(process.cwd(), '.j-preferences');
const HOME_PREFERENCES_FILE_PATH = path.join(J_DIR_PATH, '.j-preferences');
// Default preferences
const DEFAULT_PREFERENCES = {
aiProvider: null, // Will be set during first run
defaultModel: null, // Will be set during first run
showCommandConfirmation: true,
colorOutput: true,
saveCommandHistory: true,
maxHistoryItems: 100,
debug: false
};
// AI Provider configurations
const AI_PROVIDERS = {
OPENAI: 'openai',
GEMINI: 'gemini',
ANTHROPIC: 'anthropic'
};
const OPENAI_MODELS = [
{ value: 'gpt-4o', label: 'GPT-4o', recommended: true },
{ value: 'gpt-4o-mini', label: 'GPT-4o Mini' },
{ value: 'gpt-4-turbo', label: 'GPT-4 Turbo' },
{ value: 'gpt-3.5-turbo', label: 'GPT-3.5 Turbo' },
{ value: 'o1-preview', label: 'O1 Preview' }
];
const GEMINI_MODELS = [
{ value: 'gemini-2.5-flash', label: 'Gemini 2.5 Flash', recommended: true },
{ value: 'gemini-2.5-pro', label: 'Gemini 2.5 Pro' },
{ value: 'gemini-1.5-flash', label: 'Gemini 1.5 Flash' },
{ value: 'gemini-1.5-pro', label: 'Gemini 1.5 Pro' },
{ value: 'gemini-1.0-pro', label: 'Gemini 1.0 Pro' }
];
const ANTHROPIC_MODELS = [
{ value: 'claude-sonnet-4-5-20250929', label: 'Claude Sonnet 4.5', recommended: true },
{ value: 'claude-opus-4-20250514', label: 'Claude Opus 4' },
{ value: 'claude-3-7-sonnet-20250219', label: 'Claude 3.7 Sonnet' },
{ value: 'claude-3-5-haiku-20241022', label: 'Claude 3.5 Haiku' },
{ value: 'claude-3-5-sonnet-20241022', label: 'Claude 3.5 Sonnet' }
];
// Load preferences
function loadPreferences() {
try {
// First try to load from current directory
if (fs.existsSync(LOCAL_PREFERENCES_FILE_PATH)) {
const preferencesData = fs.readFileSync(LOCAL_PREFERENCES_FILE_PATH, 'utf8');
return JSON.parse(preferencesData);
}
// Then try to load from home directory
else if (fs.existsSync(HOME_PREFERENCES_FILE_PATH)) {
// We can't use debugLog here because preferences aren't loaded yet
const preferencesData = fs.readFileSync(HOME_PREFERENCES_FILE_PATH, 'utf8');
return JSON.parse(preferencesData);
}
// If no file exists, create one in the home directory
else {
fs.writeFileSync(HOME_PREFERENCES_FILE_PATH, JSON.stringify(DEFAULT_PREFERENCES, null, 2));
return DEFAULT_PREFERENCES;
}
} catch (error) {
log.error(colorize.yellow('Error loading preferences, using defaults:'), error.message);
return DEFAULT_PREFERENCES;
}
}
// Get preferences
const preferences = loadPreferences();
// Update colorize function based on preferences
if (!preferences.colorOutput) {
colorize = {
blue: text => text,
green: text => text,
yellow: text => text,
red: text => text,
cyan: text => text
};
}
// Debug log wrapper function
function debugLog(message, color = 'blue') {
if (preferences.debug) {
log.info(colorize[color](`DEBUG: ${message}`));
}
}
// Check if OpenAI API key exists, if not prompt for it
async function checkOpenAIKey() {
if (!process.env.OPENAI_API_KEY) {
log.error(colorize.yellow('OpenAI API key not found.'));
const apiKey = await password({
message: 'Please enter your OpenAI API key:',
validate: (value) => {
if (!value || value.trim() === '') return 'API key is required';
}
});
if (isCancel(apiKey)) {
cancel('Setup cancelled');
process.exit(0);
}
// Ensure the .j directory exists
if (!fs.existsSync(J_DIR_PATH)) {
fs.mkdirSync(J_DIR_PATH, { recursive: true });
}
// Read existing .env content
let envContent = '';
if (fs.existsSync(ENV_FILE_PATH)) {
envContent = fs.readFileSync(ENV_FILE_PATH, 'utf8');
}
// Add or update OpenAI API key
if (envContent.includes('OPENAI_API_KEY=')) {
envContent = envContent.replace(/OPENAI_API_KEY=.*\n?/, `OPENAI_API_KEY=${apiKey}\n`);
} else {
envContent += `OPENAI_API_KEY=${apiKey}\n`;
}
fs.writeFileSync(ENV_FILE_PATH, envContent);
// Set the API key for the current session
process.env.OPENAI_API_KEY = apiKey;
log.success(colorize.green('API key saved successfully!'));
log.info(colorize.blue('Your API key has been securely stored in ~/.j/.env'));
}
return process.env.OPENAI_API_KEY;
}
// Initialize OpenAI client
async function initOpenAI() {
const apiKey = await checkOpenAIKey();
return new OpenAI({ apiKey });
}
// Check if Google Gemini API key exists, if not prompt for it
async function checkGeminiKey() {
if (!process.env.GEMINI_API_KEY) {
log.error(colorize.yellow('Google Gemini API key not found.'));
const apiKey = await password({
message: 'Please enter your Google Gemini API key:',
validate: (value) => {
if (!value || value.trim() === '') return 'API key is required';
}
});
if (isCancel(apiKey)) {
cancel('Setup cancelled');
process.exit(0);
}
// Ensure the .j directory exists
if (!fs.existsSync(J_DIR_PATH)) {
fs.mkdirSync(J_DIR_PATH, { recursive: true });
}
// Read existing .env content
let envContent = '';
if (fs.existsSync(ENV_FILE_PATH)) {
envContent = fs.readFileSync(ENV_FILE_PATH, 'utf8');
}
// Add or update Gemini API key
if (envContent.includes('GEMINI_API_KEY=')) {
envContent = envContent.replace(/GEMINI_API_KEY=.*\n?/, `GEMINI_API_KEY=${apiKey}\n`);
} else {
envContent += `GEMINI_API_KEY=${apiKey}\n`;
}
fs.writeFileSync(ENV_FILE_PATH, envContent);
// Set the API key for the current session
process.env.GEMINI_API_KEY = apiKey;
log.success(colorize.green('API key saved successfully!'));
log.info(colorize.blue('Your API key has been securely stored in ~/.j/.env'));
}
return process.env.GEMINI_API_KEY;
}
// Initialize Google Gemini client
async function initGemini() {
const apiKey = await checkGeminiKey();
const genAI = new GoogleGenerativeAI(apiKey);
return genAI;
}
// Check if Anthropic API key exists, if not prompt for it
async function checkAnthropicKey() {
if (!process.env.ANTHROPIC_API_KEY) {
log.error(colorize.yellow('Anthropic API key not found.'));
const apiKey = await password({
message: 'Please enter your Anthropic API key:',
validate: (value) => {
if (!value || value.trim() === '') return 'API key is required';
}
});
if (isCancel(apiKey)) {
cancel('Setup cancelled');
process.exit(0);
}
// Ensure the .j directory exists
if (!fs.existsSync(J_DIR_PATH)) {
fs.mkdirSync(J_DIR_PATH, { recursive: true });
}
// Read existing .env content
let envContent = '';
if (fs.existsSync(ENV_FILE_PATH)) {
envContent = fs.readFileSync(ENV_FILE_PATH, 'utf8');
}
// Add or update Anthropic API key
if (envContent.includes('ANTHROPIC_API_KEY=')) {
envContent = envContent.replace(/ANTHROPIC_API_KEY=.*\n?/, `ANTHROPIC_API_KEY=${apiKey}\n`);
} else {
envContent += `ANTHROPIC_API_KEY=${apiKey}\n`;
}
fs.writeFileSync(ENV_FILE_PATH, envContent);
// Set the API key for the current session
process.env.ANTHROPIC_API_KEY = apiKey;
log.success(colorize.green('API key saved successfully!'));
log.info(colorize.blue('Your API key has been securely stored in ~/.j/.env'));
}
return process.env.ANTHROPIC_API_KEY;
}
// Initialize Anthropic client
async function initAnthropic() {
const apiKey = await checkAnthropicKey();
return new Anthropic({ apiKey });
}
// Initialize AI client based on provider
async function initAI(provider) {
switch (provider) {
case AI_PROVIDERS.OPENAI:
return await initOpenAI();
case AI_PROVIDERS.GEMINI:
return await initGemini();
case AI_PROVIDERS.ANTHROPIC:
return await initAnthropic();
default:
throw new Error(`Unsupported AI provider: ${provider}`);
}
}
// First-run setup for AI provider and model selection
async function firstRunSetup() {
intro(colorize.cyan('🐦 Welcome to BlueJay!')+" - "+colorize.blue('Your AI assistant for the terminal'));
// Select AI provider
const provider = await select({
message: 'Choose your AI provider:',
options: [
{ value: AI_PROVIDERS.OPENAI, label: 'OpenAI (GPT models)' },
{ value: AI_PROVIDERS.GEMINI, label: 'Google Gemini' },
{ value: AI_PROVIDERS.ANTHROPIC, label: 'Anthropic (Claude models)' }
]
});
if (isCancel(provider)) {
cancel('Setup cancelled');
process.exit(0);
}
// Check API key for the selected provider
if (provider === AI_PROVIDERS.OPENAI) {
await checkOpenAIKey();
} else if (provider === AI_PROVIDERS.GEMINI) {
await checkGeminiKey();
} else if (provider === AI_PROVIDERS.ANTHROPIC) {
await checkAnthropicKey();
}
// Select model based on provider
let model;
if (provider === AI_PROVIDERS.OPENAI) {
model = await select({
message: 'Choose your OpenAI model:',
options: OPENAI_MODELS.map(m => ({
value: m.value,
label: m.label,
hint: m.recommended ? 'Recommended' : undefined
}))
});
} else if (provider === AI_PROVIDERS.GEMINI) {
model = await select({
message: 'Choose your Google Gemini model:',
options: GEMINI_MODELS.map(m => ({
value: m.value,
label: m.label,
hint: m.recommended ? 'Recommended' : undefined
}))
});
} else if (provider === AI_PROVIDERS.ANTHROPIC) {
model = await select({
message: 'Choose your Anthropic Claude model:',
options: ANTHROPIC_MODELS.map(m => ({
value: m.value,
label: m.label,
hint: m.recommended ? 'Recommended' : undefined
}))
});
}
if (isCancel(model)) {
cancel('Setup cancelled');
process.exit(0);
}
// Update preferences
const updatedPreferences = {
...preferences,
aiProvider: provider,
defaultModel: model
};
// Save preferences
fs.writeFileSync(HOME_PREFERENCES_FILE_PATH, JSON.stringify(updatedPreferences, null, 2));
// Initialize the AI client to ensure API key is set up
await initAI(provider);
outro(colorize.green('✅ Setup complete! You can now use BlueJay.'));
log.info(colorize.blue('💡 Try: j "list files in current directory"'));
log.info(colorize.blue('💡 Use "j settings" to change your preferences anytime.'));
return updatedPreferences;
}
// Update credentials submenu
async function updateCredentials() {
intro(colorize.cyan('🔑 Update Credentials'));
const credentialAction = await select({
message: 'Which API key would you like to update?',
options: [
{ value: 'update-openai-key', label: 'Update OpenAI API Key' },
{ value: 'update-gemini-key', label: 'Update Google Gemini API Key' },
{ value: 'update-anthropic-key', label: 'Update Anthropic API Key' },
{ value: 'back', label: '← Back to Settings' }
]
});
if (isCancel(credentialAction)) {
cancel('Credential update cancelled');
return 'back';
}
if (credentialAction === 'back') {
return 'back';
}
switch (credentialAction) {
case 'update-openai-key':
const openaiKey = await password({
message: 'Enter your new OpenAI API key:',
validate: (value) => {
if (!value || value.trim() === '') return 'API key is required';
}
});
if (isCancel(openaiKey)) {
return 'back';
}
// Update .env file
let envContent = fs.existsSync(ENV_FILE_PATH) ? fs.readFileSync(ENV_FILE_PATH, 'utf8') : '';
if (envContent.includes('OPENAI_API_KEY=')) {
envContent = envContent.replace(/OPENAI_API_KEY=.*\n?/, `OPENAI_API_KEY=${openaiKey}\n`);
} else {
envContent += `OPENAI_API_KEY=${openaiKey}\n`;
}
fs.writeFileSync(ENV_FILE_PATH, envContent);
process.env.OPENAI_API_KEY = openaiKey;
log.success(colorize.green('OpenAI API key updated successfully!'));
break;
case 'update-gemini-key':
const geminiKey = await password({
message: 'Enter your new Google Gemini API key:',
validate: (value) => {
if (!value || value.trim() === '') return 'API key is required';
}
});
if (isCancel(geminiKey)) {
return 'back';
}
// Update .env file
let envContent2 = fs.existsSync(ENV_FILE_PATH) ? fs.readFileSync(ENV_FILE_PATH, 'utf8') : '';
if (envContent2.includes('GEMINI_API_KEY=')) {
envContent2 = envContent2.replace(/GEMINI_API_KEY=.*\n?/, `GEMINI_API_KEY=${geminiKey}\n`);
} else {
envContent2 += `GEMINI_API_KEY=${geminiKey}\n`;
}
fs.writeFileSync(ENV_FILE_PATH, envContent2);
process.env.GEMINI_API_KEY = geminiKey;
log.success(colorize.green('Google Gemini API key updated successfully!'));
break;
case 'update-anthropic-key':
const anthropicKey = await password({
message: 'Enter your new Anthropic API key:',
validate: (value) => {
if (!value || value.trim() === '') return 'API key is required';
}
});
if (isCancel(anthropicKey)) {
return 'back';
}
// Update .env file
let envContent3 = fs.existsSync(ENV_FILE_PATH) ? fs.readFileSync(ENV_FILE_PATH, 'utf8') : '';
if (envContent3.includes('ANTHROPIC_API_KEY=')) {
envContent3 = envContent3.replace(/ANTHROPIC_API_KEY=.*\n?/, `ANTHROPIC_API_KEY=${anthropicKey}\n`);
} else {
envContent3 += `ANTHROPIC_API_KEY=${anthropicKey}\n`;
}
fs.writeFileSync(ENV_FILE_PATH, envContent3);
process.env.ANTHROPIC_API_KEY = anthropicKey;
log.success(colorize.green('Anthropic API key updated successfully!'));
break;
}
outro(colorize.green('Credentials updated!'));
return 'continue';
}
// Preferences management with checkboxes
async function managePreferences() {
intro(colorize.cyan('⚙️ Preferences'));
const currentPreferences = [
{
name: 'showCommandConfirmation',
message: 'Command Confirmation',
checked: preferences.showCommandConfirmation
},
{
name: 'colorOutput',
message: 'Colored Output',
checked: preferences.colorOutput
},
{
name: 'debug',
message: 'Debug Mode',
checked: preferences.debug
}
];
const selectedPreferences = await inquirer.prompt([
{
type: 'checkbox',
name: 'preferences',
message: 'Select your preferences:',
choices: currentPreferences.map(pref => ({
name: pref.message,
value: pref.name,
checked: pref.checked
}))
}
]);
// Update preferences based on selections
const updatedPreferences = { ...preferences };
// Set all preferences to false first
updatedPreferences.showCommandConfirmation = false;
updatedPreferences.colorOutput = false;
updatedPreferences.debug = false;
// Then set selected ones to true
selectedPreferences.preferences.forEach(prefName => {
updatedPreferences[prefName] = true;
});
// Save updated preferences
fs.writeFileSync(HOME_PREFERENCES_FILE_PATH, JSON.stringify(updatedPreferences, null, 2));
log.success(colorize.green('Preferences updated successfully!'));
outro(colorize.green('Preferences saved!'));
return updatedPreferences;
}
// Settings management
async function showSettings() {
while (true) {
intro(colorize.cyan('⚙️ BlueJay Settings'));
const action = await select({
message: 'What would you like to do?',
options: [
{ value: 'change-provider', label: `AI Provider: ${preferences.aiProvider || 'Not set'}` },
{ value: 'change-model', label: `Model: ${preferences.defaultModel || 'Not set'}` },
{ value: 'update-credentials', label: 'Update Credentials' },
{ value: 'preferences', label: 'Preferences' },
{ value: 'view-current', label: 'View Current Settings' },
{ value: 'exit', label: '← Exit Settings' }
]
});
if (isCancel(action)) {
cancel('Settings cancelled');
return;
}
if (action === 'exit') {
outro(colorize.green('Settings closed'));
return;
}
let updatedPreferences = { ...preferences };
switch (action) {
case 'change-provider':
const newProvider = await select({
message: 'Choose your AI provider:',
options: [
{ value: AI_PROVIDERS.OPENAI, label: 'OpenAI (GPT models)' },
{ value: AI_PROVIDERS.GEMINI, label: 'Google Gemini' },
{ value: AI_PROVIDERS.ANTHROPIC, label: 'Anthropic (Claude models)' }
]
});
if (isCancel(newProvider)) {
continue; // Go back to settings menu
}
updatedPreferences.aiProvider = newProvider;
// Reset model when changing provider
updatedPreferences.defaultModel = null;
// Check API key for the selected provider
if (newProvider === AI_PROVIDERS.OPENAI) {
await checkOpenAIKey();
} else if (newProvider === AI_PROVIDERS.GEMINI) {
await checkGeminiKey();
} else if (newProvider === AI_PROVIDERS.ANTHROPIC) {
await checkAnthropicKey();
}
// Immediately prompt for model selection after provider change
let models;
let providerLabel;
if (newProvider === AI_PROVIDERS.OPENAI) {
models = OPENAI_MODELS;
providerLabel = 'OpenAI';
} else if (newProvider === AI_PROVIDERS.GEMINI) {
models = GEMINI_MODELS;
providerLabel = 'Google Gemini';
} else if (newProvider === AI_PROVIDERS.ANTHROPIC) {
models = ANTHROPIC_MODELS;
providerLabel = 'Anthropic Claude';
}
const newModel = await select({
message: `Choose your ${providerLabel} model:`,
options: models.map(m => ({
value: m.value,
label: m.label,
hint: m.recommended ? 'Recommended' : undefined
}))
});
if (!isCancel(newModel)) {
updatedPreferences.defaultModel = newModel;
}
break;
case 'change-model':
let models2;
let providerLabel2;
if (preferences.aiProvider === AI_PROVIDERS.OPENAI) {
models2 = OPENAI_MODELS;
providerLabel2 = 'OpenAI';
} else if (preferences.aiProvider === AI_PROVIDERS.GEMINI) {
models2 = GEMINI_MODELS;
providerLabel2 = 'Google Gemini';
} else if (preferences.aiProvider === AI_PROVIDERS.ANTHROPIC) {
models2 = ANTHROPIC_MODELS;
providerLabel2 = 'Anthropic Claude';
}
const newModel2 = await select({
message: `Choose your ${providerLabel2} model:`,
options: models2.map(m => ({
value: m.value,
label: m.label,
hint: m.recommended ? 'Recommended' : undefined
}))
});
if (isCancel(newModel2)) {
continue; // Go back to settings menu
}
updatedPreferences.defaultModel = newModel2;
break;
case 'update-credentials':
const credResult = await updateCredentials();
if (credResult === 'back') {
continue; // Go back to settings menu
}
break;
case 'preferences':
updatedPreferences = await managePreferences();
break;
case 'view-current':
log.info(colorize.blue('\n📋 Current Settings:'));
log.info(colorize.cyan(`AI Provider: ${preferences.aiProvider || 'Not set'}`));
log.info(colorize.cyan(`Default Model: ${preferences.defaultModel || 'Not set'}`));
log.info(colorize.blue('\nPreferences:'));
log.info(colorize.cyan(`│ ${preferences.showCommandConfirmation ? '●' : '○'} Command Confirmation`));
log.info(colorize.cyan(`│ ${preferences.colorOutput ? '●' : '○'} Colored Output`));
log.info(colorize.cyan(`│ ${preferences.debug ? '●' : '○'} Debug Mode`));
break;
}
// Save updated preferences if they changed
if (JSON.stringify(updatedPreferences) !== JSON.stringify(preferences)) {
fs.writeFileSync(HOME_PREFERENCES_FILE_PATH, JSON.stringify(updatedPreferences, null, 2));
// Update the global preferences object
Object.assign(preferences, updatedPreferences);
}
outro(colorize.green('Settings updated!'));
}
}
// Ask AI if the input is a terminal command (works with both OpenAI and Gemini)
async function isTerminalCommand(aiClient, userInput, provider, defaultModel) {
try {
const systemPrompt = 'You are a helpful assistant that runs in a terminal on a MAC OS/LINUX. Your primary goal is to interpret user input as terminal commands whenever possible. Be very liberal in your interpretation - if there is any way the user\'s request could be fulfilled with a terminal command, provide that command. Even if the request is ambiguous or could be interpreted in multiple ways, prefer to respond with a command rather than "NOT_A_COMMAND". If you provide a command, respond ONLY with the command to run, with no additional text or explanation. Only respond with "NOT_A_COMMAND" if the user\'s input is clearly not related to any possible terminal operation or file system task.';
let content;
if (provider === AI_PROVIDERS.OPENAI) {
const response = await aiClient.chat.completions.create({
model: defaultModel,
messages: [
{
role: 'system',
content: systemPrompt
},
{
role: 'user',
content: userInput
}
],
temperature: 0.2,
});
content = response.choices[0].message.content;
} else if (provider === AI_PROVIDERS.GEMINI) {
// Ensure we have a valid model name
const modelName = defaultModel || 'gemini-2.5-flash';
const model = aiClient.getGenerativeModel({ model: modelName });
const prompt = `${systemPrompt}\n\nUser: ${userInput}`;
const result = await model.generateContent(prompt);
const response = await result.response;
content = response.text();
} else if (provider === AI_PROVIDERS.ANTHROPIC) {
const response = await aiClient.messages.create({
model: defaultModel,
max_tokens: 1024,
system: systemPrompt,
messages: [
{
role: 'user',
content: userInput
}
],
temperature: 0.2,
});
content = response.content[0].text;
}
if (content.includes('NOT_A_COMMAND')) {
return { isCommand: false, command: null };
} else {
// Extract the command from the response
const command = content.replace(/```bash|```sh|```|\n/g, '').trim();
return { isCommand: true, command };
}
} catch (error) {
log.error(colorize.red(`Error communicating with ${provider}:`), error.message);
return { isCommand: false, command: null };
}
}
// Check if a command is likely to be interactive
function isInteractiveCommand(command) {
if (!command) return false;
// Method 1: Check against known interactive commands
const knownInteractiveCommands = ['vim', 'nano', 'emacs', 'less', 'more', 'top', 'htop', 'ssh', 'mysql', 'psql', 'python', 'node'];
const commandName = command.split(' ')[0];
// Method 2: Check for command flags that suggest interactivity
const interactiveFlags = ['-i', '--interactive'];
const hasInteractiveFlag = command.split(' ').some(part => interactiveFlags.includes(part));
// Method 3: Check for commands that typically open a new interface or prompt
const hasEditorPattern = /\b(edit|editor)\b/i.test(command);
return knownInteractiveCommands.some(cmd => commandName === cmd) ||
hasInteractiveFlag ||
hasEditorPattern;
}
// Function to detect current shell and return history file path
function getShellHistoryPath() {
const shell = process.env.SHELL || '/bin/bash';
const shellName = path.basename(shell);
const homeDir = os.homedir();
switch (shellName) {
case 'zsh':
return path.join(homeDir, '.zsh_history');
case 'bash':
return path.join(homeDir, '.bash_history');
case 'fish':
return path.join(homeDir, '.local/share/fish/fish_history');
default:
// Default to bash history for unknown shells
return path.join(homeDir, '.bash_history');
}
}
// Function to add command to shell history
function addToShellHistory(command) {
if (!preferences.saveCommandHistory) {
return;
}
try {
const historyPath = getShellHistoryPath();
const shell = process.env.SHELL || '/bin/bash';
const shellName = path.basename(shell);
let historyEntry;
const timestamp = Math.floor(Date.now() / 1000);
switch (shellName) {
case 'zsh':
// Zsh history format: : timestamp:0;command
historyEntry = `: ${timestamp}:0;${command}\n`;
break;
case 'fish':
// Fish history format is YAML-like
historyEntry = `- cmd: ${command}\n when: ${timestamp}\n`;
break;
case 'bash':
default:
// Bash history format: just the command
historyEntry = `${command}\n`;
break;
}
// Append to history file
fs.appendFileSync(historyPath, historyEntry);
debugLog(`Added command to ${shellName} history: ${command}`, 'green');
} catch (error) {
debugLog(`Failed to add command to history: ${error.message}`, 'red');
}
}
// Execute a terminal command
// We use spawn for all commands because:
// 1. It provides better handling of interactive commands that require user input
// 2. It allows for streaming output in real-time
// 3. It gives more control over stdio streams
// 4. It's more reliable for long-running processes
function executeCommand(command) {
return new Promise((resolve, reject) => {
// Parse the command into command name and arguments
const parts = command.split(' ');
const cmd = parts[0];
const args = parts.slice(1);
// Check if the command is likely to be interactive
const interactive = isInteractiveCommand(command);
// Configure spawn options based on whether the command is interactive
const spawnOptions = {
shell: true,
// For interactive commands: inherit all stdio to allow user interaction
// For non-interactive commands: only inherit stderr, capture stdout
stdio: interactive ? 'inherit' : ['inherit', 'pipe', 'inherit']
};
// Use debug log wrapper function
debugLog(`Executing command "${command}"`)
// Use spawn for all commands with appropriate configuration
const childProcess = spawn(cmd, args, spawnOptions);
// For non-interactive commands, we need to capture stdout
let stdout = '';
if (!interactive && childProcess.stdout) {
childProcess.stdout.on('data', (data) => {
stdout += data.toString();
});
}
childProcess.on('close', (code) => {
if (code === 0) {
if (interactive) {
resolve('Interactive command completed successfully');
} else {
resolve(stdout);
}
} else {
reject({ code, message: `Command exited with code ${code}` });
}
});
childProcess.on('error', (error) => {
reject({ code: 1, message: `Error: ${error.message}` });
});
});
}
// Show welcome message
function showWelcomeMessage() {
console.log('');
note(
`${colorize.blue('Welcome to BlueJay!')} 🐦 v${CURRENT_VERSION}
Your AI-powered terminal assistant.
${colorize.cyan('GET STARTED')}
Run: ${colorize.green('j settings')}
This will help you:
• Choose your AI provider (OpenAI, Gemini, or Anthropic)
• Select your preferred model
• Configure your API key
• Set your preferences
${colorize.cyan('LEARN MORE')}
Run: ${colorize.green('j --help')}`,
'Getting Started'
);
console.log('');
}
// Show enhanced empty command help
function showEmptyCommandHelp() {
console.log('');
if (!preferences.aiProvider || !preferences.defaultModel) {
// Unconfigured state - guide to setup
note(
`${colorize.blue('Welcome to BlueJay!')} 🐦
Your AI-powered terminal assistant.
${colorize.cyan('GET STARTED')}
Run: ${colorize.green('j settings')}
This will help you:
• Choose your AI provider (OpenAI, Gemini, or Anthropic)
• Select your preferred model
• Configure your API key
• Set your preferences
${colorize.cyan('LEARN MORE')}
Run: ${colorize.green('j --help')}`,
'Getting Started'
);
} else {
// Configured state - show quick reference
note(
`${colorize.green('Ready to assist!')} 🐦
${colorize.cyan('CURRENT SETUP')}
Provider: ${preferences.aiProvider}
Model: ${preferences.defaultModel}
${colorize.cyan('TRY THESE COMMANDS')}
${colorize.green('j "list files in current directory"')}
${colorize.green('j "show system information"')}
${colorize.green('j "find all .js files"')}
${colorize.green('j "create a directory called projects"')}
${colorize.cyan('QUICK REFERENCE')}
${colorize.blue('j settings')} - Configure provider and preferences
${colorize.blue('j --help')} - View full documentation`,
'BlueJay CLI'
);
}
console.log('');
}
// Get package version
const packageJson = require('./package.json');
const CURRENT_VERSION = packageJson.version;
// Show update notification if available
async function showUpdateNotification() {
try {
const { updateAvailable, latestVersion } = await checkForUpdates(CURRENT_VERSION);
if (updateAvailable && latestVersion) {
console.log('');
log.info(colorize.yellow(`🐦 A new BlueJay has arrived! ${CURRENT_VERSION} → ${latestVersion}`));
log.info(colorize.cyan(` Run: npm install -g @bvdr/bluejay@latest`));
console.log('');
}
} catch (error) {
// Silently fail - don't interrupt user's workflow
}
}
// Show help information
function showHelp() {
const version = CURRENT_VERSION;
console.log('');
note(
`${colorize.blue('BlueJay CLI')} - AI-powered terminal assistant v${version}
${colorize.cyan('USAGE')}
j "your natural language request"
j settings Configure AI provider and preferences
j --help | -h | help Show this help screen
${colorize.cyan('EXAMPLES')}
j "list files in current directory"
j "find all .js files modified in last week"
j "show system information"
j "create a new directory called projects"
j "search for 'TODO' in all files"