-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathclient.ts
More file actions
2701 lines (2468 loc) · 104 KB
/
Copy pathclient.ts
File metadata and controls
2701 lines (2468 loc) · 104 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
/**
* Perplexity Web API client — uses Playwright persistent browser context.
* Login (headed) and MCP server (headless) share the same browser profile directory,
* so Cloudflare cf_clearance and all state persist between runs.
*/
import { randomUUID } from "crypto";
import { chromium, type Browser, type BrowserContext, type Page } from "patchright";
import {
PERPLEXITY_URL,
AUTH_SESSION_ENDPOINT,
QUERY_ENDPOINT,
THREAD_ENDPOINT,
MODELS_CONFIG_ENDPOINT,
ASI_ACCESS_ENDPOINT,
RATE_LIMIT_ENDPOINT,
EXPERIMENTS_ENDPOINT,
SUPPORTED_BLOCK_USE_CASES,
findBrowser,
findChromeExecutable,
resolveBrowserExecutable,
getSavedCookies,
wasLastVaultLocked,
type BrowserChannel,
type ASIFile,
type SearchResult,
type ModelsConfigResponse,
type ASIAccessResponse,
type RateLimitResponse,
type AccountInfo,
} from "./config.js";
import { exportThread as exportEntry, resolveExportApiFormat, FORMAT_TO_CONTENT_TYPE } from "./export.js";
import { isImpitAvailable, impitFetchJson } from "./refresh.js";
import { writeFileSync, readFileSync, mkdirSync, existsSync } from "fs";
import { join } from "path";
import { getActiveName, getConfigDir, getProfilePaths } from "./profiles.js";
import type { DaemonAuthStatus } from "@perplexity-user-mcp/shared";
import { clearStaleSingletonLocks, launchWithRetry } from "./fs-utils.js";
import { OFFSCREEN_POSITION_ARG } from "./browser-window.js";
function getActiveProfileName(): string {
return process.env.PERPLEXITY_PROFILE || getActiveName() || "default";
}
function getActivePaths() {
return getProfilePaths(getActiveProfileName());
}
function getModelsCacheFile(): string {
return getActivePaths().modelsCache;
}
/**
* Read the on-disk AccountInfo cache for the active profile without
* touching the browser or the network. Returns null when the cache file
* is missing, unreadable, or doesn't parse as JSON. Used by the
* perplexity_models handler to skip the browser launch entirely on warm
* runs — the cache is written by every successful refresh tier
* (refresh.ts) and by login-runner.js after a fresh login.
*/
export function readCachedAccountInfoFromDisk(): AccountInfo | null {
const modelsCacheFile = getModelsCacheFile();
if (!existsSync(modelsCacheFile)) return null;
try {
const cached = JSON.parse(readFileSync(modelsCacheFile, "utf-8")) as AccountInfo;
return cached;
} catch {
return null;
}
}
const STEALTH_ARGS = [
"--disable-blink-features=AutomationControlled",
// NOTE: `--disable-web-security` was removed (2026-04-27 public-hardening
// audit). All in-page `fetch()` calls in this file are same-origin
// (perplexity.ai) — the only off-origin downloader (`downloadASIFiles`)
// now uses Playwright's `APIRequestContext` (`context.request.get`) which
// runs outside the page context and is not subject to CORS. Re-adding this
// flag would re-introduce a meaningful XSS amplification risk for no gain.
//
// NOTE: `--disable-features=IsolateOrigins,site-per-process` and
// `--disable-site-isolation-trials` were removed (2026-04-27 public-
// hardening audit). They disable Chromium's Site Isolation process model,
// which is a renderer-architecture feature invisible to JavaScript on the
// page (no documented fingerprint surface — Patchright's
// `chromiumSwitches.js` does not include them; see
// node_modules/patchright-core/lib/server/chromium/chromiumSwitches.js).
// Their historical use in puppeteer-stealth recipes was to keep cross-
// origin iframes in the same renderer process so `page.frames()` /
// CDP-based interaction worked uniformly. This codebase does not touch
// iframes (no `page.frames`, `frameLocator`, `mainFrame`, or `postMessage`
// usage in packages/mcp-server/src), so the only effect of keeping them
// was a silent reduction in the browser's Spectre/UXSS defense-in-depth.
"--no-first-run",
"--no-default-browser-check",
"--disable-infobars",
"--disable-extensions",
"--disable-popup-blocking",
];
const USER_AGENT =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";
/**
* Build launch options for Playwright persistent context.
*
* Uses the first available system browser (Chrome > Edge > Chromium > Brave)
* for best Cloudflare fingerprinting, falling back to patchright's bundled
* Chromium. The resolved `channel` is passed through so Patchright can apply
* channel-specific stealth tweaks (important for msedge on Windows).
*
* @internal Exported only so unit tests can assert the headed/headless arg
* branches; not part of the supported `perplexity-user-mcp/client` API.
*/
export function buildLaunchOptions(headless: boolean): Record<string, any> {
const browser = findBrowser();
const opts: Record<string, any> = {
headless,
// The headed branch is the CF-solving bootstrap (Phase 1 / daemon session
// refresh). It paints a real window, which the user sees flash while they
// work (issue #9). Position it off-screen so the background refresh is
// invisible — like the already-headless search path. Headless launches
// have no window, so the positioning arg is omitted there. We move the
// window rather than shrink/hide it; see OFFSCREEN_POSITION_ARG.
args: headless ? STEALTH_ARGS : [...STEALTH_ARGS, OFFSCREEN_POSITION_ARG],
viewport: headless ? { width: 1920, height: 1080 } : { width: 800, height: 600 },
userAgent: USER_AGENT,
// Strip --enable-automation (Playwright default) which is a CF red flag
ignoreDefaultArgs: ["--enable-automation"],
};
if (browser) {
opts.executablePath = browser.path;
// Only pass channel when it's a first-party Playwright channel. Brave
// uses channel "chromium" with an explicit executablePath — Patchright
// treats it as generic Chromium which is the correct behavior.
if (browser.channel === "chrome" || browser.channel === "msedge" || browser.channel === "chromium") {
opts.channel = browser.channel;
}
console.error(`[perplexity-mcp] Using ${browser.channel}: ${browser.path}`);
}
return opts;
}
// Block-shape contracts used by parseASIReconnectSSE / extractFromWorkflowBlock.
// Fields are limited to those the two parsers actually read off the wire.
//
// `OtherWorkflowBlock` is the catch-all so unknown `intended_usage` kinds flow
// through iteration without TS errors — Perplexity adds new kinds over time.
// Because TS does not subtract string literals from `string`, the catch-all
// must carry the same optional sidecar fields as the known kinds; otherwise
// narrowing on `intended_usage === "X"` produces a union that still contains
// `OtherWorkflowBlock`, blocking access to the kind-specific sidecar.
type WorkflowRootBlockSidecar = {
steps?: Array<{
items?: Array<{
payload?: {
text_payload?: { text?: string };
sources_payload?: {
sources?: Array<{ name?: string; url?: string; snippet?: string }>;
};
};
}>;
}>;
};
type WebResultsBlockSidecar = {
web_results?: Array<{ name?: string; url?: string; snippet?: string }>;
};
type AssetsAnswerModeBlockSidecar = {
assets?: Array<{
asset_type?: string;
download_info?: Array<{
url?: string;
filename?: string;
size?: number;
media_type?: string;
}>;
}>;
};
type PendingFollowupsBlockSidecar = {
followups?: Array<string | { text?: string }>;
};
interface WorkflowBlockBase {
intended_usage: string;
workflow_block?: WorkflowRootBlockSidecar;
web_result_block?: WebResultsBlockSidecar;
assets_mode_block?: AssetsAnswerModeBlockSidecar;
pending_followups_block?: PendingFollowupsBlockSidecar;
}
interface WorkflowRootBlock extends WorkflowBlockBase {
intended_usage: "workflow_root";
}
interface WebResultsBlock extends WorkflowBlockBase {
intended_usage: "web_results";
}
interface AssetsAnswerModeBlock extends WorkflowBlockBase {
intended_usage: "assets_answer_mode";
}
interface PendingFollowupsBlock extends WorkflowBlockBase {
intended_usage: "pending_followups";
}
interface OtherWorkflowBlock extends WorkflowBlockBase {
intended_usage: string;
}
type WorkflowBlock =
| WorkflowRootBlock
| WebResultsBlock
| AssetsAnswerModeBlock
| PendingFollowupsBlock
| OtherWorkflowBlock;
interface ExperimentsResponse {
server_is_pro?: boolean;
server_is_max?: boolean;
server_is_enterprise?: boolean;
}
/**
* Derive tier flags from a /rest/experiments/attributes payload.
*
* Mirrors refresh.ts:616 and session-metadata.js:73-75: Computer mode is
* gated to paid tiers, so when the ASI access endpoint reports it as
* available but the experiments payload omits server_is_pro (which has
* been observed in production), infer Pro. Without this fallback, an
* authenticated Pro account silently demotes to Free whenever the
* experiments response drops the subscription bit.
*/
function deriveTierFlagsFromExperiments(
experiments: ExperimentsResponse | undefined | null,
canUseComputer: boolean,
): { isPro: boolean; isMax: boolean; isEnterprise: boolean } {
const isProFromExp = experiments?.server_is_pro === true;
const isMax = experiments?.server_is_max === true;
const isEnterprise = experiments?.server_is_enterprise === true;
const isPro = isProFromExp || (canUseComputer && !isMax && !isEnterprise);
return { isPro, isMax, isEnterprise };
}
export interface ListAskThreadsItem {
backendUuid: string;
contextUuid: string;
slug: string;
title: string;
queryStr: string;
answerPreview: string;
firstAnswer: string | null;
createdAt: string;
mode: string | null;
displayModel: string | null;
searchFocus: string | null;
sources: string[];
queryCount: number;
threadStatus: string;
readWriteToken: string | null;
}
export interface ListAskThreadsResult {
items: ListAskThreadsItem[];
total: number;
}
export interface ListAskThreadsOpts {
limit?: number;
offset?: number;
searchTerm?: string;
excludeAsi?: boolean;
ascending?: boolean;
}
function buildListAskThreadsUrl(): string {
return `${PERPLEXITY_URL}/rest/thread/list_ask_threads?version=2.18&source=default`;
}
function buildListAskThreadsBody(opts: ListAskThreadsOpts): Record<string, unknown> {
return {
limit: opts.limit ?? 1000,
offset: opts.offset ?? 0,
ascending: opts.ascending ?? false,
search_term: opts.searchTerm ?? "",
with_temporary_threads: false,
exclude_asi: opts.excludeAsi ?? false,
};
}
function parseListThreadsRows(rows: Array<Record<string, unknown>>): ListAskThreadsResult {
const total = typeof rows[0]?.total_threads === "number" ? rows[0].total_threads as number : rows.length;
return {
total,
items: rows.map((row) => ({
backendUuid: String(row.uuid ?? ""),
contextUuid: String(row.context_uuid ?? ""),
slug: String(row.slug ?? ""),
title: String(row.title ?? row.query_str ?? "(untitled)"),
queryStr: String(row.query_str ?? ""),
answerPreview: String(row.answer_preview ?? "").slice(0, 220),
firstAnswer: typeof row.first_answer === "string" ? row.first_answer : null,
createdAt: typeof row.last_query_datetime === "string"
? /[Zz]$/.test(row.last_query_datetime) ? row.last_query_datetime : `${row.last_query_datetime}Z`
: new Date().toISOString(),
mode: typeof row.mode === "string" ? row.mode : null,
displayModel: typeof row.display_model === "string" ? row.display_model : null,
searchFocus: typeof row.search_focus === "string" ? row.search_focus : null,
sources: Array.isArray(row.sources) ? row.sources.map(String) : [],
queryCount: typeof row.query_count === "number" ? row.query_count : 1,
threadStatus: String(row.thread_status ?? row.status ?? "completed").toLowerCase(),
readWriteToken: typeof row.read_write_token === "string" ? row.read_write_token : null,
})),
};
}
/**
* Browser-free fetch of /rest/thread/list_ask_threads via impit. Returns null
* when impit isn't installed, no session cookie is on disk, or the request
* doesn't yield a parseable 200. Lets callers (cloud-sync, the class method)
* fall back to the browser path on any miss.
*/
export async function listCloudThreadsViaImpit(
opts: ListAskThreadsOpts = {},
): Promise<ListAskThreadsResult | null> {
if (!isImpitAvailable()) return null;
const cookies = await getSavedCookies().catch(() => [] as Awaited<ReturnType<typeof getSavedCookies>>);
const hasSession = cookies.some((c) => c.name === "__Secure-next-auth.session-token");
if (!hasSession) return null;
const url = buildListAskThreadsUrl();
const body = buildListAskThreadsBody(opts);
// Perplexity's frontend JS auto-injects these on every same-origin fetch.
// Without them, /rest/thread/list_ask_threads returns HTTP 200 with [] —
// a silent "no app context" rejection that we'd otherwise misread as
// "user has no threads" (root cause of the 0-rows bug seen in 0.8.17).
const headers: Record<string, string> = {
"x-app-apiclient": "default",
"x-app-apiversion": "2.18",
"x-perplexity-request-endpoint": url,
"x-perplexity-request-reason": "threads-body",
"x-perplexity-request-try-number": "1",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
referer: `${PERPLEXITY_URL}/`,
origin: PERPLEXITY_URL,
};
// 60s timeout — limit=1000 returns a payload that's a few MB, and even on
// a fast connection Perplexity sometimes takes 20-30s to assemble it. The
// 15s default in impitFetchJson is fine for unauthenticated /models/config
// probes but not for a fully-paged thread list.
const result = await impitFetchJson(url, { method: "POST", body, headers }, cookies, 60_000);
if (!result || result.challenged || result.status !== 200 || !Array.isArray(result.data)) {
console.error(
`[perplexity-mcp] list_ask_threads impit miss ` +
`(status=${result?.status ?? "n/a"} challenged=${!!result?.challenged}); ` +
`caller will fall back to browser.`,
);
return null;
}
const parsed = parseListThreadsRows(result.data as Array<Record<string, unknown>>);
console.error(
`[perplexity-mcp] list_ask_threads via impit: ${parsed.items.length} rows ` +
`(offset=${opts.offset ?? 0} limit=${opts.limit ?? 1000} total=${parsed.total})`,
);
return parsed;
}
// ── /rest/thread/<slug> (single-thread fetch) ─────────────────────────────
export interface GetCloudThreadOpts {
limit?: number;
}
export interface CloudThreadEntry {
backendUuid: string;
queryStr: string;
answer: string;
sources: Array<{ n: number; title: string; url: string; snippet?: string }>;
mediaItems: Array<{ url: string; name?: string; type?: string }>;
createdAt: string;
status: string;
}
export interface GetCloudThreadResult {
entries: CloudThreadEntry[];
thread: { slug: string; title: string | null; contextUuid: string | null };
}
function buildGetCloudThreadUrl(slug: string, limit: number): string {
// NOTE: `with_schematized_response=true` causes Perplexity to return a
// structured shape that omits the raw `entries[].text` JSON we parse
// for answer + sources. Keep it off.
return (
`${PERPLEXITY_URL}/rest/thread/${encodeURIComponent(slug)}` +
`?version=2.18&source=default&limit=${limit}&offset=0&from_first=true&with_parent_info=true`
);
}
function getCloudThreadHeaders(url: string): Record<string, string> {
// Same Perplexity request-context headers their frontend JS auto-injects.
// Without these, /rest/thread/<slug> may return a 200 with truncated /
// empty content (same silent-fallback behavior as list_ask_threads).
return {
"x-app-apiclient": "default",
"x-app-apiversion": "2.18",
"x-perplexity-request-endpoint": url,
"x-perplexity-request-reason": "thread-body",
"x-perplexity-request-try-number": "1",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
referer: `${PERPLEXITY_URL}/`,
origin: PERPLEXITY_URL,
};
}
function parseAnswerText(text: unknown): {
answer: string;
sources: Array<{ n: number; title: string; url: string; snippet?: string }>;
} {
if (typeof text !== "string") return { answer: "", sources: [] };
let steps: unknown;
try { steps = JSON.parse(text); } catch { return { answer: "", sources: [] }; }
if (!Array.isArray(steps)) return { answer: "", sources: [] };
const final = steps.find((s: any) => s?.step_type === "FINAL");
const answerRaw = final?.content?.answer;
if (typeof answerRaw !== "string") return { answer: "", sources: [] };
let parsed: Record<string, unknown> = {};
try { parsed = JSON.parse(answerRaw); } catch { return { answer: answerRaw, sources: [] }; }
const answer = typeof parsed.answer === "string" ? parsed.answer : "";
const webResults = Array.isArray(parsed.web_results) ? parsed.web_results as Array<Record<string, unknown>> : [];
const sources = webResults.map((wr, i) => ({
n: i + 1,
title: String(wr.name ?? ""),
url: String(wr.url ?? ""),
...(typeof wr.snippet === "string" && wr.snippet ? { snippet: wr.snippet } : {}),
})).filter((s) => s.title || s.url);
return { answer, sources };
}
function parseCloudThreadResponse(slug: string, body: Record<string, unknown>): GetCloudThreadResult {
const rawEntries = Array.isArray(body.entries) ? body.entries as Array<Record<string, unknown>> : [];
return {
thread: {
slug,
title: typeof rawEntries[0]?.thread_title === "string" ? rawEntries[0].thread_title as string : null,
contextUuid: typeof rawEntries[0]?.context_uuid === "string" ? rawEntries[0].context_uuid as string : null,
},
entries: rawEntries.map((e) => {
const { answer, sources: s } = parseAnswerText(e.text);
const srcFromBlock = Array.isArray(e.sources)
? (e.sources as Array<Record<string, unknown>>).map((wr, i) => ({
n: i + 1,
title: String(wr.name ?? wr.title ?? ""),
url: String(wr.url ?? ""),
...(typeof wr.snippet === "string" ? { snippet: wr.snippet } : {}),
})).filter((src) => src.title || src.url)
: [];
const createdUs = typeof e.created_us === "number" ? e.created_us : 0;
const iso = typeof e.updated_datetime === "string"
? /[Zz]$/.test(e.updated_datetime) ? e.updated_datetime : `${e.updated_datetime}Z`
: createdUs > 0
? new Date(Math.floor(createdUs / 1000)).toISOString()
: new Date().toISOString();
return {
backendUuid: String(e.backend_uuid ?? ""),
queryStr: String(e.query_str ?? ""),
answer: answer || "",
sources: s.length ? s : srcFromBlock,
mediaItems: Array.isArray(e.media_items)
? (e.media_items as Array<Record<string, unknown>>).map((m) => ({
url: String(m.url ?? m.image ?? ""),
name: typeof m.name === "string" ? m.name : undefined,
type: typeof m.type === "string" ? m.type : undefined,
})).filter((m) => m.url)
: [],
createdAt: iso,
status: String(e.status ?? "completed").toLowerCase(),
};
}),
};
}
/**
* Browser-free fetch of /rest/thread/<slug> via impit. Returns null when
* impit isn't installed/loadable, no session cookie is on disk, the
* response status is non-200, or the body shape is unexpected. Callers
* should fall back to the browser path on null. A 404 is treated as a
* miss (returns null) — the caller will hit the browser path which will
* surface the 404 as a hard error.
*/
export async function getCloudThreadViaImpit(
slug: string,
opts: GetCloudThreadOpts = {},
): Promise<GetCloudThreadResult | null> {
if (!slug) return null;
if (!isImpitAvailable()) return null;
const cookies = await getSavedCookies().catch(() => [] as Awaited<ReturnType<typeof getSavedCookies>>);
const hasSession = cookies.some((c) => c.name === "__Secure-next-auth.session-token");
if (!hasSession) return null;
const limit = opts.limit ?? 50;
const url = buildGetCloudThreadUrl(slug, limit);
const result = await impitFetchJson(url, { method: "GET", headers: getCloudThreadHeaders(url) }, cookies, 60_000);
if (!result || result.challenged || result.status !== 200 || typeof result.data !== "object" || result.data == null) {
console.error(
`[perplexity-mcp] get_cloud_thread impit miss slug=${slug} ` +
`(status=${result?.status ?? "n/a"} challenged=${!!result?.challenged}); ` +
`caller will fall back to browser.`,
);
return null;
}
const parsed = parseCloudThreadResponse(slug, result.data as Record<string, unknown>);
console.error(
`[perplexity-mcp] get_cloud_thread via impit: slug=${slug} entries=${parsed.entries.length} (limit=${limit})`,
);
return parsed;
}
// ── perplexity_search (experimental) ──────────────────────────────────────
//
// Pilot impit fast path for `searchPerplexity`. Opt-in via
// PERPLEXITY_EXPERIMENTAL_IMPIT_SEARCH=1. When enabled, search bypasses the
// browser entirely and POSTs the SSE query endpoint via impit; on any
// failure we fall back to the existing in-page `fetch` path so users with
// the flag still get answers if Perplexity changes the wire format upstream.
//
// Risk profile (vs. the cloud list/thread endpoints): the request body has
// ~40 fields driven by Perplexity's frontend state, not a documented public
// API, so it can drift between Perplexity releases. Keeping `buildSearchRequest`
// as the single source of truth means the browser path drifts with it — if
// our snapshot becomes wrong, both paths break together (visible, debuggable),
// rather than impit silently producing degraded answers.
export interface BuildSearchRequestOpts {
query: string;
modelPreference: string;
mode: string;
sources: string[];
language: string;
followUp?: { backendUuid: string; readWriteToken?: string | null };
}
function buildSearchRequest(opts: BuildSearchRequestOpts): { body: Record<string, unknown>; requestId: string } {
const frontendUuid = randomUUID();
const frontendContextUuid = randomUUID();
const requestId = randomUUID();
const isFollowup = !!opts.followUp?.backendUuid;
const params: Record<string, any> = {
attachments: [],
language: opts.language,
timezone: "America/Los_Angeles",
search_focus: "internet",
sources: opts.sources,
search_recency_filter: null,
frontend_uuid: frontendUuid,
mode: opts.mode,
model_preference: opts.modelPreference,
is_related_query: false,
is_sponsored: false,
frontend_context_uuid: frontendContextUuid,
prompt_source: "user",
query_source: isFollowup ? "followup" : "home",
is_incognito: false,
time_from_first_type: 5000 + Math.floor(Math.random() * 15000),
local_search_enabled: false,
use_schematized_api: true,
send_back_text_in_streaming_api: false,
supported_block_use_cases: SUPPORTED_BLOCK_USE_CASES,
client_coordinates: null,
mentions: [],
dsl_query: opts.query,
skip_search_enabled: true,
is_nav_suggestions_disabled: false,
source: "default",
always_search_override: false,
override_no_search: false,
should_ask_for_mcp_tool_confirmation: true,
browser_agent_allow_once_from_toggle: false,
force_enable_browser_agent: false,
supported_features: ["browser_agent_permission_banner_v1.1"],
version: "2.18",
};
if (isFollowup) {
params.last_backend_uuid = opts.followUp!.backendUuid;
params.read_write_token = opts.followUp!.readWriteToken ?? null;
params.followup_source = "link";
}
return { body: { params, query_str: opts.query }, requestId };
}
export function isExperimentalImpitSearchEnabled(): boolean {
return process.env.PERPLEXITY_EXPERIMENTAL_IMPIT_SEARCH === "1";
}
/**
* Browser-free search via impit. Returns null on any failure (impit not
* installed, no session cookie, non-200, parse error) so callers can fall
* back to the browser path. Same SSE response format as the in-page fetch
* — parsed by `PerplexityClient.parseSSEText`.
*/
export async function searchPerplexityViaImpit(opts: BuildSearchRequestOpts): Promise<SearchResult | null> {
if (!isExperimentalImpitSearchEnabled()) return null;
if (!isImpitAvailable()) return null;
const cookies = await getSavedCookies().catch(() => [] as Awaited<ReturnType<typeof getSavedCookies>>);
const hasSession = cookies.some((c) => c.name === "__Secure-next-auth.session-token");
if (!hasSession) return null;
const { body, requestId } = buildSearchRequest(opts);
const headers: Record<string, string> = {
accept: "text/event-stream",
"x-perplexity-request-reason": "perplexity-query-state-provider",
"x-request-id": requestId,
"x-app-apiclient": "default",
"x-app-apiversion": "2.18",
"x-perplexity-request-endpoint": QUERY_ENDPOINT,
"x-perplexity-request-try-number": "1",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
referer: `${PERPLEXITY_URL}/`,
origin: PERPLEXITY_URL,
};
// 3 minutes — search/reason can run long under load. Same budget the
// SDK callTool gets for cloud-sync after the 0.8.23 timeout fix.
const result = await impitFetchJson(QUERY_ENDPOINT, { method: "POST", body, headers }, cookies, 180_000);
if (!result || result.challenged || result.status !== 200) {
console.error(
`[perplexity-mcp] search impit miss ` +
`(status=${result?.status ?? "n/a"} challenged=${!!result?.challenged}); ` +
`caller will fall back to browser.`,
);
return null;
}
// SSE is text/event-stream — impitFetchJson tries JSON.parse and falls
// back to the raw text string when parsing fails (which it will here).
if (typeof result.data !== "string" || result.data.length === 0) {
console.error(`[perplexity-mcp] search impit returned non-text response (typeof=${typeof result.data}); falling back.`);
return null;
}
try {
const parsed = PerplexityClient.parseSSEText(result.data);
console.error(
`[perplexity-mcp] search via impit: model=${opts.modelPreference} answerLen=${parsed.answer?.length ?? 0} sources=${parsed.sources?.length ?? 0}`,
);
return parsed;
} catch (err) {
console.error(`[perplexity-mcp] search impit parse error: ${(err as Error).message}; falling back.`);
return null;
}
}
// ── perplexity_retrieve ───────────────────────────────────────────────────
export interface RetrieveThreadViaImpitOpts {
threadSlug: string;
backendUuid: string | null;
readWriteToken: string | null;
}
/**
* Browser-free retrieve of an ASI / research result. Tries the reconnect
* SSE path first (POST `/rest/sse/perplexity_ask/reconnect/<uuid>`) when a
* backend_uuid is available, then falls back to the GET thread JSON
* (`/rest/thread/<slug>`). Returns null on any failure (impit not
* installed, no session cookie, non-200, parse error, "still running"
* answer that the caller will want to surface via the browser path) so
* the caller can fall through to the page-context path.
*
* Files are intentionally NOT downloaded here — when the result has
* attached files we return null so the caller forces a browser session
* which can drive `downloadASIFiles` via the page's APIRequestContext.
*/
export async function retrieveThreadViaImpit(opts: RetrieveThreadViaImpitOpts): Promise<SearchResult | null> {
if (!isImpitAvailable()) return null;
const cookies = await getSavedCookies().catch(() => [] as Awaited<ReturnType<typeof getSavedCookies>>);
const hasSession = cookies.some((c) => c.name === "__Secure-next-auth.session-token");
if (!hasSession) return null;
const { threadSlug, backendUuid, readWriteToken } = opts;
const sseHeaders: Record<string, string> = {
accept: "text/event-stream",
"x-perplexity-request-reason": "reconnect-stream",
"x-app-apiclient": "default",
"x-app-apiversion": "2.18",
"x-perplexity-request-try-number": "1",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
referer: `${PERPLEXITY_URL}/`,
origin: PERPLEXITY_URL,
};
// Path 1: reconnect SSE (preferred — gets full ASI/compute output)
if (backendUuid) {
const url = `${QUERY_ENDPOINT}/reconnect/${backendUuid}`;
const result = await impitFetchJson(
url,
{ method: "POST", body: { reconnectInitialSnapshot: true }, headers: { ...sseHeaders, "x-perplexity-request-endpoint": url } },
cookies,
60_000,
);
if (result && !result.challenged && result.status === 200 && typeof result.data === "string" && result.data.length > 0) {
try {
const parsed = PerplexityClient.parseASIReconnectSSE(result.data, threadSlug, backendUuid, readWriteToken ?? "");
if (!parsed.answer.startsWith("ASI task may still be running")) {
console.error(
`[perplexity-mcp] retrieve via impit (reconnect): backendUuid=${backendUuid} answerLen=${parsed.answer?.length ?? 0} files=${parsed.files?.length ?? 0}`,
);
return parsed;
}
// Try the workflow-block extraction shape
const wb = PerplexityClient.extractFromWorkflowBlock(result.data, threadSlug, backendUuid, readWriteToken ?? "");
if (wb) {
console.error(
`[perplexity-mcp] retrieve via impit (workflow-block): backendUuid=${backendUuid} answerLen=${wb.answer?.length ?? 0}`,
);
return wb;
}
} catch (err) {
console.error(`[perplexity-mcp] retrieve impit reconnect parse error: ${(err as Error).message}`);
}
} else {
console.error(
`[perplexity-mcp] retrieve impit reconnect miss ` +
`(status=${result?.status ?? "n/a"} challenged=${!!result?.challenged}); trying thread fallback.`,
);
}
}
// Path 2: GET /rest/thread/<slug> JSON fallback
if (threadSlug) {
const url = `${PERPLEXITY_URL}/rest/thread/${encodeURIComponent(threadSlug)}`;
const result = await impitFetchJson(
url,
{ method: "GET", headers: { ...sseHeaders, accept: "application/json", "x-perplexity-request-reason": "thread-body", "x-perplexity-request-endpoint": url } },
cookies,
60_000,
);
if (result && !result.challenged && result.status === 200 && typeof result.data === "object" && result.data !== null) {
try {
const threadData = result.data as { status?: string; entries?: Array<Record<string, unknown>> };
if (threadData.status === "success") {
const entries = threadData.entries ?? [];
const lastEntry = entries[entries.length - 1];
if (lastEntry) {
const parsed = PerplexityClient.parseASIThreadEntry(lastEntry, threadSlug, backendUuid ?? "", readWriteToken ?? "");
console.error(
`[perplexity-mcp] retrieve via impit (thread): slug=${threadSlug} answerLen=${parsed.answer?.length ?? 0}`,
);
return parsed;
}
}
} catch (err) {
console.error(`[perplexity-mcp] retrieve impit thread parse error: ${(err as Error).message}`);
}
} else {
console.error(
`[perplexity-mcp] retrieve impit thread miss ` +
`(status=${result?.status ?? "n/a"} challenged=${!!result?.challenged}); falling back to browser.`,
);
}
}
return null;
}
// ── perplexity_export ─────────────────────────────────────────────────────
export interface ExportThreadViaImpitOpts {
threadSlug?: string | null;
entryUuid?: string | null;
format: "pdf" | "markdown" | "docx";
}
export interface ExportThreadResult {
buffer: Buffer;
filename: string;
contentType: string;
}
/**
* Browser-free PDF / DOCX export via impit. Returns null on any failure
* (impit not installed, no session cookie, markdown format, no entry UUID
* resolvable, non-200, empty body) so callers can fall back to the
* page-context export. Markdown export is intentionally not supported here
* — the caller assembles markdown locally from the saved history entry.
*/
export async function exportThreadViaImpit(
opts: ExportThreadViaImpitOpts,
): Promise<ExportThreadResult | null> {
// Markdown is assembled locally from the saved history entry — never
// touch the network for it. Caller short-circuits before reaching here
// in practice, but guard defensively.
if (opts.format === "markdown") return null;
if (!isImpitAvailable()) return null;
const cookies = await getSavedCookies().catch(() => [] as Awaited<ReturnType<typeof getSavedCookies>>);
const hasSession = cookies.some((c) => c.name === "__Secure-next-auth.session-token");
if (!hasSession) return null;
// Step 1: resolve entryUuid. If the caller didn't pass one, fetch the
// thread via the impit thread endpoint and take the LAST entry's
// backendUuid (matches the page-context resolveThreadEntryUuid behavior).
let entryUuid = opts.entryUuid ?? null;
if (!entryUuid && opts.threadSlug) {
const thread = await getCloudThreadViaImpit(opts.threadSlug, { limit: 1 });
const entries = thread?.entries ?? [];
entryUuid = entries[entries.length - 1]?.backendUuid ?? null;
}
if (!entryUuid) {
console.error(
`[perplexity-mcp] export impit miss (no entry UUID resolvable for slug=${opts.threadSlug ?? "n/a"}); ` +
`caller will fall back to browser.`,
);
return null;
}
// Step 2: POST /rest/entry/export — same Perplexity request-context
// headers their frontend JS auto-injects. Without these the endpoint
// responds 200 with empty file_content_64 (silent rejection — same trap
// as list_ask_threads).
let apiFormat: "pdf" | "md" | "docx";
try {
apiFormat = resolveExportApiFormat(opts.format);
} catch (err) {
console.error(`[perplexity-mcp] export impit miss: ${(err as Error).message}; falling back.`);
return null;
}
const url = `${PERPLEXITY_URL}/rest/entry/export?version=2.18&source=default`;
const headers: Record<string, string> = {
accept: "application/json",
"x-app-apiclient": "default",
"x-app-apiversion": "2.18",
"x-perplexity-request-endpoint": url,
"x-perplexity-request-reason": "entry-export",
"x-perplexity-request-try-number": "1",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
referer: `${PERPLEXITY_URL}/`,
origin: PERPLEXITY_URL,
};
const body = { entry_uuid: entryUuid, format: apiFormat };
const result = await impitFetchJson(url, { method: "POST", body, headers }, cookies, 60_000);
if (!result || result.challenged || result.status !== 200 || typeof result.data !== "object" || result.data == null) {
console.error(
`[perplexity-mcp] export impit miss ` +
`(status=${result?.status ?? "n/a"} challenged=${!!result?.challenged}); ` +
`caller will fall back to browser.`,
);
return null;
}
const data = result.data as { file_content_64?: unknown; filename?: unknown };
const buffer = Buffer.from(String(data.file_content_64 ?? ""), "base64");
if (buffer.length === 0) {
console.error(`[perplexity-mcp] export impit miss (empty file_content_64); caller will fall back to browser.`);
return null;
}
const filename = String(data.filename ?? `${entryUuid}.${apiFormat}`);
const contentType = FORMAT_TO_CONTENT_TYPE[opts.format] ?? "application/octet-stream";
console.error(
`[perplexity-mcp] export via impit: format=${opts.format} bytes=${buffer.length} filename=${filename}`,
);
return { buffer, filename, contentType };
}
export class PerplexityClient {
private browser: Browser | null = null;
private context: BrowserContext | null = null;
private page: Page | null = null;
public authenticated = false;
public userId: string | null = null;
public accountInfo: AccountInfo = {
isPro: false,
isMax: false,
isEnterprise: false,
canUseComputer: false,
modelsConfig: null,
rateLimits: null,
};
/**
* Initialize the client. Two-phase startup:
*
* Phase 1 (headed): Cloudflare Turnstile cannot be solved by headless browsers.
* A brief VISIBLE browser session navigates to Perplexity, auto-solves the CF
* challenge, and fetches all account info endpoints (models, ASI access, etc.)
* while Cloudflare isn't blocking. Then closes.
*
* Phase 2 (headless): Launches headless with the same persistent profile
* (now carrying fresh cf_clearance) for search operations.
*
* Set env PERPLEXITY_HEADLESS_ONLY=1 to skip the headed phase (uses disk cache).
*/
async init(): Promise<void> {
const _initAt = Date.now();
try {
const activePaths = getActivePaths();
if (!existsSync(activePaths.browserData)) {
mkdirSync(activePaths.browserData, { recursive: true });
}
// Fail fast with a readable message if no browser is installed at all.
const browser = await resolveBrowserExecutable();
console.error(`[perplexity-mcp] Using ${browser.source}: ${browser.path}`);
// Phase 1: Headed session — solve CF challenge + fetch account info
const skipHeaded = process.env.PERPLEXITY_HEADLESS_ONLY === "1";
if (!skipHeaded) {
await this.headedBootstrap();
} else {
console.error("[perplexity-mcp] Skipping headed session (PERPLEXITY_HEADLESS_ONLY=1).");
this.loadCachedAccountInfo();
}
// Phase 2: Headless browser for search operations.
// Use the SAME persistent browserData directory as Phase 1 so that
// any cf_clearance cookie acquired during the headed bootstrap is
// already on disk and loaded automatically. This fixes the bug where
// Phase 2 used a non-persistent context and only had stale vault
// cookies (issue #5).
console.error("[perplexity-mcp] Launching headless persistent browser...");
const launchOpts = buildLaunchOptions(true);
// Clear stale locks + retry: on Windows the Phase 1 headed context
// (just closed above) does not release the browser-data profile lock
// synchronously, so this Phase 2 launch on the SAME --user-data-dir can
// momentarily collide (issue #8). The retry absorbs that release lag.
this.context = await launchWithRetry(
() => chromium.launchPersistentContext(activePaths.browserData, launchOpts),
{ beforeAttempt: () => clearStaleSingletonLocks(activePaths.browserData) },
);
this.browser = this.context.browser();
// Inject vault cookies only for cookies not already present on disk.
// The headed bootstrap may have refreshed cf_clearance; we must not
// overwrite the fresh disk cookie with the stale vault copy.
const saved = await getSavedCookies();
if (saved.length > 0) {
const current = await this.context.cookies();
const currentNames = new Set(current.map((c) => c.name));
const toInject = saved.filter((c) => !currentNames.has(c.name));
if (toInject.length > 0) {
await this.context.addCookies(toInject);
console.error(`[perplexity-mcp] Injected ${toInject.length} missing cookies from vault.`);
} else {
console.error("[perplexity-mcp] All vault cookies already present on disk; skipping injection.");
}
}
this.page = await this.context.newPage();
// Navigate to Perplexity (headless — relies on fresh cf_clearance from headed phase)
try {
await this.page.goto(PERPLEXITY_URL, { waitUntil: "domcontentloaded", timeout: 30000 });
await this.page.waitForTimeout(2000);
} catch (err) {
console.error("[perplexity-mcp] Navigation warning:", (err as Error).message);
}
await this.checkAuth();
// If headed phase was skipped or failed, try loading account info from headless
if (!this.accountInfo.modelsConfig) {
await this.loadAccountInfo();
}
this.writeDaemonStatus(_initAt, null);
} catch (err: unknown) {
this.writeDaemonStatus(_initAt, err instanceof Error ? err.message : String(err));
throw err;
}
}
/**
* Brief VISIBLE browser session that:
* 1. Navigates to Perplexity to solve Cloudflare Turnstile (auto, no user interaction)
* 2. Fetches all account info endpoints while CF isn't blocking
* 3. Caches results to disk, then closes
*/
private async headedBootstrap(): Promise<void> {
console.error("[perplexity-mcp] Starting headed bootstrap (solving CF + loading account info)...");
let ctx: BrowserContext | null = null;
try {
const browserData = getActivePaths().browserData;
// Clear stale locks + retry to ride out a brief profile-lock release lag
// after a prior context close on the same browser-data dir (issue #8).