-
-
Notifications
You must be signed in to change notification settings - Fork 8.5k
Expand file tree
/
Copy pathmuse-spark-web.ts
More file actions
1404 lines (1279 loc) · 48.8 KB
/
Copy pathmuse-spark-web.ts
File metadata and controls
1404 lines (1279 loc) · 48.8 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 { createHash, randomUUID } from "node:crypto";
import { Buffer } from "node:buffer";
import WebSocket from "ws";
import { BaseExecutor, mergeUpstreamExtraHeaders, type ExecuteInput } from "./base.ts";
import { getRotatingApiKey } from "../services/apiKeyRotator.ts";
import { prepareToolMessages, buildToolAwareResult } from "../translator/webTools.ts";
import { sanitizeErrorMessage } from "../utils/error.ts";
import {
normalizeSessionCookieHeader,
normalizeSessionCookieHeaders,
} from "@/lib/providers/webCookieAuth";
import { type ParsedMetaAiResponse, isRecord } from "./muse-spark-web/response-parser.ts";
const META_AI_GRAPHQL_API = "https://www.meta.ai/api/graphql";
// Meta rebranded "Abra" to "Ecto"; `abra_sess` became `ecto_1_sess`.
// `normalizeSessionCookieHeader` only uses this constant for bare values with no
// `name=` prefix; full cookie lines (with any cookie names) pass through
// untouched, so users who paste their entire DevTools cookie line still work.
const META_AI_DEFAULT_COOKIE = "ecto_1_sess";
// Persisted-query id and friendly name for the current send-message
// operation. The previous Abra mutation (doc_id 078dfdff...) was retired
// when Meta removed the RewriteOptionsInput type from the schema; it now
// fails server-side validation with `Unknown type "RewriteOptionsInput"`.
// The new operation is a Subscription rather than a Mutation, but Meta's
// GraphQL endpoint still accepts it over POST and streams the response.
const META_AI_WARMUP_DOC_ID = "e7f802582dbfed8e181b012e010993eb";
const META_AI_MODE_SWITCH_DOC_ID = "c32bbe999c48e64e855dc63177d5153f";
const META_WS_APP_ID = "1522763855472543";
const META_WS_APP_VERSION = "1.0.0";
const META_WS_AUTHTYPE = "15:0";
const META_WS_DGW_VERSION = "5";
const META_WS_DGW_UUID = "0";
const META_WS_TIER = "prod";
const META_WS_INTRO_FRAME_TYPE = 0x0f;
const META_WS_PROMPT_FRAME_TYPE = 0x0d;
const META_WS_PROMPT_FRAME_FLAG = 0x80;
const META_AI_ROOT_BRANCH_PATH = "0";
const META_AI_USER_AGENT =
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36";
const BASE62_ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
type MuseSparkModelInfo = {
mode: string;
isThinking: boolean;
};
const MODEL_MAP: Record<string, MuseSparkModelInfo> = {
"muse-spark": { mode: "think_fast", isThinking: false },
"muse-spark-thinking": { mode: "think_hard", isThinking: true },
"muse-spark-contemplating": { mode: "think_hard", isThinking: true },
};
function extractMessageText(content: unknown): string {
if (typeof content === "string") {
return content.trim();
}
if (!Array.isArray(content)) {
return "";
}
return content
.map((part) => {
if (!isRecord(part)) return "";
if (part.type === "text" && typeof part.text === "string") {
return part.text;
}
if (part.type === "input_text" && typeof part.text === "string") {
return part.text;
}
return "";
})
.filter((part) => part.trim().length > 0)
.join("\n")
.trim();
}
type NormalizedMessage = { role: string; content: string };
type ParsedHistory = {
/** Whole history folded into one string (used when starting a new conversation). */
foldedPrompt: string;
/** Just the last user turn — sent on its own when we're continuing a cached conversation. */
latestUserContent: string;
/**
* Index in `normalized` of the most recent assistant turn, or -1 if none.
* Used to slice the prefix that anchors the continuation cache key (so two
* separate chats with identical assistant responses but different
* preceding history don't collide).
*/
lastAssistantIndex: number;
/**
* The role+content of every non-empty message after normalization, in
* order. The continuation-cache key hashes the prefix of this list ending
* at the last assistant message, so the key is unique to a specific
* (history → response) pair rather than just the response text alone.
*/
normalized: NormalizedMessage[];
};
function parseOpenAIMessages(messages: Array<Record<string, unknown>>): ParsedHistory {
const extracted: NormalizedMessage[] = [];
for (const message of messages) {
let role = String(message.role || "user");
if (role === "developer") role = "system";
const content = extractMessageText(message.content);
if (!content) continue;
extracted.push({ role, content });
}
if (extracted.length === 0) {
return {
foldedPrompt: "",
latestUserContent: "",
lastAssistantIndex: -1,
normalized: [],
};
}
let lastUserIndex = -1;
for (let i = extracted.length - 1; i >= 0; i--) {
if (extracted[i].role === "user") {
lastUserIndex = i;
break;
}
}
let lastAssistantIndex = -1;
for (let i = extracted.length - 1; i >= 0; i--) {
if (extracted[i].role === "assistant") {
lastAssistantIndex = i;
break;
}
}
const foldedPrompt = extracted
.map((message, index) => {
if (index === lastUserIndex) {
return message.content;
}
return `${message.role}: ${message.content}`;
})
.join("\n\n")
.trim();
const latestUserContent = lastUserIndex >= 0 ? extracted[lastUserIndex].content : "";
return { foldedPrompt, latestUserContent, lastAssistantIndex, normalized: extracted };
}
function estimateTokens(text: string): number {
return Math.max(1, Math.ceil((text || "").length / 4));
}
function encodeBase62(value: bigint, padLength: number): string {
let remaining = value;
let encoded = "";
while (remaining > 0n) {
encoded = BASE62_ALPHABET[Number(remaining % 62n)] + encoded;
remaining /= 62n;
}
return encoded.padStart(padLength, "0");
}
function decodeBase62(value: string): bigint {
let decoded = 0n;
for (const char of value) {
const index = BASE62_ALPHABET.indexOf(char);
if (index < 0) {
throw new Error(`Invalid base62 character: ${char}`);
}
decoded = decoded * 62n + BigInt(index);
}
return decoded;
}
function randomBigInt(byteLength: number): bigint {
const bytes = new Uint8Array(byteLength);
crypto.getRandomValues(bytes);
let result = 0n;
for (const byte of bytes) {
result = (result << 8n) | BigInt(byte);
}
return result;
}
function generateMetaConversationId(): string {
const timestamp = BigInt(Date.now()) & ((1n << 44n) - 1n);
const random = randomBigInt(8) & ((1n << 64n) - 1n);
const packed = (timestamp << 64n) | random;
return `c.${encodeBase62(packed, 19)}`;
}
function generateMetaEventId(conversationId: string): string | null {
if (!conversationId.startsWith("c.")) {
return null;
}
try {
const packedConversation = decodeBase62(conversationId.slice(2));
const conversationRandom = packedConversation & ((1n << 64n) - 1n);
const timestamp = BigInt(Date.now()) & ((1n << 44n) - 1n);
const eventRandom = randomBigInt(4) & ((1n << 32n) - 1n);
const packedEvent = (timestamp << (64n + 32n)) | (conversationRandom << 32n) | eventRandom;
return `e.${encodeBase62(packedEvent, 25)}`;
} catch {
return null;
}
}
function generateNumericMessageId(): string {
return (
BigInt(Date.now()) * 1000n +
BigInt(Math.floor(Math.random() * 1000)) +
(randomBigInt(2) & 0xfffn)
).toString();
}
function normalizeMetaLocale(): string {
const locale =
typeof Intl !== "undefined"
? Intl.DateTimeFormat().resolvedOptions().locale || "en-US"
: "en-US";
return locale.replace(/-/g, "_");
}
function getMuseSparkModelInfo(model: string): MuseSparkModelInfo {
return MODEL_MAP[model] || MODEL_MAP["muse-spark"];
}
// ─── Conversation continuity cache ──────────────────────────────────────────
// The default behavior of /v1/chat/completions is stateless: the caller passes
// the full message history each turn. Without continuation, every turn would
// open a brand-new meta.ai conversation containing the OpenAI history folded
// into a single user prompt — three real chat turns become three separate
// conversations in the user's meta.ai history, each polluted with the prior
// turns rendered as "user: …" / "assistant: …" text.
//
// To present a clean single growing conversation in meta.ai, we cache the
// conversationId we created on the previous turn keyed by a hash of the
// (connectionId, model, normalized history through the last assistant turn).
// On the next turn, if the incoming OpenAI history's prefix-up-to-the-last-
// assistant-turn matches a cached entry, we reuse the cached conversationId,
// set isNewConversation=false, and send only the latest user turn — Meta
// appends to the existing conversation tree.
//
// Hashing the *full prefix* (not just the assistant text) is important: two
// independent chats from the same connection that happen to land on identical
// assistant text (e.g. a generic refusal or greeting) would otherwise collide
// and route the next turn into the wrong meta.ai conversation, mixing chat
// state across logical sessions. The differing preceding history makes the
// hashes distinct.
//
// TTL is 30 minutes (Meta's web client also expires idle conversations on a
// similar window). Cache cap is generous — entries are tiny (~250 B) so 5000
// entries is ~1.25 MB, plenty of headroom for multi-user setups.
type CachedConversation = {
conversationId: string;
branchPath: string;
expiresAt: number;
};
const MUSE_CONV_CACHE_MAX = 5000;
const MUSE_CONV_CACHE_TTL_MS = 30 * 60 * 1000;
const conversationCache = new Map<string, CachedConversation>();
/**
* Canonical-stringify a normalized message list so the same logical history
* always produces the same hash. Uses ASCII Group Separator / Record
* Separator characters as field delimiters so they can't appear inside
* normal message content.
*/
function canonicalizeNormalizedHistory(messages: NormalizedMessage[]): string {
return messages.map((m) => `${m.role}\x1e${m.content}`).join("\x1f");
}
function makeConversationCacheKey(
connectionId: string,
model: string,
normalizedPrefix: NormalizedMessage[]
): string {
return createHash("sha256")
.update(`${connectionId}\x1f${model}\x1f${canonicalizeNormalizedHistory(normalizedPrefix)}`)
.digest("hex");
}
function lookupCachedConversation(key: string): CachedConversation | null {
const entry = conversationCache.get(key);
if (!entry) return null;
if (Date.now() > entry.expiresAt) {
conversationCache.delete(key);
return null;
}
return entry;
}
function rememberConversation(
key: string,
context: { conversationId: string; branchPath: string }
): void {
if (conversationCache.size >= MUSE_CONV_CACHE_MAX && !conversationCache.has(key)) {
// Map iteration is insertion order, so the first key is the oldest.
const oldest = conversationCache.keys().next().value;
if (oldest) conversationCache.delete(oldest);
}
conversationCache.set(key, {
conversationId: context.conversationId,
branchPath: context.branchPath,
expiresAt: Date.now() + MUSE_CONV_CACHE_TTL_MS,
});
}
/** Test hook — exported for unit tests; not wired to runtime callers. */
export function __resetMuseSparkConversationCacheForTesting(): void {
conversationCache.clear();
}
type ConversationContext = {
conversationId: string;
branchPath: string;
isNewConversation: boolean;
};
function buildMetaAiRequestBody(prompt: string, model: string, conversation: ConversationContext) {
const userUniqueMessageId = generateNumericMessageId();
return {
doc_id: META_AI_WARMUP_DOC_ID,
variables: {
assistantMessageId: crypto.randomUUID(),
// `attachments` was removed from Meta's GraphQL schema (the
// AttachmentInput type is gone), so sending it — even as null —
// makes the server reject the persisted query with
// `Unknown type "AttachmentInput"`. Omit it entirely; GraphQL
// input fields are nullable-by-omission by default.
clientLatitude: null,
clientLongitude: null,
clientTimezone:
typeof Intl !== "undefined" ? Intl.DateTimeFormat().resolvedOptions().timeZone : "UTC",
clippyIp: null,
content: prompt,
conversationId: conversation.conversationId,
conversationStarterId: null,
currentBranchPath: conversation.branchPath,
developerOverridesForMessage: null,
devicePixelRatio: 1,
entryPoint: "KADABRA__CHAT__UNIFIED_INPUT_BAR",
imagineOperationRequest: null,
isNewConversation: conversation.isNewConversation,
mentions: null,
mode: getMuseSparkModelInfo(model).mode,
promptEditType: null,
promptSessionId: crypto.randomUUID(),
promptType: null,
qplJoinId: null,
requestedToolCall: null,
// `rewriteOptions` was removed from Meta's GraphQL schema (the
// RewriteOptionsInput type is gone), so sending it — even as null —
// makes the server reject the persisted query with
// `Unknown type "RewriteOptionsInput"`. Omit it entirely; GraphQL
// input fields are nullable-by-omission by default.
turnId: crypto.randomUUID(),
userAgent: META_AI_USER_AGENT,
userEventId: generateMetaEventId(conversation.conversationId),
userLocale: normalizeMetaLocale(),
userMessageId: crypto.randomUUID(),
userUniqueMessageId,
},
};
}
function sseChunk(data: unknown): string {
return `data: ${JSON.stringify(data)}\n\n`;
}
function buildStreamingResponse(
deltas: string[],
reasoningDeltas: string[],
model: string,
id: string,
created: number
): ReadableStream<Uint8Array> {
const encoder = new TextEncoder();
return new ReadableStream(
{
start(controller) {
controller.enqueue(
encoder.encode(
sseChunk({
id,
object: "chat.completion.chunk",
created,
model,
system_fingerprint: null,
choices: [
{
index: 0,
delta: { role: "assistant" },
finish_reason: null,
logprobs: null,
},
],
})
)
);
for (const delta of reasoningDeltas) {
if (!delta) continue;
controller.enqueue(
encoder.encode(
sseChunk({
id,
object: "chat.completion.chunk",
created,
model,
system_fingerprint: null,
choices: [
{
index: 0,
delta: { reasoning_content: delta },
finish_reason: null,
logprobs: null,
},
],
})
)
);
}
for (const delta of deltas) {
if (!delta) continue;
controller.enqueue(
encoder.encode(
sseChunk({
id,
object: "chat.completion.chunk",
created,
model,
system_fingerprint: null,
choices: [
{
index: 0,
delta: { content: delta },
finish_reason: null,
logprobs: null,
},
],
})
)
);
}
controller.enqueue(
encoder.encode(
sseChunk({
id,
object: "chat.completion.chunk",
created,
model,
system_fingerprint: null,
choices: [{ index: 0, delta: {}, finish_reason: "stop", logprobs: null }],
})
)
);
controller.enqueue(encoder.encode("data: [DONE]\n\n"));
controller.close();
},
},
{ highWaterMark: 16384 }
);
}
function buildNonStreamingResponse(
content: string,
reasoningContent: string,
model: string,
id: string,
created: number
) {
const completionTokens = estimateTokens(content);
const message: Record<string, unknown> = { role: "assistant", content };
if (reasoningContent) {
message.reasoning_content = reasoningContent;
}
return new Response(
JSON.stringify({
id,
object: "chat.completion",
created,
model,
system_fingerprint: null,
choices: [
{
index: 0,
message,
finish_reason: "stop",
logprobs: null,
},
],
usage: {
prompt_tokens: completionTokens,
completion_tokens: completionTokens,
total_tokens: completionTokens * 2,
},
}),
{
status: 200,
headers: { "Content-Type": "application/json" },
}
);
}
function buildErrorResponse(status: number, message: string, code?: string | null) {
return new Response(
JSON.stringify({
error: {
message: sanitizeErrorMessage(message),
type: "upstream_error",
...(code ? { code } : {}),
},
}),
{ status, headers: { "Content-Type": "application/json" } }
);
}
export function normalizeMetaAiCookieHeader(apiKey: string): string {
return normalizeSessionCookieHeader(apiKey, META_AI_DEFAULT_COOKIE);
}
function selectMetaAiCookieHeader(credentials: ExecuteInput["credentials"]): string {
const extraCookieValues = Array.isArray(credentials.providerSpecificData?.extraApiKeys)
? credentials.providerSpecificData.extraApiKeys.filter(
(value): value is string => typeof value === "string" && value.trim().length > 0
)
: [];
const normalizedPool = normalizeSessionCookieHeaders(
[credentials.apiKey || "", ...extraCookieValues],
META_AI_DEFAULT_COOKIE
);
if (normalizedPool.length === 0) {
return "";
}
if (normalizedPool.length === 1 || !credentials.connectionId) {
return normalizedPool[0];
}
return getRotatingApiKey(credentials.connectionId, normalizedPool[0], normalizedPool.slice(1));
}
function buildMetaAiHeaders(cookieHeader: string): Record<string, string> {
return {
Accept: "text/event-stream",
"Accept-Language": "en-US,en;q=0.9",
"Content-Type": "application/json",
Cookie: cookieHeader,
Origin: "https://www.meta.ai",
Referer: "https://www.meta.ai/",
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "same-origin",
"User-Agent": META_AI_USER_AGENT,
"X-ASBD-ID": "129477",
"X-FB-Friendly-Name": "useEctoSendMessageSubscription",
"X-FB-Request-Analytics-Tags": "graphservice",
};
}
type MuseSparkExecuteResult = {
response: Response;
url: string;
headers: Record<string, string>;
transformedBody: unknown;
};
function resultWithResponse(
response: Response,
headers: Record<string, string>,
transformedBody: unknown
): MuseSparkExecuteResult {
return {
response,
url: META_AI_GRAPHQL_API,
headers,
transformedBody,
};
}
function errorResult(
status: number,
message: string,
code: string,
headers: Record<string, string>,
transformedBody: unknown
): MuseSparkExecuteResult {
return resultWithResponse(buildErrorResponse(status, message, code), headers, transformedBody);
}
function getOpenAiMessages(body: unknown): Array<Record<string, unknown>> | null {
const messages = (body as Record<string, unknown>).messages;
if (!messages || !Array.isArray(messages) || messages.length === 0) return null;
return messages as Array<Record<string, unknown>>;
}
// ─── Protobuf WS templates ──────────────────────────────────────────────────────
// Base64-encoded protobuf templates captured from Meta AI web client.
// These are mutated at specific field paths to inject conversation-id,
// prompt text, timestamps, and message IDs per conversation.
//
// VERIFIED against live meta.ai WS captures from TWO independent accounts
// (2026-07-19). The following fields are confirmed STATIC (app-level
// constants sent by Meta's own client, not per-user secrets):
// - 64-hex session token (e2b88f98...)
// - Actor numeric ID (867051314767696)
// - Locale (en-US)
// - App ID (1522763855472543)
// The only user-variable field is the timezone (system TZ), which is
// low-signal for anti-fraud. No fingerprint randomization is warranted.
const META_WS_HOME_TEMPLATE_B64 =
"CrYGCsQDCiBLQURBQlJBX19IT01FX19VTklGSUVEX0lOUFVUX0JBUhIQMTUyMjc2Mzg1NTQ3MjU0MyInNWE1Yi04ZDRlLWYwNTQtOTllZi1iMmRlLWRiMDItMGQwNS01MmM3KigqJgokOGYxMjliMjUtYzNlMC00NzNiLWFlNzktNWViM2YyNGU1NjRjMAU6C0hVTUFOX0FHRU5UQiIKDzg2NzA1MTMxNDc2NzY5NhIPODY3MDUxMzE0NzY3Njk2UgVFQ1RPMVoRQWJyYSBXZWIgTWFpbiBLZXliCRoDCOgHIgIIAWoITWFjIE9TIFhyCnVzZXJfaW5wdXR6dU1vemlsbGEvNS4wIChNYWNpbnRvc2g7IElud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TlmMjctOWRhYmRhMzYyMTJkEjcKJGIwODM4NWE2LTVhNTMtNGYxNC05NjZlLTM0N2YyODA4ODQ1NBCkgvuW2TMYxN23xoT2rbJnIhtlLjAwcHlKMUtxa3BHTmg5Sk9oWElNdnJRWlYSEWZvbGxvdyB1cCBwcm9iZSAyIgMKATI=";
// ─── Proto helpers ─────────────────────────────────────────────────────────────
type ProtoField = {
number: number;
wireType: number;
value: Uint8Array | number | bigint;
};
function encodeVarint(value: number): Uint8Array {
// Use BigInt arithmetic to avoid 32-bit truncation from bitwise operators.
let v = BigInt(value);
const out: number[] = [];
while (v >= 0x80n) {
out.push(Number((v & 0x7fn) | 0x80n));
v >>= 7n;
}
out.push(Number(v & 0x7fn));
return new Uint8Array(out);
}
function decodeVarint(data: Uint8Array, offset: number): [number, number] {
let shift = 0;
let value = 0;
let off = offset;
while (true) {
const byte = data[off++];
value |= (byte & 0x7f) << shift;
if (!(byte & 0x80)) return [value >>> 0, off];
shift += 7;
if (shift > 63) throw new Error("Varint too long");
}
}
function parseProtoFields(data: Uint8Array): ProtoField[] {
const fields: ProtoField[] = [];
let offset = 0;
while (offset < data.length) {
const [tag, next] = decodeVarint(data, offset);
offset = next;
const number = tag >> 3;
const wireType = tag & 0x07;
if (wireType === 0) {
const [value, n] = decodeVarint(data, offset);
offset = n;
fields.push({ number, wireType, value });
} else if (wireType === 1) {
const view = new DataView(data.buffer, data.byteOffset + offset, 8);
fields.push({ number, wireType, value: view.getBigUint64(0, true) });
offset += 8;
} else if (wireType === 2) {
const [len, n] = decodeVarint(data, offset);
offset = n;
fields.push({ number, wireType, value: data.slice(offset, offset + len) });
offset += len;
} else if (wireType === 5) {
const view = new DataView(data.buffer, data.byteOffset + offset, 4);
fields.push({ number, wireType, value: view.getUint32(0, true) });
offset += 4;
} else {
throw new Error(`Unsupported wire type: ${wireType}`);
}
}
return fields;
}
function serializeProtoFields(fields: ProtoField[]): Uint8Array {
const parts: Uint8Array[] = [];
for (const f of fields) {
const tag = (f.number << 3) | f.wireType;
parts.push(encodeVarint(tag));
if (f.wireType === 0) {
parts.push(encodeVarint(Number(f.value)));
} else if (f.wireType === 1) {
const buf = new Uint8Array(8);
if (f.value instanceof Uint8Array) {
throw new Error(
`serializeProtoFields: wire type 1 field ${f.number} has non-numeric value`
);
}
new DataView(buf.buffer).setBigUint64(0, BigInt(f.value), true);
parts.push(buf);
} else if (f.wireType === 2) {
const raw =
f.value instanceof Uint8Array ? f.value : new TextEncoder().encode(String(f.value));
parts.push(encodeVarint(raw.length));
parts.push(raw);
} else if (f.wireType === 5) {
const buf = new Uint8Array(4);
new DataView(buf.buffer).setUint32(0, Number(f.value), true);
parts.push(buf);
}
}
const total = parts.reduce((s, p) => s + p.length, 0);
const result = new Uint8Array(total);
let offset = 0;
for (const p of parts) {
result.set(p, offset);
offset += p.length;
}
return result;
}
function findProtoField(fields: ProtoField[], number: number): ProtoField | undefined {
return fields.find((f) => f.number === number);
}
function traverseAndMutate(
fields: ProtoField[],
path: number[],
mutator: (field: ProtoField) => void
): boolean {
if (path.length === 0) return false;
const field = findProtoField(fields, path[0]);
if (!field || !(field.value instanceof Uint8Array)) return false;
if (path.length === 1) {
mutator(field);
return true;
}
const nested = parseProtoFields(field.value);
if (traverseAndMutate(nested, path.slice(1), mutator)) {
field.value = serializeProtoFields(nested);
return true;
}
return false;
}
// ─── WS frame builders ─────────────────────────────────────────────────────────
function writeU24Le(value: number, arr: Uint8Array, offset: number): void {
arr[offset] = value & 0xff;
arr[offset + 1] = (value >> 8) & 0xff;
arr[offset + 2] = (value >> 16) & 0xff;
}
function buildWsIntroFrame(conversationId: string): Uint8Array {
const payload = new TextEncoder().encode(
JSON.stringify({
"x-dgw-app-x-ecto-conversation-id": conversationId,
"x-dgw-app-client-payload-type": "PROTO_INSIDE_JSON",
})
);
const header = new Uint8Array(6);
header[0] = META_WS_INTRO_FRAME_TYPE;
header[1] = 0;
header[2] = 0;
writeU24Le(payload.length, header, 3);
const result = new Uint8Array(header.length + payload.length);
result.set(header);
result.set(payload, header.length);
return result;
}
function buildWsPromptFrame(
prompt: string,
conversationId: string,
opts: {
templateB64: string;
requestId?: string;
userMessageId?: string;
submittedMs?: number;
uniqueMessageId?: number;
subSessionIdx?: number;
messageSeq?: number;
}
): Uint8Array {
const requestId = opts.requestId || crypto.randomUUID();
const userMessageId = opts.userMessageId || crypto.randomUUID();
const submittedMs = opts.submittedMs ?? Date.now();
const uniqueMessageId =
opts.uniqueMessageId ??
Number(`${submittedMs}${String(Math.floor(Math.random() * 10000)).padStart(4, "0")}`);
const raw = Buffer.from(opts.templateB64, "base64");
const protoFields = parseProtoFields(raw);
// Patch conversationId at [1,1,5]
traverseAndMutate(protoFields, [1, 1], (f) => {
const nested = parseProtoFields(f.value instanceof Uint8Array ? f.value : new Uint8Array());
const field5 = findProtoField(nested, 5);
if (field5) field5.value = new TextEncoder().encode(conversationId);
f.value = serializeProtoFields(nested);
});
// Patch userMessageId at [2,1,1]
traverseAndMutate(protoFields, [2, 1], (f) => {
const nested = parseProtoFields(f.value instanceof Uint8Array ? f.value : new Uint8Array());
const field1 = findProtoField(nested, 1);
if (field1) field1.value = new TextEncoder().encode(userMessageId);
f.value = serializeProtoFields(nested);
});
// Patch convId + timestamps at [2,1,2]
traverseAndMutate(protoFields, [2, 1, 2], (f) => {
const nested = parseProtoFields(f.value instanceof Uint8Array ? f.value : new Uint8Array());
const f1 = findProtoField(nested, 1);
const f2 = findProtoField(nested, 2);
const f3 = findProtoField(nested, 3);
if (f1) f1.value = new TextEncoder().encode(conversationId);
if (f2) f2.value = submittedMs;
if (f3) f3.value = uniqueMessageId;
f.value = serializeProtoFields(nested);
});
// Patch prompt text at [2,2]
traverseAndMutate(protoFields, [2], (f) => {
const nested = parseProtoFields(f.value instanceof Uint8Array ? f.value : new Uint8Array());
const field2 = findProtoField(nested, 2);
if (field2) field2.value = new TextEncoder().encode(prompt);
f.value = serializeProtoFields(nested);
});
// Patch timestamps at [1,5]
traverseAndMutate(protoFields, [1, 5], (f) => {
const nested = parseProtoFields(f.value instanceof Uint8Array ? f.value : new Uint8Array());
const f1 = findProtoField(nested, 1);
const f3 = findProtoField(nested, 3);
if (f1) f1.value = submittedMs + 1;
if (f3) f3.value = submittedMs;
f.value = serializeProtoFields(nested);
});
// Patch requestId at [1,6]
traverseAndMutate(protoFields, [1], (f) => {
const nested = parseProtoFields(f.value instanceof Uint8Array ? f.value : new Uint8Array());
const field6 = findProtoField(nested, 6);
if (field6) field6.value = new TextEncoder().encode(requestId);
f.value = serializeProtoFields(nested);
});
// Patch conversationId at [1,10,4]
traverseAndMutate(protoFields, [1, 10], (f) => {
const nested = parseProtoFields(f.value instanceof Uint8Array ? f.value : new Uint8Array());
const field4 = findProtoField(nested, 4);
if (field4) field4.value = new TextEncoder().encode(conversationId);
f.value = serializeProtoFields(nested);
});
const updatedB64 = Buffer.from(serializeProtoFields(protoFields)).toString("base64");
const outer = JSON.stringify({ "req-id": requestId, payload: updatedB64 });
const inner = new TextEncoder().encode(outer);
const subSessionIdx = opts.subSessionIdx || 0;
const messageSeq = opts.messageSeq || 0;
const msgBody = new Uint8Array(2 + inner.length);
msgBody[0] = messageSeq;
msgBody[1] = META_WS_PROMPT_FRAME_FLAG;
msgBody.set(inner, 2);
const header = new Uint8Array(6);
header[0] = META_WS_PROMPT_FRAME_TYPE;
header[1] = subSessionIdx & 0xff;
header[2] = (subSessionIdx >> 8) & 0xff;
writeU24Le(msgBody.length, header, 3);
const frame = new Uint8Array(header.length + msgBody.length);
frame.set(header);
frame.set(msgBody, header.length);
return frame;
}
// ─── WS URL builder + GraphQL helper + b64 helpers ─────────────────────────────
function buildWsUrl(authorization: string, requestId: string): string {
const params = new URLSearchParams({
"x-dgw-appid": META_WS_APP_ID,
"x-dgw-appversion": META_WS_APP_VERSION,
"x-dgw-authtype": META_WS_AUTHTYPE,
"x-dgw-version": META_WS_DGW_VERSION,
"x-dgw-uuid": META_WS_DGW_UUID,
"x-dgw-tier": META_WS_TIER,
Authorization: authorization,
"x-dgw-app-origin": "meta.ai",
"x-dgw-app-clippy-request-id": requestId,
"x-dgw-app-clippy-async": "true",
});
return `wss://gateway.meta.ai/ws/clippy?${params.toString()}`;
}
type GraphqlResult = { ok: true } | { ok: false; error: string };
/**
* Narrows the failure arm. Under this workspace's `strictNullChecks: false`, a
* boolean-literal discriminant narrows the positive branch but not the negative one, so
* `!result.ok` leaves the full union and `.error` is unreachable to the checker.
*/
function isGraphqlFailure(result: GraphqlResult): result is Extract<GraphqlResult, { ok: false }> {
return !result.ok;
}
async function graphqlPost(
docId: string,
variables: Record<string, unknown>,
cookieHeader: string,
label: string,
signal?: AbortSignal | null
): Promise<GraphqlResult> {
try {
const response = await fetch(META_AI_GRAPHQL_API, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "multipart/mixed, application/json",
Cookie: cookieHeader,
"User-Agent": META_AI_USER_AGENT,
Origin: "https://meta.ai",
},
body: JSON.stringify({ doc_id: docId, variables }),
signal: signal ?? undefined,
});
if (!response.ok) return { ok: false, error: `${label} failed: HTTP ${response.status}` };
// GraphQL often returns errors in the body with HTTP 200 — parse them.
const text = await response.text();
try {
const json = JSON.parse(text);
if (json && Array.isArray(json.errors) && json.errors.length > 0) {
const msg = json.errors[0]?.message || "Unknown GraphQL error";
return { ok: false, error: `${label} failed: ${msg}` };
}
} catch {
// Response wasn't JSON or had no errors — treat as success.
}
return { ok: true };
} catch (err) {
return {
ok: false,
error: `${label} fetch failed: ${sanitizeErrorMessage(
err instanceof Error ? err.message : String(err)
)}`,
};
}
}
// ─── WS response parser ────────────────────────────────────────────────────────
type WsResponseEvent = {
type: "full" | "patch";
response?: { sections?: Array<{ view_model?: { primitive?: { text?: string } } }> };
operations?: Array<{ op?: string; path?: string; value?: string }>;
};
function parseWsResponseEvents(payload: string): WsResponseEvent[] {
const events: WsResponseEvent[] = [];
let start: number | null = null;
let depth = 0;
let inString = false;
let escape = false;
for (let i = 0; i < payload.length; i++) {
const ch = payload[i];
if (start === null) {
if (ch === "{") {
start = i;
depth = 1;
inString = false;
escape = false;
}
continue;
}
if (inString) {
if (escape) {
escape = false;
} else if (ch === "\\") {
escape = true;
} else if (ch === '"') {
inString = false;
}
continue;
}
if (ch === '"') {
inString = true;
} else if (ch === "{") {
depth++;
} else if (ch === "}") {