Skip to content

Commit 45f155d

Browse files
hartmarkclaudesteipete
authored
fix(ai): exclude tools from the HTTP continuation request-equality check (#132951)
* fix(ai): exclude tools from the HTTP continuation request-equality check `requestWithoutInput()` already excludes `instructions` from the turn-to-turn request comparison in `resolveResponsesContinuationRequest`, with the reasoning that it's rebuilt fresh every request from live runtime state and comparing it just moves a false-positive rejection into `request_changed`. `tools` was never given the same exclusion, even though it's exactly the same class of field: the agent's model-visible tool surface legitimately shifts turn to turn (tool-search activation, session-scoped gating, MCP servers connecting/disconnecting) independent of whether the prior turn's server-side response state is still a valid continuation baseline. Any ordinary tool-list change between two turns on the same connection fell through to `request_changed`, silently and permanently disabling HTTP continuation for the rest of that connection's life -- every later attempt keeps comparing against the same now-stale cached tool list. Confirmed live against a real OpenAI-Responses-compatible endpoint: continuation held across a tool-calling round and a plain new-turn round, then broke exactly at the turn where a second tool became available, with `resolve: request_changed` and a JSON diff whose only differing key was `tools`. Add `tools` to the same destructure-and-drop as `instructions`, and a regression test mirroring the existing `instructions` test that fails pre-fix (`request_changed`) and passes post-fix (`continued`, with the current turn's tools kept on the wire). Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Vk2cBRQdErwRtPea8VuhG6 * fix(ai): trim invariant comment; prove tools-list-change continuation live against api.openai.com Addresses ClawSweeper review on #132951: - P2: HTTP continuation is native-api.openai.com-only on current main, so the earlier OmniRoute-only live proof didn't establish whether the official Responses API actually accepts previous_response_id after the turn's `tools` list changes, versus rejecting it. Added a live test (gated on OPENCLAW_LIVE_TEST=1 + OPENAI_API_KEY, matching the sibling continuation.live.test.ts pattern exactly, including the secret-recall proof that continuation genuinely resolved server-side history) that hits the real endpoint with a tool list that grows between turn 1 and turn 2. Passed: the real API accepts the changed tools with previous_response_id, the trimmed request never re-sent the secret, and the reply correctly recalled it -- proving genuine server-side continuation, not a lucky self-contained answer or a silent full-history fallback. - P1: compressed the new `tools` exclusion comment to the short invariant (matching the sibling `instructions` comment's density) instead of restating the PR rationale, and pointed it at the new live test as the evidence backing the claim. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Vk2cBRQdErwRtPea8VuhG6 * fix(ai): scope the tools-exclusion to HTTP continuation only Addresses ClawSweeper P2 on #132951: resolveResponsesContinuationRequest is shared by both the HTTP and WebSocket Responses transports. The `tools` exclusion was only ever proven live over HTTP; WebSocket has its own pre-existing test ("resets continuation on tool schema change" in openai-responses-websocket.test.ts) asserting that a tool-schema change resets continuation, which the unscoped exclusion silently broke for that transport too, without any corresponding proof it's safe there. Added a required `{ excludeTools: boolean }` option threaded through `requestWithoutInput()`/`resolveResponsesContinuationRequest()` so every caller states its own proof status instead of inheriting one implicitly: - HTTP (`claimOpenAIResponsesHttpContinuation`): `excludeTools: true` -- the option this PR's live evidence actually covers. - WebSocket (`openai-responses-websocket.ts`): `excludeTools: false` -- unchanged behavior, still resets on a tool-schema change, matching its existing test. - Other call sites (compaction-replay test, cache-stability test): they don't vary tools, so `excludeTools: false` (the conservative default) doesn't change their outcome; passed explicitly since the parameter is required, not defaulted, so no call site can silently coast on an unproven assumption. Added a companion unit test proving the WebSocket path still resets (`excludeTools: false` -> `request_changed`) alongside the existing HTTP-path test (`excludeTools: true` -> `continued`), so the scoping itself has regression coverage, not just a comment. Reran the full existing WebSocket suite (including the pre-existing "resets continuation on tool schema change" case) and the native api.openai.com live test -- both still pass unchanged. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Vk2cBRQdErwRtPea8VuhG6 * test(ai): widen live tools-change continuation proof to 4 real-API scenarios Addresses ClawSweeper P1 on #132951: the live proof only covered adding one unused tool after a plain-text turn -- too narrow to back a change that ignores every HTTP tool difference. Extended openai-responses-client.continuation-tools-change.live.test.ts, all run live against the real api.openai.com and all passing: - tool added (existing scenario, now via a shared helper) - tool removed - an existing tool's schema mutated (same name, different description/parameters) - tools change on the turn immediately after a completed tool-calling round -- the shape closest to real production dynamic tool-gating, and the one exercising the reasoning-replay/tool-call machinery a plain text-only round doesn't touch Also fixed a bug in the refactor: the shared secret-recall helper never restored the patched globalThis.fetch on return, which would have leaked the capture across scenarios; wrapped in try/finally. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Vk2cBRQdErwRtPea8VuhG6 * refactor(ai): compress the tools-exclusion invariant comment further Addresses ClawSweeper P1 on #132951 (production LOC growth). Trims the comment to a single short paragraph naming what's proven, where, and why WebSocket differs -- same information, fewer lines. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Vk2cBRQdErwRtPea8VuhG6 * fix(ai): satisfy strict lint/typecheck in the tools-change live test Post-rebase gaps found on the exact-head check pass, matching the same class of finding already caught and fixed on the sibling unsafe-integer live test (#134423): - no-unsafe-optional-chaining (4x): (x?.field as T).prop on a value that could be undefined. Fixed with ?? / optional chaining after the cast, same pattern already established. - no-array-sort: .sort() mutates; switched to .toSorted(). - runSecretRecallToolsChangeScenario's declared return type claimed a non-optional Record even though capture.requests[1] is a genuine array index access that can be undefined; widened the type to match reality instead of asserting past it. - toolResultMsg missing ToolResultMessage's required toolName/isError fields. Verification: oxfmt/oxlint clean, scoped tsgo clean, and the exact live scenarios still pass for real against api.openai.com: $ OPENCLAW_LIVE_TEST=1 OPENAI_API_KEY=*** node --import ./scripts/tsx.mjs scripts/test-live.mts \ packages/ai/src/transports/openai-responses-client.continuation-tools-change.live.test.ts ✓ tool added: accepts previous_response_id and carries the current (grown) tool list 4233ms ✓ tool removed: accepts previous_response_id and carries the current (shrunk) tool list 2975ms ✓ tool schema mutated: accepts previous_response_id with the same tool name but a changed definition 1882ms ✓ tools change immediately after a completed tool-calling round: accepts previous_response_id on the next turn 4253ms Test Files 1 passed (1) Tests 4 passed (4) * fix(openai): share tool-change continuation across transports Keep current tools out of history equality for native Responses continuation over HTTP and WebSocket. Remove the per-transport comparison switch while preserving strict request settings, history, credential and session ownership checks. Exercise real HTTP/SSE and WebSocket request shapes, strict negative controls and third-turn baseline advancement through one scoped wire fixture. Preserve unsafe integer replay normalization. Co-authored-by: Markus Hartung <[email protected]> --------- Co-authored-by: Claude Sonnet 5 <[email protected]> Co-authored-by: Peter Steinberger <[email protected]> Co-authored-by: Markus Hartung <[email protected]>
1 parent 95383b3 commit 45f155d

