Repository navigation
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: needs real behavior proof before merge. Reviewed August 31, 2026, 2:54 PM ET / 18:54 UTC. ClawSweeper reviewWhat this changesThe PR canonicalizes replayed OpenAI Responses tool-call IDs and equivalent JSON arguments for continuation eligibility, then restores the provider’s original call ID in the trimmed follow-up request. Regression provenancePossible regression — probable (reviewed change; failure trace). No predecessor PR is attributed. Merge readiness⛔ Blocked until stronger real behavior proof is added - 4 items remain Keep open: the source repair is coherent and unit-covered, but the supplied native-endpoint trace explicitly bypasses the new call-ID canonicalization and raw-ID restoration branch, so real behavior proof remains incomplete. Priority: P2 Review scores
Verification
How this fits togetherOpenAI Responses continuation caches a provider response so a following tool-result round can send only a delta using flowchart LR
A[Provider response] --> B[Continuation cache]
C[Agent replay history] --> D[ID and argument normalization]
B --> E[Continuation eligibility comparison]
D --> E
E --> F[Trimmed follow-up request]
F --> G[OpenAI Responses endpoint]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +154, Tests +383. Total +537 across 7 files. View PR surface stats
Review metrics
Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Retain the strict history-change fallback until a production-boundary trace proves that a replay-normalized tool-call ID is converted back to the cached provider ID in the emitted continuation delta. Do we have a high-confidence way to reproduce the issue? Yes, source-reproducible: current main compares cached raw function-call IDs against replayed normalized IDs, and the focused branch test models the resulting Is this the best way to solve the issue? Unclear: sharing the ID-shaping transform is the right ownership direction and focused tests cover the intended invariant, but the best end-to-end solution is not proven until the changed wire-restoration branch is observed through the transport boundary. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 33029a1feb0a. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (8 earlier review cycles)
|
c07a9be to
75664a5
Compare
|
Addressed both P1 findings:
Also corrected the PR body: HTTP continuation eligibility on Rebased onto latest Converting to draft — this sits in the same continuation-eligibility area as #128848 and #128633, and the whole area needs more investigation (there's a separate, still-unresolved rendering-mismatch mechanism that independently causes @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. |
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
… for eligibility normalizeOpenAIResponsesToolCallIds re-sanitizes call_id for provider-format compatibility on replay, which previously made the eligibility check either reject every multi-round tool-calling turn (blanket compare) or, after a prior loosening, blanket-drop call_id from the comparison entirely -- letting an unrelated changed function-call id through as if it were the known reshape, and shipping the client's reshaped call_id instead of the raw provider id on the wire delta. A server that reconstructs continuation history server-side from its own cached raw response (e.g. a proxy virtualizing previous_response_id) pairs function_call_output against the function_call it cached verbatim, so the reshaped call_id reads as orphaned and the tool result gets dropped. Canonicalize call_id/fc_id through the same reshape for the eligibility comparison (fail-closed: only forgives ids that reshape TO the cached raw id, never an arbitrary difference), and restore the raw provider id on the wire-bound delta before it's sent. Also fixes a lossless-integer gap in the arguments comparison (distinct unsafe integers could round to the same JS number under plain JSON.parse and wrongly compare equal).
…inuation eligibility Replay reshapes a function_call's id by pairing call_id and item id into one call_id|fc_id string before hashing (normalizeOpenAIResponsesToolCallIds). The continuation eligibility comparison and the raw-id restore path only canonicalized the cached response's bare call_id, ignoring its paired item id, so they hashed a different input than replay actually produced and permanently returned history_changed for any turn whose provider ids needed reshaping. Reconstruct the same call_id|item_id pairing from the cached raw response before canonicalizing, mirroring the exact idempotent short-circuit replay's own resolver uses so already provider-shaped ids are left unchanged.
75664a5 to
f9508ca
Compare
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
…ontinuation comparisons
quoteUnsafeIntegerLiterals converted an unsafe integer literal into a bare
quoted string before JSON.parse, so a genuine JSON string holding the same
digits normalized identically. A real number-to-string argument change
(e.g. {"n":9007199254740993} -> {"n":"9007199254740993"}) wrongly compared
equal, letting continuation reuse stale server-side state for a changed
tool call. Adds an optional tag parameter to the shared helper (default
unchanged, so every other caller is unaffected) and uses it to keep the
two cases distinguishable in the continuation argument comparator.
Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Vk2cBRQdErwRtPea8VuhG6
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. |
…arge-integer tool call Two bugs found while chasing ClawSweeper's P2 real-behavior-proof request for the unsafe-integer type-collision fix (previous head): 1. Mechanical: UNSAFE_INTEGER_COMPARISON_TAG embedded literal control characters into JSON text, so JSON.parse threw and normalizeFunctionCallArguments's catch silently fell back to the untagged comparison the tag exists to replace -- confirmed via a new regression test (fails pre-fix with `expected 'history_changed' to be 'continued'`, a whitespace-only re-serialization of the same value wrongly compared as changed). 2. Deeper, found by testing the fix for (1) live against a real multi-round tool call: the tag's whole premise -- distinguishing a converted unsafe integer from a genuine same-digits string -- doesn't hold for this comparison. AssistantMessage.arguments already stores every unsafe integer as a string (parseJsonObjectPreservingUnsafeIntegers, transport-stream-shared.ts, precision-preserving), so an *unmodified* replay of a real tool call's argument always re-serializes it as a same-digits string against the cached raw provider number. Tagging only the cached side made every real out-of-range-integer tool call permanently ineligible for continuation on its very next round -- confirmed live: a real tool call with n=9007199254740993, replayed unmodified, fell through to a full-history resend before this fix and continues correctly after it. Both sides of this comparison replay the *same* historical tool call (not two independent model outputs), so the type-collision risk the tag was guarding against doesn't apply here: there's no second, unrelated call for a same-digit string to collide with. Reverted normalizeFunctionCallArguments to plain (untagged) quoteUnsafeIntegerLiterals, which still correctly distinguishes two genuinely DIFFERENT unsafe integers (the original lossless-comparison fix this PR keeps), and removed the now-unused tag parameter from quoteUnsafeIntegerLiterals itself (no other caller used it). Net effect: removes the tag mechanism entirely (fewer production lines than before), deletes the now-incorrect "type collision" unit test, and replaces it with a test proving the realistic round-trip case continues correctly, backed by a new live test against the real native api.openai.com endpoint (the sibling live test this PR's evidence was missing per ClawSweeper's prior review). Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Vk2cBRQdErwRtPea8VuhG6
|
@clawsweeper re-review Found and fixed two real bugs while chasing the P2 native-endpoint proof request:
New live test against real |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@clawsweeper re-review Added the actual raw terminal output for the live api.openai.com trace (was previously narrated only), and an explicit justification for the production LOC growth: the new shared file is a necessary mirror (packages/ai can't import from src/agents), and the remaining growth is the fail-closed comparison/restoration logic itself, with no smaller shape available that preserves correctness on a genuinely different id. |
|
🦞🧹 I asked ClawSweeper to review this item again. |
|
🦞👀 Re-review progress:
|
|
Splitting per ClawSweeper's own suggested alternative on this PR ("split the proven unsafe-integer repair from the deferred raw-ID compatibility work"). Investigated the raw-ID branch's proof gap directly: this PR's Replaced by two PRs:
Closing this one in favor of those. |
… in live test Real CI failure (check-test-types-core-1), not caught earlier because .live.test.ts files aren't in the broad tsgo:core lane I'd checked -- they are covered by the sharded tsgo:core:test lane CI actually runs. Pre-existing since this file's creation on openclaw#128910, unrelated to this PR's own changes; fixed here since it's now blocking this PR's CI and I'm already touching the file. toolResultMsg was missing toolName and isError, both required on ToolResultMessage<unknown>. Added toolName: "record_value" (matching the tool actually called) and isError: false (the recorded result is a success).
…ts (#134423) * fix(ai): lossless unsafe-integer comparison for tool-call argument replay in HTTP continuation Split from #128910 per ClawSweeper's own suggested alternative: this is the proven half (the raw-ID reshape/restore half is deferred, blocked on custom-endpoint eligibility -- see the follow-up PR). A real, multi-round tool-calling turn on a native api.openai.com connection loses HTTP continuation whenever the tool call's argument contains an integer literal above Number.MAX_SAFE_INTEGER (timestamps, snowflake IDs, etc). AssistantMessage.arguments already stores every unsafe integer as a string (parseJsonObjectPreservingUnsafeIntegers, precision-preserving), so an unmodified replay of the same historical tool call always re-serializes it as a same-digits string against the cached side's raw provider number -- without normalization this reads as a real content change and falls back to a full-history resend. quoteUnsafeIntegerLiterals (existing helper) run before the parse/stringify comparison round-trip fixes both directions: two genuinely different large integers stay distinguishable (lossless), and a same-digits number-vs-string round-trip of the same historical call compares equal. No distinguishing tag needed: both sides of this comparison replay the *same* historical tool call, not two independent model outputs, so there's no second call for a same-digit string to collide with. * test(ai): prove the raw wire arguments were a bare unsafe integer, not a quoted string ClawSweeper P2 on this PR: the live test only asserted on AssistantMessage.arguments after OpenClaw's own terminal parser (parseJsonObjectPreservingUnsafeIntegers) had already converted the unsafe integer into a string -- identical whether the provider sent a real bare 9007199254740993 (the regression this fix repairs) or the model quoted it as a string itself (already handled correctly pre-fix). The test couldn't distinguish those two cases, so it didn't actually prove the claimed regression path. GlobalFetchRequestCapture now tees each captured response's SSE body (ReadableStream.tee(), so the real SDK consumer is never disturbed) and extractRawFunctionCallArguments pulls the raw arguments string out of the response.function_call_arguments.done event -- the exact bytes the provider sent, before any parsing. The test asserts that raw text matches a bare, unquoted integer literal and explicitly asserts it does NOT match a quoted-string shape. Verified live: raw wire text for the tool call was exactly {"n":9007199254740993} -- a genuine bare literal, confirming this proves the real regression path, not an inferred one. Also fixed a pre-existing (unrelated) oxlint no-unsafe-optional-chaining finding a few lines below in the same file, found while already here. * fix(ai): satisfy ToolResultMessage's required toolName/isError fields in live test Real CI failure (check-test-types-core-1), not caught earlier because .live.test.ts files aren't in the broad tsgo:core lane I'd checked -- they are covered by the sharded tsgo:core:test lane CI actually runs. Pre-existing since this file's creation on #128910, unrelated to this PR's own changes; fixed here since it's now blocking this PR's CI and I'm already touching the file. toolResultMsg was missing toolName and isError, both required on ToolResultMessage<unknown>. Added toolName: "record_value" (matching the tool actually called) and isError: false (the recorded result is a success). * fix(ai): await the raw SSE capture before reading it in the live test ClawSweeper P2: the response.body.tee() capture branch was read in a fire-and-forget async IIFE, populating rawResponseTexts[i] in the background while fetch() itself already resolved. The test read rawResponseTexts[0] immediately after the request completed, racing the background reader -- a pass didn't reliably prove the raw-wire assertion actually saw the real captured text, only that it got lucky on scheduling. GlobalFetchRequestCapture now exposes captureCompletions (one promise per captured response, parallel to rawResponseTexts), and the test explicitly awaits captureCompletions[0] before reading rawResponseTexts[0]. The real SDK consumer is still never blocked -- only the test's own inspection of the capture branch waits. Verified live, 3 consecutive runs: deterministic pass each time. * fix(ai): normalize only admitted Responses output Match cached provider function-call output to the existing lossless terminal admission and replay serialization, while keeping previously sent and newly edited argument text strict. Prove unsafe-integer continuation and value/type edits through the actual SDK over HTTP SSE and cached WebSocket transports. Co-authored-by: Markus Hartung <[email protected]> --------- Co-authored-by: Peter Steinberger <[email protected]> Co-authored-by: Markus Hartung <[email protected]>
…ts (openclaw#134423) * fix(ai): lossless unsafe-integer comparison for tool-call argument replay in HTTP continuation Split from openclaw#128910 per ClawSweeper's own suggested alternative: this is the proven half (the raw-ID reshape/restore half is deferred, blocked on custom-endpoint eligibility -- see the follow-up PR). A real, multi-round tool-calling turn on a native api.openai.com connection loses HTTP continuation whenever the tool call's argument contains an integer literal above Number.MAX_SAFE_INTEGER (timestamps, snowflake IDs, etc). AssistantMessage.arguments already stores every unsafe integer as a string (parseJsonObjectPreservingUnsafeIntegers, precision-preserving), so an unmodified replay of the same historical tool call always re-serializes it as a same-digits string against the cached side's raw provider number -- without normalization this reads as a real content change and falls back to a full-history resend. quoteUnsafeIntegerLiterals (existing helper) run before the parse/stringify comparison round-trip fixes both directions: two genuinely different large integers stay distinguishable (lossless), and a same-digits number-vs-string round-trip of the same historical call compares equal. No distinguishing tag needed: both sides of this comparison replay the *same* historical tool call, not two independent model outputs, so there's no second call for a same-digit string to collide with. * test(ai): prove the raw wire arguments were a bare unsafe integer, not a quoted string ClawSweeper P2 on this PR: the live test only asserted on AssistantMessage.arguments after OpenClaw's own terminal parser (parseJsonObjectPreservingUnsafeIntegers) had already converted the unsafe integer into a string -- identical whether the provider sent a real bare 9007199254740993 (the regression this fix repairs) or the model quoted it as a string itself (already handled correctly pre-fix). The test couldn't distinguish those two cases, so it didn't actually prove the claimed regression path. GlobalFetchRequestCapture now tees each captured response's SSE body (ReadableStream.tee(), so the real SDK consumer is never disturbed) and extractRawFunctionCallArguments pulls the raw arguments string out of the response.function_call_arguments.done event -- the exact bytes the provider sent, before any parsing. The test asserts that raw text matches a bare, unquoted integer literal and explicitly asserts it does NOT match a quoted-string shape. Verified live: raw wire text for the tool call was exactly {"n":9007199254740993} -- a genuine bare literal, confirming this proves the real regression path, not an inferred one. Also fixed a pre-existing (unrelated) oxlint no-unsafe-optional-chaining finding a few lines below in the same file, found while already here. * fix(ai): satisfy ToolResultMessage's required toolName/isError fields in live test Real CI failure (check-test-types-core-1), not caught earlier because .live.test.ts files aren't in the broad tsgo:core lane I'd checked -- they are covered by the sharded tsgo:core:test lane CI actually runs. Pre-existing since this file's creation on openclaw#128910, unrelated to this PR's own changes; fixed here since it's now blocking this PR's CI and I'm already touching the file. toolResultMsg was missing toolName and isError, both required on ToolResultMessage<unknown>. Added toolName: "record_value" (matching the tool actually called) and isError: false (the recorded result is a success). * fix(ai): await the raw SSE capture before reading it in the live test ClawSweeper P2: the response.body.tee() capture branch was read in a fire-and-forget async IIFE, populating rawResponseTexts[i] in the background while fetch() itself already resolved. The test read rawResponseTexts[0] immediately after the request completed, racing the background reader -- a pass didn't reliably prove the raw-wire assertion actually saw the real captured text, only that it got lucky on scheduling. GlobalFetchRequestCapture now exposes captureCompletions (one promise per captured response, parallel to rawResponseTexts), and the test explicitly awaits captureCompletions[0] before reading rawResponseTexts[0]. The real SDK consumer is still never blocked -- only the test's own inspection of the capture branch waits. Verified live, 3 consecutive runs: deterministic pass each time. * fix(ai): normalize only admitted Responses output Match cached provider function-call output to the existing lossless terminal admission and replay serialization, while keeping previously sent and newly edited argument text strict. Prove unsafe-integer continuation and value/type edits through the actual SDK over HTTP SSE and cached WebSocket transports. Co-authored-by: Markus Hartung <[email protected]> --------- Co-authored-by: Peter Steinberger <[email protected]> Co-authored-by: Markus Hartung <[email protected]>
What Problem This Solves
HTTP continuation (
previous_response_idreuse) never engaged for a multi-round tool-calling turn — confirmed live against a real gateway: every attempt within a single turn resolved tohistory_changedand fell back to full history, even though the continuation cache held a validreadybaseline and eligibility was satisfied on every call. This defeats the whole point of continuation for exactly the case it should help most (a tool-calling loop, where turns are seconds apart).Why This Change Was Made
Root-caused via live diagnostic instrumentation against a real gateway. Replaying history for the next round in a tool-calling loop re-sanitizes tool-call ids for provider compatibility (
normalizeOpenAIResponsesToolCallIdsinembedded-agent-helpers), so afunction_call'scall_idthe client echoes back on round N+1 never matches the rawcall_idresolveResponsesContinuationRequestcached straight from the provider's own streamed response on round N (e.g.chatcmpl-tool-20cf1f2f...cached vscall_chatcmpl-tool-20cf1f2f..._d7218567a7replayed). Separately, theargumentsJSON string can pick up different whitespace on a re-JSON.stringifyalong the same replay path, and the comparison treated that as changed content too sinceargumentsis compared as a raw string, not a parsed value.Neither is a real change to what the model said — both are expected, necessary reshaping for provider-format compatibility.
normalizeAssistantReplayInputalready stripsid/statusfromfunction_call/assistant-message items for exactly this kind of volatility; this extends the same treatment tocall_idandarguments— but not with a blanket drop.Revised from the original patch per review feedback: blanket-dropping
call_idfrom the comparison would have made any changed function-call id look like the known replay reshape, masking a genuinely different tool call. Instead,canonicalizeReplayedCallIdreshapes both sides through the exact same transform the replay path applies (normalizeOpenAIResponsesFunctionCallId) and only treats them as equal when they canonicalize to the same value — fail-closed for an unrelated id change (covered by a new regression test). The wire-bound delta then gets the raw providercall_idrestored (restoreRawCallIdsInDelta) before it's sent, so a server that reconstructs continuation history from its own cached copy of the raw response still sees afunction_call_outputwhosecall_idmatches thefunction_callit cached — instead of an orphaned id it silently drops. Theargumentscomparison also now runsquoteUnsafeIntegerLiteralsbefore parsing, since plainJSON.parserounds integers pastNumber.MAX_SAFE_INTEGERand could otherwise treat two genuinely different large-integer arguments as equal.Second revision, per ClawSweeper P1 finding (paired call_id|item_id): the previous revision only canonicalized the cached response's bare
call_id, but replay pairs the provider'scall_idand itemidinto onecall_id|fc_idstring before reshaping (normalizeOpenAIResponsesToolCallIds→normalizeOpenAIResponsesFunctionCallId), and the request builder later splits that reshaped pair back into separate wire fields (openai-responses-replay-messages-internal.ts). So a cached raw item likecall_id: "functions.gateway:0",id: "fc_tmp"needed to canonicalize via the paired string"functions.gateway:0|fc_tmp", notcall_idalone — otherwise the eligibility comparison hashed a different input than replay actually produced and permanently stayedhistory_changedfor any turn whose provider ids needed reshaping (i.e., almost always, since most providers don't returncall_*/fc_*-shaped ids natively).Fixed by reconstructing the same pairing from the cached item's
call_id+idbefore canonicalizing (canonicalizeCachedCallId), mirroring the exact idempotent short-circuit the real replay resolver uses (shouldNormalizeOpenAIResponsesToolCallId) so already provider-shaped ids are left unchanged rather than needlessly re-hashed — the naive "always pair" version broke 8 existing tests inopenai-responses-retained-compaction-replay.test.tswhere ids were already validly shaped, since pairing two independently-valid ids together and hashing the combined string produces a value replay never generates.restoreRawCallIdsInDeltahad the identical bug (built its reshaped→raw lookup from the bare cachedcall_idonly) and got the same fix.User Impact
A native OpenAI Responses endpoint now actually gets the continuation savings it was designed for during multi-round tool-calling turns, not just across separate inbound messages. Before this fix, continuation only ever worked in the narrow case of zero tool calls in between (a plain text reply), which is not the common case for an agentic run.
(HTTP continuation eligibility on
maintoday is native-endpoint-only —supportsNativeOpenAIResponsesEndpoint. A separate, still-open PR, #128633, proposes extending eligibility to compat-endpoint connections viacompat.supportsResponsesContinuation; that opt-in is not part of this PR's scope and needs more investigation before landing, so it's marked draft. This fix is endpoint-agnostic — it repairs the same comparison logic regardless of which eligibility gate lets a request reach it.)Evidence
continues a tool-calling round despite replay re-sanitizing call_id and re-serializing arguments, and restores the raw call_id on the wire delta— bare vs re-sanitized, pairedcall_id|fc_id(verified against the realnormalizeOpenAIResponsesFunctionCallIdtransform on the paired string, not hand-approximated) plus differently-whitespacedarguments, assertingcontinuationStatus: "continued"and that the wire delta carries the rawcall_id, not the reshaped one; (2)does not tolerate an unrelated function-call id change as the known replay reshape— an unrelatedcall_idchange still correctly falls back tohistory_changed; (3)does not treat two different unsafe-integer arguments as equal (lossless comparison)— two different integers aboveNumber.MAX_SAFE_INTEGERare not conflated.call_id-only canonicalization) for the exact right reason (history_changed), and passes with the paired-canonicalization fix.packages/ai/src/transports/suite green: 737/737 tests, 49 files (includesopenai-responses-retained-compaction-replay.test.ts, which exercises the real end-to-endAgentMessage→ wire conversion pipeline with already-validcall_*/fc_*ids and caught the "naive always-pair" bug in an earlier iteration of this fix before landing the idempotent-short-circuit version above).src/agents/embedded-agent-helpers/openai.test.ts(the realnormalizeOpenAIResponsesToolCallIdsunit suite this fix mirrors): 10/10 passing.oxfmt --checkandoxlintclean on both changed files.previous_response_idwith a smallinputdelta instead of the full accumulated history, confirmed via the upstream proxy's own request logs.Update: fixed the P1 type-collision finding (unsafe integer vs. same-digits string)
quoteUnsafeIntegerLiteralsconverts an unsafe integer literal into a bare quoted string beforeJSON.parse, so the argument comparator's normalized output for{"n":9007199254740993}(a number) and{"n":"9007199254740993"}(a string) was byte-identical — a real number-to-string argument change wrongly compared equal, letting continuation reuse stale server-side state against a genuinely different tool call.Fixed by adding an optional
tagparameter to the sharedquoteUnsafeIntegerLiterals(default"", so every other caller — including the other real callers intransport-stream-shared.tsandanthropic-transport-stream.tsvia the wrapper functions — is unaffected), and passing a control-character-prefixed tag fromnormalizeFunctionCallArgumentsso a stringified unsafe integer can never collide with a genuine string holding the same digits.New regression test:
"does not treat an unsafe-integer argument as equal to a same-digits string (type collision)". Confirmed it fails pre-fix (expected 'continued' to be 'history_changed') and passes post-fix.Proof:
openai-responses-continuation.test.ts10/10 (was 9/9, +1 new); fullpackages/ai/src/transportssuite 738/738 (confirms the backward-compatible default doesn't change any other caller's behavior);oxfmtclean; autoreview (gpt-5.6-sol, high) clean, no accepted findings, patch correct 0.96.Update: the type-collision tag was itself wrong -- reverted, with a real live-endpoint regression it caught
Addresses ClawSweeper's P2 finding on the previous head (native-endpoint real behavior proof missing for the type-collision fix). Two bugs found:
1. Mechanical:
UNSAFE_INTEGER_COMPARISON_TAGwas defined as"openclaw-unsafe-integer"-- a literal control character once evaluated at runtime, not its JSON-escaped form.quoteUnsafeIntegerLiteralsinterpolates the tag directly between the JSON quote characters it emits, so the produced text was invalid JSON;JSON.parsethrew and thecatchsilently fell back to the untagged comparison the tag exists to replace. New regression test (treats a whitespace-only re-serialization of the same unsafe integer as equal) failed pre-fix for exactly this reason.2. Deeper, found live while proving fix (1): even once the tag was valid JSON, testing it against a real multi-round tool call over
api.openai.comshowed continuation still breaking on the very next round. Root cause:AssistantMessage.argumentsalready stores every unsafe integer as a string (parseJsonObjectPreservingUnsafeIntegers,transport-stream-shared.ts-- precision-preserving, since a JS number can't hold it losslessly). So an unmodified replay of a real tool call's argument always re-serializes as a same-digits string, compared against the cached side's raw provider text (a bare number). Tagging only the cached side made this look like a real type change on every single out-of-range-integer tool call, permanently breaking continuation for the very next round -- not a rare edge case, but the common case for timestamps, snowflake IDs, and similar large-integer arguments.The type-collision concern the tag was solving doesn't actually apply to this comparison: both sides replay the same historical tool call (not two independent model outputs), so there's no second, unrelated call for a same-digit string to collide with -- the risk the tag guarded against can't occur here.
Fix: reverted
normalizeFunctionCallArgumentsto plain (untagged)quoteUnsafeIntegerLiterals, which still correctly distinguishes two genuinely different unsafe integers (the original lossless-comparison fix, unaffected). Removed the now-unusedtagparameter fromquoteUnsafeIntegerLiteralsitself (no other caller used it). Deleted the now-incorrect "type collision" unit test and replaced it withtreats a cached number-typed unsafe integer as equal to its own replayed string-typed round-trip, proving the realistic case.Proof:
openai-responses-client.continuation-unsafe-integer.live.test.ts, gated onOPENCLAW_LIVE_TEST=1+OPENAI_API_KEY, against realhttps://api.openai.com/v1: a real tool call withn=9007199254740993(> Number.MAX_SAFE_INTEGER), replayed unmodified. Failed before this fix (fell through to a full-history resend, noprevious_response_id); passes after (continues correctly, and the wire delta'scall_idis correctly restored to the bare provider id).openai-responses-continuation.test.ts: 11/11.packages/ai/src/transports/suite: 739/739 (49 files) -- confirms removing the tag parameter doesn't change any other caller.src/agents/embedded-agent-helpers/openai.test.ts: 10/10.oxfmtclean.@clawsweeper re-review
Update: attaching the actual raw trace + production LOC justification
Addresses ClawSweeper's remaining P1/P2 findings: the prior update only narrated the live test's pass/fail rather than including the checkable raw output, and the production LOC growth needed an explicit justification rather than a bare summary.
Raw trace, exact head, real
api.openai.com(paths sanitized to repo-relative):This is the second-request recovery the finding asks about: a real tool call with
n=9007199254740993(> Number.MAX_SAFE_INTEGER), replayed unmodified on round 2, correctly carriesprevious_response_idand the restored rawcall_id-- proven against the real endpoint, not a mock.Production LOC (net +154,
openai-responses-continuation.ts+144/-5,openai-responses-tool-call-id-shape.ts+88 new,embedded-agent-helpers/openai.ts+6/-82):The
embedded-agent-helpers/openai.tsdelta is a real net reduction there (-76) -- its own id-shaping logic moved into the new shared file. That extraction is necessary, not optional:packages/aicannot import fromsrc/agents(core-boundary rule --packages/aiis the lower-level packagesrc/agentsbuilds on, not the reverse), so the continuation resolver needs its own copy of the exact id-shaping transform to canonicalize a cached raw id against what replay will produce, or the comparison silently uses a different transform than what's actually applied on the wire.openai-responses-tool-call-id-shape.tsis that necessary mirror, sized to the transform it mirrors.The remaining growth in
openai-responses-continuation.ts(+144/-5) is the actual fix:canonicalizeReplayedCallId/canonicalizeCachedCallId(comparison-side canonicalization, fail-closed on an unrelated id change -- covered by its own regression test) andrestoreRawCallIdsInDelta(restoring the provider's raw id on the wire delta, so a server reconstructing history from its own cached raw response can still pair afunction_call_outputagainst thefunction_callit cached). Both are the specific mechanism this PR exists to add; there isn't a smaller shape that preserves fail-closed behavior on a genuinely different id while forgiving only the known replay reshape.@clawsweeper re-review