@wacry/codeks-bridge 0.0.19 → 0.0.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,379 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+ import { encodeReasoning } from "../carrier.js";
3
+ import { BridgeError, transportError, upstreamError } from "../errors.js";
4
+ import { isOpaqueStateItem, prepareHistory } from "../history.js";
5
+ import { newId } from "../ids.js";
6
+ import { reasoningEffort, reasoningSummaryRequested } from "../profiles.js";
7
+ import { parseJsonSse } from "../sse.js";
8
+ import { prepareToolCall, toolCallForReplay, toolResultForReplay, writeToolCall } from "../tool-calls.js";
9
+ import { buildToolSet, normalizeToolDeclarations } from "../tools.js";
10
+ import { upstreamFetch } from "../upstream.js";
11
+ const IMPORTED_SIGNATURE = "skip_thought_signature_validator";
12
+ function object(value) {
13
+ return value !== null && typeof value === "object" && !Array.isArray(value);
14
+ }
15
+ function textOf(parts) {
16
+ return parts.filter(part => typeof part.text === "string").map(part => part.text).join("");
17
+ }
18
+ function contentParts(content) {
19
+ if (typeof content === "string")
20
+ return content ? [{ text: content }] : [];
21
+ if (!Array.isArray(content))
22
+ throw new BridgeError("Gemini content must be text or a content array.");
23
+ return content.map((part) => {
24
+ if (["input_text", "output_text", "text"].includes(part?.type) && typeof part.text === "string")
25
+ return { text: part.text };
26
+ if (part?.type === "refusal" && typeof part.refusal === "string")
27
+ return { text: part.refusal };
28
+ if (part?.type === "input_image" || part?.type === "image_url") {
29
+ const url = typeof part.image_url === "string" ? part.image_url : part.image_url?.url;
30
+ if (typeof url !== "string")
31
+ throw new BridgeError("A Gemini image needs an image_url.");
32
+ const data = /^data:(image\/[a-zA-Z0-9.+-]+);base64,([\s\S]+)$/.exec(url);
33
+ if (data)
34
+ return { inlineData: { mimeType: data[1], data: data[2] } };
35
+ if (/^(https?:\/\/|gs:\/\/)/.test(url))
36
+ return { fileData: { fileUri: url } };
37
+ throw new BridgeError("Gemini images require an HTTP(S), Cloud Storage, or image data URL.");
38
+ }
39
+ throw new BridgeError(`Unsupported Gemini content type: ${String(part?.type)}.`);
40
+ });
41
+ }
42
+ function parseArguments(value) {
43
+ let parsed;
44
+ try {
45
+ parsed = typeof value === "string" ? JSON.parse(value) : value;
46
+ }
47
+ catch {
48
+ throw new BridgeError("A Gemini tool call contains invalid JSON arguments.");
49
+ }
50
+ if (!object(parsed))
51
+ throw new BridgeError("Gemini tool arguments must be an object.");
52
+ return parsed;
53
+ }
54
+ function toolChoice(value, tools) {
55
+ if (value === undefined)
56
+ return undefined;
57
+ if (value === "auto")
58
+ return { mode: "AUTO" };
59
+ if (value === "none")
60
+ return { mode: "NONE" };
61
+ if (value === "required")
62
+ return { mode: "ANY" };
63
+ if (value && ["function", "custom"].includes(value.type) && typeof value.name === "string") {
64
+ const tool = tools.get(value.namespace, value.name);
65
+ if (!tool || tool.kind !== value.type)
66
+ throw new BridgeError("The selected tool is not available on the Gemini backend.");
67
+ return { mode: "ANY", allowedFunctionNames: [tool.flatName] };
68
+ }
69
+ throw new BridgeError("Unsupported Gemini tool_choice.");
70
+ }
71
+ export function buildGeminiRequest(context) {
72
+ const request = normalizeToolDeclarations(context.request);
73
+ const { route } = context;
74
+ const tools = buildToolSet(request.tools);
75
+ const system = request.instructions ? [{ text: request.instructions }] : [];
76
+ const contents = [];
77
+ let entries = [];
78
+ const calls = new Map();
79
+ const callOrder = new Map();
80
+ const resultOrder = new Map();
81
+ const flushModel = () => {
82
+ if (entries.length)
83
+ contents.push({ role: "model", parts: entries.flatMap(entry => entry.parts) });
84
+ entries = [];
85
+ };
86
+ const appendUser = (parts) => {
87
+ if (!parts.length)
88
+ return;
89
+ flushModel();
90
+ const last = contents.at(-1);
91
+ if (last?.role === "user")
92
+ last.parts.push(...parts);
93
+ else
94
+ contents.push({ role: "user", parts });
95
+ };
96
+ for (const item of prepareHistory(request.input, route)) {
97
+ if (isOpaqueStateItem(item)) {
98
+ entries.push({ parts: [item] });
99
+ }
100
+ else if (item.type === "bridge_reasoning") {
101
+ const state = item.state.data;
102
+ if (!object(state) || !Array.isArray(state.parts) || !state.parts.length || !state.parts.every(object)) {
103
+ throw new BridgeError("Invalid Gemini reasoning carrier.");
104
+ }
105
+ if (state.projection) {
106
+ const previous = entries.at(-1);
107
+ const projection = state.projection;
108
+ const matches = previous?.projection?.type === projection.type &&
109
+ (projection.type === "message"
110
+ ? textOf(previous.parts) === textOf(state.parts)
111
+ : projection.type === "function_call" && typeof projection.call_id === "string" &&
112
+ previous.projection.call_id === projection.call_id &&
113
+ previous.parts[0]?.functionCall?.name === state.parts[0]?.functionCall?.name &&
114
+ (previous.custom
115
+ ? previous.parts[0]?.functionCall?.args?.input === state.parts[0]?.functionCall?.args?.input
116
+ : isDeepStrictEqual(previous.parts[0]?.functionCall?.args, state.parts[0]?.functionCall?.args ?? {})));
117
+ if (!matches)
118
+ throw new BridgeError("Gemini reasoning does not match its preceding message or tool call.");
119
+ entries.pop();
120
+ if (projection.type === "function_call") {
121
+ const call = state.parts[0]?.functionCall;
122
+ if (state.parts.length !== 1 || !object(call) || typeof call.name !== "string") {
123
+ throw new BridgeError("Invalid Gemini tool reasoning carrier.");
124
+ }
125
+ calls.set(projection.call_id, { name: call.name, ...(typeof call.id === "string" ? { id: call.id } : {}) });
126
+ }
127
+ }
128
+ if (state.continuation_before !== undefined) {
129
+ if (typeof state.continuation_before !== "string" || !state.continuation_before.length) {
130
+ throw new BridgeError("Invalid Gemini continuation boundary.");
131
+ }
132
+ appendUser([{ text: state.continuation_before }]);
133
+ }
134
+ entries.push({ parts: state.parts });
135
+ }
136
+ else if (item.type === "function_call" || item.type === "custom_tool_call") {
137
+ const wire = toolCallForReplay(item, tools);
138
+ const call = { name: wire.name, id: wire.id, args: item.type === "custom_tool_call" ? { input: item.input } : parseArguments(item.arguments) };
139
+ calls.set(item.call_id, { name: wire.name, id: wire.id });
140
+ callOrder.set(item.call_id, callOrder.size);
141
+ // This provisional import marker is replaced by the original signed part
142
+ // when a matching native carrier follows. Foreign histories have no signature.
143
+ entries.push({ parts: [{ functionCall: call, thoughtSignature: IMPORTED_SIGNATURE }], projection: { type: "function_call", call_id: item.call_id }, custom: item.type === "custom_tool_call" });
144
+ }
145
+ else if (item.type === "function_call_output" || item.type === "custom_tool_call_output") {
146
+ const wire = toolResultForReplay(item);
147
+ const call = calls.get(item.call_id);
148
+ if (!call)
149
+ throw new BridgeError("Gemini tool output has no matching function call.");
150
+ const parts = contentParts(wire.output);
151
+ const media = parts.filter(part => part.inlineData || part.fileData);
152
+ const result = { functionResponse: {
153
+ ...call, response: { [wire.isError ? "error" : "output"]: textOf(parts) },
154
+ ...(media.length ? { parts: media } : {}),
155
+ } };
156
+ resultOrder.set(result, callOrder.get(item.call_id));
157
+ appendUser([result]);
158
+ }
159
+ else if (item.type === "message" || item.role) {
160
+ const parts = contentParts(item.content);
161
+ if (item.role === "system" || item.role === "developer") {
162
+ if (parts.some(part => typeof part.text !== "string"))
163
+ throw new BridgeError("Gemini system messages must contain text.");
164
+ if (!contents.length && !entries.length)
165
+ system.push(...parts);
166
+ else
167
+ appendUser([{ text: `<system-reminder>\n${parts.map(part => part.text).join("\n\n")}\n</system-reminder>` }]);
168
+ }
169
+ else if (item.role === "assistant") {
170
+ if (parts.length)
171
+ entries.push({ parts, projection: { type: "message" } });
172
+ }
173
+ else if (item.role === "user")
174
+ appendUser(parts);
175
+ else
176
+ throw new BridgeError(`Unsupported Gemini role: ${String(item.role)}.`);
177
+ }
178
+ else
179
+ throw new BridgeError(`Unsupported Gemini history item: ${String(item.type)}.`);
180
+ }
181
+ flushModel();
182
+ // Gemini requires parallel responses in the corresponding call order.
183
+ // Keep text/media and all other message boundaries in their original place.
184
+ for (const content of contents) {
185
+ if (content.role !== "user")
186
+ continue;
187
+ for (let index = 0; index < content.parts.length;) {
188
+ if (!resultOrder.has(content.parts[index])) {
189
+ index++;
190
+ continue;
191
+ }
192
+ let end = index + 1;
193
+ while (end < content.parts.length && resultOrder.has(content.parts[end]))
194
+ end++;
195
+ const ordered = content.parts.slice(index, end).sort((a, b) => resultOrder.get(a) - resultOrder.get(b));
196
+ content.parts.splice(index, end - index, ...ordered);
197
+ index = end;
198
+ }
199
+ }
200
+ const tail = contents.at(-1);
201
+ const continuationBefore = tail?.role === "model" && !tail.parts.some(part => part.functionCall) ? "Continue." : undefined;
202
+ if (continuationBefore)
203
+ appendUser([{ text: continuationBefore }]);
204
+ const generationConfig = {
205
+ thinkingConfig: {
206
+ thinkingLevel: reasoningEffort(route, request.reasoning?.effort).toUpperCase(),
207
+ includeThoughts: reasoningSummaryRequested(request),
208
+ },
209
+ };
210
+ const limit = request.max_output_tokens ?? route.profile.max_output_tokens;
211
+ if (limit !== undefined)
212
+ generationConfig.maxOutputTokens = limit;
213
+ if (request.temperature !== undefined)
214
+ generationConfig.temperature = request.temperature;
215
+ if (request.top_p !== undefined)
216
+ generationConfig.topP = request.top_p;
217
+ const format = request.text?.format;
218
+ if (format && format.type !== "text" && !context.compacting) {
219
+ if (!["json_schema", "json_object"].includes(format.type))
220
+ throw new BridgeError(`Unsupported Gemini text format: ${String(format.type)}.`);
221
+ generationConfig.responseMimeType = "application/json";
222
+ if (format.type === "json_schema")
223
+ generationConfig.responseJsonSchema = format.schema;
224
+ }
225
+ const choice = toolChoice(request.tool_choice, tools);
226
+ const body = {
227
+ generationConfig,
228
+ ...(choice ? { toolConfig: { functionCallingConfig: choice } } : {}),
229
+ ...route.upstream.options, ...route.config.options,
230
+ contents,
231
+ };
232
+ // Merge generation options once: native values own supplied fields, while
233
+ // required thinking defaults survive an unrelated temperature override.
234
+ body.generationConfig = { ...generationConfig, ...route.upstream.options?.generationConfig, ...route.config.options?.generationConfig };
235
+ if (context.compacting) {
236
+ delete body.generationConfig.responseMimeType;
237
+ delete body.generationConfig.responseSchema;
238
+ delete body.generationConfig.responseJsonSchema;
239
+ // Newer native endpoints expose the same structured-output constraint here.
240
+ delete body.generationConfig.responseFormat;
241
+ }
242
+ if (system.length)
243
+ body.systemInstruction = { parts: system };
244
+ else
245
+ delete body.systemInstruction;
246
+ if (tools.entries.length)
247
+ body.tools = [{ functionDeclarations: tools.entries.map(tool => ({
248
+ name: tool.flatName, description: tool.description, parametersJsonSchema: tool.parameters,
249
+ })) }];
250
+ else
251
+ delete body.tools;
252
+ return { body, tools, continuationBefore };
253
+ }
254
+ function count(value, optional = false) {
255
+ if (optional && value === undefined)
256
+ return 0;
257
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
258
+ throw new BridgeError("Gemini stream has invalid or missing token usage.", "upstream_error", 502);
259
+ }
260
+ return value;
261
+ }
262
+ function readUsage(value) {
263
+ return {
264
+ input_tokens: count(value.promptTokenCount) + count(value.toolUsePromptTokenCount, true),
265
+ output_tokens: count(value.candidatesTokenCount, true) + count(value.thoughtsTokenCount, true),
266
+ cached_tokens: count(value.cachedContentTokenCount, true),
267
+ reasoning_tokens: count(value.thoughtsTokenCount, true),
268
+ };
269
+ }
270
+ export const runGemini = async (context, writer) => {
271
+ const { body, tools, continuationBefore } = buildGeminiRequest(context);
272
+ const model = context.route.config.model.replace(/^models\//, "");
273
+ const response = await upstreamFetch(context.route, `models/${encodeURIComponent(model)}:streamGenerateContent?alt=sse`, body, context.signal, context.requestHeaders, undefined, context.fetch);
274
+ context.onAccepted?.(response.headers);
275
+ if (!response.body)
276
+ throw new BridgeError("Gemini returned an empty stream.", "upstream_error", 502);
277
+ let segment = [];
278
+ let thinking = false;
279
+ let calls = 0;
280
+ let visible = false;
281
+ let finish;
282
+ let finalCandidate;
283
+ let rawUsage;
284
+ const ids = new Set();
285
+ let pendingContinuation = continuationBefore;
286
+ const carrier = (parts, projection) => {
287
+ const encoded = encodeReasoning({
288
+ source: context.route.origin, format: context.route.profile.reasoning_format,
289
+ data: { parts, ...(projection ? { projection } : {}),
290
+ ...(pendingContinuation ? { continuation_before: pendingContinuation } : {}) },
291
+ });
292
+ pendingContinuation = undefined;
293
+ return encoded;
294
+ };
295
+ const flush = (final = false) => {
296
+ if (!segment.length)
297
+ return;
298
+ const text = textOf(segment);
299
+ if (!thinking && text)
300
+ writer.closeMessage(final ? "final_answer" : "commentary");
301
+ writer.endReasoning(carrier(segment, !thinking && text ? { type: "message" } : undefined));
302
+ segment = [];
303
+ };
304
+ try {
305
+ for await (const { json } of parseJsonSse(response.body)) {
306
+ context.signal.throwIfAborted();
307
+ if (json.error)
308
+ throw upstreamError(Number.isInteger(json.error.code) ? json.error.code : undefined, json, response.headers);
309
+ if (json.promptFeedback?.blockReason) {
310
+ throw new BridgeError(`Gemini blocked the prompt: ${json.promptFeedback.blockReason}.`, "invalid_prompt", 400, undefined, { upstream: { body: json } });
311
+ }
312
+ if (json.usageMetadata)
313
+ rawUsage = json.usageMetadata;
314
+ for (const candidate of json.candidates ?? []) {
315
+ if ((candidate.index ?? 0) !== 0 || json.candidates.length !== 1) {
316
+ throw new BridgeError("Gemini returned more than one candidate.", "upstream_error", 502);
317
+ }
318
+ if (candidate.finishReason) {
319
+ finish = candidate.finishReason;
320
+ finalCandidate = candidate;
321
+ }
322
+ for (const raw of candidate.content?.parts ?? []) {
323
+ if (!object(raw))
324
+ throw new BridgeError("Gemini returned an invalid content part.", "upstream_error", 502);
325
+ const part = structuredClone(raw);
326
+ if (part.functionCall) {
327
+ flush();
328
+ const value = part.functionCall;
329
+ if (!object(value) || !object(value.args ?? {}) || typeof value.name !== "string") {
330
+ throw new BridgeError("Gemini returned an invalid function call.", "upstream_error", 502);
331
+ }
332
+ const id = value.id ?? newId("call");
333
+ if (typeof id !== "string" || !id || ids.has(id))
334
+ throw new BridgeError("Gemini returned an invalid or repeated function call ID.", "upstream_error", 502);
335
+ ids.add(id);
336
+ const call = prepareToolCall(tools, id, value.name, value.args ?? {});
337
+ writeToolCall(writer, call);
338
+ writer.endReasoning(carrier([part], { type: "function_call", call_id: call.call.call_id }));
339
+ calls++;
340
+ }
341
+ else if (typeof part.text === "string" || typeof part.thoughtSignature === "string") {
342
+ const isThinking = part.thought === true;
343
+ if (segment.length && isThinking !== thinking)
344
+ flush();
345
+ thinking = isThinking;
346
+ segment.push(part);
347
+ if (isThinking)
348
+ writer.reasoningDelta(part.text ?? "");
349
+ else if (part.text) {
350
+ writer.textDelta(part.text);
351
+ visible = true;
352
+ }
353
+ }
354
+ else
355
+ throw new BridgeError("Gemini returned an unsupported content part.", "upstream_error", 502);
356
+ }
357
+ }
358
+ }
359
+ }
360
+ catch (error) {
361
+ if (context.signal.aborted)
362
+ throw context.signal.reason;
363
+ throw transportError(error);
364
+ }
365
+ context.signal.throwIfAborted();
366
+ if (!finish)
367
+ throw new BridgeError("Gemini stream ended before a finishReason.", "upstream_error", 502);
368
+ if (finish !== "STOP") {
369
+ throw new BridgeError(`Gemini generation stopped with ${finish}${finalCandidate?.finishMessage ? `: ${finalCandidate.finishMessage}` : "."}`, "invalid_prompt", 400, undefined, { upstream: { body: finalCandidate } });
370
+ }
371
+ if (!rawUsage)
372
+ throw new BridgeError("Gemini stream ended without token usage.", "upstream_error", 502);
373
+ // Intermediate chunks can contain only routing metadata, not token counts.
374
+ const usage = readUsage(rawUsage);
375
+ if (!visible && !calls)
376
+ throw new BridgeError("Gemini returned no text or tool calls.", "upstream_error", 502);
377
+ flush(calls === 0);
378
+ return { usage, endTurn: calls === 0 };
379
+ };
package/dist/errors.js CHANGED
@@ -87,7 +87,7 @@ export function upstreamError(status, payload, headers) {
87
87
  : status !== undefined ? `Upstream returned HTTP ${status}` : "The upstream response failed";
88
88
  const kind = [error?.code, error?.type].filter((value) => typeof value === "string").join(" ");
89
89
  let code;
90
- if (/context_length|too_many_tokens/.test(kind) || /prompt is too long|maximum context length|too many tokens/i.test(message))
90
+ if (/context_length|too_many_tokens/.test(kind) || /prompt is too long|maximum context length|too many tokens|input token count[^\n]*exceeds the maximum number of tokens/i.test(message))
91
91
  code = "context_length_exceeded";
92
92
  else if (/quota|billing|credit|balance/.test(kind) || /insufficient (quota|credit|balance)/i.test(message))
93
93
  code = "insufficient_quota";
package/dist/headers.js CHANGED
@@ -18,7 +18,7 @@ export function incomingHeaders(input) {
18
18
  /** Credentials belong to the selected upstream, never to the bridge client. */
19
19
  export function forwardRequestHeaders(input, authHeader) {
20
20
  const headers = withoutTransportHeaders(input);
21
- for (const name of ["host", "accept-encoding", "authorization", "x-api-key", "api-key", "cookie", ...(authHeader ? [authHeader] : [])])
21
+ for (const name of ["host", "accept-encoding", "authorization", "x-api-key", "x-goog-api-key", "api-key", "cookie", ...(authHeader ? [authHeader] : [])])
22
22
  headers.delete(name);
23
23
  return headers;
24
24
  }
@@ -1,6 +1,6 @@
1
1
  // In-memory capture of complete exchanges for the inspector. A capture keeps
2
- // every byte the bridge received and sent. Only credential header values are
3
- // redacted; bodies are never filtered.
2
+ // every byte the bridge received and sent. Credential headers and URL query
3
+ // values are redacted; bodies are never filtered.
4
4
  import { AsyncLocalStorage } from "node:async_hooks";
5
5
  import { createHash } from "node:crypto";
6
6
  const MIB = 1024 * 1024;
@@ -14,6 +14,20 @@ function redact(name, value, extra) {
14
14
  const digest = createHash("sha256").update(value).digest("hex").slice(0, 8);
15
15
  return `[redacted: ${value.length} chars, sha256 ${digest}]`;
16
16
  }
17
+ function redactUrl(value) {
18
+ const url = new URL(value);
19
+ const query = new URLSearchParams();
20
+ let changed = false;
21
+ for (const [name, original] of url.searchParams) {
22
+ const filtered = redact(name.toLowerCase(), original, new Set());
23
+ changed ||= filtered !== original;
24
+ query.append(name, filtered);
25
+ }
26
+ if (!changed)
27
+ return value;
28
+ url.search = query.toString();
29
+ return url.toString();
30
+ }
17
31
  /** Lowercase names, join repeated values, and redact credentials. */
18
32
  export function headerMap(headers, extra = new Set()) {
19
33
  const result = {};
@@ -110,7 +124,7 @@ export class Call {
110
124
  this.index = exchange.calls.length;
111
125
  this.label = label;
112
126
  this.startedMs = exchange.now();
113
- this.url = url;
127
+ this.url = redactUrl(url);
114
128
  this.headers = headers;
115
129
  this.text = text;
116
130
  this.bytes = Buffer.byteLength(text);
@@ -18,6 +18,6 @@ export interface CatalogEntry {
18
18
  max_output_tokens?: number;
19
19
  model: Record<string, any>;
20
20
  }
21
- export declare const catalogKeys: readonly ["gpt-6-astra", "gpt-6.1-sol", "gpt-6.1-terra", "gpt-6-sol", "gpt-6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna", "gpt-5.5", "gpt-daybreak-blue-latest", "gpt-daybreak-red-latest", "codex-auto-review", "gpt-reserve", "claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-5-5", "deepseek-flash"];
21
+ export declare const catalogKeys: readonly ["gpt-6-astra", "gpt-6.1-sol", "gpt-6.1-terra", "gpt-6-sol", "gpt-6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna", "gpt-5.5", "gpt-daybreak-blue-latest", "gpt-daybreak-red-latest", "codex-auto-review", "gpt-reserve", "claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-5-5", "deepseek-flash", "gemini-3.8-flash", "gemini-4-argon"];
22
22
  /** Each alias gets its own copy of the reviewed entry. */
23
23
  export declare function getCatalogEntry(key: string): CatalogEntry;
@@ -4,6 +4,7 @@ export const catalogKeys = [
4
4
  "gpt-6-astra", "gpt-6.1-sol", "gpt-6.1-terra", "gpt-6-sol", "gpt-6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna",
5
5
  "gpt-5.5", "gpt-daybreak-blue-latest", "gpt-daybreak-red-latest", "codex-auto-review", "gpt-reserve",
6
6
  "claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-5-5", "deepseek-flash",
7
+ "gemini-3.8-flash", "gemini-4-argon",
7
8
  ];
8
9
  const entries = new Map(catalogKeys.map(key => [
9
10
  key, JSON.parse(readFileSync(new URL(`../catalog/${key}.json`, import.meta.url), "utf8")),
package/dist/profiles.js CHANGED
@@ -11,6 +11,9 @@ const FORMATS = {
11
11
  "deepseek-chat": {
12
12
  id: "deepseek-chat", api: "chat", reasoning_format: "reasoning.text.v1",
13
13
  },
14
+ "gemini-native": {
15
+ id: "gemini-native", api: "gemini", reasoning_format: "gemini.parts.v1",
16
+ },
14
17
  };
15
18
  /** Match Codex's Ultra resolution without rewriting the original catalog metadata. */
16
19
  function ultraEffort(info, levels) {
package/dist/server.js CHANGED
@@ -8,13 +8,14 @@ import { ResponseWriter, usageJson } from "./writer.js";
8
8
  import { runResponses } from "./backends/responses.js";
9
9
  import { runAnthropic } from "./backends/anthropic.js";
10
10
  import { runDeepSeek } from "./backends/deepseek.js";
11
+ import { runGemini } from "./backends/gemini.js";
11
12
  import { compact, isCompactionRequest } from "./compaction.js";
12
13
  import { CompactionHandoffStore } from "./compaction-handoff.js";
13
14
  import { Inspector, withCaptureLabel } from "./inspect/capture.js";
14
15
  import { isInspectorPath, serveInspector } from "./inspect/http.js";
15
16
  import { forwardResponseHeaders, incomingHeaders } from "./headers.js";
16
17
  import { upstreamFetch } from "./upstream.js";
17
- const BACKENDS = { "gpt-responses": runResponses, "claude-messages": runAnthropic, "deepseek-chat": runDeepSeek };
18
+ const BACKENDS = { "gpt-responses": runResponses, "claude-messages": runAnthropic, "deepseek-chat": runDeepSeek, "gemini-native": runGemini };
18
19
  function json(res, status, body, headers = {}) {
19
20
  for (const [name, value] of Object.entries(headers))
20
21
  res.setHeader(name, value);
package/dist/types.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { ResponseWriter, Usage } from "./writer.ts";
2
2
  import type { ChatgptAuthConfig } from "./chatgpt-auth.ts";
3
- export type Api = "responses" | "anthropic" | "chat";
4
- export type AdapterId = "gpt-responses" | "claude-messages" | "deepseek-chat";
3
+ export type Api = "responses" | "anthropic" | "chat" | "gemini";
4
+ export type AdapterId = "gpt-responses" | "claude-messages" | "deepseek-chat" | "gemini-native";
5
5
  export type UnrecognizedStatePolicy = "passthrough" | "drop" | "error";
6
6
  export interface ClaudeMessagesOptions {
7
7
  thinking_mismatch: "drop_block" | "error" | "upstream_default";
@@ -0,0 +1,78 @@
1
+ # Gemini 原生接口
2
+
3
+ 模型选择 `catalog: "gemini-3.8-flash"` 或 `"gemini-4-argon"`,条目指定 `gemini-native` adapter。bridge 将 Responses 请求转换为 `POST <base_url>/models/<model>:streamGenerateContent?alt=sse`,使用原生 `contents` / `parts` 协议;不经过 Chat Completions 兼容接口。`model` 是实际部署名,目录 key 只选择已经审阅的能力与默认值。
4
+
5
+ ```json
6
+ {
7
+ "upstreams": {
8
+ "gemini": {
9
+ "base_url": "https://generativelanguage.googleapis.com/v1beta",
10
+ "api_key_env": "GEMINI_API_KEY"
11
+ }
12
+ },
13
+ "models": {
14
+ "flash": {
15
+ "upstream": "gemini",
16
+ "catalog": "gemini-3.8-flash",
17
+ "model": "gemini-3.8-flash"
18
+ },
19
+ "argon": {
20
+ "upstream": "gemini",
21
+ "catalog": "gemini-4-argon",
22
+ "model": "gemini-4-argon"
23
+ }
24
+ }
25
+ }
26
+ ```
27
+
28
+ 官方连接使用 `x-goog-api-key`;其他连接可通过现有 `headers`、`auth_header` 和凭据命令配置鉴权。`base_url` 包含版本及部署前缀,不包含具体模型和操作名。客户端继续使用 bridge 的 Responses Lite、Code Mode Only 和多代理工具。
29
+
30
+ ## 目录与 thinking
31
+
32
+ 两模型默认 `medium`;`low`、`medium`、`high` 对应 `generationConfig.thinkingConfig.thinkingLevel` 的 `LOW`、`MEDIUM`、`HIGH`。codeks 的 `ultra` 仍启用客户端的自动分工提示词,原生 effort 使用 `HIGH`。原生 Argon 要求提供 thinking level,不能依赖未指定值;两模型都不支持 `minimal`,目录也不宣传关闭 thinking 的 `none`。未映射的显式 effort 由上游裁决,不静默替换为另一个档位。[原生 thinking 文档](https://ai.google.dev/gemini-api/docs/generate-content/thinking)
33
+
34
+ `reasoning.summary` 为 `auto`、`concise` 或 `detailed` 时请求 `includeThoughts: true`,将上游标记 `thought: true` 的文本作为可见摘要。缺省或 `none` 不展示摘要;这不等于关闭 thinking,也不应丢失签名。目录沿用 Sol 的摘要默认值 `none`,可在 codeks 中设置 `model_reasoning_summary = "auto"`。
35
+
36
+ 默认工作窗口为 `272000`;两个条目的最大窗口为 `1048576`。Flash 的官方限制是输入 token 上限,Argon 则是输入与输出共用的窗口,不能把后者理解成可以在 1M 输入之后再输出 1M。官方标准输出上限为 `65536` token;Argon 的更长输出需要另一种后台 long decode 路径。本 adapter 不设置额外默认输出预算或压缩阈值。显式预算从请求或模型配置取得,再接受原生 options 覆盖。[Flash 规格](https://ai.google.dev/gemini-api/docs/models/gemini-3.8-flash)、[Argon 规格](https://ai.google.dev/gemini-api/docs/models/gemini-4-argon)
37
+
38
+ ## 消息、工具与图片
39
+
40
+ 开头的 instructions、system 和 developer 指令进入 `systemInstruction`;中途 system/developer 指令转换为原位置的 user `<system-reminder>`,不会为每条新指令重写顶部。user 与 assistant 对应原生 `user` / `model`;相邻同角色内容按原协议组成 parts。
41
+
42
+ Lite 的 `additional_tools` 按历史顺序合并,声明放入顶层 `tools.functionDeclarations`,同身份保留最新版本。namespace 名称、自由文本工具和 Lark/regex 语法沿用[共同工具转换](tools.md),不为 Gemini 另造命名约定。工具调用成为 `functionCall`,结果成为 `functionResponse`;跨消息交错的调用与结果先使用现有工具历史配对规则整理。
43
+
44
+ 图片 data URL 转为 `inlineData`,远程 URL 使用 `fileData`;bridge 不下载远程图片,也不猜测上游是否有权限访问。模型是否接受 URI、MIME 和尺寸由上游裁决。工具输出中的图片随对应的 `functionResponse` 发送,保留与调用的关系。客户端目录不宣称 `detail: "original"`。
45
+
46
+ ## 保留历史与压缩
47
+
48
+ Gemini 的 thought signature 是原生 Part 上的 `thoughtSignature`,不等同于可见思考摘要。它可能附在文本或 `functionCall` 上,也可能单独出现在流末尾的空文本 part;同源续接需要保留它与原始 part 的关系。官方要求工具调用时返回签名,并且不能把带签名与不带签名的 part 随意合并。[Thought signatures](https://ai.google.dev/gemini-api/docs/generate-content/thought-signatures)
49
+
50
+ 原生载荷保存为现有 `cxbr1:` reasoning carrier,格式为 `gemini.parts.v1`,data 保存原始 `parts`。正文或工具调用还记录对应的 Responses 投影标记:客户端仍看到正常文本和可执行调用,下一次同源请求恢复完整原生 parts 并替换紧邻的前一项投影,避免把文字或工具重复发送。签名不编码进 call ID;工具身份继续使用共用的调用转换与目标协议 ID 处理。原生末尾的空文本签名 part 也要保留。
51
+
52
+ 其他模型转入的工具历史没有 Gemini 签名。适配器使用官方允许的 `skip_thought_signature_validator` 标记这一边界;它不补造 reasoning,也不是服务端返回的真实签名。可以恢复的同源载荷始终原样回放。[跨模型工具历史规则](https://ai.google.dev/gemini-api/docs/generate-content/thought-signatures)
53
+
54
+ 来源隔离和用户允许的 reasoning 复用仍使用 bridge 的公共策略,不能因为都属于 Gemini 就默认共享签名。默认压缩为标准文字摘要;需要委托已有 GPT 做原生压缩时,使用现有 `compaction.model` 配置,无需额外的 Gemini 压缩接口。[Reasoning](reasoning.md)、[压缩](compaction.md)
55
+
56
+ 失败重试或子代理继承的历史可能以 `model` 结束。原生接口需要新的 user 或工具结果边界;若末尾 model 不含待处理的 `functionCall`,本次出站追加 user `Continue.`。新生成的第一个 carrier 用 `continuation_before` 记录这次边界,后续同源请求在原位置恢复,避免下一轮改变签名前缀。正文仍然流式显示,bridge 不代替客户端重试;末尾有工具调用时不会用 Continue 掩盖缺失结果。
57
+
58
+ ## 结构化输出与原生 options
59
+
60
+ Responses 的 JSON object 请求使用原生 `responseMimeType: "application/json"`;JSON Schema 使用 `responseJsonSchema`。schema 保留原始约束,不转换成提示词或另建桥接校验器;上游不支持的 schema 直接返回错误。原生参数位于 `generationConfig`,包括 thinking 配置与可选的输出预算。[原生结构化输出](https://ai.google.dev/gemini-api/docs/generate-content/structured-output)
61
+
62
+ 工具参数通过原生 `parametersJsonSchema` 保留根 `$ref` 和组合约束。Gemini `FunctionDeclaration` 没有逐工具的 `strict` 字段,bridge 不添加此字段,也不宣称复现 OpenAI 的 strict 保证;模型的原生 schema 与工具选择行为由端点决定。
63
+
64
+ 上游和模型 `options` 可以设置原生请求字段,`generationConfig` 在自动转换的配置上合并。明确的原生参数优先;内容、工具表与客户端路由仍由 bridge 管理,options 不替换这些字段。bridge 不为每个原生选项新增单独配置项。
65
+
66
+ ## 流、用量与失败
67
+
68
+ 原生 SSE 的正文和可见 thought 文本转换成 Responses 增量事件。工具只有在响应成功结束、参数完整且用量有效后才交付;断流或失败不会执行尚未提交的调用。结束必须收到成功的 `STOP`,其他 finish reason、缺失终止或缺失必要用量都按失败交给客户端,不在 bridge 内重试或偷偷续接。
69
+
70
+ Responses input usage 包含 `promptTokenCount` 与存在时的 `toolUsePromptTokenCount`;output usage 包含 `candidatesTokenCount` 与 `thoughtsTokenCount`。Vertex 的 `totalTokenCount` 明确为这四项之和。缓存数来自 `cachedContentTokenCount`,它已包含在输入统计内,不再次累加。thoughts 同时作为 output 的 reasoning 明细,不能再加到上下文使用量里。转换保留服务端统计语义,不能用可见文本长度估算替代。[UsageMetadata](https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/rest/v1/GenerateContentResponse#UsageMetadata)
71
+
72
+ ## 范围
73
+
74
+ 本 adapter 面向文本回答、工具和图片输入;没有接入 Gemini 服务端搜索、代码执行、文件检索、音频、视频、图片生成、Live API 或后台 long decode。bridge 的独立订阅搜索和图片生成配置仍可与 Gemini 工作模型一起使用。官方文档可能以 Interactions API 为主;这里实现的是用户选择的 Generate Content 接口,两者的字段和流事件不能混用。
75
+
76
+ 新模型不能只凭名称加入目录。更新时需要核对原生 thinking 档位、上下文语义、签名载荷及返回顺序、工具与结构化输出字段,并通过相应的真实请求验证。
77
+
78
+ 2026-10-27 的真实原生请求通过 Vertex AI 路由验证两个模型的 `MEDIUM`、thought 摘要、末尾空文本签名、工具签名回放、图片与 JSON Schema;Flash 省略输出预算也能成功。该记录验证实际收到的原生协议,不等同于已直连 Google AI Developer API,也不证明所有区域、缓存条件或跨模型签名兼容。适配器自身另以合成数据测试转换与客户端交付。
package/docs/config.md CHANGED
@@ -19,6 +19,7 @@
19
19
  | GPT 系列 | [`gpt-responses`](backends-responses.md) | `/responses` |
20
20
  | Claude Opus / Sonnet / Haiku | [`claude-messages`](backends-anthropic.md) | `/messages` |
21
21
  | DeepSeek Flash | [`deepseek-chat`](backends-deepseek-chat.md) | `/chat/completions` |
22
+ | Gemini 3.8 Flash / 4 Argon | [`gemini-native`](backends-gemini.md) | `/models/{model}:streamGenerateContent?alt=sse` |
22
23
 
23
24
  同一个兼容网关的连接可供不同条目使用。服务按每条请求的别名独立选路,因此父代理、子代理和并行会话可以同时使用不同上游。别名固定对应一个目标,不做上游模型发现或自动负载均衡。
24
25
 
@@ -66,7 +67,7 @@
66
67
  | `auth` | `{"type":"chatgpt"}` 使用 codeks 的文件登录凭据;可选 `codex_home` 指定登录目录 |
67
68
  | `api_key_env` | API key 环境变量名称 |
68
69
  | `api_key_command` | 与 `api_key_env` 二选一;argv 数组,程序 stdout 返回当前凭据 |
69
- | `auth_header` | 覆盖鉴权 header 名;默认 GPT/DeepSeek 用 `authorization: Bearer …`,Claude 用 `x-api-key` |
70
+ | `auth_header` | 覆盖鉴权 header 名;默认 GPT/DeepSeek 用 `authorization: Bearer …`,Claude 用 `x-api-key`,Gemini 用 `x-goog-api-key`;OAuth Bearer 连接可显式选择 `authorization` |
70
71
  | `headers_timeout_ms` | 等待上游响应头的最长时间;省略时沿用 `stream_idle_timeout_ms`,`null` 表示禁用 |
71
72
  | `stream_idle_timeout_ms` | 收到上游响应头后,等待下一批字节的最长空闲时间,默认 300000 ms;`null` 表示禁用 |
72
73
  | `headers` | 静态 header,覆盖同名客户端 header,例如 API 版本 |
@@ -234,7 +235,7 @@ model_reasoning_summary = "auto"
234
235
 
235
236
  ## 压缩模式与执行模型
236
237
 
237
- `models.<别名>.compaction.mode` 可选择 `summary` 或 `native`。默认值取自工作模型:GPT 默认 `native`,Claude/DeepSeek 默认 `summary`。`compaction.model` 可引用另一个已配置的模型别名,让它执行压缩;省略时由工作模型自己执行。两项独立,仅设置执行模型不会改变模式。
238
+ `models.<别名>.compaction.mode` 可选择 `summary` 或 `native`。默认值取自工作模型:GPT 默认 `native`,Claude/DeepSeek/Gemini 默认 `summary`。`compaction.model` 可引用另一个已配置的模型别名,让它执行压缩;省略时由工作模型自己执行。两项独立,仅设置执行模型不会改变模式。
238
239
 
239
240
  GPT 的默认配置等价于:
240
241
 
@@ -322,7 +323,7 @@ bridge 能识别的自身状态默认允许恢复;两份列表增加其他允
322
323
  { "replay": { "unrecognized": "error" } }
323
324
  ```
324
325
 
325
- GPT 将透传项保留在 Responses `input` 中,包括其 `id`;Claude/DeepSeek 将原项放入 assistant 消息的 content 数组,不把未知密文猜解为 thinking 或文字。这保留了原始数据,但不保证跨协议或跨模型兼容,上游可以拒绝;bridge 不自动重试或改用其他策略。
326
+ GPT 将透传项保留在 Responses `input` 中,包括其 `id`;Claude/DeepSeek 将原项放入 assistant 消息的 content 数组,Gemini 放入 model 的 parts,不把未知密文猜解为 thinking 或文字。这保留了原始数据,但不保证跨协议或跨模型兼容,上游可以拒绝;bridge 不自动重试或改用其他策略。
326
327
 
327
328
  这些项没有可确认的来源与复述配方,因此不套用来源允许列表、不创建来源身份,也不触发按需复述。能解码的 bridge carrier 仍遵循原有来源、格式和压缩表示规则。三个选项都不改写客户端已保存的历史;`drop` 会减少本次请求的 reasoning 上下文,丢弃压缩检查点还可能失去早期对话的唯一表示。普通请求取工作模型的策略,委托压缩取实际执行模型的策略。
328
329
 
@@ -330,7 +331,7 @@ GPT 将透传项保留在 Responses `input` 中,包括其 `id`;Claude/DeepSe
330
331
 
331
332
  bridge 的 `GET /v1/models` 返回 Codex 专用的 `{"models": [...]}`,每项包含完整提示词、窗口、工具、多代理和 reasoning 元数据。它与经典 OpenAI 的 `{"object":"list","data":[...]}` 格式不同。仅列出配置中的别名,不暴露上游连接、实际部署名或凭据设置。
332
333
 
333
- 这些条目来自仓库内已审阅的 [catalog](../catalog/README.md),运行时只展开别名和显式配置覆盖。GPT 优先使用自己的 Codex 源码条目,源码尚未收录的模型使用已审阅订阅快照;Claude 和 DeepSeek 使用经过精调的 GPT-6.1 Sol 模板。不会启动 codeks 导出模板,也不请求订阅账号的模型目录。目录版本随 bridge 代码更新,升级客户端不会自动改写它。
334
+ 这些条目来自仓库内已审阅的 [catalog](../catalog/README.md),运行时只展开别名和显式配置覆盖。GPT 优先使用自己的 Codex 源码条目,源码尚未收录的模型使用已审阅订阅快照;Claude、DeepSeek 和 Gemini 使用经过精调的 GPT-6.1 Sol 模板。不会启动 codeks 导出模板,也不请求订阅账号的模型目录。目录版本随 bridge 代码更新,升级客户端不会自动改写它。
334
335
 
335
336
  ### HTTP 发现
336
337