7 files changed

Lines changed: 528 additions & 108 deletions
Lines changed: 179 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,179 @@
1+
import { randomUUID } from "node:crypto";
2+
import type { Context, Model, Tool } from "@openclaw/llm-core";
3+
import OpenAI from "openai";
4+
import { describe, expect, it } from "vitest";
5+
import { cleanupSessionResources } from "../session-resources.js";
6+
import { createOpenAIResponsesTransportStreamFn } from "./openai-responses-client.js";
7+
import type { OpenAIResponsesOptions } from "./openai-responses-contracts.js";
8+
import { captureOpenAIResponses } from "./openai-responses-live-capture.test-support.js";
9+
10+
const apiKey = process.env.OPENAI_API_KEY ?? "";
11+
const describeLive = process.env.OPENCLAW_LIVE_TEST === "1" && apiKey ? describe : describe.skip;
12+
const modelId = process.env.OPENCLAW_LIVE_RESPONSES_MODEL || "gpt-5.6-luna";
13+
const model = {
14+
id: modelId,
15+
name: modelId,
16+
api: "openai-responses",
17+
provider: "openai",
18+
baseUrl: "https://api.openai.com/v1",
19+
reasoning: true,
20+
input: ["text"],
21+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
22+
contextWindow: 200_000,
23+
maxTokens: 1024,
24+
} satisfies Model<"openai-responses">;
25+
26+
const remember: Tool = {
27+
name: "remember_code",
28+
description: "Record the supplied code.",
29+
parameters: {
30+
type: "object",
31+
properties: { code: { type: "string" } },
32+
required: ["code"],
33+
additionalProperties: false,
34+
},
35+
};
36+
const report: Tool = { ...remember, name: "report_code" };
37+
const revisedReport: Tool = {
38+
...report,
39+
parameters: {
40+
type: "object",
41+
properties: { code: { type: "string" }, revision: { type: "integer", const: 2 } },
42+
required: ["code", "revision"],
43+
additionalProperties: false,
44+
},
45+
};
46+
47+
describeLive("native HTTP Responses continuation with current tools", () => {
48+
it.each([
49+
{ name: "added", before: [remember], after: [remember, report], selected: report },
50+
{ name: "removed", before: [remember, report], after: [report], selected: report },
51+
{ name: "schema changed", before: [report], after: [revisedReport], selected: revisedReport },
52+
{ name: "empty", before: [remember], after: [], selected: undefined },
53+
{ name: "omitted", before: [remember], after: undefined, selected: undefined },
54+
] satisfies Array<{
55+
name: string;
56+
before: [Tool, ...Tool[]];
57+
after: Tool[] | undefined;
58+
selected: Tool | undefined;
59+
}>)(
60+
"honors $name tools while recalling omitted history",
61+
async ({ name, before, after, selected }) => {
62+
const sessionId = `live-tools-${randomUUID()}`;
63+
const code = `CODE_${randomUUID()}`;
64+
const responseIds: string[] = [];
65+
const run = async (context: Context) => {
66+
const options = {
67+
apiKey,
68+
sessionId,
69+
transport: "sse",
70+
reasoningEffort: "low",
71+
onPayload: (payload) => ({
72+
...(payload as Record<string, unknown>),
73+
store: true,
74+
tool_choice: "auto",
75+
}),
76+
} satisfies OpenAIResponsesOptions;
77+
const stream = await createOpenAIResponsesTransportStreamFn()(model, context, options);
78+
const result = await stream.result();
79+
if (result.responseId) {
80+
responseIds.push(result.responseId);
81+
}
82+
return result;
83+
};
84+
try {
85+
const captured = await captureOpenAIResponses(async () => {
86+
const firstUser = {
87+
role: "user" as const,
88+
content: `Remember ${code}. Call only ${before[0].name} with that exact code.`,
89+
timestamp: 1,
90+
};
91+
const first = await run({ messages: [firstUser], tools: before });
92+
expect(first.stopReason).toBe("toolUse");
93+
const calls = first.content.filter((block) => block.type === "toolCall");
94+
expect(calls).toHaveLength(1);
95+
const call = calls[0];
96+
if (!call) {
97+
throw new Error("Expected one completed tool call");
98+
}
99+
expect(call.name).toBe(before[0].name);
100+
expect(call.arguments).toEqual({ code });
101+
const prompt = selected
102+
? name === "removed"
103+
? "Call remember_code if available; otherwise call report_code with the remembered code."
104+
: `Call only ${selected.name} with the remembered code, using the current schema. If it asks for a revision, use 2.`
105+
: "Call remember_code if available; otherwise reply with only the remembered code.";
106+
const second = await run({
107+
messages: [
108+
firstUser,
109+
first,
110+
{
111+
role: "toolResult",
112+
toolCallId: call.id,
113+
toolName: call.name,
114+
content: [{ type: "text", text: "recorded" }],
115+
isError: false,
116+
timestamp: 2,
117+
},
118+
{ role: "user", content: prompt, timestamp: 3 },
119+
],
120+
tools: after,
121+
});
122+
return { first, second, call, prompt };
123+
});
124+
const { first, second, call, prompt } = captured.result;
125+
expect(captured.requests).toHaveLength(2);
126+
const current = captured.requests[1];
127+
expect(first.responseId).toEqual(expect.any(String));
128+
expect(current).toMatchObject({
129+
previous_response_id: first.responseId,
130+
tool_choice: "auto",
131+
input: [
132+
{ type: "function_call_output", call_id: call.id.split("|")[0], output: "recorded" },
133+
{ type: "message", role: "user", content: [{ type: "input_text", text: prompt }] },
134+
],
135+
});
136+
expect(JSON.stringify(current)).not.toContain(code);
137+
if (after === undefined) {
138+
expect(current).not.toHaveProperty("tools");
139+
} else {
140+
expect(current?.tools).toEqual(
141+
after
142+
.toSorted((a, b) => a.name.localeCompare(b.name))
143+
.map((tool) =>
144+
expect.objectContaining({
145+
type: "function",
146+
name: tool.name,
147+
parameters: tool.parameters,
148+
}),
149+
),
150+
);
151+
}
152+
if (selected) {
153+
expect(second.stopReason).toBe("toolUse");
154+
expect(second.content.filter((block) => block.type === "toolCall")).toMatchObject([
155+
{
156+
name: selected.name,
157+
arguments: selected === revisedReport ? { code, revision: 2 } : { code },
158+
},
159+
]);
160+
} else {
161+
expect(second.stopReason).toBe("stop");
162+
expect(second.content.filter((block) => block.type === "toolCall")).toEqual([]);
163+
expect(
164+
second.content
165+
.filter((block) => block.type === "text")
166+
.map((block) => block.text)
167+
.join("")
168+
.trim(),
169+
).toBe(code);
170+
}
171+
} finally {
172+
cleanupSessionResources(sessionId);
173+
const client = new OpenAI({ apiKey, maxRetries: 0 });
174+
await Promise.all(responseIds.map((id) => client.responses.delete(id)));
175+
}
176+
},
177+
120_000,
178+
);
179+
});

