-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.ts
More file actions
1053 lines (914 loc) · 34.2 KB
/
Copy pathauth.ts
File metadata and controls
1053 lines (914 loc) · 34.2 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
import fs from "fs";
import os from "os";
import path from "path";
import makeWASocket, {
useMultiFileAuthState,
fetchLatestBaileysVersion,
makeCacheableSignalKeyStore,
} from "@whiskeysockets/baileys";
import chalk from "chalk";
import qrcode from "qrcode-terminal";
import type { MCPServerEntry } from "../../shared/types";
import { setApiKey, setBotToken } from "../../utils/keychain";
import { loadMCPServersCatalog, type MCPCatalogServer } from "../../utils/mcp-catalog-loader";
import {
discoverHuggingFaceModels,
discoverOpenRouterModels,
} from "../../utils/model-discovery-util";
import { loadModelsCatalog } from "../../utils/models-catalog-loader";
import { showCenteredList, showCenteredInput, showCenteredConfirm } from "../tui";
const CONFIG_DIR = path.join(os.homedir(), ".txtcode");
const CONFIG_FILE = path.join(CONFIG_DIR, "config.json");
const WA_AUTH_DIR = path.join(CONFIG_DIR, ".wacli_auth");
type BaileysLogger = NonNullable<Parameters<typeof makeWASocket>[0]["logger"]>;
const noop = () => {};
const silentLogger: BaileysLogger = {
level: "silent" as const,
fatal: noop,
error: noop,
warn: noop,
info: noop,
debug: noop,
trace: noop,
child: () => silentLogger,
} as BaileysLogger;
// Validate API key
function validateApiKeyFormat(apiKey: string): { valid: boolean; error?: string } {
const trimmed = apiKey.trim();
if (!trimmed) {
return { valid: false, error: "API key is required" };
}
return { valid: true };
}
function authenticateWhatsApp(): Promise<void> {
let resolvePromise!: () => void;
let rejectPromise!: (err: Error) => void;
const promise = new Promise<void>((resolve, reject) => {
resolvePromise = resolve;
rejectPromise = reject;
});
const closeSock = (s: unknown) => {
try {
(s as { ws?: { close: () => void } })?.ws?.close();
} catch {
// Ignore
}
};
(async () => {
let sock: ReturnType<typeof makeWASocket> | null = null;
let pairingComplete = false;
let connectionTimeout: NodeJS.Timeout;
let connectionAttempted = false;
try {
if (fs.existsSync(WA_AUTH_DIR)) {
const files = fs.readdirSync(WA_AUTH_DIR);
if (files.length > 0) {
console.log(chalk.yellow("Existing WhatsApp session found."));
console.log(chalk.gray("Clearing old session to start fresh..."));
console.log();
try {
fs.rmSync(WA_AUTH_DIR, { recursive: true, force: true });
fs.mkdirSync(WA_AUTH_DIR, { recursive: true });
} catch {
console.log(chalk.yellow("Warning: Could not clear old session"));
}
}
} else {
fs.mkdirSync(WA_AUTH_DIR, { recursive: true });
}
console.log(chalk.gray("Initializing WhatsApp connection..."));
console.log();
const { state, saveCreds } = await useMultiFileAuthState(WA_AUTH_DIR);
const { version } = await fetchLatestBaileysVersion();
connectionTimeout = setTimeout(() => {
if (!pairingComplete && sock) {
closeSock(sock);
if (!connectionAttempted) {
rejectPromise(
new Error(
"Connection timeout - No response from WhatsApp servers. Please check your internet connection.",
),
);
} else {
rejectPromise(new Error("QR code generation timeout - Please try again."));
}
}
}, 60000);
sock = makeWASocket({
auth: {
creds: state.creds,
keys: makeCacheableSignalKeyStore(state.keys, silentLogger),
},
version,
printQRInTerminal: false,
browser: ["TxtCode", "CLI", "1.0.0"],
syncFullHistory: false,
markOnlineOnConnect: false,
logger: silentLogger,
});
let hasShownQR = false;
sock.ev.on("creds.update", saveCreds);
sock.ev.on("connection.update", async (update) => {
connectionAttempted = true;
const { connection, qr, lastDisconnect } = update;
if (qr && !hasShownQR) {
clearTimeout(connectionTimeout);
hasShownQR = true;
console.log();
console.log(chalk.yellow("[QR] Scan this QR code with WhatsApp:"));
console.log();
qrcode.generate(qr, { small: true });
console.log();
console.log(chalk.gray("Open WhatsApp → Settings → Linked Devices → Link a Device"));
console.log();
connectionTimeout = setTimeout(() => {
if (!pairingComplete) {
closeSock(sock);
rejectPromise(new Error("QR code scan timeout - Please try again"));
}
}, 120000);
}
if (connection === "open" && !pairingComplete) {
clearTimeout(connectionTimeout);
pairingComplete = true;
console.log(chalk.green("\n[OK] WhatsApp authenticated successfully!"));
setTimeout(() => {
closeSock(sock);
resolvePromise();
}, 500);
}
if (connection === "close" && !pairingComplete) {
clearTimeout(connectionTimeout);
const statusCode = (lastDisconnect?.error as { output?: { statusCode?: number } })?.output
?.statusCode;
const errorMessage = lastDisconnect?.error?.message || "Unknown error";
if (!hasShownQR) {
closeSock(sock);
if (statusCode === 405) {
rejectPromise(
new Error(
`WhatsApp connection failed (Error 405). This usually means:\n • WhatsApp updated their protocol and the library needs updating\n • Try updating: npm install @whiskeysockets/baileys@latest\n • Or use Telegram/Discord instead (more reliable)`,
),
);
} else {
rejectPromise(
new Error(
`Failed to connect to WhatsApp servers (${statusCode || "no status"}). ${errorMessage}. Please check your internet connection and try again.`,
),
);
}
return;
}
if (statusCode === 515 && hasShownQR) {
console.log(
chalk.cyan("\n[INFO] WhatsApp pairing complete, restarting connection...\n"),
);
closeSock(sock);
const { state: newState, saveCreds: newSaveCreds } =
await useMultiFileAuthState(WA_AUTH_DIR);
const retrySock = makeWASocket({
auth: newState,
printQRInTerminal: false,
logger: silentLogger,
});
retrySock.ev.on("creds.update", newSaveCreds);
retrySock.ev.on("connection.update", (retryUpdate) => {
if (retryUpdate.connection === "open") {
pairingComplete = true;
console.log(chalk.green("[OK] WhatsApp linked successfully!\n"));
setTimeout(() => {
closeSock(retrySock);
resolvePromise();
}, 500);
}
if (retryUpdate.connection === "close") {
closeSock(retrySock);
rejectPromise(new Error("WhatsApp authentication failed after restart"));
}
});
} else if (hasShownQR && statusCode !== 515) {
closeSock(sock);
rejectPromise(new Error(`WhatsApp authentication failed (code: ${statusCode})`));
}
}
});
} catch (error) {
if (sock) {
closeSock(sock);
}
rejectPromise(error instanceof Error ? error : new Error(String(error)));
}
})();
return promise;
}
export async function authCommand() {
console.clear();
console.log();
console.log(chalk.blue.bold("TxtCode Authentication"));
console.log();
console.log(chalk.gray("Configure your TxtCode CLI for remote IDE control"));
console.log();
// Check for existing configuration
const existingConfig = loadConfig();
const existingProviders = existingConfig?.providers as
| Record<string, { model: string }>
| undefined;
if (existingConfig && existingProviders) {
console.log(chalk.yellow("⚠️ Existing configuration detected!"));
console.log();
console.log(chalk.gray("Currently configured providers:"));
Object.keys(existingProviders).forEach((provider) => {
const providerConfig = existingProviders[provider];
console.log(chalk.white(`• ${provider} (${providerConfig.model})`));
});
console.log();
const shouldOverwrite = await showCenteredConfirm({
message: "Do you want to reconfigure? This will overwrite existing providers.",
default: false,
});
if (!shouldOverwrite) {
console.log();
console.log(
chalk.gray("Authentication cancelled. Use 'txtcode config' to modify individual settings."),
);
console.log();
return;
}
console.log();
console.log(chalk.yellow("Reconfiguring all providers..."));
console.log();
}
const selectedProviders = new Set<string>();
// Load models catalog
const modelsCatalog = loadModelsCatalog();
// Helper function to get all available providers dynamically from catalog
function getAllProviders() {
return Object.keys(modelsCatalog.providers).map((providerId) => {
const providerData = modelsCatalog.providers[providerId];
return {
name: providerData.name,
value: providerId,
};
});
}
// Helper function to configure a provider
async function configureProvider(
label: string,
): Promise<{ provider: string; apiKey: string; model: string } | null> {
console.log();
console.log(chalk.cyan(label));
console.log();
// Get available providers dynamically (excluding already selected ones)
const providers = getAllProviders();
const availableProviders = providers.filter((p) => !selectedProviders.has(p.value));
if (availableProviders.length === 0) {
throw new Error("No more providers available to configure");
}
// Add "Back" option if this is not the primary provider
const providerChoices =
label === "Primary AI Provider"
? availableProviders
: [...availableProviders, { name: "← Back", value: "__BACK__" }];
const providerValue = await showCenteredList({
message: `Select ${label}: (Use arrow keys)`,
choices: providerChoices,
});
// Handle back navigation
if (providerValue === "__BACK__") {
return null;
}
const apiKey = await showCenteredInput({
message: "Enter API Key:",
password: true,
validate: (input) => input.length > 0 || "API key is required",
});
console.log(); // Add spacing after API key input
// Validate API key (just check it's not empty)
const validation = validateApiKeyFormat(apiKey);
if (!validation.valid) {
console.log();
console.log(chalk.red(`[ERROR] ${validation.error}`));
console.log();
const retry = await showCenteredConfirm({
message: "Would you like to enter a different API key?",
default: true,
});
if (retry) {
// Retry with same provider
return await configureProvider(label);
} else {
throw new Error(
"API key validation failed. Please run 'txtcode auth' again with a valid key.",
);
}
}
// Mark this provider as selected
selectedProviders.add(providerValue);
// Load models - use dynamic discovery for HuggingFace and OpenRouter, static catalog for others
let modelChoices: Array<{ name: string; value: string }>;
if (providerValue === "huggingface") {
console.log(chalk.gray("Discovering available models from HuggingFace..."));
try {
const discoveredModels = await discoverHuggingFaceModels(apiKey);
modelChoices = discoveredModels.map((model) => ({
name: model.description ? `${model.name} - ${model.description}` : model.name,
value: model.id,
}));
console.log(chalk.green(`Found ${discoveredModels.length} models\n`));
} catch (error) {
console.log();
console.log(
chalk.red(
`[ERROR] Failed to discover HuggingFace models: ${error instanceof Error ? error.message : "Unknown error"}`,
),
);
console.log(chalk.yellow("Please check your API key and try again."));
console.log();
const retry = await showCenteredConfirm({
message: "Would you like to enter a different API key?",
default: true,
});
if (retry) {
return await configureProvider(label);
} else {
throw new Error(
"HuggingFace model discovery failed. Please run 'txtcode auth' again with a valid API key.",
{ cause: error },
);
}
}
} else if (providerValue === "openrouter") {
console.log(chalk.gray("Discovering available models from OpenRouter..."));
try {
const discoveredModels = await discoverOpenRouterModels(apiKey);
modelChoices = discoveredModels.map((model) => ({
name: model.description ? `${model.name} - ${model.description}` : model.name,
value: model.id,
}));
console.log(chalk.green(`Found ${discoveredModels.length} models\n`));
} catch (error) {
console.log();
console.log(
chalk.red(
`[ERROR] Failed to discover OpenRouter models: ${error instanceof Error ? error.message : "Unknown error"}`,
),
);
console.log(chalk.yellow("Please check your API key and try again."));
console.log();
const retry = await showCenteredConfirm({
message: "Would you like to enter a different API key?",
default: true,
});
if (retry) {
return await configureProvider(label);
} else {
throw new Error(
"OpenRouter model discovery failed. Please run 'txtcode auth' again with a valid API key.",
{ cause: error },
);
}
}
} else {
const providerModels = modelsCatalog.providers[providerValue];
modelChoices = providerModels.models.map(
(model: { id: string; name: string; recommended?: boolean }) => ({
name: model.recommended ? `${model.name} - Recommended` : model.name,
value: model.id,
}),
);
}
// Add "Enter custom model name" option at the top
const modelChoicesWithCustom = [
{ name: "Enter custom model name", value: "__CUSTOM__" },
...modelChoices,
];
console.log(); // Add spacing before model selection
// Use pagination for OpenRouter and HuggingFace (10 items per page)
const usePagination = providerValue === "openrouter" || providerValue === "huggingface";
const selectedModel = await showCenteredList({
message: "Select model: (Use arrow keys)",
choices: modelChoicesWithCustom,
pageSize: usePagination ? 10 : undefined,
});
let finalModel = selectedModel;
// Handle custom model entry
if (selectedModel === "__CUSTOM__") {
finalModel = await showCenteredInput({
message: "Enter model name/ID:",
validate: (input) => input.trim().length > 0 || "Model name is required",
});
console.log();
console.log(chalk.gray(`Using custom model: ${finalModel}`));
console.log();
}
console.log();
console.log(chalk.green(`${label} configured: ${providerValue} (${finalModel})`));
console.log();
return {
provider: providerValue,
apiKey: apiKey,
model: finalModel,
};
}
// Step 1: Configure Primary AI Provider (cannot go back from primary)
let primaryProvider = await configureProvider("Primary AI Provider");
// Primary provider should never be null, but handle it just in case
while (primaryProvider === null) {
console.log(chalk.yellow("\nPrimary provider is required. Please select a provider.\n"));
primaryProvider = await configureProvider("Primary AI Provider");
}
// Collect all configured providers
const configuredProviders: Array<{ provider: string; apiKey: string; model: string }> = [
primaryProvider,
];
// Step 2: Keep asking if user wants to add more providers (unlimited)
let continueAdding = true;
let providerCount = 1;
while (continueAdding) {
// Check if there are more providers available (dynamic)
const allProviders = getAllProviders();
const remainingProviders = allProviders.filter((p) => !selectedProviders.has(p.value));
if (remainingProviders.length === 0) {
console.log(
chalk.yellow(`\n✓ All available providers configured (${providerCount} total)\n`),
);
break;
}
const addMore = await showCenteredConfirm({
message: `Add another provider for hot-switching? (${providerCount} configured, ${remainingProviders.length} available)`,
default: providerCount === 1,
});
if (!addMore) {
continueAdding = false;
break;
}
providerCount++;
const secondaryProvider = await configureProvider(
`Secondary AI Provider #${providerCount - 1}`,
);
// Handle back navigation
if (secondaryProvider === null) {
providerCount--;
continue;
}
configuredProviders.push(secondaryProvider);
}
// Validate all providers are unique (safety check)
const allProviderNames = configuredProviders.map((p) => p.provider);
const uniqueProviders = new Set(allProviderNames);
if (uniqueProviders.size !== allProviderNames.length) {
console.log(
chalk.red("\n[ERROR] Duplicate providers detected. Each provider must be unique.\n"),
);
console.log(chalk.yellow("Please run 'txtcode auth' again and select different providers.\n"));
process.exit(1);
}
console.log();
console.log(chalk.green(`✅ Configured ${configuredProviders.length} provider(s)`));
console.log();
// Step 2.5: MCP Servers (optional)
const mcpServerEntries = await configureMCPServers();
// Step 3: Messaging Platform
const platform = await showCenteredList({
message: "Select messaging platform: (Use arrow keys)",
choices: [
{ name: "WhatsApp", value: "whatsapp" },
{ name: "Telegram", value: "telegram" },
{ name: "Discord", value: "discord" },
{ name: "Slack", value: "slack" },
{ name: "Microsoft Teams", value: "teams" },
{ name: "Signal", value: "signal" },
],
});
let telegramToken = "";
let discordToken = "";
let slackBotToken = "";
let slackAppToken = "";
let slackSigningSecret = "";
let teamsAppId = "";
let teamsAppPassword = "";
let teamsTenantId = "";
let signalPhoneNumber = "";
let signalCliRestUrl = "";
// Complete messaging platform auth immediately
if (platform === "telegram") {
console.log();
console.log(chalk.cyan("Telegram Bot Setup"));
console.log();
console.log(chalk.gray("1. Open Telegram and search for @BotFather"));
console.log(chalk.gray("2. Send /newbot and follow the instructions"));
console.log(chalk.gray("3. Copy the bot token you receive"));
console.log();
telegramToken = await showCenteredInput({
message: "Enter Telegram Bot Token:",
password: true,
validate: (input) => input.length > 0 || "Token is required",
});
console.log();
console.log(chalk.green("Telegram bot configured"));
console.log();
} else if (platform === "discord") {
console.log();
console.log(chalk.cyan("Discord Bot Setup"));
console.log();
console.log(chalk.gray("1. Go to https://discord.com/developers/applications"));
console.log(chalk.gray("2. Create a New Application"));
console.log(chalk.gray("3. Go to Bot → Add Bot"));
console.log(chalk.gray("4. Copy the bot token"));
console.log(chalk.gray("5. Enable MESSAGE CONTENT INTENT"));
console.log();
discordToken = await showCenteredInput({
message: "Enter Discord Bot Token:",
password: true,
validate: (input) => input.length > 0 || "Token is required",
});
console.log();
console.log(chalk.green("Discord bot configured"));
console.log();
} else if (platform === "slack") {
console.log();
console.log(chalk.cyan("Slack Bot Setup"));
console.log();
console.log(chalk.gray("1. Go to https://api.slack.com/apps and create a new app"));
console.log(chalk.gray("2. Enable Socket Mode (Settings → Socket Mode)"));
console.log(
chalk.gray(
"3. Add Bot Token Scopes: chat:write, channels:history, groups:history, im:history, mpim:history",
),
);
console.log(chalk.gray("4. Install the app to your workspace"));
console.log(
chalk.gray(
"5. Subscribe to bot events: message.channels, message.groups, message.im, message.mpim",
),
);
console.log();
slackBotToken = await showCenteredInput({
message: "Enter Slack Bot Token (xoxb-...):",
password: true,
validate: (input) => input.length > 0 || "Bot token is required",
});
console.log();
slackAppToken = await showCenteredInput({
message: "Enter Slack App-Level Token (xapp-...):",
password: true,
validate: (input) => input.length > 0 || "App token is required",
});
console.log();
slackSigningSecret = await showCenteredInput({
message: "Enter Slack Signing Secret:",
password: true,
validate: (input) => input.length > 0 || "Signing secret is required",
});
console.log();
console.log(chalk.green("Slack bot configured"));
console.log();
} else if (platform === "teams") {
console.log();
console.log(chalk.cyan("Microsoft Teams Bot Setup"));
console.log();
console.log(chalk.gray("1. Go to https://dev.teams.microsoft.com/bots"));
console.log(chalk.gray("2. Create a new Bot registration"));
console.log(chalk.gray("3. Copy the App ID and generate a client secret"));
console.log(chalk.gray("4. Set the messaging endpoint to https://<your-domain>/api/messages"));
console.log();
teamsAppId = await showCenteredInput({
message: "Enter Teams App (Bot) ID:",
password: false,
validate: (input) => input.length > 0 || "App ID is required",
});
console.log();
teamsAppPassword = await showCenteredInput({
message: "Enter Teams App Password (Client Secret):",
password: true,
validate: (input) => input.length > 0 || "App password is required",
});
console.log();
teamsTenantId = await showCenteredInput({
message: "Enter Azure Tenant ID:",
password: false,
validate: (input) => input.length > 0 || "Tenant ID is required",
});
console.log();
console.log(chalk.green("Microsoft Teams bot configured"));
console.log();
} else if (platform === "signal") {
console.log();
console.log(chalk.cyan("Signal Bot Setup"));
console.log();
console.log(chalk.gray("Signal requires signal-cli-rest-api running as a companion service."));
console.log();
console.log(chalk.gray("Setup:"));
console.log(chalk.gray(" 1. Run signal-cli-rest-api via Docker:"));
console.log(chalk.white(" docker run -p 8080:8080 bbernhard/signal-cli-rest-api"));
console.log(chalk.gray(" 2. Register/link your phone number with signal-cli"));
console.log(chalk.gray(" 3. Provide the phone number and API URL below"));
console.log();
signalPhoneNumber = await showCenteredInput({
message: "Enter Signal phone number (e.g. +1234567890):",
password: false,
validate: (input) => input.startsWith("+") || "Phone number must start with +",
});
console.log();
signalCliRestUrl = await showCenteredInput({
message: "Enter signal-cli-rest-api URL (default: http://localhost:8080):",
password: false,
validate: () => true,
});
if (!signalCliRestUrl.trim()) {
signalCliRestUrl = "http://localhost:8080";
}
console.log();
console.log(chalk.green("Signal bot configured"));
console.log();
} else {
console.log();
console.log(chalk.cyan("WhatsApp Setup"));
console.log();
// Ensure stdin is fully reset after TUI interactions
if (process.stdin.isTTY) {
process.stdin.setRawMode(false);
}
process.stdin.removeAllListeners("keypress");
process.stdin.pause();
// Give stdin time to settle
await new Promise((resolve) => setTimeout(resolve, 200));
// Authenticate WhatsApp immediately
try {
await authenticateWhatsApp();
console.log();
console.log(chalk.green("WhatsApp authenticated successfully!"));
console.log();
} catch (error) {
console.log();
const errorMsg = error instanceof Error ? error.message : "Unknown error";
// Check if it's a 405 error
if (errorMsg.includes("405")) {
console.log(chalk.red(`[ERROR] WhatsApp authentication failed (Error 405)`));
console.log();
console.log(chalk.yellow("This is a known issue with WhatsApp's protocol changes."));
console.log(chalk.yellow("The WhatsApp library needs to be updated by the maintainers."));
console.log();
console.log(chalk.cyan("Recommended alternatives:"));
console.log(chalk.white(" • Telegram - More stable and reliable"));
console.log(chalk.white(" • Discord - Also very stable"));
console.log(chalk.white(" • Slack - Great for workspace integration"));
console.log(chalk.white(" • Signal - Privacy-focused alternative"));
console.log();
console.log(chalk.gray("Would you like to restart and choose a different platform?"));
} else {
console.log(chalk.red(`[ERROR] WhatsApp authentication failed: ${errorMsg}`));
console.log();
console.log(chalk.yellow("Please try running authentication again."));
}
console.log();
process.exit(1);
}
}
// Step 5: Coding Adapter Selection
const ideType = await showCenteredList({
message: "Select coding adapter: (Use arrow keys)",
choices: [
{ name: "Claude Code (Anthropic)", value: "claude-code" },
{ name: "Cursor CLI (Headless)", value: "cursor" },
{ name: "OpenAI Codex (OpenAI)", value: "codex" },
{ name: "Gemini CLI (Google)", value: "gemini-code" },
{ name: "Kiro CLI (AWS)", value: "kiro" },
{ name: "OpenCode (Open Source, Multi-Provider)", value: "opencode" },
{ name: "Ollama Claude Code (Local, Free)", value: "ollama-claude-code" },
],
});
// Create config directory
if (!fs.existsSync(CONFIG_DIR)) {
fs.mkdirSync(CONFIG_DIR, { recursive: true });
}
// Store API keys in keychain for all configured providers
try {
for (const provider of configuredProviders) {
await setApiKey(provider.provider, provider.apiKey);
}
// Store bot tokens in keychain
if (telegramToken) {
await setBotToken("telegram", telegramToken);
}
if (discordToken) {
await setBotToken("discord", discordToken);
}
if (slackBotToken) {
await setBotToken("slack-bot", slackBotToken);
await setBotToken("slack-app", slackAppToken);
await setBotToken("slack-signing", slackSigningSecret);
}
if (teamsAppId) {
await setBotToken("teams-app-id", teamsAppId);
await setBotToken("teams-app-password", teamsAppPassword);
await setBotToken("teams-tenant-id", teamsTenantId);
}
if (signalPhoneNumber) {
await setBotToken("signal-phone", signalPhoneNumber);
await setBotToken("signal-api-url", signalCliRestUrl);
}
} catch {
console.log(chalk.red("\n[ERROR] Failed to store credentials in keychain"));
console.log(chalk.yellow("Falling back to encrypted file storage...\n"));
}
// Build providers object dynamically
const providersConfig: { [key: string]: { model: string } } = {};
for (const provider of configuredProviders) {
providersConfig[provider.provider] = {
model: provider.model,
};
}
// Save configuration WITHOUT API keys (stored in keychain)
const config = {
// Primary provider (active)
aiProvider: primaryProvider.provider,
aiModel: primaryProvider.model,
// All providers (models only, keys in keychain)
providers: providersConfig,
platform: platform,
ideType: ideType,
idePort: 3000,
authorizedUser: "", // Will be set on first message
configuredAt: new Date().toISOString(),
// MCP servers (tokens in keychain)
mcpServers: mcpServerEntries,
};
fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2));
// Set strict file permissions
try {
if (process.platform === "win32") {
const { execSync } = require("child_process");
const user = process.env.USERNAME || process.env.USER || "";
if (user) {
execSync(`icacls "${CONFIG_DIR}" /inheritance:r /grant:r "${user}:(OI)(CI)F" /T`, {
stdio: "ignore",
});
execSync(`icacls "${CONFIG_FILE}" /inheritance:r /grant:r "${user}:F"`, {
stdio: "ignore",
});
}
} else {
fs.chmodSync(CONFIG_DIR, 0o700);
fs.chmodSync(CONFIG_FILE, 0o600);
}
} catch {
// Permissions could not be set — non-critical
}
console.log(chalk.green("\nAuthentication successful!"));
console.log(chalk.gray(`\nConfiguration saved to: ${CONFIG_FILE}`));
console.log(chalk.cyan("\nConfigured Providers:"));
// Show all configured providers
configuredProviders.forEach((provider, index) => {
const label = index === 0 ? "Primary" : `Secondary ${index}`;
console.log(chalk.white(` ${label}: ${provider.provider} (${provider.model})`));
});
if (mcpServerEntries.length > 0) {
console.log(chalk.cyan("\nMCP Servers:"));
mcpServerEntries.forEach((server) => {
const status = server.enabled ? chalk.green("enabled") : chalk.gray("disabled");
console.log(chalk.white(` ${server.id} (${server.transport}) - ${status}`));
});
}
console.log(
chalk.cyan("\nRun ") +
chalk.bold("txtcode") +
chalk.cyan(" and choose ") +
chalk.bold("Start Agent") +
chalk.cyan(" to begin.\n"),
);
if (configuredProviders.length > 1) {
console.log(chalk.gray(" Use /switch to change between your configured providers\n"));
}
}
async function configureMCPServers(): Promise<MCPServerEntry[]> {
const catalog = loadMCPServersCatalog();
if (!catalog || catalog.servers.length === 0) {
return [];
}
console.log(chalk.cyan("MCP Servers (optional)"));
console.log();
console.log(
chalk.gray("Connect external tools to your AI provider (GitHub, databases, cloud, etc.)"),
);
console.log();
const categoryNames = catalog.categories as Record<string, string>;
const serversByCategory = new Map<string, MCPCatalogServer[]>();
for (const server of catalog.servers) {
const cat = server.category || "other";
if (!serversByCategory.has(cat)) {
serversByCategory.set(cat, []);
}
serversByCategory.get(cat)!.push(server);
}
const selectedServers: MCPCatalogServer[] = [];
const selectedIds = new Set<string>();
let continueSelecting = true;
while (continueSelecting) {
const choices: Array<{ name: string; value: string }> = [
{ name: "Configure later", value: "__SKIP__" },
];
if (selectedServers.length > 0) {
choices[0] = { name: `← Done (${selectedServers.length} selected)`, value: "__SKIP__" };
}
for (const [category, servers] of serversByCategory) {
const label = categoryNames[category] || category;
for (const server of servers) {
if (selectedIds.has(server.id)) {
continue;
}
const transportTag = server.transport === "http" ? " [remote]" : "";
choices.push({
name: `[${label}] ${server.name} - ${server.description}${transportTag}`,
value: server.id,
});
}
}
if (choices.length === 1) {
console.log(chalk.yellow("\nAll available MCP servers have been selected.\n"));
break;
}
const selected = await showCenteredList({
message:
selectedServers.length > 0
? `Add another MCP server: (Use arrow keys)`
: `Select MCP server to connect: (Use arrow keys)`,
choices,
pageSize: 10,
});
if (selected === "__SKIP__") {
if (selectedServers.length === 0) {
console.log();
console.log(
chalk.gray(
"You can configure MCP servers anytime from 'txtcode config' → 'Manage MCP Servers'.",
),
);
console.log();
}
continueSelecting = false;
break;
}
const server = catalog.servers.find((s) => s.id === selected);
if (!server) {
continue;
}
selectedIds.add(server.id);
if (server.requiresToken) {
console.log();
const token = await showCenteredInput({
message: server.tokenPrompt || `Enter token for ${server.name}:`,
password: true,
validate: (input) => input.length > 0 || "Token/credential is required",
});
await setBotToken(server.keychainKey, token);
if (server.additionalTokens) {
for (const additional of server.additionalTokens) {
console.log();
const additionalToken = await showCenteredInput({
message: additional.tokenPrompt,