File size: 5,277 Bytes
2a14e5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { GEMINI_WEB_USER_AGENT } from "../constants";
import { makeSapisidHash } from "../auth";
import { accountPrefix, resinProxyUrl } from "../proxy";
import { nowSec } from "../../shared/logging";
import { uuid } from "../../shared/crypto";
import type { RuntimeConfig } from "../../config";

type PayloadFileRef =
	| string
	| {
			ref?: unknown;
			fileRef?: unknown;
			id?: unknown;
			name?: unknown;
			filename?: unknown;
	  };

const GEMINI_PAYLOAD_INNER_LENGTH = 102;
const GEMINI_PAYLOAD_FIELD = {
	request: 0,
	language: 1,
	clientContext: 2,
	defaultGenerationFlags: 6,
	requestKind: 7,
	responseMode: 10,
	toolMode: 11,
	thinkingMode: 17,
	responseSeed: 18,
	conversationMode: 27,
	responseOptions: 30,
	enhancedMode: 31,
	mediaMode: 41,
	safetyMode: 53,
	requestId: 59,
	toolContext: 61,
	clientFeature: 68,
	modelFamily: 79,
	enhancedRouting: 80,
} as const;
const MODEL_EXTRA_PAYLOAD_FIELDS = new Set<number>([
	GEMINI_PAYLOAD_FIELD.enhancedMode,
	GEMINI_PAYLOAD_FIELD.enhancedRouting,
]);

export function buildPayload(

	prompt: string,

	modelId: number,

	thinkMode: number,

	fileRefs: readonly PayloadFileRef[] | null,

	extra: Record<number, unknown> | null,

	requestId: string = uuid(),

): string {
	const inner = createGeminiPayloadInner(
		prompt,
		modelId,
		thinkMode,
		fileRefs,
		requestId.toUpperCase(),
	);
	applyModelPayloadExtras(inner, extra);
	const outer = [null, JSON.stringify(inner)];
	return new URLSearchParams({ "f.req": JSON.stringify(outer) }).toString();
}

function createGeminiPayloadInner(

	prompt: string,

	modelId: number,

	thinkMode: number,

	fileRefs: readonly PayloadFileRef[] | null,

	requestId: string,

): unknown[] {
	const inner = new Array(GEMINI_PAYLOAD_INNER_LENGTH);
	if (fileRefs?.length) {
		const files = fileRefs.map((item) => {
			if (item && typeof item === "object" && !Array.isArray(item)) {
				return [
					[item.ref || item.fileRef || item.id || "", 1],
					item.name || item.filename || "file.txt",
				];
			}
			return [[item, 1], "file.txt"];
		});
		inner[GEMINI_PAYLOAD_FIELD.request] = [
			prompt,
			0,
			null,
			files,
			null,
			null,
			0,
		];
	} else {
		inner[GEMINI_PAYLOAD_FIELD.request] = [
			prompt,
			0,
			null,
			null,
			null,
			null,
			0,
		];
	}
	inner[GEMINI_PAYLOAD_FIELD.language] = ["en"];
	inner[GEMINI_PAYLOAD_FIELD.clientContext] = [
		"",
		"",
		"",
		null,
		null,
		null,
		null,
		null,
		null,
		"",
	];
	inner[GEMINI_PAYLOAD_FIELD.defaultGenerationFlags] = [0];
	inner[GEMINI_PAYLOAD_FIELD.requestKind] = 1;
	inner[GEMINI_PAYLOAD_FIELD.responseMode] = 1;
	inner[GEMINI_PAYLOAD_FIELD.toolMode] = 0;
	inner[GEMINI_PAYLOAD_FIELD.thinkingMode] = [[thinkMode]];
	inner[GEMINI_PAYLOAD_FIELD.responseSeed] = 0;
	inner[GEMINI_PAYLOAD_FIELD.conversationMode] = 1;
	inner[GEMINI_PAYLOAD_FIELD.responseOptions] = [4];
	inner[GEMINI_PAYLOAD_FIELD.mediaMode] = [2];
	inner[GEMINI_PAYLOAD_FIELD.safetyMode] = 0;
	inner[GEMINI_PAYLOAD_FIELD.requestId] = requestId;
	inner[GEMINI_PAYLOAD_FIELD.toolContext] = [];
	inner[GEMINI_PAYLOAD_FIELD.clientFeature] = 1;
	inner[GEMINI_PAYLOAD_FIELD.modelFamily] = modelId;
	return inner;
}

function applyModelPayloadExtras(

	inner: unknown[],

	extra: Record<number, unknown> | null,

): void {
	if (extra) {
		for (const k of Object.keys(extra)) {
			const index = Number(k);
			if (!Number.isInteger(index) || !MODEL_EXTRA_PAYLOAD_FIELDS.has(index)) {
				throw new Error(`Unsupported Gemini model extra payload field: ${k}`);
			}
			inner[index] = extra[index];
		}
	}
}

export function getUrl(cfg: RuntimeConfig): string {
	const reqid = nowSec() % 1000000;
	const prefix = accountPrefix(cfg);
	const path =
		`${prefix}/_/BardChatUi/data/assistant.lamda.BardFrontendService/StreamGenerate` +
		`?bl=${encodeURIComponent(cfg.gemini_bl)}&hl=en&_reqid=${reqid}&rt=c`;
	if (cfg.resin_proxy)
		return resinProxyUrl(cfg, `https://gemini.google.com${path}`);
	const origin = (cfg.gemini_origin || "https://gemini.google.com").replace(
		/\/$/,
		"",
	);
	return origin + path;
}

export async function buildHeaders(

	cfg: RuntimeConfig,

	modelHeaders: Record<string, string> | null = null,

	requestId: string | null = null,

): Promise<Record<string, string>> {
	const prefix = accountPrefix(cfg);
	const headers: Record<string, string> = {
		"Content-Type": "application/x-www-form-urlencoded",
		Origin: "https://gemini.google.com",
		Referer: `https://gemini.google.com${prefix}/app`,
		"X-Same-Domain": "1",
		"User-Agent": GEMINI_WEB_USER_AGENT,
		"Accept-Language": "en-US,en;q=0.9",
		// 流式响应禁用压缩:gzip/br 按块解压会把细粒度 delta 合成大片;
		// 经 Resin/反代时尤其明显。identity 让上游按原文分帧下发。
		"Accept-Encoding": "identity",
	};
	if (modelHeaders) Object.assign(headers, modelHeaders);
	if (requestId)
		headers["x-goog-ext-525005358-jspb"] = `["${requestId.toUpperCase()}",1]`;
	if (cfg.cookie) headers.Cookie = cfg.cookie;
	if (cfg.sapisid) headers.Authorization = await makeSapisidHash(cfg.sapisid);
	if (prefix) headers["X-Goog-AuthUser"] = cfg.auth_user;
	return headers;
}