Skip to content

Commit 6bede37

Browse files
olddonkeyclaude
andcommitted
fix(responses): make namespace dedup order-independent and restore custom calls by wire identity
Review found two defects in the flattening layer; both are fixed here. Deduplication depended on declaration order. A bare declaration and a `functions` child of the same name are one logical tool, but which one owned the wire name — and therefore which one was emitted — followed whichever container the rewrite reached first. The plan now records the bare wire names from the complete catalog and the bare declaration always wins, so the same catalog flattens identically whichever container declares it. Custom-call restoration used the wrong coordinate. A custom tool inside a non-`functions` namespace is lowered twice on the way out (custom to function, then renamed to `<ns>__<name>`), while on the way back namespace restore runs first and replaces the wire name with the bare one. Custom restore then matched that bare name and could convert an unrelated same-named function call, sending Codex a `custom_tool_call` with the wrong payload shape. Converted custom tools are now tracked by their final upstream wire name, and restoration reconstructs that identity from the `{namespace, name}` an earlier rewrite restored. A namespaced custom and a namespaced function sharing a child name now round-trip to their own item types, on both the JSON and SSE paths. Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent bf84d17 commit 6bede37

7 files changed

Lines changed: 320 additions & 12 deletions

File tree

‎src/adapters/base.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ export interface AdapterRequest {
6868
method: string;
6969
headers: Record<string, string>;
7070
body: string;
71-
/** Custom-tool names actually lowered to upstream function calls while building this request. */
71+
/** Final upstream wire names of custom tools lowered to functions while building this request. */
7272
convertedRoutedCustomToolNames?: ReadonlySet<string>;
7373
/** Client tool-search names actually lowered to upstream function calls for this request. */
7474
convertedRoutedToolSearchNames?: ReadonlySet<string>;

‎src/responses/custom-tool-compat.ts‎

Lines changed: 70 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1+
import { namespacedToolName } from "../types";
2+
import { collectResponsesToolGroups } from "./tool-groups";
3+
14
const ROUTED_CUSTOM_TOOL_PASSTHROUGH = new Set(["apply_patch"]);
5+
const BUILTIN_FUNCTIONS_NAMESPACE = "functions";
26

37
function isPlainObject(value: unknown): value is Record<string, unknown> {
48
return !!value && typeof value === "object" && !Array.isArray(value);
@@ -13,6 +17,65 @@ function customToolInput(argumentsText: unknown): string {
1317
return argumentsText;
1418
}
1519

20+
function customToolWireName(namespace: string | undefined, name: string): string {
21+
return namespace === BUILTIN_FUNCTIONS_NAMESPACE ? name : namespacedToolName(namespace, name);
22+
}
23+
24+
/** Final upstream identity of a call, including a namespace restored by an earlier rewrite. */
25+
export function routedCustomToolWireName(value: unknown): string | undefined {
26+
if (!isPlainObject(value) || typeof value.name !== "string") return undefined;
27+
return customToolWireName(
28+
typeof value.namespace === "string" ? value.namespace : undefined,
29+
value.name,
30+
);
31+
}
32+
33+
/**
34+
* Names of converted custom declarations after namespace lowering. Restoration uses these exact
35+
* wire identities so same-named function and custom children in different namespaces stay distinct.
36+
*/
37+
function collectRoutedCustomToolWireNames(body: unknown): Set<string> {
38+
const names = new Set<string>();
39+
const groups = collectResponsesToolGroups(body);
40+
const bareWireNames = new Set<string>();
41+
for (const group of groups) {
42+
for (const tool of group) {
43+
if (
44+
isPlainObject(tool)
45+
&& tool.type !== "namespace"
46+
&& typeof tool.name === "string"
47+
) bareWireNames.add(tool.name);
48+
}
49+
}
50+
51+
for (const group of groups) {
52+
for (const tool of group) {
53+
if (!isPlainObject(tool)) continue;
54+
if (
55+
tool.type === "custom"
56+
&& typeof tool.name === "string"
57+
&& !ROUTED_CUSTOM_TOOL_PASSTHROUGH.has(tool.name)
58+
) {
59+
names.add(tool.name);
60+
continue;
61+
}
62+
if (tool.type !== "namespace" || typeof tool.name !== "string" || !Array.isArray(tool.tools)) {
63+
continue;
64+
}
65+
for (const child of tool.tools) {
66+
if (
67+
isPlainObject(child)
68+
&& child.type === "custom"
69+
&& typeof child.name === "string"
70+
&& !ROUTED_CUSTOM_TOOL_PASSTHROUGH.has(child.name)
71+
&& !(tool.name === BUILTIN_FUNCTIONS_NAMESPACE && bareWireNames.has(child.name))
72+
) names.add(customToolWireName(tool.name, child.name));
73+
}
74+
}
75+
}
76+
return names;
77+
}
78+
1679
export function customToolItemId(id: unknown): unknown {
1780
if (typeof id !== "string") return id;
1881
return id.startsWith("fc_") ? `ctc_${id.slice(3)}` : id;
@@ -125,11 +188,12 @@ export function rewriteRoutedCustomToolsForUpstream(body: unknown): {
125188
body: unknown;
126189
names: Set<string>;
127190
} {
128-
const names = collectRoutedCustomToolNames(body);
129-
if (names.size === 0) return { body, names };
191+
const conversionNames = collectRoutedCustomToolNames(body);
192+
const names = collectRoutedCustomToolWireNames(body);
193+
if (conversionNames.size === 0) return { body, names };
130194
const callIds = new Set<string>();
131-
collectConvertedCallIds(body, names, callIds);
132-
return { body: rewriteForUpstream(body, names, callIds), names };
195+
collectConvertedCallIds(body, conversionNames, callIds);
196+
return { body: rewriteForUpstream(body, conversionNames, callIds), names };
133197
}
134198

135199
export function restoreRoutedCustomCalls(
@@ -155,7 +219,8 @@ export function restoreRoutedCustomCalls(
155219
changed ||= result.changed;
156220
}
157221

158-
if (value.type === "function_call" && typeof value.name === "string" && names.has(value.name)) {
222+
const wireName = routedCustomToolWireName(value);
223+
if (value.type === "function_call" && wireName !== undefined && names.has(wireName)) {
159224
restored.type = "custom_tool_call";
160225
restored.id = customToolItemId(value.id);
161226
restored.input = customToolInput(value.arguments);

‎src/responses/namespace-tool-compat.ts‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ function addSelector(
9090

9191
type NamespaceRewritePlan = {
9292
aliases: Map<string, RoutedNamespaceToolIdentity>;
93+
bareWireNames: Set<string>;
9394
identities: Map<string, string>;
9495
selectors: Map<string, string | null>;
9596
};
@@ -99,6 +100,7 @@ export class NamespaceToolCollisionError extends Error {}
99100

100101
function buildRewritePlan(groups: readonly unknown[][]): NamespaceRewritePlan {
101102
const aliases = new Map<string, RoutedNamespaceToolIdentity>();
103+
const bareWireNames = new Set<string>();
102104
const identities = new Map<string, string>();
103105
const selectors = new Map<string, string | null>();
104106
const wireOwners = new Map<string, string>();
@@ -110,6 +112,7 @@ function buildRewritePlan(groups: readonly unknown[][]): NamespaceRewritePlan {
110112
// declaring the same tool both ways is the duplicate the parser already tolerates, not a
111113
// collision, and `promoteClientLoadedTools` produces exactly that shape.
112114
wireOwners.set(tool.name, loweredIdentity(BUILTIN_FUNCTIONS_NAMESPACE, tool.name));
115+
bareWireNames.add(tool.name);
113116
addSelector(selectors, tool.name, tool.name);
114117
}
115118
}
@@ -141,7 +144,7 @@ function buildRewritePlan(groups: readonly unknown[][]): NamespaceRewritePlan {
141144
}
142145
}
143146

144-
return { aliases, identities, selectors };
147+
return { aliases, bareWireNames, identities, selectors };
145148
}
146149

147150
/**
@@ -165,13 +168,25 @@ function rewriteToolList(
165168
if (!parsed) continue;
166169
for (const child of parsed.children) {
167170
const wireName = plan.identities.get(loweredIdentity(parsed.namespace, child.name as string));
168-
if (wireName === undefined || emitted.has(wireName)) continue;
171+
// A bare declaration is the canonical representation of a `functions` child. Decide that
172+
// from the complete catalog rather than whichever container happens to be rewritten first.
173+
if (
174+
wireName === undefined
175+
|| (parsed.namespace === BUILTIN_FUNCTIONS_NAMESPACE && plan.bareWireNames.has(wireName))
176+
|| emitted.has(wireName)
177+
) continue;
169178
emitted.add(wireName);
170179
rewritten.push(wireName === child.name ? child : { ...child, name: wireName });
171180
}
172181
continue;
173182
}
174-
if (isPlainObject(tool) && isRepresentableName(tool.name)) emitted.add(tool.name);
183+
if (isPlainObject(tool) && isRepresentableName(tool.name)) {
184+
if (emitted.has(tool.name)) {
185+
changed = true;
186+
continue;
187+
}
188+
emitted.add(tool.name);
189+
}
175190
rewritten.push(tool);
176191
}
177192
return changed ? rewritten : tools;

‎src/server/responses-custom-tool-repair.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import type { TranslatorBudget } from "../lib/translator-budget";
22
import {
33
customToolItemId,
44
restoreRoutedCustomCalls,
5+
routedCustomToolWireName,
56
unwrapRoutedCustomToolArguments,
67
} from "../responses/custom-tool-compat";
78
import {
@@ -181,7 +182,8 @@ export function createRoutedCustomToolRestoreBlockRewrite(
181182
&& typeof parsed.item.name === "string"
182183
) {
183184
const upstreamItemId = typeof parsed.item.id === "string" ? parsed.item.id : undefined;
184-
const routed = names.has(parsed.item.name);
185+
const wireName = routedCustomToolWireName(parsed.item);
186+
const routed = wireName !== undefined && names.has(wireName);
185187
if (upstreamItemId) {
186188
if (routed) {
187189
itemNames.set(upstreamItemId, parsed.item.name);

‎src/server/responses/core.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2545,7 +2545,10 @@ async function handleResponsesInner(
25452545
}
25462546
if (route.provider.authMode !== "forward") {
25472547
for (const name of request.convertedRoutedCustomToolNames ?? []) {
2548-
if (toolBridgeMaps.freeformToolNames.has(name)) routedCustomToolNames.add(name);
2548+
if (
2549+
toolBridgeMaps.freeformToolNames.has(name)
2550+
|| toolBridgeMaps.toolNsMap.get(name)?.freeform === true
2551+
) routedCustomToolNames.add(name);
25492552
}
25502553
}
25512554
for (const name of request.convertedRoutedToolSearchNames ?? []) {

‎tests/namespace-tool-compat.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,38 @@ describe("Responses namespace tool compatibility", () => {
166166
expect([...rewritten.aliases]).toEqual([]);
167167
});
168168

169+
test("chooses the bare declaration regardless of which tool container comes first", () => {
170+
const bare = {
171+
type: "function",
172+
name: "exec",
173+
description: "canonical bare declaration",
174+
parameters: { type: "object", properties: { input: { type: "string" } } },
175+
};
176+
const functionsGroup = {
177+
type: "namespace",
178+
name: "functions",
179+
tools: [{
180+
type: "function",
181+
name: "exec",
182+
description: "namespace duplicate",
183+
parameters: { type: "object", properties: {} },
184+
}],
185+
};
186+
const flatten = (bodyTools: unknown[], additionalTools: unknown[]) => {
187+
const rewritten = rewriteRoutedNamespaceToolsForUpstream({
188+
tools: bodyTools,
189+
input: [{ type: "additional_tools", role: "developer", tools: additionalTools }],
190+
}).body as {
191+
tools: Array<Record<string, unknown>>;
192+
input: Array<{ tools: Array<Record<string, unknown>> }>;
193+
};
194+
return [...rewritten.tools, ...rewritten.input[0]!.tools];
195+
};
196+
197+
expect(flatten([bare], [functionsGroup])).toEqual([bare]);
198+
expect(flatten([functionsGroup], [bare])).toEqual([bare]);
199+
});
200+
169201
// The routed compaction turn strips the whole tool surface before this runs, and a catalog can
170202
// change mid-session — but the client is still replaying items this layer's own restoration
171203
// stamped with a private `namespace`.

0 commit comments

Comments
 (0)