|
| 1 | +import type { AssistantMessage, Context, Model } from "@openclaw/llm-core"; |
| 2 | +import { afterEach, describe, expect, it } from "vitest"; |
| 3 | +import { cleanupSessionResources } from "../session-resources.js"; |
| 4 | +import { createOpenAIResponsesTransportStreamFn } from "./openai-responses-client.js"; |
| 5 | + |
| 6 | +// Live coverage, against the real native api.openai.com endpoint, for the |
| 7 | +// argument-canonicalization half of this PR: HTTP continuation must still |
| 8 | +// hold across a real multi-round tool-calling turn whose argument contains |
| 9 | +// an integer value ABOVE Number.MAX_SAFE_INTEGER. This isolates the |
| 10 | +// native-only path this PR's own code (claimOpenAIResponsesHttpContinuation) |
| 11 | +// actually gates on, rather than the stack this PR's prior live evidence |
| 12 | +// used, which also carried #128633's separate compat-endpoint opt-in. |
| 13 | +// |
| 14 | +// This test caught a real regression on first run: an earlier revision of |
| 15 | +// this fix tagged the cached side's unsafe integer to distinguish it from a |
| 16 | +// genuine same-digits string, but AssistantMessage.arguments already stores |
| 17 | +// every unsafe integer as a string (parseJsonObjectPreservingUnsafeIntegers, |
| 18 | +// precision-preserving), so an *unmodified* replay of this exact call always |
| 19 | +// re-serializes it as a same-digits string -- tagging only the cached side |
| 20 | +// made every real large-integer tool call permanently ineligible for |
| 21 | +// continuation on its very next round. Confirmed live: this test failed |
| 22 | +// (fell through to a full-history resend) before that tag was removed, and |
| 23 | +// passes now. See the unit regression test with the same shape |
| 24 | +// (`treats a cached number-typed unsafe integer as equal to its own |
| 25 | +// replayed string-typed round-trip`) for the deterministic version of this |
| 26 | +// proof. |
| 27 | +// |
| 28 | +// (The call_id-reshaping half of this PR is not exercisable here: a real |
| 29 | +// native OpenAI tool-call id already arrives in the call_*/fc_*-paired shape |
| 30 | +// normalizeOpenAIResponsesToolCallIds produces, so its idempotent |
| 31 | +// short-circuit correctly leaves it unchanged -- an earlier version of this |
| 32 | +// test asserted the id WOULD change and failed for exactly that reason. |
| 33 | +// That half stays covered by the existing unit tests using the real |
| 34 | +// transform function directly.) |
| 35 | +const LIVE = process.env.OPENCLAW_LIVE_TEST === "1"; |
| 36 | +const OPENAI_KEY = process.env.OPENAI_API_KEY ?? ""; |
| 37 | +const describeLive = LIVE && OPENAI_KEY ? describe : describe.skip; |
| 38 | +const LIVE_MODEL_ID = process.env.OPENCLAW_LIVE_RESPONSES_MODEL || "gpt-5.6-luna"; |
| 39 | +const LIVE_TIMEOUT_MS = 120_000; |
| 40 | + |
| 41 | +class GlobalFetchRequestCapture { |
| 42 | + readonly requests: Array<Record<string, unknown>> = []; |
| 43 | + private readonly realFetch = globalThis.fetch; |
| 44 | + |
| 45 | + install(): void { |
| 46 | + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { |
| 47 | + const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url; |
| 48 | + const body = init?.body; |
| 49 | + if (url.includes("api.openai.com") && typeof body === "string") { |
| 50 | + try { |
| 51 | + this.requests.push(JSON.parse(body) as Record<string, unknown>); |
| 52 | + } catch { |
| 53 | + // Non-JSON body on this host is unexpected for a Responses call. |
| 54 | + } |
| 55 | + } |
| 56 | + return this.realFetch(input, init); |
| 57 | + }) as typeof fetch; |
| 58 | + } |
| 59 | + |
| 60 | + restore(): void { |
| 61 | + globalThis.fetch = this.realFetch; |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +function userMessage(text: string, timestamp: number) { |
| 66 | + return { role: "user" as const, content: text, timestamp }; |
| 67 | +} |
| 68 | + |
| 69 | +const recordValueTool = { |
| 70 | + name: "record_value", |
| 71 | + description: "Record an integer value for the test harness.", |
| 72 | + parameters: { type: "object", properties: { n: { type: "integer" } }, required: ["n"] }, |
| 73 | +}; |
| 74 | + |
| 75 | +function model(): Model<"openai-responses"> { |
| 76 | + return { |
| 77 | + id: LIVE_MODEL_ID, |
| 78 | + name: LIVE_MODEL_ID, |
| 79 | + api: "openai-responses", |
| 80 | + provider: "openai", |
| 81 | + baseUrl: "https://api.openai.com/v1", |
| 82 | + reasoning: true, |
| 83 | + input: ["text"], |
| 84 | + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, |
| 85 | + contextWindow: 200_000, |
| 86 | + maxTokens: 8192, |
| 87 | + } satisfies Model<"openai-responses">; |
| 88 | +} |
| 89 | + |
| 90 | +async function run(context: Context, sessionId: string): Promise<AssistantMessage> { |
| 91 | + const stream = await createOpenAIResponsesTransportStreamFn()(model(), context, { |
| 92 | + apiKey: OPENAI_KEY, |
| 93 | + sessionId, |
| 94 | + transport: "sse", |
| 95 | + reasoningEffort: "low", |
| 96 | + maxTokens: 256, |
| 97 | + onPayload: (payload: Record<string, unknown>) => ({ ...payload, store: true }), |
| 98 | + } as never); |
| 99 | + return stream.result(); |
| 100 | +} |
| 101 | + |
| 102 | +describeLive( |
| 103 | + "HTTP continuation across a real unsafe-integer tool-call argument (real api.openai.com)", |
| 104 | + () => { |
| 105 | + afterEach(() => { |
| 106 | + cleanupSessionResources(); |
| 107 | + }); |
| 108 | + |
| 109 | + it( |
| 110 | + "continues a real tool-calling round whose argument is above Number.MAX_SAFE_INTEGER", |
| 111 | + async () => { |
| 112 | + const capture = new GlobalFetchRequestCapture(); |
| 113 | + capture.install(); |
| 114 | + try { |
| 115 | + const sessionId = "live-toolcall-arg-canonicalization"; |
| 116 | + const unsafeInt = "9007199254740993"; // > Number.MAX_SAFE_INTEGER |
| 117 | + const firstUser = userMessage( |
| 118 | + `This is an automated test. Call the record_value tool with exactly n=${unsafeInt}. ` + |
| 119 | + "Do not round or alter the number.", |
| 120 | + 1, |
| 121 | + ); |
| 122 | + const callTurn = await run( |
| 123 | + { messages: [firstUser], tools: [recordValueTool] }, |
| 124 | + sessionId, |
| 125 | + ); |
| 126 | + const toolCall = callTurn.content.find((block) => block.type === "toolCall") as |
| 127 | + | { type: "toolCall"; id: string; name: string; arguments: Record<string, unknown> } |
| 128 | + | undefined; |
| 129 | + expect(toolCall).toBeDefined(); |
| 130 | + expect(String(toolCall?.arguments.n)).toBe(unsafeInt); |
| 131 | + |
| 132 | + const toolResultMsg = { |
| 133 | + role: "toolResult" as const, |
| 134 | + toolCallId: toolCall?.id ?? "", |
| 135 | + content: [{ type: "text" as const, text: "recorded" }], |
| 136 | + timestamp: 2, |
| 137 | + }; |
| 138 | + const round1Messages: Context["messages"] = [firstUser, callTurn, toolResultMsg]; |
| 139 | + const afterToolResult = await run( |
| 140 | + { messages: round1Messages, tools: [recordValueTool] }, |
| 141 | + sessionId, |
| 142 | + ); |
| 143 | + expect(afterToolResult.stopReason).toBe("stop"); |
| 144 | + |
| 145 | + // Exactly two requests reached the real API -- a rejected |
| 146 | + // previous_response_id (the recovery path is a silent |
| 147 | + // full-history resend) would show up as a third. |
| 148 | + expect(capture.requests).toHaveLength(2); |
| 149 | + const secondRequest = capture.requests[1]; |
| 150 | + expect(secondRequest).toHaveProperty("previous_response_id"); |
| 151 | + expect(typeof secondRequest?.previous_response_id).toBe("string"); |
| 152 | + expect((secondRequest?.previous_response_id as string).length).toBeGreaterThan(0); |
| 153 | + // toolCall.id is OpenClaw's own internal call_id|fc_id pairing; |
| 154 | + // the wire delta's call_id must be restored to the bare provider |
| 155 | + // call_id (the part before the pairing separator), not the |
| 156 | + // compound internal id. |
| 157 | + const rawCallId = toolCall?.id.split("|")[0]; |
| 158 | + expect(secondRequest?.input).toEqual([ |
| 159 | + { |
| 160 | + type: "function_call_output", |
| 161 | + call_id: rawCallId, |
| 162 | + output: "recorded", |
| 163 | + }, |
| 164 | + ]); |
| 165 | + } finally { |
| 166 | + capture.restore(); |
| 167 | + } |
| 168 | + }, |
| 169 | + LIVE_TIMEOUT_MS, |
| 170 | + ); |
| 171 | + }, |
| 172 | +); |
0 commit comments