@wacry/codeks-bridge 0.0.15 → 0.0.16

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.
@@ -19,12 +19,9 @@ export function validateAdapterConfig(value, location, adapter) {
19
19
  if (!object(settings))
20
20
  fail(`${name} must be an object`);
21
21
  for (const field of Object.keys(settings)) {
22
- if (field !== "tool_updates" && field !== "thinking_mismatch")
22
+ if (field !== "thinking_mismatch")
23
23
  fail(`unknown ${name} setting ${field}`);
24
24
  }
25
- if (settings.tool_updates !== undefined && !["inline", "top_level"].includes(settings.tool_updates)) {
26
- fail(`${name}.tool_updates must be inline or top_level`);
27
- }
28
25
  if (settings.thinking_mismatch !== undefined && !["drop_block", "error", "upstream_default"].includes(settings.thinking_mismatch)) {
29
26
  fail(`${name}.thinking_mismatch must be drop_block, error, or upstream_default`);
30
27
  }
@@ -35,7 +32,6 @@ export function resolveClaudeOptions(route) {
35
32
  const upstream = route.upstream.adapters?.["claude-messages"];
36
33
  const model = route.config.adapters?.["claude-messages"];
37
34
  return {
38
- tool_updates: model?.tool_updates ?? upstream?.tool_updates ?? "inline",
39
35
  thinking_mismatch: model?.thinking_mismatch ?? upstream?.thinking_mismatch ?? "drop_block",
40
36
  };
41
37
  }
@@ -4,12 +4,10 @@ import { BridgeError, upstreamError } from "../errors.js";
4
4
  import { isOpaqueStateItem, prepareHistory } from "../history.js";
5
5
  import { reasoningEffort, reasoningSummaryRequested } from "../profiles.js";
6
6
  import { parseJsonSse } from "../sse.js";
7
- import { safeCallId } from "../tools.js";
7
+ import { buildToolSet, normalizeToolDeclarations, safeCallId } from "../tools.js";
8
8
  import { upstreamFetch } from "../upstream.js";
9
- import { buildAnthropicTools } from "./anthropic-tools.js";
10
9
  import { prepareToolCall, toolCallForReplay, toolResultForReplay, writeToolCall } from "../tool-calls.js";
11
10
  const THINKING_BINDING_BETA = "thinking-binding-controls-2026-08-01";
12
- const INLINE_TOOLS_BETA = "inline-tools-2026-09-15";
13
11
  function contentBlocks(content) {
14
12
  if (typeof content === "string")
15
13
  return content ? [{ type: "text", text: content }] : [];
@@ -69,53 +67,26 @@ function toolChoice(value, tools) {
69
67
  /** Convert only request-owned copies; stored history remains unchanged. */
70
68
  export function buildAnthropicRequest(context) {
71
69
  const { route } = context;
72
- const request = context.request;
70
+ const request = normalizeToolDeclarations(context.request);
73
71
  const settings = resolveClaudeOptions(route);
74
- const { tools, definitions, input } = buildAnthropicTools(request, settings.tool_updates);
72
+ const tools = buildToolSet(request.tools);
73
+ const definitions = tools.entries.map(tool => ({
74
+ name: tool.flatName, description: tool.description, input_schema: tool.parameters,
75
+ ...(tool.strict === undefined ? {} : { strict: tool.strict }),
76
+ }));
75
77
  const system = request.instructions ? [{ type: "text", text: request.instructions }] : [];
76
78
  const messages = [];
77
- let additions = [];
78
- let hasInlineTools = false;
79
- const continueAssistant = () => {
80
- const tail = messages.at(-1);
81
- if (tail?.role === "assistant" && !tail.content.some(block => block.type === "tool_use")) {
82
- const text = "Continue.";
83
- messages.push({ role: "user", content: [{ type: "text", text }] });
84
- return text;
85
- }
86
- };
87
- const flushAdditions = () => {
88
- if (!additions.length)
89
- return;
90
- // A persisted declaration also anchors this boundary on later replays.
91
- continueAssistant();
92
- if (messages.at(-1)?.role !== "user") {
93
- throw new BridgeError("Inline tool declarations require a user or completed tool-result boundary.");
94
- }
95
- messages.push({ role: "system", content: additions });
96
- additions = [];
97
- hasInlineTools = true;
98
- };
99
79
  const append = (role, blocks) => {
100
80
  if (!blocks.length)
101
81
  return;
102
- // Several reminders/results may share a user turn. Tool declarations take
103
- // effect after that complete boundary, before the next assistant step.
104
- if (role === "assistant")
105
- flushAdditions();
106
82
  const last = messages.at(-1);
107
83
  if (last?.role === role)
108
84
  last.content.push(...blocks);
109
85
  else
110
86
  messages.push({ role, content: blocks });
111
87
  };
112
- for (const item of prepareHistory(input, route)) {
113
- if (item.type === "additional_tools") {
114
- additions.push(...item.tools.map((definition) => ({
115
- type: "tool_addition", tool: { type: "tool_definition", definition },
116
- })));
117
- }
118
- else if (isOpaqueStateItem(item)) {
88
+ for (const item of prepareHistory(request.input, route)) {
89
+ if (isOpaqueStateItem(item)) {
119
90
  // Keep unknown state opaque. The endpoint decides whether it accepts it.
120
91
  append("assistant", [item]);
121
92
  }
@@ -153,9 +124,8 @@ export function buildAnthropicRequest(context) {
153
124
  throw new BridgeError("System messages must contain text.");
154
125
  if (!messages.length)
155
126
  system.push(...blocks);
156
- // Inline system roles have placement restrictions that arbitrary Responses
157
- // history cannot satisfy. Keep reminders in order without rewriting a
158
- // signed assistant prefix or moving new instructions to the beginning.
127
+ // Keep reminders in order without rewriting a signed assistant prefix
128
+ // or moving new instructions to the beginning.
159
129
  else
160
130
  append("user", [{ type: "text", text: `<system-reminder>\n${blocks.map((block) => block.text).join("\n\n")}\n</system-reminder>` }]);
161
131
  }
@@ -170,9 +140,11 @@ export function buildAnthropicRequest(context) {
170
140
  }
171
141
  // A failed response can leave a complete thinking/text item in codeks history.
172
142
  // Claude requires a user boundary to resume. Do not mask a missing tool result.
173
- // Pending declarations already persist their own continuation boundary.
174
- const continuationBefore = additions.length ? undefined : continueAssistant();
175
- flushAdditions();
143
+ const tail = messages.at(-1);
144
+ const continuationBefore = tail?.role === "assistant" && !tail.content.some(block => block.type === "tool_use")
145
+ ? "Continue." : undefined;
146
+ if (continuationBefore)
147
+ append("user", [{ type: "text", text: continuationBefore }]);
176
148
  // Keep stable prefixes at 1h. The one-off compaction suffix uses 5m.
177
149
  const cache = (block, ttl = "1h") => {
178
150
  if (block)
@@ -237,7 +209,7 @@ export function buildAnthropicRequest(context) {
237
209
  delete body.output_config.format;
238
210
  }
239
211
  }
240
- return { body, tools, betas: [THINKING_BINDING_BETA, ...(hasInlineTools ? [INLINE_TOOLS_BETA] : [])], continuationBefore };
212
+ return { body, tools, betas: [THINKING_BINDING_BETA], continuationBefore };
241
213
  }
242
214
  function tokenCount(value) {
243
215
  if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
@@ -3,6 +3,7 @@ import { BridgeError, ResponsesIncompleteError, responsesStreamError } from "../
3
3
  import { isOpaqueStateItem, prepareHistory } from "../history.js";
4
4
  import { reasoningEffort } from "../profiles.js";
5
5
  import { parseJsonSse } from "../sse.js";
6
+ import { toolItemForResponses } from "../tool-calls.js";
6
7
  import { upstreamFetch } from "../upstream.js";
7
8
  /** Replay complete content, never a server-side item reference. */
8
9
  export function responsesBody({ request, route, compacting }) {
@@ -20,7 +21,7 @@ export function responsesBody({ request, route, compacting }) {
20
21
  throw new BridgeError("Invalid Responses reasoning data.");
21
22
  return { type: "reasoning", summary: item.summary, encrypted_content: item.state.data };
22
23
  }
23
- return item;
24
+ return toolItemForResponses(item);
24
25
  });
25
26
  const body = {
26
27
  ...(route.profile.max_output_tokens ? { max_output_tokens: route.profile.max_output_tokens } : {}),
@@ -21,3 +21,5 @@ export declare function toolResultForReplay(item: Record<string, any>): {
21
21
  output: unknown;
22
22
  isError: boolean;
23
23
  };
24
+ /** Project tool history onto Responses without changing the client's stored identity. */
25
+ export declare function toolItemForResponses(item: Record<string, any>): Record<string, any>;
@@ -1,3 +1,4 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { BridgeError } from "./errors.js";
2
3
  // call_id survives codeks persistence and tool-result pairing. Keep only the
3
4
  // original wire identity and a diagnostic, never credentials or session state.
@@ -63,3 +64,20 @@ export function toolResultForReplay(item) {
63
64
  const wire = decode(item.call_id);
64
65
  return { id: wire?.id ?? item.call_id, output: wire?.error ?? item.output, isError: wire?.error !== undefined };
65
66
  }
67
+ /** Project tool history onto Responses without changing the client's stored identity. */
68
+ export function toolItemForResponses(item) {
69
+ if (!["function_call", "custom_tool_call", "function_call_output", "custom_tool_call_output"].includes(item.type) ||
70
+ typeof item.call_id !== "string")
71
+ return item;
72
+ const wire = item.type.endsWith("_output") ? decode(item.call_id) : undefined;
73
+ if (item.call_id.length <= 64 && wire?.error === undefined)
74
+ return item;
75
+ // Responses limits call_id to 64 characters. Hash the complete client id,
76
+ // not wire.id: distinct carriers can contain the same upstream id.
77
+ const call_id = item.call_id.length > 64
78
+ ? `call_${createHash("sha256").update(item.call_id).digest("base64url")}` : item.call_id;
79
+ const output = wire?.error !== undefined ? { output: wire.error } : {};
80
+ // Accepted aliases already have the correct Responses name/namespace/type.
81
+ // Failed calls retain their non-executable identity and actionable feedback.
82
+ return { ...item, call_id, ...output };
83
+ }
package/dist/tools.d.ts CHANGED
@@ -12,8 +12,6 @@ export interface ToolEntry {
12
12
  }
13
13
  export interface ToolSet {
14
14
  entries: ToolEntry[];
15
- /** Applies a declaration batch and returns detached snapshots of its definitions. */
16
- add(tools: unknown[]): ToolEntry[];
17
15
  /** Upstream name -> tool. */
18
16
  byFlat: Map<string, ToolEntry>;
19
17
  /** Upstream name for a call found in history. */
package/dist/tools.js CHANGED
@@ -118,7 +118,7 @@ export function buildToolSet(tools) {
118
118
  Object.assign(previous, entry);
119
119
  if (entry.strict === undefined)
120
120
  delete previous.strict;
121
- return previous;
121
+ return;
122
122
  }
123
123
  let flatName = baseFlatName(entry.namespace, entry.name);
124
124
  // Add a suffix only when two different tools would get the same name.
@@ -130,48 +130,38 @@ export function buildToolSet(tools) {
130
130
  entries.push(full);
131
131
  byFlat.set(flatName, full);
132
132
  byIdentity.set(id, full);
133
- return full;
134
133
  };
135
134
  const visit = (tool, namespace) => {
136
135
  if (!tool || typeof tool !== "object")
137
- return [];
136
+ return;
138
137
  if (tool.type === "function") {
139
- return [add({
140
- kind: "function",
141
- name: String(tool.name),
142
- namespace,
143
- description: String(tool.description ?? ""),
144
- parameters: objectSchema(tool.parameters),
145
- ...(typeof tool.strict === "boolean" ? { strict: tool.strict } : {}),
146
- })];
138
+ add({
139
+ kind: "function",
140
+ name: String(tool.name),
141
+ namespace,
142
+ description: String(tool.description ?? ""),
143
+ parameters: objectSchema(tool.parameters),
144
+ ...(typeof tool.strict === "boolean" ? { strict: tool.strict } : {}),
145
+ });
147
146
  }
148
147
  else if (tool.type === "custom") {
149
- return [add({
150
- kind: "custom",
151
- name: String(tool.name),
152
- namespace,
153
- description: customToolDescription(String(tool.description ?? ""), tool.format),
154
- parameters: CUSTOM_PARAMETERS,
155
- })];
148
+ add({
149
+ kind: "custom",
150
+ name: String(tool.name),
151
+ namespace,
152
+ description: customToolDescription(String(tool.description ?? ""), tool.format),
153
+ parameters: CUSTOM_PARAMETERS,
154
+ });
156
155
  }
157
156
  else if (tool.type === "namespace" && Array.isArray(tool.tools)) {
158
- return tool.tools.flatMap((inner) => visit(inner, String(tool.name)));
157
+ for (const inner of tool.tools)
158
+ visit(inner, String(tool.name));
159
159
  }
160
160
  // Hosted tools (web_search, image_generation, tool_search, ...) have no
161
161
  // equivalent on these upstreams and are left out.
162
- return [];
163
162
  };
164
- const addTools = (declarations) => {
165
- const changed = new Map();
166
- for (const declaration of declarations) {
167
- for (const entry of visit(declaration, undefined))
168
- changed.set(entry.flatName, entry);
169
- }
170
- // Later updates may mutate the registry's current definition. Earlier
171
- // inline definitions must retain the exact payload used at that point.
172
- return structuredClone([...changed.values()]);
173
- };
174
- addTools(tools ?? []);
163
+ for (const declaration of tools ?? [])
164
+ visit(declaration, undefined);
175
165
  const candidates = (name) => {
176
166
  const exact = byFlat.get(name);
177
167
  if (exact)
@@ -186,7 +176,6 @@ export function buildToolSet(tools) {
186
176
  };
187
177
  return {
188
178
  entries,
189
- add: addTools,
190
179
  byFlat,
191
180
  flatFor(namespace, name) {
192
181
  return byIdentity.get(identity(namespace, name))?.flatName ?? baseFlatName(namespace, name);
package/dist/types.d.ts CHANGED
@@ -4,7 +4,6 @@ export type Api = "responses" | "anthropic" | "chat";
4
4
  export type AdapterId = "gpt-responses" | "claude-messages" | "deepseek-chat";
5
5
  export type UnrecognizedStatePolicy = "passthrough" | "drop" | "error";
6
6
  export interface ClaudeMessagesOptions {
7
- tool_updates: "inline" | "top_level";
8
7
  thinking_mismatch: "drop_block" | "error" | "upstream_default";
9
8
  }
10
9
  /** Bridge behavior, distinct from native request-body options. */
@@ -44,9 +44,7 @@ Opus / Sonnet / Haiku 5.5 目录按用户选择设置默认上下文窗口 `4000
44
44
 
45
45
  流式响应可能已交付完整 thinking 或文字项,随后才过载或断流。codeks 保存这些已完成项并负责重试,因此重试历史可能以 assistant 结束。若最后的 assistant 不含 `tool_use`,bridge 在出站请求追加 user `Continue.`,提供合法续接边界;含工具调用时不补这一句,以免掩盖缺失工具结果。
46
46
 
47
- 若这个 assistant 后紧跟持久化的增量工具声明,同样在声明前补续接边界;后续回放时,声明的位置让 bridge 能重新构造相同边界,不需要另存隐藏会话状态。
48
-
49
- 对于没有增量工具声明锚定的尾部 `Continue.`,若本次响应的第一个原生内容块是 `thinking` 或 `redacted_thinking`,bridge 在该块的 `cxbr1:` 外层记录可选字段 `continuation_before`,值为实际补入的文本。原生 thinking、签名和隐藏数据保持不变;字段随原 reasoning item 的 `output_item.done` 进入 codeks 历史,不产生独立的控制项或用户消息。
47
+ 对于补入的尾部 `Continue.`,若本次响应的第一个原生内容块是 `thinking` 或 `redacted_thinking`,bridge 在该块的 `cxbr1:` 外层记录可选字段 `continuation_before`,值为实际补入的文本。原生 thinking、签名和隐藏数据保持不变;字段随原 reasoning item 的 `output_item.done` 进入 codeks 历史,不产生独立的控制项或用户消息。
50
48
 
51
49
  以后恢复这块 reasoning 时,先在同一位置补回记录的 user 文本。假设失败前已保存 T1,重试的首块为 T2:
52
50
 
@@ -58,11 +56,11 @@ Opus / Sonnet / Haiku 5.5 目录按用户选择设置默认上下文窗口 `4000
58
56
 
59
57
  这样 T2 不会仅因续接边界消失而失配。同一响应只标记首块,后续 thinking、正文和工具继续保持原顺序;如果 T2 完整交付后又发生故障,这个边界已随 T2 保存,下一次重试可恢复它并记录新的续接边界。首块尚未完整交付时没有新载荷,下次仍按已有历史重试。字段跟随 reasoning 的来源与格式筛选:本次不恢复该载荷时,也不恢复其中的边界;以后允许恢复时,两者一起生效。
60
58
 
61
- 覆盖范围按实际输出顺序决定。Adaptive thinking 不保证第一个内容块就是 thinking;若先输出正文或工具,再输出 thinking,bridge 不给后来的块添加这个字段,否则会把 `Continue.` 恢复到错误的位置。这类响应及没有字段的既有历史仍沿用当前失配策略;没有 thinking 的响应则没有新签名需要通过这个字段保护。由增量工具声明锚定的边界不重复记录。[官方 thinking 规则](https://platform.claude.com/docs/en/build-with-claude/thinking)
59
+ 覆盖范围按实际输出顺序决定。Adaptive thinking 不保证第一个内容块就是 thinking;若先输出正文或工具,再输出 thinking,bridge 不给后来的块添加这个字段,否则会把 `Continue.` 恢复到错误的位置。这类响应及没有字段的既有历史仍沿用当前失配策略;没有 thinking 的响应则没有新签名需要通过这个字段保护。[官方 thinking 规则](https://platform.claude.com/docs/en/build-with-claude/thinking)
62
60
 
63
61
  用户选择保留正常 thinking、正文的流式显示,并用少量自包含状态恢复边界。因此只记录位置确定的首块,不缓存整轮正文,也不引入会话索引、独立控制载荷或向前查找历史位置的规则。工具调用仍按现有规则等完整成功后交付。`continuation_before` 记录已发生的请求事实,不改变来源复用配置,也不替代 `thinking_mismatch`。
64
62
 
65
- 工具定义等其他前缀变化仍可能导致失配,未覆盖的续接次序也可能丢失 thinking。默认 `drop_block` 让服务端报告并丢弃失配块;`error` 或 `upstream_default` 下,服务端仍可能拒绝请求。丢失推理上下文可能影响质量或增加重新推理成本,不能把边界恢复视为所有签名和输入均可接受的保证。具体发生了什么以[检查器中的服务端报告](inspect.md#claude-服务端输入处理)为准。
63
+ 工具定义等其他前缀变化仍可能导致失配,未覆盖的续接次序也可能丢失 thinking。默认 `drop_block` 让服务端报告并丢弃失配块及可能依赖其前缀的后续 thinking;`error` 或 `upstream_default` 下,服务端仍可能拒绝请求。丢失推理上下文可能影响质量或增加重新推理成本,不能把边界恢复视为所有签名和输入均可接受的保证。具体发生了什么以[检查器中的服务端报告](inspect.md#claude-服务端输入处理)为准。
66
64
 
67
65
  一次失配不会令今后生成的 thinking 永久失效。后续请求保持前缀稳定时,新生成的块仍可正常复用;原始历史里的旧失配块可能在多轮请求中被重复报告,重复报告不代表每轮都丢弃新的 thinking。实际保留与丢弃以各次上游报告为准。
68
66
 
@@ -72,9 +70,7 @@ Responses `text.format: {type: "json_schema", schema: ...}` 转为 `output_confi
72
70
 
73
71
  namespace 和 custom tool 使用共享映射。自由文本工具转换成 `{input: string}`,Lark/regex 放入描述,返回时恢复原始字符串;不添加工具专属提示词。指定工具必须能在当前工具表中解析,`tool_choice: "required"` 转为原生 `any`,不会改成 `auto`。显式 `temperature`、`top_p` 也继续发送;这些参数与具体模型、thinking 的组合是否受支持由上游判断。静默删除参数或关闭 thinking 会改变用户请求,bridge 不做这类修正。
74
72
 
75
- 工具更新默认使用完整 inline 定义,保持已有顶部工具与历史前缀稳定;仅实际包含中途工具更新的请求添加 `inline-tools-2026-09-15` beta。初始声明、更新位置与兼容模式见 [Lite 工具声明](tools.md#lite-工具声明)。端点不支持时可在连接配置中显式选择 `tool_updates: "top_level"`;不会在错误后自动探测或降级。
76
-
77
- 从 `0.0.1` 的顶部合并方式切到默认 inline 时,已有增量声明历史会改变出站工具前缀,可能触发旧 thinking 丢弃或缓存重建;可显式设为 `top_level` 保持原工具策略。切换模式不改变状态来源身份,也不改写客户端保存的历史。
73
+ 工具定义由共享转换层按历史顺序合并到顶层 `tools`,同身份的新定义覆盖旧定义,其他成员保留。每个上游工具名只对应一份最终定义;详情与取舍见 [Lite 工具声明](tools.md#lite-工具声明)。
78
74
 
79
75
  有工具且未选择 `none` 时,显式 `parallel_tool_calls: false` 转为 `tool_choice.disable_parallel_tool_use: true`,显式 `true` 则转为 `false`;未指定 choice 时采用 `auto`,原生 options 仍可覆盖。这保留 Codex Lite 的外层工具调用限制,不限制一次 `exec` 内 JavaScript 的并发执行。[Claude 并行工具调用](https://platform.claude.com/docs/en/agents-and-tools/tool-use/parallel-tool-use)
80
76
 
@@ -84,7 +80,7 @@ namespace 和 custom tool 使用共享映射。自由文本工具转换成 `{inp
84
80
 
85
81
  ## 缓存与压缩
86
82
 
87
- 最多四个显式缓存断点:最后一个顶层工具、最后一段顶层 system、最近两条 user 消息的末块。普通请求 TTL 为 `1h`。压缩保留公共前缀的 `1h`,只将最后的摘要请求末块设为 `5m`,使长 TTL 位于短 TTL 之前。thinking 块不直接设置缓存断点。inline 模式不为新增定义重写顶部 tools;兼容模式修改顶部定义可能导致缓存未命中及 thinking 前缀失配,两者最终由上游判断。
83
+ 最多四个显式缓存断点:最后一个顶层工具、最后一段顶层 system、最近两条 user 消息的末块。普通请求 TTL 为 `1h`。压缩保留公共前缀的 `1h`,只将最后的摘要请求末块设为 `5m`,使长 TTL 位于短 TTL 之前。thinking 块不直接设置缓存断点。工具定义改变时,顶部 `tools` 会随之更新,可能导致缓存未命中及 thinking 前缀失配,实际结果由上游判断。
88
84
 
89
85
  压缩只生成文字摘要,保留工具定义及普通请求的工具选择,移除 `output_config.format`,其他参数保留。摘要封装为客户端 V2 compaction item,可供其他模型恢复。保留工具选择的缓存依据及意外工具调用的处理见 [压缩](compaction.md#工具选择与缓存)。
90
86
 
package/docs/config.md CHANGED
@@ -179,17 +179,16 @@ token 临近过期时自动续期并写回原文件;HTTP 401 可触发一次
179
179
 
180
180
  | 字段 | 值与默认行为 |
181
181
  | --- | --- |
182
- | `tool_updates` | 默认 `inline`,把中途工具声明转换为原生完整 `tool_addition`;兼容模式 `top_level` 将所有定义合并到顶部 |
183
182
  | `thinking_mismatch` | 默认 `drop_block`,请服务端丢弃前缀失配的 thinking;`error` 请求报错;`upstream_default` 不补充该策略 |
184
183
 
185
- 连接级设置适合端点差异,模型级设置适合同一连接下的模型差异。每个叶字段依次取模型设置、连接设置、adapter 默认值;模型只覆盖一个字段时,仍继承连接里的其他字段。下面的连接显式使用兼容工具模式,模型再单独调整 thinking 策略:
184
+ 连接级设置适合端点差异,模型级设置适合同一连接下的模型差异。每个叶字段依次取模型设置、连接设置、adapter 默认值;模型只覆盖一个字段时,仍继承连接里的其他字段。下面的连接显式使用默认失配策略,模型再单独选择报错:
186
185
 
187
186
  ```json
188
187
  {
189
188
  "upstreams": {
190
189
  "compatible": {
191
190
  "base_url": "https://example.com/v1",
192
- "adapters": { "claude-messages": { "tool_updates": "top_level" } }
191
+ "adapters": { "claude-messages": { "thinking_mismatch": "drop_block" } }
193
192
  }
194
193
  },
195
194
  "models": {
@@ -203,7 +202,7 @@ token 临近过期时自动续期并写回原文件;HTTP 401 可触发一次
203
202
 
204
203
  省略 `thinking_mismatch` 表示 bridge 默认的 `drop_block`,与显式 `upstream_default` 不同。对最终 `thinking.type` 为 `adaptive` 或 `enabled` 的请求,bridge 补充 `block_binding.prefix_mismatch_behavior`;原生 `options.thinking.block_binding` 中明确设置的同名值优先。`between_tools` 等不支持该字段的模式不补充策略,不擅自换 thinking 模式。`options` 本身仍按前述浅层规则合并,不进行通用递归合并。
205
204
 
206
- 专用设置不作为请求参数发给上游,不改变状态来源身份或客户端目录。共享连接可以配置供不同模型使用的 adapter;模型级只接受自身 adapter 的设置。未知命名空间、字段及枚举会报配置错误;尚无专用字段的 adapter 无需配置空对象。`inline` 需要上游支持相关协议,不兼容时直接返回错误,应在该连接显式选择 `top_level`。恢复代价及端点行为见 [Claude Messages](backends-anthropic.md#失配策略与故障续接)。
205
+ 专用设置不作为请求参数发给上游,不改变状态来源身份或客户端目录。共享连接可以配置供不同模型使用的 adapter;模型级只接受自身 adapter 的设置。未知命名空间、字段及枚举会报配置错误;尚无专用字段的 adapter 无需配置空对象。恢复代价及端点行为见 [Claude Messages](backends-anthropic.md#失配策略与故障续接)。
207
206
 
208
207
  ## Reasoning 与模型目录
209
208
 
package/docs/design.md CHANGED
@@ -22,7 +22,7 @@ flowchart LR
22
22
 
23
23
  优先匹配最新 Codex 的 GPT 默认行为,以 OpenAI 订阅、AWS 和 Azure 的使用场景为基准。当前模型条目使用 Responses Lite,现代条目保留 Code Mode Only 和多代理字段;GPT-5.5 显式启用 Lite,其余工具与多代理元数据仍跟随源条目。目录固定到已审阅的来源版本,不随用户本机二进制或订阅账号变化。
24
24
 
25
- Lite 仍调用 `/responses` 并返回 Responses SSE。完整工具 schema 位于历史中的 `additional_tools` 项,普通函数和 custom 工具归入默认 `functions` namespace。GPT 路径保留这些声明的位置、顺序、schema 和 grammar,并发送 `x-openai-internal-codex-responses-lite: true`。Claude 默认将初始声明放到顶部,增量声明转换为原生中途工具更新;DeepSeek 及 Claude 的显式兼容模式将各批定义合并到顶部。声明不会变成 user reminder。中途提醒保留所在对话位置;若插在一次完整的工具交换内,则移至该批结果之后,以满足目标协议的配对要求。
25
+ Lite 仍调用 `/responses` 并返回 Responses SSE。完整工具 schema 位于历史中的 `additional_tools` 项,普通函数和 custom 工具归入默认 `functions` namespace。GPT 路径保留这些声明的位置、顺序、schema 和 grammar,并发送 `x-openai-internal-codex-responses-lite: true`。Claude 与 DeepSeek 按历史顺序将各批定义合并到顶部,同 namespace 与工具名只保留最新定义,未变的其他成员保留。声明不会变成 user reminder。中途提醒保留所在对话位置;若插在一次完整的工具交换内,则移至该批结果之后,以满足目标协议的配对要求。
26
26
 
27
27
  已核对 Codex `0.163.0`:Lite 设置 `reasoning.context: "all_turns"` 和 `parallel_tool_calls: false`。bridge 保留客户端传入值,原生 options 仍可按配置覆盖普通参数。reasoning 的来源筛选与服务端 context 语义是两件事:前者决定发送哪些载荷,后者决定 GPT 如何使用它们。原生压缩与随后的复述保留源 Lite 工具声明及 transport 标记。
28
28
 
@@ -38,7 +38,7 @@ Lite 仍调用 `/responses` 并返回 Responses SSE。完整工具 schema 位于
38
38
 
39
39
  `models.catalog` 选择条目;`upstreams` 包含连接、鉴权及共用的 adapter 设置;别名和真实部署名独立。目录条目决定 adapter,实际模型名不参与方言推断。模型窗口、输入模态、effort 映射、状态复用范围、压缩模式及执行模型可由配置覆盖。
40
40
 
41
- 协议专用桥接行为放在 `adapters.<adapter ID>`,模型逐字段覆盖连接,再取对应 adapter 默认值;原生请求参数仍通过开放的 `options` 浅层合并。这样的边界让未来 GPT、Messages 或 Chat 方言可以添加各自确有需求的设置,而不用在连接顶层堆积特例,也不提前维护空的配置对象或通用插件框架。配置行为不改变来源身份和模型目录。当前 Claude 的工具更新方式与 thinking 失配策略分别配置,因为前者保持工具前缀,后者还影响故障续接等其他历史变化;见 [Adapter 专用行为](config.md#adapter-专用行为)。
41
+ 协议专用桥接行为放在 `adapters.<adapter ID>`,模型逐字段覆盖连接,再取对应 adapter 默认值;原生请求参数仍通过开放的 `options` 浅层合并。这样的边界让未来 GPT、Messages 或 Chat 方言可以添加各自确有需求的设置,而不用在连接顶层堆积特例,也不提前维护空的配置对象或通用插件框架。配置行为不改变来源身份和模型目录。Claude 的 thinking 失配策略通过这里配置,适用于工具定义变化、故障续接等引起的前缀差异;见 [Adapter 专用行为](config.md#adapter-专用行为)。
42
42
 
43
43
  `src/profiles.ts` 将目录与配置组合为运行时 profile,同时用于客户端目录和出站请求,避免界面显示一套 effort、实际发送另一套。未覆盖字段保留原模型差异,不能用一套通用默认值改写所有 GPT。来源身份继续取连接、adapter 与实际部署,不因提示词更新或窗口预设改变。
44
44
 
package/docs/testing.md CHANGED
@@ -15,7 +15,7 @@ npm run check
15
15
  ## 测试覆盖什么
16
16
 
17
17
  - 工具:普通函数、namespace、自定义工具的原始字符串、Lark/regex 描述、名称冲突与超长名称、加密 schema 关键字的清理。
18
- - Lite:工具声明原位传给 GPT;Claude/DeepSeek 提取增量 schema,保留原历史与默认 namespace 身份;header、all-turns 和原生压缩前缀保持。
18
+ - Lite:工具声明原位传给 GPT;Claude/DeepSeek 将增量 schema 按历史合并为唯一的最新顶层定义,保留其他成员、原历史与默认 namespace 身份;header、all-turns 和原生压缩前缀保持。
19
19
  - 流:跨字节分块的 UTF-8、CR/LF、SSE 多行数据、结束标记、非法 JSON。
20
20
  - Responses 输出:先 added 后 delta/done、完整历史项、usage、reasoning carrier、原生消息 phase(含 `partial_answer`)、缺省 phase 与 `end_turn` 的关系、摘要分段索引和最终数组一致、明文多代理参数、失败时不执行尚未提交的工具。
21
21
  - 配置与目录:有限 key、原始 GPT 条目保留、第三方精调、别名与部署名分离、窗口覆盖、effort 映射及默认值、catalog 与出站参数一致、options 覆盖顺序。
@@ -34,7 +34,7 @@ npm run check
34
34
 
35
35
  压缩后的信息保留与 handoff 质量另有[手动 benchmark](../benchmarks/compaction/README.md):使用公开合成材料,对比两种文字 prompt、原生压缩和原生压缩后 handoff。它独立于 CI,提供复跑方法、输入、产物和逐题结果;真实模型请求需要显式执行。
36
36
 
37
- Claude 续接边界的回归同时检查生成和下一轮回放:首块 thinking/redacted 的 `continuation_before` 只记录一次,原生载荷不变;连续失败、多个 thinking、关闭摘要显示时仍保持顺序;来源过滤与切回按同一载荷生效;增量工具声明已有边界时不重复插入。正文或工具先于 thinking、没有 thinking,以及没有该字段的既有载荷,继续使用原有失配策略。`test/claude-continuation.test.ts` 检查转换,`test/claude-recovery-e2e.test.ts` 使用真实 codeks 和假上游检查持久化与重试;签名是否被真实上游接受须另行验证,不能由合成签名测试推断。
37
+ Claude 续接边界的回归同时检查生成和下一轮回放:首块 thinking/redacted 的 `continuation_before` 只记录一次,原生载荷不变;连续失败、多个 thinking、关闭摘要显示时仍保持顺序;来源过滤与切回按同一载荷生效。正文或工具先于 thinking、没有 thinking,以及没有该字段的既有载荷,继续使用原有失配策略。`test/claude-continuation.test.ts` 检查转换,`test/claude-recovery-e2e.test.ts` 使用真实 codeks 和假上游检查持久化与重试;签名是否被真实上游接受须另行验证,不能由合成签名测试推断。
38
38
 
39
39
  2026-10-20(America/Los_Angeles),以 `@wacry/codeks@0.163.0-codeks.5` 启用全部客户端测试,286 项通过、0 跳过,类型检查、构建和私有内容检查通过。续接场景覆盖 overload、EOF、连续两次失败及进程重启后的 resume。另复用真实 T1/T2 签名直接请求官方 Sonnet 5.5:恢复原位 `user: Continue.` 后返回 HTTP 200,`input_transformations` 明确为空数组。这验证边界恢复的协议依据;carrier 的生成、保存与重放由真实客户端加本地假上游验证,两类证据分别成立。
40
40
 
@@ -119,6 +119,16 @@ TypeScript 检查和普通测试通过,客户端场景各在两个现成二进
119
119
 
120
120
  真实验证应区分:单次请求、工具回环、图片、切换模型后 reasoning 隔离、压缩后续接。原生压缩模式还需要检查同源续聊没有辅助请求,跨目标首次导出与缓存复用行为正确,文字准备完成后才发送目标请求。未允许的端点或模型使用可读摘要,允许来源且目标开启 native replay 时恢复原生压缩内容;分别测允许与不允许的配对。某一服务上的成功不代表另一服务也支持同样的字段。
121
121
 
122
+ ### 跨模型工具历史
123
+
124
+ 2026-10-26(America/Los_Angeles),用公开合成历史验证 GPT-6-Luna、官方 Claude Haiku 5.5 与 DeepSeek Flash,均使用 medium effort;Claude 探测将缓存 TTL 设为 5 分钟。每次模型切换都追加新版本的 `exec` 描述,历史同时包含别名调用和失败调用的 `cxbt1_` 载体。
125
+
126
+ - Claude 的同名工具只发送最后一份顶层定义。真实 thinking 生成后改变工具定义,下一次请求仍返回 HTTP 200,并明确报告 `thinking_dropped`、原因 `prefix_binding_mismatch`。这是接受顶层更新的实际代价,不是推理上下文无损的保证。
127
+ - Claude → DeepSeek → GPT → Claude 连续请求全部成功。GPT 的两组调用与结果 ID 均为 48 字符;切回后仍可按原载体回放,客户端输入未被改写。另一次 GPT 探测确认失败调用的保留身份与诊断可被接受。
128
+ - `test/tool-alias-e2e.test.ts` 用真实 codeks 0.164 与本地假上游,分别验证 Claude、DeepSeek 的工具执行与持久化、切到 GPT 两轮、再切回。实际客户端生成了不同版本的 `exec` 声明,转换后的工具表仅含最新定义,同时覆盖 call/result 配对与稳定 ID。
129
+
130
+ 真实端点测试验证请求被接受及服务端报告;工具执行和进程重启后的恢复由客户端集成测试验证。合成签名不用于推断真实签名兼容性,短请求也不用于推断通常的缓存命中率。
131
+
122
132
  ### 缓存实验的边界
123
133
 
124
134
  2026-10-19(America/Los_Angeles),透传及压缩工具选择修改通过类型检查、构建和私有内容检查;普通测试 222 项通过,20 项需显式启用的真实客户端测试跳过。HTTP 假上游覆盖三种 adapter 的未知 header、鉴权覆盖、SSE/JSON、错误诊断、handoff metadata 透传,以及意外工具调用不交付、不执行、不自动重试。上述自动化测试未调用真实模型,不据此声明缓存命中率。OpenAI 订阅端点的 state 实测依据及适用范围另见 [header 边界](responses-stream.md#header-与转发边界)。
package/docs/tools.md CHANGED
@@ -4,20 +4,13 @@
4
4
 
5
5
  ## Lite 工具声明
6
6
 
7
- 客户端默认把完整工具 schema 放在 `input[].additional_tools`。GPT 保留原始声明项。DeepSeek 及 Claude 的 `top_level` 模式在转换消息前提取声明,与顶层 `tools` 按历史顺序合并;Claude 默认 `inline` 模式保留增量定义生效的位置。声明不会变成普通 reminder。
7
+ 客户端默认把完整工具 schema 放在 `input[].additional_tools`。GPT 保留原始声明项。Claude 与 DeepSeek 在转换消息前提取声明,与顶层 `tools` 按历史顺序合并,最终只向上游发送一张顶层工具表。声明不会变成普通 reminder,客户端保存的历史不变。
8
8
 
9
- 增量声明只包含新增或变更的成员,按 namespace 与工具名覆盖旧定义,保留未变的其他成员和已分配的上游名字。工具移除的 developer 通知保留原位置,不从提示词文字推断删工具。codeks 将默认 `functions` namespace、空 namespace 和省略 namespace 视为同一身份,因此历史调用和显式工具选择均按此规则查找;返回调用保留声明中的原 namespace。
9
+ 增量声明只包含新增或变更的成员,按 namespace 与工具名覆盖旧定义,保留未变的其他成员和已分配的上游名字。每个工具身份最终只有一份定义;反复切换模型产生的同名版本也只保留最后一份。工具移除的 developer 通知保留原位置,不从提示词文字推断删工具。codeks 将默认 `functions` namespace、空 namespace 和省略 namespace 视为同一身份,因此历史调用和显式工具选择均按此规则查找;返回调用保留声明中的原 namespace。
10
10
 
11
- Claude 的 `adapters.claude-messages.tool_updates` 有两种明确模式:
11
+ 选择合并顶层定义,是为了让会话中的同名更新具有确定的替换语义,而不是同时声明多个不同版本。Code Mode Only 下多数工具位于 `exec` 内的目录,外层工具变化较少;但模型切换仍可能改变 `exec` 的描述,例如 `supports_image_detail_original` 决定嵌套 `view_image` 是否提供 `detail` 参数。此时同名工具必须使用最新定义。
12
12
 
13
- | 模式 | 初始定义 | 中途新增与同名更新 |
14
- | --- | --- | --- |
15
- | `inline`(默认) | 顶层 `tools` 及会话开始前的声明组成原生顶部工具表 | 在原生中途 system 消息中发送 `tool_addition`,携带完整 `tool_definition`;此前定义不变 |
16
- | `top_level` | 各批定义累积成同一顶部工具表 | 用最新定义覆盖同身份工具,适用于尚未支持完整 inline 的端点 |
17
-
18
- 完整 inline 定义能同时表达新工具和同名工具更新,避免为了更新定义重写早先的工具前缀;这是选择它作为默认方式的理由。bridge 在 user 或整批工具结果之后、下一条 assistant 之前发送中途 system 工具声明;工具交换内的声明先等待结果完整,无法形成合法边界则报错。普通 system/developer 提醒仍转为原位 user reminder,不因工具使用原生中途 system 而改变角色。
19
-
20
- 端点需要支持 `inline-tools-2026-09-15` beta;bridge 在请求包含中途更新时自动追加,保留已有 beta。不兼容时直接交付错误,不自动切换模式。`top_level` 可能改变缓存前缀和旧 thinking 的绑定;失配处理由独立的 [thinking 策略](backends-anthropic.md#失配策略与故障续接)决定。Code Mode Only 下多数工具位于 `exec` 内的目录,因此外层更新较少,但仍按协议完整处理。
13
+ 代价是定义变化时,顶层工具前缀也随之变化,可能导致缓存未命中及 Claude 旧 thinking 绑定失配。默认 `drop_block` 请服务端处理失配,可能丢弃失配块及依赖其前缀的后续 thinking,并不保证推理上下文无损。具体行为与诊断见 [thinking 策略](backends-anthropic.md#失配策略与故障续接)。普通 system/developer 提醒仍在原位置转换成 user reminder。
21
14
 
22
15
  ## 工具发现与网页搜索
23
16
 
@@ -31,12 +24,18 @@ Claude 的 `adapters.claude-messages.tool_updates` 有两种明确模式:
31
24
 
32
25
  Messages/Chat 返回的调用还接受完整的 `namespace.name` 和唯一的原始短名。例如 `functions__exec`、`functions.exec`、`exec` 都可定位同一个工具;`agents`、`clock` 及其他 namespace 使用相同规则。省略 namespace 的默认工具也接受 `functions.name` 和 `functions__name`。精确声明名优先;其他别名只有唯一对应工具时才成功,不猜后缀或拼写。exec 内的 JavaScript 原样传递,其中 `tools.*` 的解析仍由客户端负责。
33
26
 
34
- 这一选择来自实际模型会省略声明名前缀,而提示词仍用 `functions.exec` 等原始身份。保留声明、增加确定性别名,可以修复调用而不重写工具表和 Claude 的签名前缀。GPT Responses 保留原生工具协议,不使用这层转换。
27
+ 这一选择来自实际模型会省略声明名前缀,而提示词仍用 `functions.exec` 等原始身份。保留声明、增加确定性别名,可以修复调用而不重写工具表和 Claude 的签名前缀。GPT 返回的调用保留原生工具协议,不做这种别名匹配;切换到 GPT 时,来自其他 adapter 的历史载体仍需转换为 Responses 可接受的表示。
35
28
 
36
29
  歧义或未知调用通过普通工具错误反馈,提示可用的完整声明名。例如两个 namespace 都有 `read` 时,提示 `files__read`、`database__read`,让模型下一次明确选择。bridge 不擅自执行其中一个,也不把这类错误变成网络重试。它将失败调用交给客户端不存在的保留身份 `codeks_bridge_tool_error.invalid_call`,客户端记录普通未知工具结果;后续发包恢复原始调用并将该结果替换为保存的候选诊断。真实缺失 id、损坏 JSON 或 custom 输入仍是协议错误。
37
30
 
38
31
  只有接受了别名或需要反馈的调用才将原始上游 id、名字和可选诊断编码为 `cxbt1_` call ID。客户端照常保存该 id 并配对结果,bridge 在 Messages/Chat 回放时恢复原始 id 和名字,避免把模型生成的 `exec` 悄悄改成 `functions__exec` 而改变签名前缀;诊断也随历史固定,不随以后工具表变化。载体不含参数、凭据或完整会话,不需要额外状态文件。检查器可查看原始上游调用、客户端失败身份与下一次上游收到的诊断。
39
32
 
33
+ Responses 的 `call_id` 最长 64 字符,`cxbt1_` 载体可能超过这个限制。GPT 出站时,对超过 64 字符的工具 ID(包括载体和其他上游的原始 ID),使用完整客户端 ID 的 SHA-256 生成固定 48 字符的 `call_`+base64url 摘要;function/custom 调用及对应结果使用同一映射。64 字符以内的 ID(包括短载体)保留原值,减少对已被 GPT 接受的历史前缀的改动;无 ID 的主动通知不生成 ID。映射不依赖调用位置、模型别名或内存状态,因此恢复会话、重试及后续 turn 都保持一致。
34
+
35
+ 不直接用载体内的原始 ID,是因为它本身可能超长,两个不同载体也可能包含同一个原始 ID;不直接截断或去除空白,以免合并不同调用。GPT 历史保留客户端已确定的工具类型、name、namespace、参数及正常结果,失败结果使用载体保存的原诊断。转换仅作用于请求副本:旧会话无需迁移,切回 Messages/Chat 仍能恢复原始调用。普通请求、原生压缩、文字压缩和 handoff 共用这条出站路径。
36
+
37
+ 这种无状态的目标协议边界处理也见于 [Magpie 的 `BoundCallID`](https://github.com/yetone/magpie/blob/11c3fbb197f17403183bdae424327aa0de7f0558/internal/provider/codex_request.go#L368)。这里额外保留 bridge 的载体诊断和规范化工具身份。回归覆盖真实 codeks 的 DeepSeek/Claude → GPT → 原模型切换;另用合成历史实测 GPT‑6‑Luna / medium,280、73、90 字符 ID 转换后均为 48 字符,未声明的失败工具身份及诊断可正常回放。该实测验证协议接受性,不评估模型质量。
38
+
40
39
  共享转换层将 Messages/Chat 工具名统一限制为 64 字符,沿用 Chat 端点的较小限制,不为不同后端维护两套命名规则;这不表示所有端点的原生上限都是 64。超长名称保留 55 字符可读前缀,加 `_` 与 8 位摘要,以区别同前缀工具。正常长度不加 hash。历史名称根据当前工具集映射,因此同一次工具调用的名称不依赖模型临时起名。
41
40
 
42
41
  ## 自由文本与语法
@@ -57,7 +56,7 @@ Messages 对不符合端点格式的 call ID 采用确定性映射,并添加
57
56
 
58
57
  根 schema 的 `$ref`、`$defs`、`allOf`、`anyOf`、`oneOf` 及其他约束均保留;缺少根 `type` 时补为 `object`,已有类型不覆盖,由上游判断是否支持。codeks 可以发送没有根 `type` 的引用或组合 schema,不能因此把参数清空。未提供参数 schema 时使用空对象定义;显式提供非对象 schema 值则报错,不在 bridge 内解析引用或删减约束。
59
58
 
60
- 普通函数显式给出的 `strict: true` 或 `strict: false` 原样保留:Messages 放在工具定义顶层,Chat 放在 `function` 内;省略时不添加默认值。Lite 同名更新替换完整定义,因此新定义省略 `strict` 时也不继承旧值;Claude inline 的早先版本保持不变。custom 工具的 JSON 外壳不因此自动启用 strict。
59
+ 普通函数显式给出的 `strict: true` 或 `strict: false` 原样保留:Messages 放在工具定义顶层,Chat 放在 `function` 内;省略时不添加默认值。Lite 同名更新替换完整定义,因此新定义省略 `strict` 时也不继承旧值。custom 工具的 JSON 外壳不因此自动启用 strict。
61
60
 
62
61
  [Claude strict tool use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/strict-tool-use) 与 [DeepSeek strict mode](https://api-docs.deepseek.com/guides/tool_calls/#strict-mode-beta) 各有支持的 schema 范围;DeepSeek 官方文档还要求 beta 端点及所有函数都设为 `strict: true`。bridge 只转换调用方明确提供的字段,不切换端点、不改其他工具或删减 schema 来满足 strict。需要该能力时由用户配置支持的端点,上游不接受则保留错误。
63
62
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wacry/codeks-bridge",
3
- "version": "0.0.15",
3
+ "version": "0.0.16",
4
4
  "description": "Configurable local Responses API bridge for codeks with GPT, Claude Messages, and DeepSeek Chat adapters.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "David Zhang",
@@ -1,14 +0,0 @@
1
- import { type ToolSet } from "../tools.ts";
2
- import type { ResponsesRequest } from "../types.ts";
3
- export interface AnthropicToolDefinition {
4
- name: string;
5
- description: string;
6
- input_schema: Record<string, unknown>;
7
- strict?: boolean;
8
- }
9
- /** Keep later definitions at their original conversation boundary. */
10
- export declare function buildAnthropicTools(request: ResponsesRequest, mode: "inline" | "top_level"): {
11
- tools: ToolSet;
12
- definitions: AnthropicToolDefinition[];
13
- input: ResponsesRequest["input"];
14
- };
@@ -1,44 +0,0 @@
1
- import { BridgeError } from "../errors.js";
2
- import { buildToolSet, normalizeToolDeclarations } from "../tools.js";
3
- function definition(tool) {
4
- return {
5
- name: tool.flatName, description: tool.description, input_schema: tool.parameters,
6
- ...(tool.strict === undefined ? {} : { strict: tool.strict }),
7
- };
8
- }
9
- /** Keep later definitions at their original conversation boundary. */
10
- export function buildAnthropicTools(request, mode) {
11
- if (mode === "top_level") {
12
- const normalized = normalizeToolDeclarations(request);
13
- const tools = buildToolSet(normalized.tools);
14
- return { tools, definitions: tools.entries.map(definition), input: normalized.input };
15
- }
16
- const tools = buildToolSet(request.tools);
17
- const initial = new Map(tools.entries.map((tool) => [tool.flatName, definition(tool)]));
18
- if (!Array.isArray(request.input)) {
19
- return { tools, definitions: [...initial.values()], input: request.input };
20
- }
21
- const input = [];
22
- let prefix = true;
23
- for (const item of request.input) {
24
- if (item?.type === "additional_tools") {
25
- if (!Array.isArray(item.tools))
26
- throw new BridgeError("additional_tools requires a tools array.");
27
- const definitions = tools.add(item.tools).map(definition);
28
- if (prefix) {
29
- for (const tool of definitions)
30
- initial.set(tool.name, tool);
31
- }
32
- else if (definitions.length) {
33
- input.push({ ...item, tools: definitions });
34
- }
35
- }
36
- else {
37
- input.push(item);
38
- if (!item || !["system", "developer"].includes(item.role) ||
39
- (item.type !== undefined && item.type !== "message"))
40
- prefix = false;
41
- }
42
- }
43
- return { tools, definitions: [...initial.values()], input };
44
- }