From 86b993daee7e612889b3224e5af8a82b7cfeb72d Mon Sep 17 00:00:00 2001 From: Christopher Kevin Date: Sat, 14 Nov 2026 23:18:06 +0000 Subject: [PATCH 1/4] fix(bridge): preserve NVIDIA Build token usage Signed-off-by: Christopher Kevin --- CHANGELOG.md | 3 + .../tier3/harbor/nvidia_build_bridge.py | 64 +++++++++++++++++-- tests/test_nvidia_build_bridge.py | 44 ++++++++++++- 3 files changed, 106 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 86317f39e..afb854dc1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -249,6 +249,9 @@ All notable changes to SkillEvaluator are documented in this file. ### Fixed +- The NVIDIA Build bridge preserves reported input, output and cached token + usage in Anthropic Messages and Responses API replies instead of discarding + it or reporting synthetic zero counts. - The Copilot CLI `CP-NO-FRONTMATTER` finding and the plugin component findings of `harness-check` no longer show internal test notes in their messages. - The behavior judge's FILE CHANGES evidence now covers Codex `apply_patch` diff --git a/src/skillevaluator/tier3/harbor/nvidia_build_bridge.py b/src/skillevaluator/tier3/harbor/nvidia_build_bridge.py index f7acc3b0f..92ca6e414 100644 --- a/src/skillevaluator/tier3/harbor/nvidia_build_bridge.py +++ b/src/skillevaluator/tier3/harbor/nvidia_build_bridge.py @@ -221,7 +221,10 @@ def do_POST(self) -> None: self._log(error.status_code, route, error.category) return - self._send_sse(events) + if payload.get("stream") is False and route == MESSAGES_PATH: + self._send_json(200, _anthropic_message_from_events(events)) + else: + self._send_sse(events) self._log(200, route, "none") def _client_is_authorized(self) -> bool: @@ -1303,7 +1306,13 @@ def chat_completion_to_responses_events( ) events.append( - {"type": "response.completed", "response": _responses_response(response_id, model, "completed", output)} + { + "type": "response.completed", + "response": { + **_responses_response(response_id, model, "completed", output), + "usage": _chat_usage(payload, anthropic=False), + }, + } ) for sequence_number, event in enumerate(events, start=1): yield {**event, "sequence_number": sequence_number} @@ -1324,7 +1333,7 @@ def chat_completion_to_anthropic_events( "model": model, "content": [], "stop_reason": None, - "usage": {"input_tokens": 0, "output_tokens": 0}, + "usage": _chat_usage(payload, anthropic=True), }, } @@ -1354,11 +1363,58 @@ def chat_completion_to_anthropic_events( yield { "type": "message_delta", "delta": {"stop_reason": "tool_use" if normalized_tool_calls else "end_turn", "stop_sequence": None}, - "usage": {"input_tokens": 0, "output_tokens": 0}, + "usage": _chat_usage(payload, anthropic=True), } yield {"type": "message_stop"} +def _chat_usage(payload: dict[str, Any], *, anthropic: bool) -> dict[str, Any] | None: + usage = payload.get("usage") + if not isinstance(usage, dict): + return None + result: dict[str, Any] = {} + for source, target in (("prompt_tokens", "input_tokens"), ("completion_tokens", "output_tokens")): + value = usage.get(source) + if isinstance(value, int) and not isinstance(value, bool) and value >= 0: + result[target] = value + details = usage.get("prompt_tokens_details") + cached = details.get("cached_tokens") if isinstance(details, dict) else None + if isinstance(cached, int) and not isinstance(cached, bool) and cached >= 0: + if anthropic: + result["cache_read_input_tokens"] = cached + if "input_tokens" in result: + result["input_tokens"] -= cached + else: + result["input_tokens_details"] = {"cached_tokens": cached} + if not anthropic: + total = usage.get("total_tokens") + if isinstance(total, int) and not isinstance(total, bool) and total >= 0: + result["total_tokens"] = total + elif "input_tokens" in result and "output_tokens" in result: + result["total_tokens"] = result["input_tokens"] + result["output_tokens"] + return result or None + + +def _anthropic_message_from_events(events: list[dict[str, Any]]) -> dict[str, Any]: + message = dict(events[0]["message"]) + content: list[dict[str, Any]] = [] + for event in events: + if event["type"] == "content_block_start": + content.append(dict(event["content_block"])) + elif event["type"] == "content_block_delta": + block = content[event["index"]] + delta = event["delta"] + if delta["type"] == "text_delta": + block["text"] += delta["text"] + else: + block["input"] = json.loads(delta["partial_json"]) + elif event["type"] == "message_delta": + message.update(event["delta"]) + message["usage"] = event["usage"] + message["content"] = content + return message + + def redact_bridge_text(value: Any) -> str: """Redact common credential-bearing text before bridge diagnostics are written.""" text = str(value) diff --git a/tests/test_nvidia_build_bridge.py b/tests/test_nvidia_build_bridge.py index 61ec3bc20..ec1088ebe 100644 --- a/tests/test_nvidia_build_bridge.py +++ b/tests/test_nvidia_build_bridge.py @@ -2515,6 +2515,37 @@ def test_build_tool_call_emits_anthropic_tool_use_and_message_stop() -> None: assert events[-1] == {"type": "message_stop"} +@pytest.mark.parametrize( + ("usage", "anthropic", "responses"), + [ + (None, None, None), + ({}, None, None), + ({"prompt_tokens": "bad", "completion_tokens": -1}, None, None), + ({"completion_tokens": 0}, {"output_tokens": 0}, {"output_tokens": 0}), + ( + {"prompt_tokens": 100, "completion_tokens": 20, "prompt_tokens_details": {"cached_tokens": 30}}, + {"input_tokens": 70, "output_tokens": 20, "cache_read_input_tokens": 30}, + { + "input_tokens": 100, + "output_tokens": 20, + "total_tokens": 120, + "input_tokens_details": {"cached_tokens": 30}, + }, + ), + ], +) +def test_bridge_preserves_reported_usage(usage: object, anthropic: object, responses: object) -> None: + completion = {**CHAT_TEXT_RESPONSE, "usage": usage} + events = list(chat_completion_to_anthropic_events(completion)) + assert events[0]["message"]["usage"] == anthropic + assert events[-2]["usage"] == anthropic + message = bridge._anthropic_message_from_events(events) + assert message["usage"] == anthropic + assert message["content"][0]["text"] == CHAT_TEXT_RESPONSE["choices"][0]["message"]["content"] + response_events = list(chat_completion_to_responses_events(completion)) + assert response_events[-1]["response"]["usage"] == responses + + def test_anthropic_tool_arguments_are_validated_before_first_event() -> None: malformed_completion = { **CHAT_TOOL_RESPONSE, @@ -2583,7 +2614,18 @@ def test_responses_events_validate_with_openai_sdk_and_have_sequence_numbers(com @pytest.mark.parametrize("completion", [CHAT_TOOL_RESPONSE, CHAT_TEXT_RESPONSE]) def test_anthropic_events_validate_with_sdk(completion: dict[str, object]) -> None: - events = list(chat_completion_to_anthropic_events(completion)) + events = list( + chat_completion_to_anthropic_events( + { + **completion, + "usage": { + "prompt_tokens": 100, + "completion_tokens": 20, + "prompt_tokens_details": {"cached_tokens": 30}, + }, + } + ) + ) validator = TypeAdapter(RawMessageStreamEvent) for event in events: From 86234a070cb2e6ebdfebd284d92b99a2d5b43a36 Mon Sep 17 00:00:00 2001 From: Christopher Kevin Date: Sat, 14 Nov 2026 23:34:50 +0000 Subject: [PATCH 2/4] fix(bridge): keep Anthropic usage schema-valid Signed-off-by: Christopher Kevin --- CHANGELOG.md | 5 +-- .../tier3/harbor/nvidia_build_bridge.py | 8 +++-- tests/test_nvidia_build_bridge.py | 36 ++++++++++++++++--- 3 files changed, 39 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index afb854dc1..f15dbfa37 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -250,8 +250,9 @@ All notable changes to SkillEvaluator are documented in this file. ### Fixed - The NVIDIA Build bridge preserves reported input, output and cached token - usage in Anthropic Messages and Responses API replies instead of discarding - it or reporting synthetic zero counts. + usage in Anthropic Messages and Responses API replies. Anthropic replies use + schema-required zero defaults for missing input/output fields and clamp + uncached input counts at zero; Responses usage remains absent when unreported. - The Copilot CLI `CP-NO-FRONTMATTER` finding and the plugin component findings of `harness-check` no longer show internal test notes in their messages. - The behavior judge's FILE CHANGES evidence now covers Codex `apply_patch` diff --git a/src/skillevaluator/tier3/harbor/nvidia_build_bridge.py b/src/skillevaluator/tier3/harbor/nvidia_build_bridge.py index 92ca6e414..3cb3daea1 100644 --- a/src/skillevaluator/tier3/harbor/nvidia_build_bridge.py +++ b/src/skillevaluator/tier3/harbor/nvidia_build_bridge.py @@ -1371,8 +1371,10 @@ def chat_completion_to_anthropic_events( def _chat_usage(payload: dict[str, Any], *, anthropic: bool) -> dict[str, Any] | None: usage = payload.get("usage") if not isinstance(usage, dict): - return None - result: dict[str, Any] = {} + if not anthropic: + return None + usage = {} + result: dict[str, Any] = {"input_tokens": 0, "output_tokens": 0} if anthropic else {} for source, target in (("prompt_tokens", "input_tokens"), ("completion_tokens", "output_tokens")): value = usage.get(source) if isinstance(value, int) and not isinstance(value, bool) and value >= 0: @@ -1383,7 +1385,7 @@ def _chat_usage(payload: dict[str, Any], *, anthropic: bool) -> dict[str, Any] | if anthropic: result["cache_read_input_tokens"] = cached if "input_tokens" in result: - result["input_tokens"] -= cached + result["input_tokens"] = max(0, result["input_tokens"] - cached) else: result["input_tokens_details"] = {"cached_tokens": cached} if not anthropic: diff --git a/tests/test_nvidia_build_bridge.py b/tests/test_nvidia_build_bridge.py index ec1088ebe..95bdd7286 100644 --- a/tests/test_nvidia_build_bridge.py +++ b/tests/test_nvidia_build_bridge.py @@ -20,7 +20,7 @@ from threading import Event, Thread import pytest -from anthropic.types import RawMessageStreamEvent +from anthropic.types import Message, RawMessageStreamEvent from openai.types.responses import ResponsesServerEvent from pydantic import TypeAdapter @@ -2518,10 +2518,10 @@ def test_build_tool_call_emits_anthropic_tool_use_and_message_stop() -> None: @pytest.mark.parametrize( ("usage", "anthropic", "responses"), [ - (None, None, None), - ({}, None, None), - ({"prompt_tokens": "bad", "completion_tokens": -1}, None, None), - ({"completion_tokens": 0}, {"output_tokens": 0}, {"output_tokens": 0}), + (None, {"input_tokens": 0, "output_tokens": 0}, None), + ({}, {"input_tokens": 0, "output_tokens": 0}, None), + ({"prompt_tokens": "bad", "completion_tokens": -1}, {"input_tokens": 0, "output_tokens": 0}, None), + ({"completion_tokens": 0}, {"input_tokens": 0, "output_tokens": 0}, {"output_tokens": 0}), ( {"prompt_tokens": 100, "completion_tokens": 20, "prompt_tokens_details": {"cached_tokens": 30}}, {"input_tokens": 70, "output_tokens": 20, "cache_read_input_tokens": 30}, @@ -2546,6 +2546,32 @@ def test_bridge_preserves_reported_usage(usage: object, anthropic: object, respo assert response_events[-1]["response"]["usage"] == responses +@pytest.mark.parametrize("completion", [CHAT_TOOL_RESPONSE, CHAT_TEXT_RESPONSE]) +@pytest.mark.parametrize( + ("usage_fields", "expected"), + [ + ({}, {"input_tokens": 0, "output_tokens": 0}), + ({"usage": {"completion_tokens": 20}}, {"input_tokens": 0, "output_tokens": 20}), + ( + {"usage": {"prompt_tokens": 10, "prompt_tokens_details": {"cached_tokens": 30}}}, + {"input_tokens": 0, "output_tokens": 0, "cache_read_input_tokens": 30}, + ), + ], +) +def test_anthropic_missing_usage_is_schema_valid( + completion: dict[str, object], usage_fields: dict[str, object], expected: dict[str, int] +) -> None: + events = list(chat_completion_to_anthropic_events({**completion, **usage_fields})) + validator = TypeAdapter(RawMessageStreamEvent) + for event in events: + validator.validate_python(event, strict=True) + assert events[0]["message"]["usage"] == expected + assert events[-2]["usage"] == expected + message = bridge._anthropic_message_from_events(events) + TypeAdapter(Message).validate_python(message, strict=True) + assert message["usage"] == expected + + def test_anthropic_tool_arguments_are_validated_before_first_event() -> None: malformed_completion = { **CHAT_TOOL_RESPONSE, From f29e9f86a52e1096c04d84bb59bd7466cc851ced Mon Sep 17 00:00:00 2001 From: Christopher Kevin Date: Sat, 14 Nov 2026 20:06:48 -0800 Subject: [PATCH 3/4] Keep only this change's changelog entry after merging main Signed-off-by: Christopher Kevin --- CHANGELOG.md | 51 --------------------------------------------------- 1 file changed, 51 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2ad67d011..54fe18f4d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -268,61 +268,10 @@ All notable changes to SkillEvaluator are documented in this file. touches rather than letting the first stand for the rest, and keep the patch text itself as the write body. A headerless or malformed `input` is left alone, so a shell source string is not reported as a file change. -- Automatic SkillSpector selection now verifies the pinned release on first use - and falls back to the verified managed wheel for a different or unverifiable - version. Discovery stays free of subprocesses, version probes omit provider - credentials and respect the caller timeout, and explicit executable overrides - remain available. Doctor reports the path and source selected by the probe. -- `health-check --tier 1` (and `doctor --tier 1`) labels a scanner that - SkillEvaluator provisions itself: `(uv tool run)` for SkillSpector and - `(managed)` for the downloaded Gitleaks binary. Before, the Gitleaks row - ended in `(from None)` and the SkillSpector row named - `SKILLEVALUATOR_SKILLSPECTOR_PATH` although no override was set. -- The comments-only consumer template now grants its required read and PR-comment - permissions only to the comment job, with no workflow-wide token permissions. -- The behavior evidence gate no longer keeps a score for an expectation that - names an observed artifact but also asks for something only the final answer - could show. "Writes `report.py` and explains why each column was dropped" was - treated as settled by the artifact alone, so a case kept a score whose second - half was never checked. Every clause of an expectation must now name a - checkable artifact of its own; one that does not keeps the gate, as a wholly - prose expectation already did. -- SARIF `artifactLocation.uri` values percent-encode a `%` in a file name as - `%25`. A file such as `a%20b.md` no longer shares the URI of `a b.md`, and - `100%.md` no longer produces an invalid URI. -- Reports no longer fail on Linux when a skill file name is not valid UTF-8 - (#525). Finding IDs, HTML issue keys, the written HTML, JSON, Markdown and - SARIF reports, the CI workflow scripts that re-render retained reports, and - generated `evals/evals.json` datasets accept the surrogate-escaped name - Python gives such a file. The SARIF `artifactLocation.uri` percent-encodes - the name's original bytes (`caf%E9.md`). -- SARIF `artifactLocation.uri` values stay valid for more paths. A - repository-relative path whose first segment contains a colon, such as - `notes:v2.md`, gets a `./` prefix so it no longer reads as a URI scheme. A - path outside the workspace is written as an absolute `file:` URI instead of - a bare file system path, and a symlink in the workspace that points outside - it keeps the link's repository-relative path. -- Accuracy and Behavior judge prompts clarify that explicit final-answer formats - apply to the entire final response, independently of correct values in tool - output or references. Scoring and thresholds are unchanged; an Accuracy format - failure alone can still score 0.8 and pass the default threshold. - - The NVIDIA Build bridge preserves reported input, output and cached token usage in Anthropic Messages and Responses API replies. Anthropic replies use schema-required zero defaults for missing input/output fields and clamp uncached input counts at zero; Responses usage remains absent when unreported. -- The Copilot CLI `CP-NO-FRONTMATTER` finding and the plugin component findings - of `harness-check` no longer show internal test notes in their messages. -- The behavior judge's FILE CHANGES evidence now covers Codex `apply_patch` - calls. Codex passes its patch as a single `input` argument, which the write - evidence helpers did not read, so a Codex patch contributed no FILE CHANGES - entry and its contents survived only in the compact tool history -- the - section budgeted last, and so the first dropped when the bundle is trimmed. - The helpers now take the changed paths from the patch's `Add File`, - `Update File` and `Delete File` headers, naming every file a multi-file patch - touches rather than letting the first stand for the rest, and keep the patch - text itself as the write body. A headerless or malformed `input` is left - alone, so a shell source string is not reported as a file change. - Automatic SkillSpector selection now verifies the pinned release on first use and falls back to the verified managed wheel for a different or unverifiable version. Discovery stays free of subprocesses, version probes omit provider From f1b1894c1e1a4ef0d18463b5120116a1f8cdff26 Mon Sep 17 00:00:00 2001 From: Christopher Kevin Date: Sat, 14 Nov 2026 20:13:14 -0800 Subject: [PATCH 4/4] fix(bridge): send complete Responses usage objects Signed-off-by: Christopher Kevin --- .../tier3/harbor/nvidia_build_bridge.py | 25 +++-- tests/test_nvidia_build_bridge.py | 105 +++++++++++++++++- 2 files changed, 121 insertions(+), 9 deletions(-) diff --git a/src/skillevaluator/tier3/harbor/nvidia_build_bridge.py b/src/skillevaluator/tier3/harbor/nvidia_build_bridge.py index 3cb3daea1..16beb01f7 100644 --- a/src/skillevaluator/tier3/harbor/nvidia_build_bridge.py +++ b/src/skillevaluator/tier3/harbor/nvidia_build_bridge.py @@ -1388,13 +1388,24 @@ def _chat_usage(payload: dict[str, Any], *, anthropic: bool) -> dict[str, Any] | result["input_tokens"] = max(0, result["input_tokens"] - cached) else: result["input_tokens_details"] = {"cached_tokens": cached} - if not anthropic: - total = usage.get("total_tokens") - if isinstance(total, int) and not isinstance(total, bool) and total >= 0: - result["total_tokens"] = total - elif "input_tokens" in result and "output_tokens" in result: - result["total_tokens"] = result["input_tokens"] + result["output_tokens"] - return result or None + if anthropic: + return result + completion_details = usage.get("completion_tokens_details") + reasoning = completion_details.get("reasoning_tokens") if isinstance(completion_details, dict) else None + if isinstance(reasoning, int) and not isinstance(reasoning, bool) and reasoning >= 0: + result["output_tokens_details"] = {"reasoning_tokens": reasoning} + total = usage.get("total_tokens") + if isinstance(total, int) and not isinstance(total, bool) and total >= 0: + result["total_tokens"] = total + if not result: + return None + # Responses usage has no optional fields once present, so fill what Build did not report. + result.setdefault("input_tokens", 0) + result.setdefault("output_tokens", 0) + result.setdefault("input_tokens_details", {"cached_tokens": 0}) + result.setdefault("output_tokens_details", {"reasoning_tokens": 0}) + result.setdefault("total_tokens", result["input_tokens"] + result["output_tokens"]) + return result def _anthropic_message_from_events(events: list[dict[str, Any]]) -> dict[str, Any]: diff --git a/tests/test_nvidia_build_bridge.py b/tests/test_nvidia_build_bridge.py index 95bdd7286..e3e97668e 100644 --- a/tests/test_nvidia_build_bridge.py +++ b/tests/test_nvidia_build_bridge.py @@ -2521,15 +2521,26 @@ def test_build_tool_call_emits_anthropic_tool_use_and_message_stop() -> None: (None, {"input_tokens": 0, "output_tokens": 0}, None), ({}, {"input_tokens": 0, "output_tokens": 0}, None), ({"prompt_tokens": "bad", "completion_tokens": -1}, {"input_tokens": 0, "output_tokens": 0}, None), - ({"completion_tokens": 0}, {"input_tokens": 0, "output_tokens": 0}, {"output_tokens": 0}), + ( + {"completion_tokens": 0}, + {"input_tokens": 0, "output_tokens": 0}, + { + "input_tokens": 0, + "input_tokens_details": {"cached_tokens": 0}, + "output_tokens": 0, + "output_tokens_details": {"reasoning_tokens": 0}, + "total_tokens": 0, + }, + ), ( {"prompt_tokens": 100, "completion_tokens": 20, "prompt_tokens_details": {"cached_tokens": 30}}, {"input_tokens": 70, "output_tokens": 20, "cache_read_input_tokens": 30}, { "input_tokens": 100, + "input_tokens_details": {"cached_tokens": 30}, "output_tokens": 20, + "output_tokens_details": {"reasoning_tokens": 0}, "total_tokens": 120, - "input_tokens_details": {"cached_tokens": 30}, }, ), ], @@ -2546,6 +2557,96 @@ def test_bridge_preserves_reported_usage(usage: object, anthropic: object, respo assert response_events[-1]["response"]["usage"] == responses +@pytest.mark.parametrize("completion", [CHAT_TOOL_RESPONSE, CHAT_TEXT_RESPONSE]) +@pytest.mark.parametrize( + ("usage", "expected"), + [ + pytest.param( + { + "prompt_tokens": 100, + "completion_tokens": 20, + "total_tokens": 125, + "prompt_tokens_details": {"cached_tokens": 30}, + "completion_tokens_details": {"reasoning_tokens": 5}, + }, + { + "input_tokens": 100, + "input_tokens_details": {"cached_tokens": 30}, + "output_tokens": 20, + "output_tokens_details": {"reasoning_tokens": 5}, + "total_tokens": 125, + }, + id="measured", + ), + pytest.param( + {"prompt_tokens": 100, "completion_tokens": 20}, + { + "input_tokens": 100, + "input_tokens_details": {"cached_tokens": 0}, + "output_tokens": 20, + "output_tokens_details": {"reasoning_tokens": 0}, + "total_tokens": 120, + }, + id="uncached", + ), + pytest.param( + {"completion_tokens": 20}, + { + "input_tokens": 0, + "input_tokens_details": {"cached_tokens": 0}, + "output_tokens": 20, + "output_tokens_details": {"reasoning_tokens": 0}, + "total_tokens": 20, + }, + id="completion-only", + ), + pytest.param( + {"prompt_tokens": 10, "prompt_tokens_details": {"cached_tokens": 4}}, + { + "input_tokens": 10, + "input_tokens_details": {"cached_tokens": 4}, + "output_tokens": 0, + "output_tokens_details": {"reasoning_tokens": 0}, + "total_tokens": 10, + }, + id="prompt-only", + ), + pytest.param( + {"total_tokens": 7}, + { + "input_tokens": 0, + "input_tokens_details": {"cached_tokens": 0}, + "output_tokens": 0, + "output_tokens_details": {"reasoning_tokens": 0}, + "total_tokens": 7, + }, + id="total-only", + ), + pytest.param( + {"prompt_tokens": 10, "completion_tokens": 3, "completion_tokens_details": {"reasoning_tokens": "bad"}}, + { + "input_tokens": 10, + "input_tokens_details": {"cached_tokens": 0}, + "output_tokens": 3, + "output_tokens_details": {"reasoning_tokens": 0}, + "total_tokens": 13, + }, + id="invalid-reasoning", + ), + ], +) +def test_responses_usage_is_complete_and_sdk_valid( + completion: dict[str, object], usage: dict[str, object], expected: dict[str, object] +) -> None: + events = list(chat_completion_to_responses_events({**completion, "usage": usage})) + validator = TypeAdapter(ResponsesServerEvent) + + for event in events: + validator.validate_python(event, strict=True) + assert events[-1]["type"] == "response.completed" + assert events[-1]["response"]["usage"] == expected + + @pytest.mark.parametrize("completion", [CHAT_TOOL_RESPONSE, CHAT_TEXT_RESPONSE]) @pytest.mark.parametrize( ("usage_fields", "expected"),