@wacry/codeks-bridge 0.0.28 → 0.0.29

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,14 @@
1
+ type Item = Record<string, any>;
2
+ export interface GeminiProjection {
3
+ type: "message" | "function_call";
4
+ call_id?: string;
5
+ }
6
+ export interface GeminiParts {
7
+ parts: Item[];
8
+ projection?: GeminiProjection;
9
+ continuation_before?: string;
10
+ generation?: string;
11
+ }
12
+ /** Called independently for each compaction epoch after source filtering. */
13
+ export declare function prepareGeminiHistory(items: Item[]): Item[];
14
+ export {};
@@ -0,0 +1,133 @@
1
+ import { BridgeError } from "../errors.js";
2
+ const isCall = (item) => ["function_call", "custom_tool_call"].includes(item.type);
3
+ const isResult = (item) => ["function_call_output", "custom_tool_call_output"].includes(item.type);
4
+ const isBoundary = (item) => !isCall(item) && !isResult(item) &&
5
+ item.type !== "bridge_reasoning" && item.role !== "assistant";
6
+ function stateOf(item) {
7
+ if (item.type !== "bridge_reasoning")
8
+ return undefined;
9
+ const state = item.state.data;
10
+ if (!state || !Array.isArray(state.parts) || !state.parts.length ||
11
+ !state.parts.every((part) => part && typeof part === "object" && !Array.isArray(part))) {
12
+ throw new BridgeError("Invalid Gemini reasoning carrier.");
13
+ }
14
+ if (state.generation !== undefined && (typeof state.generation !== "string" || !state.generation.length)) {
15
+ throw new BridgeError("Invalid Gemini reasoning generation.");
16
+ }
17
+ return state;
18
+ }
19
+ /** Associate native state before generic tool normalization can split it. */
20
+ function associate(items, checkpointCalls) {
21
+ const calls = new Map();
22
+ for (const item of items)
23
+ if (isCall(item)) {
24
+ const matches = calls.get(item.call_id) ?? [];
25
+ matches.push(item);
26
+ calls.set(item.call_id, matches);
27
+ }
28
+ const attached = new Map();
29
+ const consumed = new Set();
30
+ for (const [index, item] of items.entries()) {
31
+ const state = stateOf(item);
32
+ if (state?.projection?.type !== "function_call")
33
+ continue;
34
+ const id = state.projection.call_id;
35
+ if (typeof id !== "string" || !id)
36
+ throw new BridgeError("Invalid Gemini tool reasoning projection.");
37
+ const matches = calls.get(id) ?? [];
38
+ if (!matches.length && state.generation !== undefined && !checkpointCalls.has(id) && items.slice(index + 1).every(isResult)) {
39
+ // A snapshot can stop after state was committed but before its tool item.
40
+ // State alone never creates a call or a synthetic result.
41
+ consumed.add(item);
42
+ continue;
43
+ }
44
+ if (matches.length !== 1 || attached.has(matches[0])) {
45
+ throw new BridgeError("Gemini tool reasoning has no unique matching call in this history segment.");
46
+ }
47
+ const callIndex = items.indexOf(matches[0]);
48
+ if (!items.slice(Math.min(index, callIndex) + 1, Math.max(index, callIndex)).every(isResult)) {
49
+ throw new BridgeError("Gemini tool reasoning crosses another assistant item.");
50
+ }
51
+ attached.set(matches[0], item);
52
+ consumed.add(item);
53
+ }
54
+ const units = [];
55
+ for (const item of items) {
56
+ if (consumed.has(item))
57
+ continue;
58
+ const carrier = attached.get(item);
59
+ if (carrier) {
60
+ units.push({ items: [item, carrier], state: stateOf(carrier), callId: item.call_id });
61
+ continue;
62
+ }
63
+ const state = stateOf(item);
64
+ const previous = units.at(-1);
65
+ if (state?.projection?.type === "message" && previous?.items.length === 1 && previous.items[0].role === "assistant") {
66
+ previous.items.push(item);
67
+ previous.state = state;
68
+ }
69
+ else
70
+ units.push({ items: [item], ...(state ? { state } : {}) });
71
+ }
72
+ return units;
73
+ }
74
+ /** Restore the observed prefix of each native response, then its tool results. */
75
+ function group(units) {
76
+ const output = [];
77
+ let native = [];
78
+ let results = [];
79
+ let generation;
80
+ let legacyCalls = false;
81
+ const flush = () => {
82
+ output.push(...native.flatMap(unit => unit.items), ...results);
83
+ native = [];
84
+ results = [];
85
+ generation = undefined;
86
+ legacyCalls = false;
87
+ };
88
+ for (const unit of units) {
89
+ const item = unit.items[0];
90
+ if (native.length && isResult(item)) {
91
+ results.push(item);
92
+ continue;
93
+ }
94
+ const state = unit.state;
95
+ const sameGeneration = state?.generation !== undefined && state.generation === generation;
96
+ // Old carriers have no generation ID. For the supported native models,
97
+ // unsigned calls following a signed call belong to that parallel step.
98
+ const legacyParallel = legacyCalls && state?.generation === undefined && unit.callId !== undefined &&
99
+ state?.parts.length === 1 && state.parts[0].functionCall && state.parts[0].thoughtSignature === undefined;
100
+ const legacyTail = legacyCalls && state?.generation === undefined && !state?.projection &&
101
+ state?.parts.every(part => part.text === "" && part.thought !== true && !part.functionCall);
102
+ if (!state || state.continuation_before !== undefined || (!sameGeneration && !legacyParallel && !legacyTail))
103
+ flush();
104
+ if (state?.generation !== undefined || unit.callId !== undefined || legacyTail) {
105
+ native.push(unit);
106
+ generation = state?.generation;
107
+ if (unit.callId !== undefined) {
108
+ legacyCalls ||= state?.generation === undefined && typeof state?.parts[0]?.thoughtSignature === "string";
109
+ }
110
+ }
111
+ else
112
+ output.push(...unit.items);
113
+ }
114
+ flush();
115
+ return output;
116
+ }
117
+ /** Called independently for each compaction epoch after source filtering. */
118
+ export function prepareGeminiHistory(items) {
119
+ const checkpointCalls = new Set(items.filter(isCall).map(item => item.call_id));
120
+ const output = [];
121
+ let segment = [];
122
+ const flush = () => { output.push(...group(associate(segment, checkpointCalls))); segment = []; };
123
+ for (const item of items) {
124
+ if (isBoundary(item)) {
125
+ flush();
126
+ output.push(item);
127
+ }
128
+ else
129
+ segment.push(item);
130
+ }
131
+ flush();
132
+ return output;
133
+ }
@@ -8,6 +8,7 @@ import { parseJsonSse } from "../sse.js";
8
8
  import { prepareToolCall, toolCallForReplay, toolResultForReplay, writeToolCall } from "../tool-calls.js";