‎packages/ai/src/transports/openai-responses-client.continuation.integration.test.ts‎

Lines changed: 10 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,10 @@
1-
import { createServer } from "node:http";
2-
import type { Context, Model } from "@openclaw/llm-core";
3-
import OpenAI from "openai";
4-
import { expect, it, vi } from "vitest";
5-
import { WebSocketServer } from "ws";
6-
import { cleanupSessionResources } from "../session-resources.js";
1+
import type { Context } from "@openclaw/llm-core";
2+
import { expect, it } from "vitest";
73
import { createOpenAIResponsesTransportStreamFn } from "./openai-responses-client.js";
8-
9-
const model = {
10-
id: "scripted-model",
11-
name: "Scripted Model",
12-
api: "openai-responses",
13-
provider: "openai",
14-
baseUrl: "https://api.openai.com/v1",
15-
reasoning: false,
16-
input: ["text"],
17-
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
18-
contextWindow: 8192,
19-
maxTokens: 256,
20-
} satisfies Model<"openai-responses">;
4+
import {
5+
createResponsesLoopbackServer,
6+
responsesLoopbackModel,
7+
} from "./openai-responses-loopback.test-support.js";
218

229
const tool = {
2310
name: "record_value",
@@ -81,62 +68,11 @@ it.each([
8168
] as const)(
8269
"preserves real %s continuation with edited arguments=%s",
8370
async (transport, edited) => {
84-
const requests: Array<Record<string, unknown>> = [];
85-
const eventsForRequest = (body: string) => {
86-
requests.push(JSON.parse(body) as Record<string, unknown>);
87-
return responseEvents(requests.length === 1);
88-
};
89-
const server = createServer((request, response) => {
90-
request.setEncoding("utf8");
91-
let body = "";
92-
request.on("data", (chunk: string) => {
93-
body += chunk;
94-
});
95-
request.on("end", () => {
96-
response.writeHead(200, { "content-type": "text/event-stream" });
97-
for (const event of eventsForRequest(body)) {
98-
response.write(`data: ${JSON.stringify(event)}\n\n`);
99-
}
100-
response.end();
101-
});
102-
});
103-
const sockets = new WebSocketServer({ server });
104-
sockets.on("connection", (socket) => {
105-
socket.on("message", (body) => {
106-
if (!Buffer.isBuffer(body)) {
107-
throw new Error("Expected a Buffer from the WebSocket server");
108-
}
109-
for (const event of eventsForRequest(body.toString("utf8"))) {
110-
socket.send(JSON.stringify(event));
111-
}
112-
});
113-
});
114-
await new Promise<void>((resolve, reject) => {
115-
server.once("error", reject);
116-
server.listen(0, "127.0.0.1", resolve);
117-
});
118-
const address = server.address();
119-
if (!address || typeof address === "string") {
120-
throw new Error("Expected a loopback TCP address");
121-
}
122-
// The replacement calls this original method with the active SDK client as `this`.
123-
// oxlint-disable-next-line typescript/unbound-method
124-
const buildURL = OpenAI.prototype.buildURL;
125-
// Route only the network destination; native eligibility, the SDK, and all request bytes stay real.
126-
vi.spyOn(OpenAI.prototype, "buildURL").mockImplementation(
127-
function (this: OpenAI, path, query, baseURL) {
128-
const url = new URL(buildURL.call(this, path, query, baseURL));
129-
expect(url.origin).toBe("https://api.openai.com");
130-
expect(url.pathname).toBe("/v1/responses");
131-
url.protocol = "http:";
132-
url.hostname = "127.0.0.1";
133-
url.port = String(address.port);
134-
return url.href;
135-
},
136-
);
71+
const server = await createResponsesLoopbackServer((turn) => responseEvents(turn === 1));
72+
const { requests } = server;
13773
const run = async (messages: Context["messages"]) => {
13874
const stream = await createOpenAIResponsesTransportStreamFn()(
139-
model,
75+
responsesLoopbackModel,
14076
{ messages, tools: [tool] },
14177
{
14278
apiKey: "synthetic-continuation-key",
@@ -218,18 +154,7 @@ it.each([
218154
);
219155
}
220156
} finally {
221-
cleanupSessionResources();
222-
vi.restoreAllMocks();
223-
for (const socket of sockets.clients) {
224-
socket.terminate();
225-
}
226-
await new Promise<void>((resolve, reject) => {
227-
sockets.close((error) => (error ? reject(error) : resolve()));
228-
});
229-
await new Promise<void>((resolve, reject) => {
230-
server.close((error) => (error ? reject(error) : resolve()));
231-
server.closeAllConnections();
232-
});
157+
await server.close();
233158
}
234159
},
235160
);

0 commit comments

Comments
 (0)