-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathcli.js
More file actions
1296 lines (1202 loc) · 55.5 KB
/
Copy pathcli.js
File metadata and controls
1296 lines (1202 loc) · 55.5 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
// Shebang is added by tsup banner for the built dist/cli.mjs so the bin entry
// works as a CLI. Kept out of source so vitest/esbuild can parse this file
// during tests.
import { execFile as execFileCallback } from "node:child_process";
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { promisify } from "node:util";
import { fileURLToPath, pathToFileURL } from "node:url";
import { isMainModule } from "./is-main-module.js";
import { probeKeychainState } from "./vault.js";
const execFile = promisify(execFileCallback);
export function parseArgs(argv) {
if (argv.length === 0) return { command: "server", flags: {} };
const first = argv[0];
if (first === "--version" || first === "-v") return { command: "version", flags: {} };
if (first === "--help" || first === "-h") return { command: "help", flags: {} };
if (first === "daemon") {
const subcommand = argv[1] ?? "help";
const flags = {};
const positional = [];
for (let i = 2; i < argv.length; i++) {
const a = argv[i];
if (a.startsWith("--")) {
const key = a.slice(2);
const next = argv[i + 1];
if (next === undefined || next.startsWith("--")) {
flags[key] = true;
} else {
flags[key] = next;
i++;
}
} else {
positional.push(a);
}
}
return { command: `daemon:${subcommand}`, flags, positional };
}
const command = first;
const flags = {};
let positional = [];
for (let i = 1; i < argv.length; i++) {
const a = argv[i];
if (a.startsWith("--")) {
const key = a.slice(2);
const next = argv[i + 1];
if (next === undefined || next.startsWith("--")) {
flags[key] = true;
} else {
flags[key] = next;
i++;
}
} else {
positional.push(a);
}
}
return { command, flags, positional };
}
const KNOWN_COMMANDS = new Set([
"server", "version", "help",
"login", "logout", "status", "doctor", "install-browser", "setup-vault",
"install-speed-boost", "uninstall-speed-boost", "speed-boost-status",
"add-account", "switch-account", "list-accounts",
"export", "open", "rebuild-history-index", "sync-cloud",
"daemon:help", "daemon:start", "daemon:stop", "daemon:status", "daemon:attach",
"daemon:rotate-token", "daemon:install-tunnel", "daemon:enable-tunnel", "daemon:disable-tunnel",
"daemon:list-providers", "daemon:set-provider",
"daemon:set-ngrok-authtoken", "daemon:set-ngrok-domain", "daemon:clear-ngrok",
"daemon:cf-named-login", "daemon:cf-named-list",
"daemon:cf-named-create", "daemon:cf-named-bind",
]);
function normalizeExportFormat(value) {
if (value === "md") return "markdown";
if (value === "markdown" || value === "pdf" || value === "docx") return value;
return null;
}
/**
* Probe the full vault-unseal state for the current process.
*
* Returns a structured snapshot covering every input the runtime path
* (vault.js getUnsealMaterial) considers: keychain availability and
* whether the master key was persisted there, env-var passphrase, TTY
* fallback, and (when a profile is given) whether the on-disk vault.enc
* actually decrypts with the resolved unseal material. The setup-vault
* command and the add-account/login preflight share this so user-facing
* advice stays consistent with what the runner will actually do.
*/
async function probeVaultState({ profile } = {}) {
const { available: keychainAvailable, hasKey: keychainHasKey } = await probeKeychainState();
const envPassphraseSet = !!process.env.PERPLEXITY_VAULT_PASSPHRASE;
const hasTty = process.stdin?.isTTY === true && process.env.PERPLEXITY_MCP_STDIO !== "1";
let vaultExists = false;
let vaultDecryptsOk = null;
let decryptError = null;
if (profile) {
try {
const { getProfilePaths } = await import("./profiles.js");
const { existsSync } = await import("node:fs");
vaultExists = existsSync(getProfilePaths(profile).vault);
if (vaultExists && (keychainAvailable || envPassphraseSet)) {
const { Vault, __resetKeyCache } = await import("./vault.js");
__resetKeyCache();
try {
await new Vault().get(profile, "cookies");
vaultDecryptsOk = true;
} catch (err) {
vaultDecryptsOk = false;
decryptError = err instanceof Error ? err.message : String(err);
}
}
} catch (err) {
// Probe is best-effort; don't crash the CLI just because the
// profile dir or modules failed to load.
decryptError = err instanceof Error ? err.message : String(err);
}
}
return {
platform: process.platform,
keychainAvailable,
keychainHasKey,
envPassphraseSet,
hasTty,
vaultExists,
vaultDecryptsOk,
decryptError,
};
}
/**
* Surface vault-unseal status BEFORE the user kicks off an interactive
* operation (add-account, login). Returns {ok: true} when at least one
* unseal path is configured. Returns {ok: false, ...} with structured
* guidance when none of those are available — caller decides whether to
* warn-then-continue or hard-stop.
*/
async function checkVaultUnseal() {
const state = await probeVaultState();
if (state.keychainAvailable || state.envPassphraseSet || state.hasTty) {
return {
ok: true,
hasKeychain: state.keychainAvailable,
envPass: state.envPassphraseSet,
hasTty: state.hasTty,
};
}
const isLinux = state.platform === "linux";
const isMac = state.platform === "darwin";
const isWin = state.platform === "win32";
const hint = isLinux
? "Install libsecret + gnome-keyring (Debian/Ubuntu: `sudo apt install libsecret-1-0 gnome-keyring`; Fedora: `sudo dnf install libsecret gnome-keyring`), OR run `npx perplexity-user-mcp setup-vault` to generate a passphrase and get persistence snippets for your shell / MCP-client config."
: isMac
? "Keychain Access should be available on macOS — keytar usually loads here. If you still see this, run `npx perplexity-user-mcp setup-vault` for a generated passphrase + persistence snippets."
: isWin
? "Credential Manager is always available on Windows — keytar usually loads here. If you still see this, run `npx perplexity-user-mcp setup-vault` for a generated passphrase + persistence snippets."
: "Run `npx perplexity-user-mcp setup-vault` for a generated passphrase + persistence snippets.";
return {
ok: false,
hasKeychain: false,
envPass: false,
hasTty: false,
reason: "no_unseal_material",
hint,
};
}
/**
* Generate a strong random passphrase encoded as a shell-safe base64url
* string (no `+`, `/`, or `=` so it can be pasted into shell rcs and JSON
* env blocks without escaping). 32 bytes = 256 bits of entropy, matching
* the AES key strength so the passphrase is never the weak link.
*/
async function generatePassphrase() {
const { randomBytes } = await import("node:crypto");
// base64url encoding in Node ≥16.
return randomBytes(32).toString("base64url");
}
/**
* Build platform-specific persistence snippets the user can copy into
* their environment. Kept format-agnostic — does NOT write any file —
* because the safest place to put a passphrase varies by deployment
* (per-IDE mcp.json env block, ~/.zshrc, systemd unit, Docker secret).
*/
function buildPersistenceSnippets(passphrase) {
const platform = process.platform;
const snippets = [];
// 1. MCP client env block (preferred — scoped per client).
snippets.push({
title: "MCP client env block (preferred — scoped to one client only)",
detail: "Edit your MCP client's config (Cursor: ~/.cursor/mcp.json, Claude Desktop: claude_desktop_config.json, Codex CLI: ~/.codex/config.toml, etc.). Add an `env` field next to `command`/`args`:",
code: `{
"mcpServers": {
"Perplexity": {
"command": "npx",
"args": ["-y", "perplexity-user-mcp"],
"env": {
"PERPLEXITY_VAULT_PASSPHRASE": "${passphrase}"
}
}
}
}`,
});
// 2. Shell rc — platform-specific.
if (platform === "win32") {
snippets.push({
title: "Windows — PowerShell user environment (persistent)",
detail: "Sets the variable for your user account; persists across reboots. Open PowerShell and run:",
code: `[Environment]::SetEnvironmentVariable("PERPLEXITY_VAULT_PASSPHRASE", "${passphrase}", "User")`,
});
snippets.push({
title: "Windows — cmd.exe (persistent)",
detail: "Equivalent for cmd.exe users:",
code: `setx PERPLEXITY_VAULT_PASSPHRASE "${passphrase}"`,
});
} else if (platform === "darwin") {
snippets.push({
title: "macOS — zsh (default since Catalina)",
detail: "Append to ~/.zshrc and restart your terminal:",
code: `echo 'export PERPLEXITY_VAULT_PASSPHRASE='\\''${passphrase}'\\''' >> ~/.zshrc`,
});
snippets.push({
title: "macOS — bash (legacy)",
detail: "If you use bash instead, append to ~/.bash_profile:",
code: `echo 'export PERPLEXITY_VAULT_PASSPHRASE='\\''${passphrase}'\\''' >> ~/.bash_profile`,
});
} else {
// Linux + everything else
snippets.push({
title: "Linux — bash",
detail: "Append to ~/.bashrc and restart your terminal (or `source ~/.bashrc`):",
code: `echo 'export PERPLEXITY_VAULT_PASSPHRASE='\\''${passphrase}'\\''' >> ~/.bashrc`,
});
snippets.push({
title: "Linux — zsh",
detail: "If you use zsh, append to ~/.zshrc:",
code: `echo 'export PERPLEXITY_VAULT_PASSPHRASE='\\''${passphrase}'\\''' >> ~/.zshrc`,
});
snippets.push({
title: "Linux — systemd unit (for daemon deployments)",
detail: "If you run perplexity-user-mcp as a systemd service, add to the [Service] block:",
code: `Environment=PERPLEXITY_VAULT_PASSPHRASE=${passphrase}`,
});
}
return snippets;
}
/**
* Render a plain-text setup-vault report. Used for the default human-
* readable output. JSON output uses `--json` and bypasses this entirely.
*/
function renderSetupVaultReport({ state, recommendation, passphrase, snippets }) {
const lines = [];
const tick = "✓";
const cross = "✗";
const warn = "!";
lines.push("Vault setup status:");
lines.push(` ${state.keychainAvailable ? tick : cross} OS keychain ${state.keychainAvailable ? "available" : "unavailable"}${state.keychainHasKey ? " (master key persisted)" : state.keychainAvailable ? " (no master key yet — will be generated on first login)" : ""}`);
lines.push(` ${state.envPassphraseSet ? tick : cross} PERPLEXITY_VAULT_PASSPHRASE ${state.envPassphraseSet ? "is set" : "is not set"}`);
if (state.vaultExists) {
if (state.vaultDecryptsOk === true) {
lines.push(` ${tick} vault.enc decrypts cleanly with the active unseal material`);
} else if (state.vaultDecryptsOk === false) {
lines.push(` ${cross} vault.enc cannot be decrypted — ${state.decryptError ?? "unknown error"}`);
}
}
if (state.keychainAvailable && state.envPassphraseSet) {
lines.push(` ${warn} both keychain and env var are set — keychain wins at runtime; the env var is a fallback`);
}
lines.push("");
lines.push(`Recommendation: ${recommendation.message}`);
if (passphrase) {
lines.push("");
lines.push("Generated passphrase (256 bits, base64url):");
lines.push(` ${passphrase}`);
lines.push("");
lines.push("⚠ Save this somewhere safe — losing it means losing access to vaults written under it.");
lines.push("");
lines.push("Pick ONE persistence method below:");
snippets.forEach((s, i) => {
lines.push("");
lines.push(`${i + 1}. ${s.title}`);
if (s.detail) lines.push(` ${s.detail}`);
lines.push("");
const indent = " ";
lines.push(s.code.split("\n").map((l) => indent + l).join("\n"));
});
lines.push("");
lines.push("After applying ONE of those, run `npx perplexity-user-mcp doctor` to verify the unseal-verify check passes.");
}
return lines.join("\n");
}
/**
* Decide what the user should do given the probed vault state.
*
* - keychain works + vault decrypts (or no vault yet) → nothing to do.
* - keychain works + vault fails to decrypt → tell user to logout --purge.
* - no keychain + env var set → done; vault will use passphrase.
* - no keychain + no env var → setup needed; generate + show snippets.
*/
function recommendVaultSetup(state) {
if (state.vaultExists && state.vaultDecryptsOk === false) {
return {
status: "decrypt_broken",
message: "Existing vault.enc cannot be decrypted with any available unseal material. The blob was likely written under a since-rotated keychain key or PERPLEXITY_VAULT_PASSPHRASE. Run `npx perplexity-user-mcp logout --purge --profile <name>` and log in again to write a fresh vault. (v0.8.40+ self-heals this on the next login by quarantining the bad blob.)",
generatePassphrase: false,
};
}
if (state.keychainAvailable) {
return {
status: "ok_keychain",
message: state.keychainHasKey
? "OS keychain holds the master key — nothing to do."
: "OS keychain is available; the master key will be generated and persisted there on your first login. Nothing to do.",
generatePassphrase: false,
};
}
if (state.envPassphraseSet) {
return {
status: "ok_envvar",
message: "PERPLEXITY_VAULT_PASSPHRASE is set; the vault will use it. (For better UX, install an OS keychain so the env var becomes optional — see https://github.com/Automations-Project/VSCode-Perplexity-MCP for platform docs.)",
generatePassphrase: false,
};
}
return {
status: "setup_needed",
message: "No keychain available and no PERPLEXITY_VAULT_PASSPHRASE set. Generating a strong passphrase and showing persistence snippets below.",
generatePassphrase: true,
};
}
async function openTarget(target) {
if (process.platform === "win32") {
const escaped = String(target).replace(/'/g, "''");
await execFile("powershell", ["-NoProfile", "-Command", `Start-Process -FilePath '${escaped}'`]);
return;
}
if (process.platform === "darwin") {
await execFile("open", [String(target)]);
return;
}
await execFile("xdg-open", [String(target)]);
}
export async function routeCommand(parsed) {
const { command, flags } = parsed;
if (!KNOWN_COMMANDS.has(command)) {
return { code: 1, stdout: "", stderr: `Unknown command: ${command}\nRun --help for usage.` };
}
if (command === "version") {
/* v8 ignore start -- catch fallback fires only if package.json is missing at runtime */
let version = "0.0.0";
try {
const pkgPath = fileURLToPath(new URL("../package.json", import.meta.url));
version = JSON.parse(readFileSync(pkgPath, "utf8")).version ?? "0.0.0";
} catch {
// fall through with default
}
/* v8 ignore stop */
return { code: 0, stdout: version + "\n", stderr: "" };
}
if (command === "help") {
return { code: 0, stdout: HELP_TEXT, stderr: "" };
}
/* v8 ignore start -- starting the real MCP server is impractical in unit tests */
if (command === "server") {
const { main } = await import("./index.js");
await main();
return { code: 0, stdout: "", stderr: "" };
}
/* v8 ignore stop */
if (command === "daemon:help") {
return { code: 0, stdout: DAEMON_HELP_TEXT, stderr: "" };
}
if (command === "daemon:start") {
const port = parseOptionalPort(flags.port);
if (flags.port !== undefined && port === null) {
return { code: 1, stdout: "", stderr: "daemon start requires --port to be a positive integer.\n" };
}
const { startDaemon } = await import("./daemon/launcher.js");
const daemon = await startDaemon({
configDir: process.env.PERPLEXITY_CONFIG_DIR,
port: port ?? undefined,
tunnel: !!flags.tunnel,
});
if (daemon.attached) {
const body = flags.json
? JSON.stringify({ ok: true, attached: true, ...serializeDaemonConnection(daemon) })
: `Attached to daemon pid=${daemon.pid} port=${daemon.port}`;
return { code: 0, stdout: body + "\n", stderr: "" };
}
await daemon.closed;
return { code: 0, stdout: "", stderr: "" };
}
if (command === "daemon:status") {
const { getDaemonStatus } = await import("./daemon/launcher.js");
const status = await getDaemonStatus({
configDir: process.env.PERPLEXITY_CONFIG_DIR,
reclaimStale: true,
});
const body = flags.json
? JSON.stringify(serializeDaemonStatus(status))
: formatDaemonStatus(status);
return { code: 0, stdout: body + "\n", stderr: "" };
}
if (command === "daemon:stop") {
const { stopDaemon } = await import("./daemon/launcher.js");
const result = await stopDaemon({ configDir: process.env.PERPLEXITY_CONFIG_DIR });
const body = flags.json
? JSON.stringify({ ok: true, ...result })
: result.stopped
? `Stopped daemon pid=${result.pid ?? "unknown"}.`
: "Daemon is not running.";
return { code: 0, stdout: body + "\n", stderr: "" };
}
if (command === "daemon:rotate-token") {
try {
const { rotateDaemonToken } = await import("./daemon/launcher.js");
const daemon = await rotateDaemonToken({ configDir: process.env.PERPLEXITY_CONFIG_DIR });
const body = flags.json
? JSON.stringify({ ok: true, ...serializeDaemonConnection(daemon) })
: `Rotated daemon token for pid=${daemon.pid} port=${daemon.port}.`;
return { code: 0, stdout: body + "\n", stderr: "" };
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return { code: 1, stdout: "", stderr: message + "\n" };
}
}
if (command === "daemon:attach") {
// 8.3.2: PERPLEXITY_NO_DAEMON=1 opt-out. Must short-circuit BEFORE importing
// the daemon layer — the whole point is air-gapped / single-client users
// keep the daemon code cold. Warning goes to stderr only (stdout is the
// MCP JSON-RPC channel; any byte on stdout corrupts the protocol).
const noDaemonRaw = process.env.PERPLEXITY_NO_DAEMON;
if (typeof noDaemonRaw === "string" && /^(1|true)$/i.test(noDaemonRaw.trim())) {
process.stderr.write(
"[perplexity-mcp] PERPLEXITY_NO_DAEMON=1 set; running in-process stdio (daemon bypass)\n",
);
const mod = await import("./index.js");
await mod.main();
return { code: 0, stdout: "", stderr: "" };
}
const { attachToDaemon } = await import("./daemon/attach.js");
const ensureTimeoutRaw = flags["ensure-timeout-ms"];
const ensureTimeoutMs =
typeof ensureTimeoutRaw === "string" && /^\d+$/.test(ensureTimeoutRaw)
? Number(ensureTimeoutRaw)
: undefined;
try {
await attachToDaemon({
configDir: process.env.PERPLEXITY_CONFIG_DIR,
clientId: "daemon-attach-cli",
fallbackStdio: !!flags["fallback-stdio"],
ensureTimeoutMs,
});
} catch (err) {
// Phase 2 / Task 2.4: mirror the launcher's DaemonAttachError contract.
// Stdout is the JSON-RPC framing channel for the attached client, so the
// bullet remediation must land on stderr only; the script entry below
// converts code:2 into process.exit(2).
if (err && err.code === "DAEMON_UNREACHABLE") {
let stderr = "Perplexity MCP: cannot reach the extension-managed daemon.\n";
const remediation = Array.isArray(err.remediation) ? err.remediation : [];
for (const line of remediation) {
stderr += " • " + line + "\n";
}
if (err.cause && err.cause.message) {
stderr += "Underlying error: " + err.cause.message + "\n";
}
return { code: 2, stdout: "", stderr };
}
throw err;
}
return { code: 0, stdout: "", stderr: "" };
}
if (command === "daemon:install-tunnel") {
const { installCloudflared } = await import("./daemon/install-tunnel.js");
const result = await installCloudflared({ configDir: process.env.PERPLEXITY_CONFIG_DIR });
const body = flags.json
? JSON.stringify({ ok: true, ...result })
: `Installed cloudflared ${result.version} to ${result.binaryPath}`;
return { code: 0, stdout: body + "\n", stderr: "" };
}
if (command === "daemon:enable-tunnel") {
try {
const { enableDaemonTunnel } = await import("./daemon/launcher.js");
const status = await enableDaemonTunnel({ configDir: process.env.PERPLEXITY_CONFIG_DIR });
const body = flags.json
? JSON.stringify({ ok: true, ...serializeDaemonStatus(status) })
: status.health?.tunnel?.url
? `Tunnel enabled: ${status.health.tunnel.url}`
: "Tunnel enable requested.";
return { code: 0, stdout: body + "\n", stderr: "" };
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return { code: 1, stdout: "", stderr: message + "\n" };
}
}
if (command === "daemon:disable-tunnel") {
try {
const { disableDaemonTunnel } = await import("./daemon/launcher.js");
const status = await disableDaemonTunnel({ configDir: process.env.PERPLEXITY_CONFIG_DIR });
const body = flags.json
? JSON.stringify({ ok: true, ...serializeDaemonStatus(status) })
: "Tunnel disabled.";
return { code: 0, stdout: body + "\n", stderr: "" };
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return { code: 1, stdout: "", stderr: message + "\n" };
}
}
if (command === "daemon:list-providers") {
const providersModule = await import("./daemon/tunnel-providers/index.js");
const configDir = process.env.PERPLEXITY_CONFIG_DIR;
const statuses = await providersModule.listTunnelProviderStatuses(configDir);
const active = providersModule.readTunnelSettings(configDir).activeProvider;
const body = flags.json
? JSON.stringify({ active, providers: statuses })
: statuses
.map((s) => `${s.isActive ? "*" : " "} ${s.id.padEnd(10)} ${s.displayName.padEnd(22)} ${s.setup.ready ? "ready" : s.setup.reason ?? "needs setup"}`)
.join("\n");
return { code: 0, stdout: body + "\n", stderr: "" };
}
if (command === "daemon:set-provider") {
const providerId = parsed.positional?.[0];
if (!providerId) {
return { code: 1, stdout: "", stderr: "set-provider requires a provider id (cf-quick | ngrok | cf-named).\n" };
}
try {
const providersModule = await import("./daemon/tunnel-providers/index.js");
const configDir = process.env.PERPLEXITY_CONFIG_DIR;
providersModule.writeTunnelSettings(configDir, { activeProvider: providerId });
return { code: 0, stdout: `Active tunnel provider set to ${providerId}.\n`, stderr: "" };
} catch (error) {
return { code: 1, stdout: "", stderr: (error instanceof Error ? error.message : String(error)) + "\n" };
}
}
if (command === "daemon:set-ngrok-authtoken") {
const authtoken = parsed.positional?.[0] ?? flags.token;
if (!authtoken || typeof authtoken !== "string" || authtoken.length < 10) {
return { code: 1, stdout: "", stderr: "set-ngrok-authtoken requires an authtoken (see dashboard.ngrok.com/get-started/your-authtoken).\n" };
}
try {
const providersModule = await import("./daemon/tunnel-providers/index.js");
providersModule.writeNgrokSettings(process.env.PERPLEXITY_CONFIG_DIR, { authtoken });
return { code: 0, stdout: "ngrok authtoken saved.\n", stderr: "" };
} catch (error) {
return { code: 1, stdout: "", stderr: (error instanceof Error ? error.message : String(error)) + "\n" };
}
}
if (command === "daemon:set-ngrok-domain") {
const domain = parsed.positional?.[0] ?? flags.domain ?? null;
try {
const providersModule = await import("./daemon/tunnel-providers/index.js");
providersModule.writeNgrokSettings(process.env.PERPLEXITY_CONFIG_DIR, { domain: domain ?? null });
return { code: 0, stdout: (domain ? `ngrok domain set to ${domain}.\n` : "ngrok domain cleared.\n"), stderr: "" };
} catch (error) {
return { code: 1, stdout: "", stderr: (error instanceof Error ? error.message : String(error)) + "\n" };
}
}
if (command === "daemon:clear-ngrok") {
try {
const providersModule = await import("./daemon/tunnel-providers/index.js");
providersModule.clearNgrokSettings(process.env.PERPLEXITY_CONFIG_DIR);
return { code: 0, stdout: "ngrok settings cleared.\n", stderr: "" };
} catch (error) {
return { code: 1, stdout: "", stderr: (error instanceof Error ? error.message : String(error)) + "\n" };
}
}
// ─────────────────────────────────────────────────────────────────────
// cf-named (Cloudflare Named Tunnel) CLI — mirrors the 8.4.3 dashboard
// widget for npm-only users. Helpers imported directly from the
// mcp-server; do NOT import the extension's runtime.ts (VS Code-private).
//
// Dashed subcommand names (daemon cf-named-login, etc.) so the existing
// parseArgs one-level-deep routing (daemon <x> → daemon:<x>) works
// unchanged. Documented identically in DAEMON_HELP_TEXT.
//
// Login, create, bind each modal-confirm via stderr/stdin unless --yes.
// Exit 130 on user decline (standard "interrupted by user" code).
// ─────────────────────────────────────────────────────────────────────
if (command === "daemon:cf-named-login") {
if (!flags.yes) {
const { promptYesNo } = await import("./tty-prompt.js");
const ok = await promptYesNo({
prompt: "This opens your default browser to authorize Cloudflare. Continue? [y/N] ",
});
if (!ok) {
return { code: 130, stdout: "", stderr: "Cancelled.\n" };
}
}
try {
const { runCloudflaredLogin } = await import("./daemon/tunnel-providers/index.js");
// forwardOutput: pipe cloudflared's child stderr AND stdout to OUR
// stderr so the CLI user sees the "open this URL in your browser"
// prompt. Never to our stdout — that's reserved for --json payload.
const result = await runCloudflaredLogin({
configDir: process.env.PERPLEXITY_CONFIG_DIR,
forwardOutput: true,
});
const body = flags.json
? JSON.stringify({ ok: true, certPath: result.certPath })
: `cloudflared login completed. Cert at ${result.certPath}`;
return { code: 0, stdout: body + "\n", stderr: "" };
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
const hint = /not installed/i.test(msg)
? `${msg}\nRun 'npx perplexity-user-mcp daemon install-tunnel' to install cloudflared.\n`
: msg + "\n";
return { code: 1, stdout: "", stderr: hint };
}
}
if (command === "daemon:cf-named-list") {
try {
const { listNamedTunnels } = await import("./daemon/tunnel-providers/index.js");
const tunnels = await listNamedTunnels({ configDir: process.env.PERPLEXITY_CONFIG_DIR });
const body = flags.json
? JSON.stringify({ tunnels })
: tunnels.length === 0
? "No named tunnels."
: tunnels
.map((t) => `${t.uuid} ${t.name} (${t.connections ?? 0} connections)`)
.join("\n");
return { code: 0, stdout: body + "\n", stderr: "" };
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
return { code: 1, stdout: "", stderr: msg + "\n" };
}
}
if (command === "daemon:cf-named-create") {
const name = flags.name ?? parsed.positional?.[0];
const hostname = flags.hostname ?? parsed.positional?.[1];
if (!name || typeof name !== "string") {
return { code: 1, stdout: "", stderr: "cf-named-create requires --name (or first positional argument).\n" };
}
if (!hostname || typeof hostname !== "string") {
return { code: 1, stdout: "", stderr: "cf-named-create requires --hostname (or second positional argument).\n" };
}
if (!flags.yes) {
const { promptYesNo } = await import("./tty-prompt.js");
const ok = await promptYesNo({
prompt: `This creates a Cloudflare tunnel "${name}" and routes DNS "${hostname}" under your zone. Continue? [y/N] `,
});
if (!ok) {
return { code: 130, stdout: "", stderr: "Cancelled.\n" };
}
}
try {
const { createNamedTunnel, writeTunnelConfig } = await import("./daemon/tunnel-providers/index.js");
const configDir = process.env.PERPLEXITY_CONFIG_DIR;
const created = await createNamedTunnel({ configDir, name, hostname });
// Placeholder port=1; the cf-named provider's start() rewrites it to the
// live daemon port on every spawn (port-drift rewrite), so this value is
// never read in practice. Matches the 8.4.3 dashboard behavior.
const config = writeTunnelConfig({
configDir,
uuid: created.uuid,
hostname,
port: 1,
credentialsPath: created.credentialsPath,
});
const body = flags.json
? JSON.stringify({ ok: true, uuid: created.uuid, name: created.name, hostname, configPath: config.configPath, credentialsPath: created.credentialsPath })
: `Tunnel created: uuid=${created.uuid} hostname=${hostname}\nConfig written to ${config.configPath}`;
return { code: 0, stdout: body + "\n", stderr: "" };
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
return { code: 1, stdout: "", stderr: msg + "\n" };
}
}
if (command === "daemon:cf-named-bind") {
const uuid = flags.uuid ?? parsed.positional?.[0];
const hostname = flags.hostname ?? parsed.positional?.[1];
if (!uuid || typeof uuid !== "string") {
return { code: 1, stdout: "", stderr: "cf-named-bind requires --uuid (or first positional argument).\n" };
}
if (!hostname || typeof hostname !== "string") {
return { code: 1, stdout: "", stderr: "cf-named-bind requires --hostname (or second positional argument).\n" };
}
const credentialsPath = join(homedir(), ".cloudflared", `${uuid}.json`);
if (!existsSync(credentialsPath)) {
return {
code: 1,
stdout: "",
stderr: `Credentials file not found at ${credentialsPath}. Run 'cloudflared tunnel create' for this UUID first, or use 'cf-named-create'.\n`,
};
}
if (!flags.yes) {
const { promptYesNo } = await import("./tty-prompt.js");
const ok = await promptYesNo({
prompt: `This writes a managed config binding tunnel ${uuid} to ${hostname}. Continue? [y/N] `,
});
if (!ok) {
return { code: 130, stdout: "", stderr: "Cancelled.\n" };
}
}
try {
const { writeTunnelConfig } = await import("./daemon/tunnel-providers/index.js");
const configDir = process.env.PERPLEXITY_CONFIG_DIR;
const config = writeTunnelConfig({
configDir,
uuid,
hostname,
port: 1,
credentialsPath,
});
const body = flags.json
? JSON.stringify({ ok: true, uuid, hostname, configPath: config.configPath, credentialsPath })
: `Bound tunnel ${uuid} to ${hostname}.\nConfig written to ${config.configPath}`;
return { code: 0, stdout: body + "\n", stderr: "" };
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
return { code: 1, stdout: "", stderr: msg + "\n" };
}
}
if (command === "list-accounts") {
const { listProfiles, getActiveName } = await import("./profiles.js");
const profiles = listProfiles();
const active = getActiveName();
const body = flags.json
? JSON.stringify({ ok: true, active, profiles })
: profiles.length === 0
? "No profiles yet. Run `add-account` to create one."
: profiles.map((p) => `${p.name === active ? "* " : " "}${p.name} [${p.tier ?? "?"}] mode=${p.loginMode ?? "?"} lastLogin=${p.lastLogin ?? "never"}`).join("\n");
return { code: 0, stdout: body + "\n", stderr: "" };
}
if (command === "setup-vault") {
const profile = flags.profile ?? (await import("./profiles.js")).getActiveName() ?? null;
const state = await probeVaultState({ profile });
const recommendation = recommendVaultSetup(state);
let passphrase = null;
let snippets = [];
if (recommendation.generatePassphrase && !flags["probe-only"]) {
passphrase = await generatePassphrase();
snippets = buildPersistenceSnippets(passphrase);
}
if (flags.json) {
const body = JSON.stringify({
ok: true,
state,
recommendation: { status: recommendation.status, message: recommendation.message },
passphrase: passphrase ?? null,
snippets: snippets.map((s) => ({ title: s.title, detail: s.detail, code: s.code })),
});
return { code: 0, stdout: body + "\n", stderr: "" };
}
const report = renderSetupVaultReport({ state, recommendation, passphrase, snippets });
return { code: 0, stdout: report + "\n", stderr: "" };
}
if (command === "add-account") {
const name = flags.name ?? (await import("./profiles.js")).suggestNextDefaultName();
const mode = flags.mode ?? "manual";
// Pre-flight the unseal chain BEFORE touching the profile dir, so users
// creating a new account on a fresh box get an actionable setup hint
// instead of a "Vault decrypt failed" / "Vault locked" surprise on the
// first login. Bypass with --skip-vault-check (e.g. when the daemon
// owns the vault and the CLI is just used for account management).
if (!flags["skip-vault-check"]) {
const unseal = await checkVaultUnseal();
if (!unseal.ok) {
const msg = `No vault unseal path configured. ${unseal.hint}`;
const body = flags.json
? JSON.stringify({ ok: false, reason: unseal.reason, hint: unseal.hint })
: "";
return { code: 1, stdout: body + (body ? "\n" : ""), stderr: msg + "\n" };
}
}
try {
const { createProfile } = await import("./profiles.js");
const profile = createProfile(name, { loginMode: mode });
const body = flags.json ? JSON.stringify({ ok: true, profile }) : `Created profile '${name}'.`;
return { code: 0, stdout: body + "\n", stderr: "" };
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
return { code: 1, stdout: flags.json ? JSON.stringify({ ok: false, error: msg }) + "\n" : "", stderr: msg + "\n" };
}
}
if (command === "switch-account") {
const target = parsed.positional?.[0];
if (!target) return { code: 1, stdout: "", stderr: "switch-account requires a profile name.\n" };
try {
const { setActive } = await import("./profiles.js");
setActive(target);
const body = flags.json ? JSON.stringify({ ok: true, active: target }) : `Switched to '${target}'.`;
return { code: 0, stdout: body + "\n", stderr: "" };
} catch (err) {
return { code: 1, stdout: "", stderr: `${err.message}\n` };
}
}
if (command === "logout") {
const { softLogout, hardLogout } = await import("./logout.js");
const name = flags.profile ?? (await import("./profiles.js")).getActiveName() ?? "default";
if (flags.purge) await hardLogout(name); else await softLogout(name);
const body = flags.json ? JSON.stringify({ ok: true, purged: !!flags.purge, profile: name }) : `Logged out of '${name}'.`;
return { code: 0, stdout: body + "\n", stderr: "" };
}
if (command === "status") {
const name = flags.profile ?? (await import("./profiles.js")).getActiveName() ?? "default";
const { Vault } = await import("./vault.js");
/* v8 ignore next -- defensive catch for unreadable vault (malformed blob, wrong key) */
const cookies = await new Vault().get(name, "cookies").catch(() => null);
if (!cookies) {
const body = flags.json ? JSON.stringify({ valid: false, reason: "no_cookies", profile: name }) : `No session for '${name}'. Run login first.`;
return { code: 0, stdout: body + "\n", stderr: "" };
}
const { getProfile } = await import("./profiles.js");
const meta = getProfile(name);
const body = flags.json
? JSON.stringify({ valid: true, profile: name, tier: meta?.tier, lastLogin: meta?.lastLogin })
: `Profile '${name}' has stored cookies. Tier=${meta?.tier ?? "?"} lastLogin=${meta?.lastLogin ?? "?"}`;
return { code: 0, stdout: body + "\n", stderr: "" };
}
/* v8 ignore start -- login spawns a long-lived fork with a real browser; covered by integration suites */
if (command === "login") {
const { fork } = await import("node:child_process");
const mode = flags.mode ?? "manual";
const profile = flags.profile ?? (await import("./profiles.js")).getActiveName() ?? "default";
// Same preflight as add-account: surface unseal-path setup BEFORE the
// browser opens, so a user on a fresh headless box doesn't complete a
// 30s login flow only to crash at vault.set with a stack trace. Skip
// when --plain-cookies is set since plaintext mode bypasses the vault.
if (!flags["plain-cookies"] && !flags["skip-vault-check"]) {
const unseal = await checkVaultUnseal();
if (!unseal.ok) {
const msg = `No vault unseal path configured for profile '${profile}'. ${unseal.hint}`;
const body = flags.json
? JSON.stringify({ ok: false, reason: unseal.reason, hint: unseal.hint, profile })
: "";
return { code: 1, stdout: body + (body ? "\n" : ""), stderr: msg + "\n" };
}
}
const env = { ...process.env, PERPLEXITY_PROFILE: profile };
if (mode === "auto") {
if (!flags.email) return { code: 1, stdout: "", stderr: "`--email` required for --mode auto.\n" };
env.PERPLEXITY_EMAIL = String(flags.email);
}
// Auto-enable when impit (Speed Boost) is installed — the install is
// the opt-in. `--no-impit` or PERPLEXITY_DISABLE_IMPIT_LOGIN=1 forces
// the browser path. Falls back to the browser-based runner on impit-
// only failures (cf_blocked, impit_missing, crash).
const wantImpit =
mode === "auto" &&
!flags["no-impit"] &&
process.env.PERPLEXITY_DISABLE_IMPIT_LOGIN !== "1" &&
(await import("./refresh.js")).isImpitAvailable();
const browserRunnerName = mode === "auto" ? "./login-runner.mjs" : "./manual-login-runner.mjs";
const browserRunner = fileURLToPath(new URL(browserRunnerName, import.meta.url));
const impitRunner = fileURLToPath(new URL("./impit-login-runner.mjs", import.meta.url));
const IMPIT_FALLBACK_REASONS = new Set(["cf_blocked", "impit_missing", "impit_load_failed", "auto_unsupported", "crash"]);
async function spawnRunner(runner) {
return new Promise((resolve) => {
const child = fork(runner, [], { env, stdio: ["inherit", "pipe", "inherit", "ipc"] });
let out = "";
child.stdout.on("data", (d) => { out += d.toString(); process.stderr.write(d); });
child.on("message", async (m) => {
if (m?.phase === "awaiting_otp") {
const { promptSecret } = await import("./tty-prompt.js");
const otp = await promptSecret({ prompt: "Enter OTP from your email: " });
child.send({ otp });
}
});
child.on("close", (code) => {
const lines = out.trim().split("\n").filter(Boolean);
const last = lines[lines.length - 1];
let parsed = null;
try { parsed = last ? JSON.parse(last) : null; } catch { /* not JSON */ }
resolve({ code: code ?? 0, last, parsed });
});
});
}
if (wantImpit) {
const impitResult = await spawnRunner(impitRunner);
const reason = impitResult.parsed?.reason;
const ok = impitResult.parsed?.ok === true;
if (ok || (reason && !IMPIT_FALLBACK_REASONS.has(reason))) {
return { code: impitResult.code, stdout: (flags.json ? impitResult.last : `login finished (${impitResult.code})`) + "\n", stderr: "" };
}
process.stderr.write(`[cli login] impit runner failed (${reason ?? "unknown"}); falling back to browser.\n`);
}
const browserResult = await spawnRunner(browserRunner);
return { code: browserResult.code, stdout: (flags.json ? browserResult.last : `login finished (${browserResult.code})`) + "\n", stderr: "" };
}
/* v8 ignore stop */
if (command === "install-speed-boost") {
const { installImpit, getImpitStatus } = await import("./native-deps.js");
const before = getImpitStatus();
if (before.installed && !flags.force) {
const msg = flags.json
? JSON.stringify({ ok: true, alreadyInstalled: true, version: before.version, runtimeDir: before.runtimeDir })
: `Speed Boost (impit ${before.version ?? "?"}) already installed at ${before.runtimeDir}.\nPass --force to reinstall.`;
return { code: 0, stdout: msg + "\n", stderr: "" };
}
const log = (line) => process.stderr.write(`[speed-boost] ${line}\n`);
const result = await installImpit({ log });
if (!result.ok) {
const stderr = flags.json
? JSON.stringify({ ok: false, error: result.error }) + "\n"
: `Speed Boost install failed: ${result.error}\n`;
return { code: 1, stdout: "", stderr };
}
const status = getImpitStatus();
const out = flags.json
? JSON.stringify({ ok: true, version: status.version, installedAt: status.installedAt, runtimeDir: status.runtimeDir })
: `Speed Boost installed: impit ${status.version ?? "?"} at ${status.runtimeDir}.\nAll impit-eligible tools (sync, hydrate, retrieve, export, models, login) will use it automatically.`;
return { code: 0, stdout: out + "\n", stderr: "" };
}
if (command === "uninstall-speed-boost") {
const { uninstallImpit, getImpitStatus } = await import("./native-deps.js");
const before = getImpitStatus();
const log = (line) => process.stderr.write(`[speed-boost] ${line}\n`);
const result = uninstallImpit({ log });
if (!result.ok) {
const stderr = flags.json
? JSON.stringify({ ok: false, error: result.error }) + "\n"
: `Speed Boost uninstall failed: ${result.error}\n`;
return { code: 1, stdout: "", stderr };
}
const out = flags.json
? JSON.stringify({ ok: true, hadImpit: before.installed })
: before.installed
? `Speed Boost removed (was impit ${before.version ?? "?"}). Affected tools fall back to the browser path.`
: `Speed Boost was not installed. Nothing to remove.`;
return { code: 0, stdout: out + "\n", stderr: "" };
}
if (command === "speed-boost-status") {
const { getImpitStatus } = await import("./native-deps.js");
const status = getImpitStatus();
if (flags.json) {
return { code: 0, stdout: JSON.stringify(status) + "\n", stderr: "" };
}
const out = status.installed
? `Speed Boost: installed (impit ${status.version ?? "?"}${status.installedAt ? `, installed ${status.installedAt}` : ""}).\nRuntime dir: ${status.runtimeDir}`
: `Speed Boost: not installed.\nRun: npx perplexity-user-mcp install-speed-boost\nRuntime dir (for manual install): ${status.runtimeDir}`;
return { code: 0, stdout: out + "\n", stderr: "" };
}
if (command === "doctor") {
const { runAll, exitCodeFor, formatReportMarkdown } = await import("./doctor.js");
const report = await runAll({
profile: flags.profile,
probe: !!flags.probe,
allProfiles: !!flags.all,
});
const exit = exitCodeFor(report);
if (flags.json) {
return { code: exit, stdout: JSON.stringify(report) + "\n", stderr: "" };
}