9
9
  import { buildToolSet, normalizeToolDeclarations } from "../tools.js";
10
10
  import { upstreamFetch } from "../upstream.js";
11
+ import { prepareGeminiHistory } from "./gemini-history.js";
11
12
  const IMPORTED_SIGNATURE = "skip_thought_signature_validator";
12
13
  function object(value) {
13
14
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -94,7 +95,7 @@ export function buildGeminiRequest(context) {
94
95
  else
95
96
  contents.push({ role: "user", parts });
96
97
  };
97
- for (const item of prepareHistory(request.input, route)) {
98
+ for (const item of prepareHistory(request.input, route, prepareGeminiHistory)) {
98
99
  if (isOpaqueStateItem(item)) {
99
100
  entries.push({ parts: [item] });
100
101
  }
@@ -287,7 +288,7 @@ export const runGemini = async (context, writer) => {
287
288
  const carrier = (parts, projection) => {
288
289
  const encoded = encodeReasoning({
289
290
  source: context.route.origin, format: context.route.profile.reasoning_format,
290
- data: { parts, ...(projection ? { projection } : {}),
291
+ data: { parts, generation: writer.responseId, ...(projection ? { projection } : {}),
291
292
  ...(pendingContinuation ? { continuation_before: pendingContinuation } : {}) },
292
293
  });
293
294
  pendingContinuation = undefined;
@@ -335,8 +336,9 @@ export const runGemini = async (context, writer) => {
335
336
  throw new BridgeError("Gemini returned an invalid or repeated function call ID.", "upstream_error", 502);
336
337
  ids.add(id);
337
338
  const call = prepareToolCall(tools, id, value.name, value.args ?? {});
338
- writeToolCall(writer, call);
339
+ writer.beginToolOutput();
339
340
  writer.endReasoning(carrier([part], { type: "function_call", call_id: call.call.call_id }));
341
+ writeToolCall(writer, call);
340
342
  calls++;
341
343
  }
342
344
  else if (typeof part.text === "string" || typeof part.thoughtSignature === "string") {
package/dist/history.d.ts CHANGED
@@ -8,4 +8,4 @@ export declare function rejectUnrecognizedState(input: ResponsesRequest["input"]
8
8
  export declare function replaysReasoning(carrier: StatePayload, route: ResolvedModel): boolean;
9
9
  export declare function restoresNativeCompaction(carrier: CompactionCarrier, route: ResolvedModel): boolean;
10
10
  /** Selects model-specific opaque state without changing the stored history. */
11
- export declare function prepareHistory(input: ResponsesRequest["input"], route: ResolvedModel): Record<string, any>[];
11
+ export declare function prepareHistory(input: ResponsesRequest["input"], route: ResolvedModel, beforeTools?: (items: Record<string, any>[]) => Record<string, any>[]): Record<string, any>[];
package/dist/history.js CHANGED
@@ -29,7 +29,7 @@ export function restoresNativeCompaction(carrier, route) {
29
29
  carrier.native.format === route.profile.native_compaction_format;
30
30
  }
31
31
  /** Selects model-specific opaque state without changing the stored history. */
32
- export function prepareHistory(input, route) {
32
+ export function prepareHistory(input, route, beforeTools) {
33
33
  if (typeof input === "string") {
34
34
  return [{ type: "message", role: "user", content: [{ type: "input_text", text: input }] }];
35
35
  }
@@ -42,7 +42,8 @@ export function prepareHistory(input, route) {
42
42
  let toolSegmentStart = 0;
43
43
  const finishToolSegment = () => {
44
44
  if (route.profile.api !== "responses") {
45
- result.push(...translateToolHistory(result.splice(toolSegmentStart)));
45
+ const segment = result.splice(toolSegmentStart);
46
+ result.push(...translateToolHistory(beforeTools ? beforeTools(segment) : segment));
46
47
  toolSegmentStart = result.length;
47
48
  }
48
49
  };
package/dist/writer.d.ts CHANGED
@@ -56,6 +56,8 @@ export declare class ResponseWriter {
56
56
  private send;
57
57
  private emit;
58
58
  private holdSuffix;
59
+ /** Hold native tool state together with the calls that depend on it. */
60
+ beginToolOutput(): void;
59
61
  private releaseSuffix;
60
62
  private discardSuffix;
61
63
  private responseObject;
package/dist/writer.js CHANGED
@@ -91,6 +91,11 @@ export class ResponseWriter {
91
91
  this.suffix = [];
92
92
  this.suffixOutputStart = this.output.length;
93
93
  }
94
+ /** Hold native tool state together with the calls that depend on it. */
95
+ beginToolOutput() {
96
+ this.flushPendingMessage("commentary");
97
+ this.holdSuffix();
98
+ }
94
99
  releaseSuffix() {
95
100
  const suffix = this.suffix;
96
101
  this.suffix = undefined;
@@ -52,7 +52,11 @@ Lite 的 `additional_tools` 按历史顺序合并,声明放入顶层 `tools.fu
52
52
 
53
53
  Gemini 的 thought signature 是原生 Part 上的 `thoughtSignature`,不等同于可见思考摘要。它可能附在文本或 `functionCall` 上,也可能单独出现在流末尾的空文本 part;同源续接需要保留它与原始 part 的关系。官方要求工具调用时返回签名,并且不能把带签名与不带签名的 part 随意合并。[Thought signatures](https://ai.google.dev/gemini-api/docs/generate-content/thought-signatures)
54
54
 
55
- 原生载荷保存为现有 `cxbr1:` reasoning carrier,格式为 `gemini.parts.v1`,data 保存原始 `parts`。正文或工具调用还记录对应的 Responses 投影标记:客户端仍看到正常文本和可执行调用,下一次同源请求恢复完整原生 parts 并替换紧邻的前一项投影,避免把文字或工具重复发送。签名不编码进 call ID;工具身份继续使用共用的调用转换与目标协议 ID 处理。原生末尾的空文本签名 part 也要保留。
55
+ 原生载荷保存为现有 `cxbr1:` reasoning carrier,格式为 `gemini.parts.v1`,data 保存原始 `parts`。正文或工具调用还记录对应的 Responses 投影标记:客户端仍看到正常文本和可执行调用,同源回放时恢复完整原生 parts 并替换对应投影,避免把文字或工具重复发送。工具按 `call_id` 关联,允许调用与载荷之间插入已有工具结果;名称、参数仍须匹配,重复或跨其他模型输出、用户指令、压缩边界的歧义关联会报错。正文投影继续在原位置核对可见文字。签名不编码进 call ID;原生末尾的空文本签名 part 也要保留。
56
+
57
+ 新载荷用可选的 `generation` 记录本次 Responses response ID。同一次生成中,历史实际保留的 parts 先组成 model Content,再发送已有工具结果和通知;不会把并行调用拆成多轮。恢复关联先于公共工具历史整理。没有该字段的旧载荷仍可读取:按旧工具签名规则,将首个带签名调用及后续无签名调用恢复为同一并行步骤,并保留空文本尾 Part;下一个带签名调用开始另一工具步骤。
58
+
59
+ 工具载荷在其可执行投影之前交付,二者都使用现有的成功后提交缓冲。这样客户端开始工具或 fork 时,已经保存对应的原生状态。快照只有载荷而没有工具项时,不凭载荷构造调用;快照只包含并行组的首个调用时,只恢复已继承的部分,不要求后续调用到齐,也不补造结果。此前 `call → aborted → carrier` 的旧顺序继续兼容。字段与封装保持向后读取兼容;回放新交付顺序需要更新后的 bridge,不依赖旧版的相邻项假设。
56
60
 
57
61
  其他模型转入的工具历史没有 Gemini 签名。适配器使用官方允许的 `skip_thought_signature_validator` 标记这一边界;它不补造 reasoning,也不是服务端返回的真实签名。可以恢复的同源载荷始终原样回放。[跨模型工具历史规则](https://ai.google.dev/gemini-api/docs/generate-content/thought-signatures)
58
62
 
@@ -84,4 +88,6 @@ Gemini 4 Argon 与 Carbon 的官方隐式缓存要求共享前缀至少 `4096` t
84
88
 
85
89
  2026-10-27 的真实原生请求通过 Vertex AI 路由验证两个模型的 `MEDIUM`、thought 摘要、末尾空文本签名、工具签名回放、图片与 JSON Schema;Flash 省略输出预算也能成功。该记录验证实际收到的原生协议,不等同于已直连 Google AI Developer API,也不证明所有区域、缓存条件或跨模型签名兼容。适配器自身另以合成数据测试转换与客户端交付。
86
90
 
87
- 2026-11-10 的 Carbon 条目按官方规格复用 Argon 的原生协议、Codex 模板和工作预算,覆盖目录与实际 npm 包的加载测试。Carbon 的真实模型推理尚待可用端点验证;该条目不宣称已经验证模型生成质量、签名或缓存命中率。
91
+ 2026-11-10 的 Carbon 条目按官方规格复用 Argon 的原生协议、Codex 模板和工作预算,覆盖目录与实际 npm 包的加载测试;当时真实端点尚未可用。
92
+
93
+ 2026-11-13 的真实原生验证确认 Argon、Carbon 均接受完整并行调用组、仅首个带签名调用及其结果、以及完整调用组的两个 `aborted` 结果;单独保留无签名的第二调用被拒绝。另在保留原始 Part 与签名的条件下,分别修改 system、工具说明/schema、先前消息、当前用户请求或删除较早对话,两模型均成功;删除或损坏当前轮签名则返回 400。这说明当前测试路由没有表现出阻断式前缀绑定,不证明任意历史改写都无损,也不能仅凭成功响应确认内部状态的使用方式。bridge 不增加移除签名后重试的策略。
package/docs/design.md CHANGED
@@ -54,7 +54,9 @@ Claude、DeepSeek 与 Gemini 从 GPT-6.1 Sol 模板开始,`shell_type` 沿用
54
54
 
55
55
  Gemini 使用 `streamGenerateContent`,不走 Chat 兼容层。`thoughtSignature` 绑定原始 part,工具和正文的可见输出仍由 Responses 交付,同源回放时再由 carrier 恢复对应的完整 part。这样签名可以随 codeks 会话、resume 和 fork 一起保存,不依赖运行中的 bridge 进程。
56
56
 
57
- 对比参考实现后保留这个选择:[Magpie 的磁盘签名存储](https://github.com/yetone/magpie/blob/e056779a67d2024a09aa25edad8a4373931a5b64/internal/gateway/gemini_sigstore.go)依赖本地文件及 call ID 引用,[CC Switch 的 session shadow](https://github.com/farion1231/cc-switch/blob/ee8ee25ebc63faa877e779f0831e29cf2b369604/src-tauri/src/proxy/providers/gemini_shadow.rs)依赖有限容量的内存会话。bridge 已有自包含的 `cxbr1:` 格式,无需增加另一份恢复状态,也不把签名塞进可能受长度限制的调用 ID。原生 JSON Schema 通道可以保留工具约束;不复制参考实现中的 schema 猜测、签名重排或缺少终止时的成功回退。协议细节和真实验证范围见 [Gemini adapter](backends-gemini.md)。
57
+ 2026-11-13 对照最新参考源码后保留这个选择:[Magpie 的原生 Gemini 路线](https://github.com/yetone/magpie/blob/71079b69f53ba2c1f4ce0b5b4c7f1f7f5c287cfc/internal/gateway/gemini_signature.go)通过 call ID 引用磁盘签名库,Responses 路线不保存文本签名;[CC Switch 的 Codex Chat 历史恢复](https://github.com/farion1231/cc-switch/blob/8c76bfe1e2628fe385b2c009020036d85510b01d/src-tauri/src/proxy/providers/codex_chat_history.rs)通过进程内缓存找回 Gemini Chat 工具签名,其 Gemini Native shadow 属于 Claude 客户端路线。值得采用的是按工具身份关联状态、先恢复再转换的原则。bridge 的 `cxbr1:` 可以随历史持久保存完整 Part,无需另建签名库或修改 call ID,也不采用签名失效后自动删除重试的方案。
58
+
59
+ Gemini 先在压缩检查点内按调用身份关联载荷,再整理工具历史。新载荷记录生成 ID,使 Codex 插入的 `aborted` 和异步通知不会拆散已观察到的原生并行组;旧载荷保留有限的签名结构兼容。载荷先于可执行工具项交付,未交付的投影不成为调用。子代理可以只继承首个调用,不必等待父响应的全部调用,也不改变 Codex 的快照或工具调度。原生 JSON Schema 和完整 Part 继续保留;协议细节和真实验证范围见 [Gemini adapter](backends-gemini.md)。
58
60
 
59
61
  ## 订阅鉴权复用文件登录
60
62
 
package/docs/reasoning.md CHANGED
@@ -42,6 +42,8 @@ JSON 的结构如下,示例指纹为占位值:
42
42
 
43
43
  Claude 的外层还可包含 `continuation_before: "Continue."`,记录生成该块前实际补入的 user 续接边界。它只用于响应首块为 thinking/redacted 的情况,原生 `data` 和签名不变,前缀仍为 `cxbr1:`。字段随载荷保存、筛选和恢复,不改变复用策略;具体时序与覆盖范围见 [Claude 故障续接](backends-anthropic.md#失配策略与故障续接)。
44
44
 
45
+ Gemini 的 `data.generation` 可选字段记录一次原生生成对应的 Responses response ID,用来恢复历史已保留的 Part 分组;旧载荷没有该字段仍可读取。工具投影按 `call_id` 关联,载荷在可执行项之前交付。只有载荷、没有投影的未提交工具不会被回放;实际签名、来源策略及 `gemini.parts.v1` 格式不变。[Gemini 历史恢复](backends-gemini.md#保留历史与压缩)
46
+
45
47
  codeks 会再次发送 `encrypted_content`,因此载荷可以跨请求、会话恢复、服务重启和子代理 fork 保留。只放在 reasoning 的可见 `content` 中不足以完成这种回放。
46
48
 
47
49
  ## 来源身份
package/docs/testing.md CHANGED
@@ -44,6 +44,10 @@ Claude 续接边界的回归同时检查生成和下一轮回放:首块 thinki
44
44
 
45
45
  `test/gemini.test.ts` 覆盖原生 parts 和签名绑定、并行同名调用、别名错误反馈、跨来源筛选、原位提醒、图片、根引用 schema、结构化输出及失败不释放工具。中间 `usageMetadata` 可以仅有非计数字段;最终快照在终止后验证,不逐 chunk 累加。`test/gemini-e2e.test.ts` 用真实客户端检查工具执行、载体持久化与跨进程 resume,摘要开关不影响签名保存。
46
46
 
47
+ `test/gemini-history.test.ts` 覆盖新旧载荷被 `aborted` 分隔、并行和顺序调用、原生生成内的通知、空尾 Part、Continue、来源过滤及压缩边界;逐个截断已提交项,检查前置载荷不会凭空产生工具调用。`test/gemini-fork-e2e.test.ts` 使用现成 codeks 和假上游,实际执行并行创建子代理与 Code Mode 调用,检查子代理继承的 `aborted`、原签名和分组,以及父代理的真实结果。子代理是否继承后续调用以实际快照为准,测试不强求完整响应快照。
48
+
49
+ 2026-11-13,真实 Codeks 0.167.1 通过上述 fork 场景,子代理没有重试,父代理成功取得两个工具的结果。另以 Argon、Carbon 的真实签名验证首调用子集和完整 `aborted` 并行组;缺少首签名的子集按预期被拒绝。候选 bridge 的 HTTP 验证共 10 例,包含两个原始失败历史,以及两模型的新旧载荷、完整并行组和首调用子集;全部首次成功,原始输入和原生 Parts 保持不变,返回的工具没有执行。真实原生验证与使用假上游的客户端执行验证分别成立,不以合成签名测试推断服务端验签。
50
+
47
51
  2026-10-27 通过 Vertex AI 路由对 Gemini 3.8 Flash / 4 Argon 做原生协议与真实 bridge HTTP 验证。原生 18 个请求中,15 个成功,3 个按预期拒绝无签名当前工具轮次或末尾 model;bridge 的 9 个成功请求覆盖两个模型的工具往返、签名回放、新用户轮次、图片与 JSON Schema,以及 Flash 的标准文字压缩。另一次上游 HTTP 502 原样报错;测试脚本后来重跑成功,bridge 没有自动重试。测试也发现并修复了中间 usage 缺计数导致过早拒绝的问题。
48
52
 
49
53
  这些结果不是 AI Developer API 直连、所有区域或跨模型签名兼容的证明;没有评估压缩质量或缓存命中率。公开测试使用合成签名和内容,真实端点、鉴权及原始响应保存在仓库外。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wacry/codeks-bridge",
3
- "version": "0.0.28",
3
+ "version": "0.0.29",
4
4
  "description": "Configurable local Responses API bridge for codeks with GPT, Claude Messages, DeepSeek Chat, and native Gemini adapters.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "David Zhang",