From 41946c44c94b4d6e08f7afc1967eec4803d59786 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 11 May 2026 21:26:05 -0300 Subject: [PATCH 1/2] deps: bump mermaid from 11.14.0 to 11.15.0 (#2178) Bumps [mermaid](https://github.com/mermaid-js/mermaid) from 11.14.0 to 11.15.0. - [Release notes](https://github.com/mermaid-js/mermaid/releases) - [Commits](https://github.com/mermaid-js/mermaid/compare/mermaid@11.14.0...mermaid@11.15.0) --- updated-dependencies: - dependency-name: mermaid dependency-version: 11.15.0 dependency-type: direct:production ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 165 ++++------------------------------------------ 1 file changed, 13 insertions(+), 152 deletions(-) diff --git a/package-lock.json b/package-lock.json index 588bc0ac42a4..d057e9fcbf26 100644 --- a/package-lock.json +++ b/package-lock.json @@ -476,41 +476,10 @@ "specificity": "bin/cli.js" } }, - "node_modules/@chevrotain/cst-dts-gen": { - "version": "12.0.0", - "resolved": "https://registry.npmjs.org/@chevrotain/cst-dts-gen/-/cst-dts-gen-12.0.0.tgz", - "integrity": "sha512-fSL4KXjTl7cDgf0B5Rip9Q05BOrYvkJV/RrBTE/bKDN096E4hN/ySpcBK5B24T76dlQ2i32Zc3PAE27jFnFrKg==", - "license": "Apache-2.0", - "dependencies": { - "@chevrotain/gast": "12.0.0", - "@chevrotain/types": "12.0.0" - } - }, - "node_modules/@chevrotain/gast": { - "version": "12.0.0", - "resolved": "https://registry.npmjs.org/@chevrotain/gast/-/gast-12.0.0.tgz", - "integrity": "sha512-1ne/m3XsIT8aEdrvT33so0GUC+wkctpUPK6zU9IlOyJLUbR0rg4G7ZiApiJbggpgPir9ERy3FRjT6T7lpgetnQ==", - "license": "Apache-2.0", - "dependencies": { - "@chevrotain/types": "12.0.0" - } - }, - "node_modules/@chevrotain/regexp-to-ast": { - "version": "12.0.0", - "resolved": "https://registry.npmjs.org/@chevrotain/regexp-to-ast/-/regexp-to-ast-12.0.0.tgz", - "integrity": "sha512-p+EW9MaJwgaHguhoqwOtx/FwuGr+DnNn857sXWOi/mClXIkPGl3rn7hGNWvo31HA3vyeQxjqe+H36yZJwYU8cA==", - "license": "Apache-2.0" - }, "node_modules/@chevrotain/types": { - "version": "12.0.0", - "resolved": "https://registry.npmjs.org/@chevrotain/types/-/types-12.0.0.tgz", - "integrity": "sha512-S+04vjFQKeuYw0/eW3U52LkAHQsB1ASxsPGsLPUyQgrZ2iNNibQrsidruDzjEX2JYfespXMG0eZmXlhA6z7nWA==", - "license": "Apache-2.0" - }, - "node_modules/@chevrotain/utils": { - "version": "12.0.0", - "resolved": "https://registry.npmjs.org/@chevrotain/utils/-/utils-12.0.0.tgz", - "integrity": "sha512-lB59uJoaGIfOOL9knQqQRfhl9g7x8/wqFkp13zTdkRu1huG9kg6IJs1O8hqj9rs6h7orGxHJUKb+mX3rPbWGhA==", + "version": "11.1.2", + "resolved": "https://registry.npmjs.org/@chevrotain/types/-/types-11.1.2.tgz", + "integrity": "sha512-U+HFai5+zmJCkK86QsaJtoITlboZHBqrVketcO2ROv865xfCMSFpELQoz1GkX5GzME8pTa+3kbKrZHQtI0gdbw==", "license": "Apache-2.0" }, "node_modules/@csstools/color-helpers": { @@ -2178,12 +2147,12 @@ } }, "node_modules/@mermaid-js/parser": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@mermaid-js/parser/-/parser-1.1.0.tgz", - "integrity": "sha512-gxK9ZX2+Fex5zu8LhRQoMeMPEHbc73UKZ0FQ54YrQtUxE1VVhMwzeNtKRPAu5aXks4FasbMe4xB4bWrmq6Jlxw==", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@mermaid-js/parser/-/parser-1.1.1.tgz", + "integrity": "sha512-VuHdsYMK1bT6X2JbcAaWAhugTRvRBRyuZgd+c22swUeI9g/ntaxF7CY7dYarhZovofCbUNO0G7JesfmNtjYOCw==", "license": "MIT", "dependencies": { - "langium": "^4.0.0" + "@chevrotain/types": "~11.1.1" } }, "node_modules/@modelcontextprotocol/sdk": { @@ -6165,34 +6134,6 @@ "url": "https://github.com/sponsors/wooorm" } }, - "node_modules/chevrotain": { - "version": "12.0.0", - "resolved": "https://registry.npmjs.org/chevrotain/-/chevrotain-12.0.0.tgz", - "integrity": "sha512-csJvb+6kEiQaqo1woTdSAuOWdN0WTLIydkKrBnS+V5gZz0oqBrp4kQ35519QgK6TpBThiG3V1vNSHlIkv4AglQ==", - "license": "Apache-2.0", - "dependencies": { - "@chevrotain/cst-dts-gen": "12.0.0", - "@chevrotain/gast": "12.0.0", - "@chevrotain/regexp-to-ast": "12.0.0", - "@chevrotain/types": "12.0.0", - "@chevrotain/utils": "12.0.0" - }, - "engines": { - "node": ">=22.0.0" - } - }, - "node_modules/chevrotain-allstar": { - "version": "0.4.3", - "resolved": "https://registry.npmjs.org/chevrotain-allstar/-/chevrotain-allstar-0.4.3.tgz", - "integrity": "sha512-2X4mkroolSMKqW+H22pyPMUVDqYZzPhephTmg/NODKb1IGYPHfxfhcW0EjS7wcPJNbze2i4vBWT7zT5FKF2lrQ==", - "license": "MIT", - "dependencies": { - "lodash-es": "^4.18.1" - }, - "peerDependencies": { - "chevrotain": "^12.0.0" - } - }, "node_modules/chownr": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", @@ -10623,24 +10564,6 @@ "url": "https://liberapay.com/Koromix" } }, - "node_modules/langium": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/langium/-/langium-4.2.3.tgz", - "integrity": "sha512-sOPIi4hISFnY7twwV97ca1TsxpBtXq0URu/LL1AvxwccPG/RIBBlKS7a/f/EL6w8lTNaS0EFs/F+IdSOaqYpng==", - "license": "MIT", - "dependencies": { - "@chevrotain/regexp-to-ast": "~12.0.0", - "chevrotain": "~12.0.0", - "chevrotain-allstar": "~0.4.3", - "vscode-languageserver": "~9.0.1", - "vscode-languageserver-textdocument": "~1.0.11", - "vscode-uri": "~3.1.0" - }, - "engines": { - "node": ">=20.10.0", - "npm": ">=10.2.3" - } - }, "node_modules/language-subtag-registry": { "version": "0.3.23", "resolved": "https://registry.npmjs.org/language-subtag-registry/-/language-subtag-registry-0.3.23.tgz", @@ -11437,14 +11360,14 @@ } }, "node_modules/mermaid": { - "version": "11.14.0", - "resolved": "https://registry.npmjs.org/mermaid/-/mermaid-11.14.0.tgz", - "integrity": "sha512-GSGloRsBs+JINmmhl0JDwjpuezCsHB4WGI4NASHxL3fHo3o/BRXTxhDLKnln8/Q0lRFRyDdEjmk1/d5Sn1Xz8g==", + "version": "11.15.0", + "resolved": "https://registry.npmjs.org/mermaid/-/mermaid-11.15.0.tgz", + "integrity": "sha512-pTMbcf3rWdtLiYGpmoTjHEpeY8seiy6sR+9nD7LOs8KfUbHE4lOUAprTRqRAcWSQ6MQpdX+YEsxShtGsINtPtw==", "license": "MIT", "dependencies": { "@braintree/sanitize-url": "^7.1.1", "@iconify/utils": "^3.0.2", - "@mermaid-js/parser": "^1.1.0", + "@mermaid-js/parser": "^1.1.1", "@types/d3": "^7.4.3", "@upsetjs/venn.js": "^2.0.0", "cytoscape": "^3.33.1", @@ -11455,14 +11378,14 @@ "dagre-d3-es": "7.0.14", "dayjs": "^1.11.19", "dompurify": "^3.3.1", + "es-toolkit": "^1.45.1", "katex": "^0.16.25", "khroma": "^2.1.0", - "lodash-es": "^4.17.23", "marked": "^16.3.0", "roughjs": "^4.6.6", "stylis": "^4.3.6", "ts-dedent": "^2.2.0", - "uuid": "^11.1.0" + "uuid": "^11.1.0 || ^12 || ^13 || ^14.0.0" } }, "node_modules/mermaid/node_modules/marked": { @@ -11477,19 +11400,6 @@ "node": ">= 20" } }, - "node_modules/mermaid/node_modules/uuid": { - "version": "11.1.1", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.1.tgz", - "integrity": "sha512-vIYxrBCC/N/K+Js3qSN88go7kIfNPssr/hHCesKCQNAjmgvYS2oqr69kIufEG+O4+PfezOH4EbIeHCfFov8ZgQ==", - "funding": [ - "https://github.com/sponsors/broofa", - "https://github.com/sponsors/ctavan" - ], - "license": "MIT", - "bin": { - "uuid": "dist/esm/bin/uuid" - } - }, "node_modules/micromark": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.2.tgz", @@ -15854,55 +15764,6 @@ } } }, - "node_modules/vscode-jsonrpc": { - "version": "8.2.0", - "resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-8.2.0.tgz", - "integrity": "sha512-C+r0eKJUIfiDIfwJhria30+TYWPtuHJXHtI7J0YlOmKAo7ogxP20T0zxB7HZQIFhIyvoBPwWskjxrvAtfjyZfA==", - "license": "MIT", - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/vscode-languageserver": { - "version": "9.0.1", - "resolved": "https://registry.npmjs.org/vscode-languageserver/-/vscode-languageserver-9.0.1.tgz", - "integrity": "sha512-woByF3PDpkHFUreUa7Hos7+pUWdeWMXRd26+ZX2A8cFx6v/JPTtd4/uN0/jB6XQHYaOlHbio03NTHCqrgG5n7g==", - "license": "MIT", - "dependencies": { - "vscode-languageserver-protocol": "3.17.5" - }, - "bin": { - "installServerIntoExtension": "bin/installServerIntoExtension" - } - }, - "node_modules/vscode-languageserver-protocol": { - "version": "3.17.5", - "resolved": "https://registry.npmjs.org/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.17.5.tgz", - "integrity": "sha512-mb1bvRJN8SVznADSGWM9u/b07H7Ecg0I3OgXDuLdn307rl/J3A9YD6/eYOssqhecL27hK1IPZAsaqh00i/Jljg==", - "license": "MIT", - "dependencies": { - "vscode-jsonrpc": "8.2.0", - "vscode-languageserver-types": "3.17.5" - } - }, - "node_modules/vscode-languageserver-textdocument": { - "version": "1.0.12", - "resolved": "https://registry.npmjs.org/vscode-languageserver-textdocument/-/vscode-languageserver-textdocument-1.0.12.tgz", - "integrity": "sha512-cxWNPesCnQCcMPeenjKKsOCKQZ/L6Tv19DTRIGuLWe32lyzWhihGVJ/rcckZXJxfdKCFvRLS3fpBIsV/ZGX4zA==", - "license": "MIT" - }, - "node_modules/vscode-languageserver-types": { - "version": "3.17.5", - "resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.17.5.tgz", - "integrity": "sha512-Ld1VelNuX9pdF39h2Hgaeb5hEZM2Z3jUrrMgWQAu82jMtZp7p3vJT3BzToKtZI7NgQssZje5o0zryOrhQvzQAg==", - "license": "MIT" - }, - "node_modules/vscode-uri": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-3.1.0.tgz", - "integrity": "sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==", - "license": "MIT" - }, "node_modules/w3c-xmlserializer": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", From 231a27afc09d2cf7ff51e51f5f1271b23cbd4a98 Mon Sep 17 00:00:00 2001 From: OmniRoute Ops Date: Wed, 13 May 2026 14:45:47 +0000 Subject: [PATCH 2/2] fix(translator): coerce submit_pr_review functionalChanges/findings to arrays MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Some strict-schema downstream tools (e.g. submit_pr_review with required `functionalChanges`/`findings` array fields) hard-reject when those fields arrive as null, plain object, empty string, or stringified array — malformation modes that can emerge from OpenAI-shape upstream models routed through the streaming openai-to-claude translator. Without defense, the caller enters a retry loop it cannot recover from. Adds a small `TOOL_SHIMS` registry that the SSE translator applies on the streaming OpenAI -> Anthropic tool_use path. For registered tools the shim buffers raw args, suppresses passthrough `input_json_delta` events, then emits one corrective delta with the fully patched JSON just before `content_block_stop`. Handles five malformation modes per field. Zero overhead for non-shimmed tools. Side benefit: neutralises the collateral damage from the strip-empty heuristic in #1852 when legitimate empty arrays are required by the tool schema. Adding another strict-schema tool to the registry is one entry. 20/20 unit + streaming integration tests in `tests/unit/translator-tool-call-shim.test.ts`. Adjacent translator suites stay green. Verified stable for ~24h on a downstream deploy under heavy review-harness traffic. --- open-sse/translator/helpers/toolCallShim.ts | 67 +++++ .../translator/response/openai-to-claude.ts | 36 ++- tests/unit/translator-tool-call-shim.test.ts | 263 ++++++++++++++++++ 3 files changed, 361 insertions(+), 5 deletions(-) create mode 100644 open-sse/translator/helpers/toolCallShim.ts create mode 100644 tests/unit/translator-tool-call-shim.test.ts diff --git a/open-sse/translator/helpers/toolCallShim.ts b/open-sse/translator/helpers/toolCallShim.ts new file mode 100644 index 000000000000..94ebfece01f2 --- /dev/null +++ b/open-sse/translator/helpers/toolCallShim.ts @@ -0,0 +1,67 @@ +// Defensive shims for tool calls whose strict-schema fields can be malformed +// by upstream models (e.g. MiMo emitting empty objects/strings instead of +// arrays for Capy's submit_pr_review). +// +// Applied on the assembled OpenAI tool-call arguments after streaming, just +// before they are re-emitted as a single Claude input_json_delta. +// +// To add a new shim: register a (input) => input transformer in TOOL_SHIMS +// keyed by the tool name. The transformer must accept arbitrary input and +// return a JSON-safe value. + +type ShimFn = (input: unknown) => unknown; + +function coerceToArray(v: unknown): unknown[] { + if (Array.isArray(v)) return v; + if (v == null) return []; + if (typeof v === "string") { + if (v === "") return []; + try { + const parsed = JSON.parse(v); + return Array.isArray(parsed) ? parsed : []; + } catch { + return []; + } + } + // Plain object or other non-array → empty + return []; +} + +const TOOL_SHIMS: Record = { + submit_pr_review: (input) => { + if (typeof input !== "object" || input === null || Array.isArray(input)) return input; + const patched = { ...(input as Record) }; + for (const key of ["functionalChanges", "findings"]) { + patched[key] = coerceToArray(patched[key]); + } + return patched; + }, +}; + +export function hasToolCallShim(name: string | undefined | null): boolean { + return typeof name === "string" && Object.prototype.hasOwnProperty.call(TOOL_SHIMS, name); +} + +/** + * Apply the registered shim for a tool call's raw assembled arguments string. + * Returns a stringified JSON value safe to emit as input_json_delta.partial_json. + * If the buffer is unparseable, returns the empty-object JSON `{}` after applying + * the shim with `{}` as input (so required arrays still get injected). + */ +export function applyToolCallShimToBuffer(name: string, raw: string): string { + const shim = TOOL_SHIMS[name]; + if (!shim) return raw; + + let parsed: unknown; + try { + parsed = raw && raw.length > 0 ? JSON.parse(raw) : {}; + } catch { + parsed = {}; + } + + const patched = shim(parsed); + return JSON.stringify(patched); +} + +// Exposed for unit tests only. +export const __test = { coerceToArray, TOOL_SHIMS }; diff --git a/open-sse/translator/response/openai-to-claude.ts b/open-sse/translator/response/openai-to-claude.ts index 801594f01ef2..2dfa246d2dac 100644 --- a/open-sse/translator/response/openai-to-claude.ts +++ b/open-sse/translator/response/openai-to-claude.ts @@ -1,6 +1,7 @@ import { register } from "../registry.ts"; import { FORMATS } from "../formats.ts"; import { CLAUDE_OAUTH_TOOL_PREFIX } from "../request/openai-to-claude.ts"; +import { hasToolCallShim, applyToolCallShimToBuffer } from "../helpers/toolCallShim.ts"; // Helper: stop thinking block if started function stopThinkingBlock(state, results) { @@ -157,11 +158,6 @@ export function openaiToClaudeResponse(chunk, state) { stopTextBlock(state, results); const toolBlockIndex = state.nextBlockIndex++; - state.toolCalls.set(idx, { - id: tc.id, - name: tc.function?.name || "", - blockIndex: toolBlockIndex, - }); // Strip prefix from tool name for response let toolName = tc.function?.name || ""; @@ -169,6 +165,16 @@ export function openaiToClaudeResponse(chunk, state) { toolName = toolName.slice(CLAUDE_OAUTH_TOOL_PREFIX.length); } + state.toolCalls.set(idx, { + id: tc.id, + name: toolName, + blockIndex: toolBlockIndex, + // Shimmed tools buffer their raw args and emit a single corrected + // input_json_delta at content_block_stop time (see finish handler). + shimmed: hasToolCallShim(toolName), + argBuffer: "", + }); + results.push({ type: "content_block_start", index: toolBlockIndex, @@ -184,6 +190,15 @@ export function openaiToClaudeResponse(chunk, state) { if (tc.function?.arguments) { const toolInfo = state.toolCalls.get(idx); if (toolInfo) { + // Always buffer the raw stream so shimmed tools can re-emit a + // corrected JSON at stop time. + toolInfo.argBuffer = (toolInfo.argBuffer || "") + tc.function.arguments; + + if (toolInfo.shimmed) { + // Suppress passthrough; we emit one corrective delta at finish. + continue; + } + let deltaStr = tc.function.arguments; // Fix #1852: Strip empty string and array placeholders from streaming tool arguments @@ -211,6 +226,17 @@ export function openaiToClaudeResponse(chunk, state) { stopTextBlock(state, results); for (const [, toolInfo] of state.toolCalls) { + // For shimmed tools, emit one corrective input_json_delta with the + // fully patched JSON before closing the block. + if (toolInfo.shimmed) { + const patched = applyToolCallShimToBuffer(toolInfo.name, toolInfo.argBuffer || ""); + results.push({ + type: "content_block_delta", + index: toolInfo.blockIndex, + delta: { type: "input_json_delta", partial_json: patched }, + }); + } + results.push({ type: "content_block_stop", index: toolInfo.blockIndex, diff --git a/tests/unit/translator-tool-call-shim.test.ts b/tests/unit/translator-tool-call-shim.test.ts new file mode 100644 index 000000000000..14e9b4b0affc --- /dev/null +++ b/tests/unit/translator-tool-call-shim.test.ts @@ -0,0 +1,263 @@ +import test from "node:test"; +import assert from "node:assert/strict"; + +const { applyToolCallShimToBuffer, hasToolCallShim, __test } = await import( + "../../open-sse/translator/helpers/toolCallShim.ts" +); +const { openaiToClaudeResponse } = await import( + "../../open-sse/translator/response/openai-to-claude.ts" +); + +const { coerceToArray } = __test as { coerceToArray: (v: unknown) => unknown[] }; + +// -------- Helper-level tests -------- + +test("hasToolCallShim: returns true for submit_pr_review only", () => { + assert.equal(hasToolCallShim("submit_pr_review"), true); + assert.equal(hasToolCallShim("some_other_tool"), false); + assert.equal(hasToolCallShim(""), false); + assert.equal(hasToolCallShim(undefined), false); + assert.equal(hasToolCallShim(null), false); +}); + +test("coerceToArray: passes arrays through unchanged", () => { + assert.deepEqual(coerceToArray([]), []); + assert.deepEqual(coerceToArray([{ a: 1 }]), [{ a: 1 }]); +}); + +test("coerceToArray: null/undefined -> []", () => { + assert.deepEqual(coerceToArray(null), []); + assert.deepEqual(coerceToArray(undefined), []); +}); + +test("coerceToArray: plain object -> []", () => { + assert.deepEqual(coerceToArray({}), []); + assert.deepEqual(coerceToArray({ a: 1 }), []); +}); + +test("coerceToArray: empty string -> []", () => { + assert.deepEqual(coerceToArray(""), []); +}); + +test("coerceToArray: stringified array parsed", () => { + assert.deepEqual(coerceToArray("[]"), []); + assert.deepEqual(coerceToArray('[{"title":"x"}]'), [{ title: "x" }]); +}); + +test("coerceToArray: unparseable string -> []", () => { + assert.deepEqual(coerceToArray("not json"), []); + assert.deepEqual(coerceToArray("{"), []); +}); + +test("coerceToArray: stringified non-array -> []", () => { + assert.deepEqual(coerceToArray('{"a":1}'), []); + assert.deepEqual(coerceToArray('"a string"'), []); +}); + +test("applyToolCallShimToBuffer: submit_pr_review with valid arrays preserved", () => { + const raw = JSON.stringify({ + summary: "ok", + functionalChanges: [{ description: "x" }], + findings: [{ title: "y" }], + }); + const out = JSON.parse(applyToolCallShimToBuffer("submit_pr_review", raw)); + assert.equal(out.summary, "ok"); + assert.deepEqual(out.functionalChanges, [{ description: "x" }]); + assert.deepEqual(out.findings, [{ title: "y" }]); +}); + +test("applyToolCallShimToBuffer: submit_pr_review missing both keys -> arrays injected", () => { + const raw = JSON.stringify({ summary: "no findings" }); + const out = JSON.parse(applyToolCallShimToBuffer("submit_pr_review", raw)); + assert.equal(out.summary, "no findings"); + assert.deepEqual(out.functionalChanges, []); + assert.deepEqual(out.findings, []); +}); + +test("applyToolCallShimToBuffer: submit_pr_review with functionalChanges=null replaced", () => { + const raw = JSON.stringify({ functionalChanges: null, findings: [] }); + const out = JSON.parse(applyToolCallShimToBuffer("submit_pr_review", raw)); + assert.deepEqual(out.functionalChanges, []); + assert.deepEqual(out.findings, []); +}); + +test("applyToolCallShimToBuffer: submit_pr_review with findings={} replaced", () => { + const raw = JSON.stringify({ functionalChanges: [], findings: {} }); + const out = JSON.parse(applyToolCallShimToBuffer("submit_pr_review", raw)); + assert.deepEqual(out.findings, []); +}); + +test("applyToolCallShimToBuffer: submit_pr_review with findings='' replaced", () => { + const raw = JSON.stringify({ functionalChanges: [], findings: "" }); + const out = JSON.parse(applyToolCallShimToBuffer("submit_pr_review", raw)); + assert.deepEqual(out.findings, []); +}); + +test("applyToolCallShimToBuffer: submit_pr_review with findings='[]' parsed", () => { + const raw = JSON.stringify({ functionalChanges: [], findings: "[]" }); + const out = JSON.parse(applyToolCallShimToBuffer("submit_pr_review", raw)); + assert.deepEqual(out.findings, []); +}); + +test("applyToolCallShimToBuffer: submit_pr_review with stringified array of objects parsed", () => { + const raw = JSON.stringify({ + functionalChanges: [], + findings: '[{"title":"x"}]', + }); + const out = JSON.parse(applyToolCallShimToBuffer("submit_pr_review", raw)); + assert.deepEqual(out.findings, [{ title: "x" }]); +}); + +test("applyToolCallShimToBuffer: submit_pr_review with empty buffer -> empty arrays injected", () => { + const out = JSON.parse(applyToolCallShimToBuffer("submit_pr_review", "")); + assert.deepEqual(out.functionalChanges, []); + assert.deepEqual(out.findings, []); +}); + +test("applyToolCallShimToBuffer: submit_pr_review with unparseable buffer -> empty arrays", () => { + const out = JSON.parse(applyToolCallShimToBuffer("submit_pr_review", "{broken")); + assert.deepEqual(out.functionalChanges, []); + assert.deepEqual(out.findings, []); +}); + +test("applyToolCallShimToBuffer: non-shimmed tool passes raw through", () => { + const raw = '{"x":1}'; + assert.equal(applyToolCallShimToBuffer("some_other_tool", raw), raw); +}); + +// -------- Streaming integration tests -------- + +function freshState() { + return { + messageStartSent: false, + nextBlockIndex: 0, + toolCalls: new Map(), + thinkingBlockStarted: false, + textBlockStarted: false, + textBlockClosed: false, + }; +} + +function streamChunks(chunks: any[], state: any): any[] { + const all: any[] = []; + for (const c of chunks) { + const out = openaiToClaudeResponse(c, state); + if (out) all.push(...out); + } + return all; +} + +test("streaming: submit_pr_review with missing arrays gets corrective delta at finish", () => { + const state = freshState(); + const chunks = [ + // chunk 1: message start + tool call start with name + { + id: "chatcmpl-1", + model: "xiaomi-mimo/mimo-v2.5-pro", + choices: [ + { + delta: { + tool_calls: [ + { + index: 0, + id: "call_1", + function: { name: "submit_pr_review", arguments: "" }, + }, + ], + }, + }, + ], + }, + // chunk 2: argument fragment (summary only — no findings/functionalChanges) + { + choices: [ + { + delta: { + tool_calls: [ + { + index: 0, + function: { arguments: '{"summary":"no findings"}' }, + }, + ], + }, + }, + ], + }, + // chunk 3: finish + { + choices: [{ delta: {}, finish_reason: "tool_calls" }], + }, + ]; + + const events = streamChunks(chunks, state); + + // No passthrough input_json_delta for shimmed tool + const passthroughDeltas = events.filter( + (e) => + e.type === "content_block_delta" && + e.delta?.type === "input_json_delta" && + e.delta?.partial_json === '{"summary":"no findings"}' + ); + assert.equal(passthroughDeltas.length, 0, "raw passthrough delta should be suppressed"); + + // Exactly one corrective input_json_delta on the tool block + const correctiveDeltas = events.filter( + (e) => e.type === "content_block_delta" && e.delta?.type === "input_json_delta" + ); + assert.equal(correctiveDeltas.length, 1, "expected exactly one corrective delta"); + + const finalInput = JSON.parse(correctiveDeltas[0].delta.partial_json); + assert.equal(finalInput.summary, "no findings"); + assert.deepEqual(finalInput.functionalChanges, []); + assert.deepEqual(finalInput.findings, []); + + // Corrective delta MUST come before the content_block_stop for that tool block + const correctiveIdx = events.findIndex( + (e) => e.type === "content_block_delta" && e.delta?.type === "input_json_delta" + ); + const stopIdx = events.findIndex( + (e) => e.type === "content_block_stop" && e.index === correctiveDeltas[0].index + ); + assert.ok(correctiveIdx < stopIdx, "corrective delta must precede content_block_stop"); +}); + +test("streaming: non-shimmed tool still streams partials through", () => { + const state = freshState(); + const chunks = [ + { + id: "chatcmpl-1", + model: "x", + choices: [ + { + delta: { + tool_calls: [ + { + index: 0, + id: "call_1", + function: { name: "some_other_tool", arguments: "" }, + }, + ], + }, + }, + ], + }, + { + choices: [ + { + delta: { + tool_calls: [{ index: 0, function: { arguments: '{"x":1}' } }], + }, + }, + ], + }, + { choices: [{ delta: {}, finish_reason: "tool_calls" }] }, + ]; + + const events = streamChunks(chunks, state); + const deltas = events.filter( + (e) => e.type === "content_block_delta" && e.delta?.type === "input_json_delta" + ); + // For non-shimmed tools, the original passthrough delta survives (and no extra corrective delta). + assert.equal(deltas.length, 1); + assert.equal(deltas[0].delta.partial_json, '{"x":1}'); +});