Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
docs(model-hub): gate CPA agentic fidelity spike (#1214)
Call White2b79e794bb8a
diff --git a/docs/plans/fixtures/cpa-agentic-fidelity/README.md b/docs/plans/fixtures/cpa-agentic-fidelity/README.mdnew file mode 100644index 000000000..92b1a74c4--- /dev/null+++ b/docs/plans/fixtures/cpa-agentic-fidelity/README.md@@ -0,0 +1,175 @@+# CPA agentic-fidelity fixture++This directory contains a self-contained probe for the M0 spike in+`model-hub-engine-survey.md`. It sends the same small agentic workload through+an isolated, pinned CPA v7.2.95 instance for these four client/upstream+directions:++- Anthropic Messages client to an OpenAI Responses source;+- OpenAI Responses client to an Anthropic Messages source;+- Anthropic Messages client to an OpenAI Chat Completions source;+- OpenAI Chat Completions client to an Anthropic Messages source.++The probe is standard-library-only and does not print request or response+bodies, call ids, arguments, model prefixes, environment values, or+credentials. `run_relay.py` is the runtime harness: it obtains CPA through+`vibe/model_hub_runtime/`, creates a private temporary source projection, binds+CPA to `127.0.0.1`, and removes the temporary state when the run ends.++## Run++Load the owner-provided regression environment in the shell, then run the+launcher from the repository root:++```sh+set -a+. "$AVIBE_REGRESSION_ENV"+set +a+python3 docs/plans/fixtures/cpa-agentic-fidelity/run_relay.py+```++`AVIBE_REGRESSION_ENV` is a caller-provided path to the local regression+environment. It is never committed. The environment must provide+`ANTHROPIC_API_KEY`, `ANTHROPIC_BASE_URL`, and `OPENAI_API_KEY`; the launcher+derives the OpenAI-compatible base as the relay root plus `/v1`. It selects+`claude-haiku-4-5` and `gpt-5.4-mini`, and configures one Claude fallback model+for bounded 503 recovery. The packaged v7.2.95 manifest is selected explicitly,+ambient manifest overrides are ignored, and the installed version is verified+before requests begin. The values are injected into private runtime state and+child-process environments only.++The output is a compact JSON report containing case names, HTTP statuses,+redacted semantic checks, tool names/counts, and stream event counts. Each case+makes a second exchange when the first response contains parsed tool calls; when+it does not, the report records that the follow-up was skipped because the+multi-turn path was not reached. When reached, the first response supplies the+observed tool-call ids and complete continuation, and the second request returns+tool results using those exact ids. The eight cases cover single and parallel calls,+streaming, tool-fragment reconstruction, system scope, stop reasons, and+thinking/reasoning in both directions of both conversion pairs. A semantic+failure exits non-zero; missing credentials or an unsafe endpoint exits with a+blocked status before network access.++Anthropic thinking uses the minimum valid manual budget (`1024`) with+`max_tokens` above that budget. OpenAI Responses uses low reasoning effort and+requests `reasoning.encrypted_content` so stateless follow-ups can carry an+opaque reasoning item.+The probe records whether the requested reasoning signal remains observable. For+Chat, it accepts either explicit `reasoning_content` or a positive standard+`usage.completion_tokens_details.reasoning_tokens` value; it does not infer+equivalence from parameter names alone. Loopback requests disable environment+proxy handlers, and exhausted 503 capacity is reported as blocked for every+target while the alternate Claude model is tried only for Anthropic targets.+Each case reports only a redacted `fallback_used` boolean and primary/fallback+scope; fallback evidence must not be attributed to the primary model. The+latest closed-matrix rerun (r45) exercised all eight cases after additionally+requiring an explicit empty Anthropic text opening snapshot, an explicit empty+Responses function-call argument snapshot, and an explicit Chat delta object+whose unique assistant role precedes every payload delta. All eight cases+completed both turns with HTTP 200. No fallback was used. The+full-value/excerpt leakage check passed on all 16 returned turns.+Messages-to-Responses single retained reasoning in both turns and failed both+parse gates and the final exact tuple; its parallel retained reasoning in both+turns but failed both parse/order gates. Responses-to-Messages single passed+both parse gates but lacked reasoning in both turns and failed final system+scope and the exact tuple. Its parallel lacked reasoning in both turns, failed+both parse/order gates, and failed final system scope and the exact tuple.+Messages-to-Chat single retained reasoning in both turns, failed both parse+gates, and failed the final exact tuple; its parallel retained reasoning only+in the first turn, failed the first parse/order gates, and failed the final+exact tuple. Chat-to-Messages single passed both parse gates but lacked+reasoning in both turns and failed final system scope. Its parallel also lacked+reasoning, failed both parse gates and first-turn stream ordering, and failed+final system scope. The focused suite contains 206 tests.++Per the owner decision recorded on 2026-08-08, r45 is sealed M0 evidence.+Subsequent validator hardening applies to future collections only and does not+retroactively rewrite r45 or its direction-level decisions without a new,+explicitly adopted matrix run.++## S4 matrix mapping++The eight S4 capability rows are closed to the following named probe cases and+assertions. A row marked not verified is an explicit residual, not an implicit+success claim.++| S4 capability row | Probe case or assertion |+| --- | --- |+| Single tool call | `_request` strict JSON, protocol-specific `_parse_arguments` wire encoding, `_parse_responses_document` nonempty `output_item_id`, plus `_validate_first`: `expected_tool_count`, `tool_names`, `tool_arguments`, `tool_ids_unique`, and protocol `stop_reason` |+| Parallel tools | `CaseSpec.expected_tools`, `_user_prompt(True)`, and the same `_validate_first` tool invariants |+| Multi-turn loop | `_run_case` observed `first_turn.tool_calls` with nonempty unique call IDs before any follow-up request, `_validate_first`: `no_premature_tool_outputs`, plus `_validate_second`: `no_followup_tool_calls`, `tool_outputs`, and `_tool_output_tuples` independent tuple-candidate recognition, empty/malformed identity rejection, and exact complete call-ID/result tuple-set comparison |+| Streaming text | `_request` strict UTF-8/JSON and `text/event-stream` checks with one-space SSE field handling, default-event normalization, and immediate Chat `[DONE]` dispatch termination, `_parse_anthropic_stream`/`_parse_responses_stream` delta, done-event, item, terminal snapshot, required explicit empty Anthropic text opening snapshots, required Anthropic `message_delta` before `message_stop`, and unique optional `response.in_progress` transition validation for both `text` and `output_text` content parts including a required explicit empty opening `text`, `RESPONSES_MESSAGE_PART_TYPES` plus content-part-to-item snapshot correlation, per-item `stream_text_snapshot_mismatch`, `_parse_chat_stream` explicit delta objects, `CHAT_STREAM_EVENT_TYPES`/`chat.completion.chunk` and typed content checks, one assistant role before every payload delta, `_stream_order_ok`, and `stream_complete` |+| Streaming tool fragments | `_parse_anthropic_stream`, `_parse_responses_stream`, `_parse_chat_stream`, and `_stream_order_ok` opening/terminal envelopes, explicit `stream_failure_event`, `ANTHROPIC_STREAM_EVENT_TYPES`/`RESPONSES_STREAM_EVENT_TYPES`/`CHAT_STREAM_EVENT_TYPES` and supported content-block/output-item discriminators, required explicit empty Responses opening `arguments`, at least two nonempty Anthropic, Responses, or Chat argument deltas per function call, no duplicate Chat tool index within one wire chunk, monotonic wire sequence, contiguous block/item/content-part indexes, content-part and block/delta/done snapshot compatibility, response/item/choice/output-index/ID continuity from the opening snapshot including required opening Chat call ids, `summary_index` continuity with exact delta/done pairing, typed `stream_name_invalid`/`stream_arguments_invalid` fragments and done events, duplicate terminal usage rejection, and monotonic lifecycle checks |+| System prompt | `_system_prompt`, `_token_present`, `_validate_first`: negative `user_scope`, and `_validate_second`: exact-token `system_marker` and `system_scope` |+| Thinking/reasoning | `_anthropic_payload`, `_responses_payload`, `_chat_payload`, `_parse_anthropic_document` payload/signature/redacted-data validation and protected-part collection, `_parse_anthropic_stream` explicitly present, string, empty `thinking`/`signature` opening snapshots plus terminal signature ordering, `_parse_responses_document` `RESPONSES_REASONING_PART_TYPES`/encrypted reasoning type validation and protected-part collection, `_parse_responses_stream` reasoning text, exact summary-index lifecycle, and encrypted snapshot comparison, `_reasoning_item_has_signal`, `_chat_reasoning_usage_present` terminal integer-token gate, and `_validate_first`/`_validate_second`: `reasoning_present` plus `_protected_reasoning_visible` normalized full-value/meaningful-excerpt rejection against all readable and opaque protected parts while `reasoning_text` remains readable-only |+| Context length/truncation | `probe.CONTEXT_LENGTH_NOT_VERIFIED` residual; no low-cost context-limit run was included in M0 |++## Required envelope field matrix++Future collections use `REQUIRED_ENVELOPE_FIELDS` as the single authority for+the required fields inside the protocol envelopes claimed by the closed S4+matrix. The table covers 25 envelope kinds and 123 required-field cells. The+`test_required_envelope_matrix_rejects_every_missing_field` mutation test owns+one valid sample per envelope kind, removes every required field one at a time,+and requires the declared validation error for all 123 mutations. Lifecycle,+cross-event identity, snapshot equality, and nested tool/content semantics stay+in their named S4 assertions; fields explicitly listed as residuals below are+not silently promoted into this required set. The required sets are shaped+against the upstream [Anthropic streaming event+contract](https://platform.claude.com/docs/en/build-with-claude/streaming),+[OpenAI Chat Completions schema](https://developers.openai.com/api/reference/resources/chat),+and [OpenAI Responses streaming event+schema](https://developers.openai.com/api/reference/resources/responses/streaming-events),+then limited to the protocol envelopes the S4 probe claims to validate.++| Protocol envelope kind | Required field paths |+| --- | --- |+| `anthropic.message` | `type`, `role`, `content` |+| `anthropic.stream.message_start` | `type`, `message`, `message.type`, `message.role`, `message.content`, `message.usage`, `message.usage.input_tokens`, `message.usage.output_tokens`, `message.stop_reason`, `message.stop_sequence` |+| `anthropic.stream.content_block_start` | `type`, `index`, `content_block` |+| `anthropic.stream.content_block_delta` | `type`, `index`, `delta` |+| `anthropic.stream.content_block_stop` | `type`, `index` |+| `anthropic.stream.message_delta` | `type`, `delta`, `delta.stop_reason`, `delta.stop_sequence`, `usage`, `usage.output_tokens` |+| `anthropic.stream.message_stop` | `type` |+| `anthropic.stream.ping` | `type` |+| `chat.completion` | `id`, `object`, `choices`, `choices[0].index`, `choices[0].message`, `choices[0].message.role`, `choices[0].message.content` |+| `chat.stream.choice` | `id`, `object`, `choices`, `choices[0].index`, `choices[0].delta` |+| `chat.stream.usage` | `id`, `object`, `choices`, `usage` |+| `responses.response` | `id`, `object`, `output` |+| `responses.stream.created` | `type`, `sequence_number`, `response`, `response.id`, `response.object`, `response.status`, `response.output` |+| `responses.stream.in_progress` | `type`, `sequence_number`, `response`, `response.id`, `response.object`, `response.status`, `response.output` |+| `responses.stream.terminal` | `type`, `sequence_number`, `response`, `response.id`, `response.object`, `response.status`, `response.output` |+| `responses.stream.output_item_added` | `type`, `sequence_number`, `output_index`, `item` |+| `responses.stream.output_item_done` | `type`, `sequence_number`, `output_index`, `item` |+| `responses.stream.content_part_added` | `type`, `sequence_number`, `item_id`, `output_index`, `content_index`, `part` |+| `responses.stream.content_part_done` | `type`, `sequence_number`, `item_id`, `output_index`, `content_index`, `part` |+| `responses.stream.function_arguments_delta` | `type`, `sequence_number`, `item_id`, `output_index`, `delta` |+| `responses.stream.function_arguments_done` | `type`, `sequence_number`, `item_id`, `output_index`, `arguments` |+| `responses.stream.output_text_delta` | `type`, `sequence_number`, `item_id`, `output_index`, `content_index`, `delta` |+| `responses.stream.output_text_done` | `type`, `sequence_number`, `item_id`, `output_index`, `content_index`, `text` |+| `responses.stream.reasoning_summary_delta` | `type`, `sequence_number`, `item_id`, `output_index`, `summary_index`, `delta` |+| `responses.stream.reasoning_summary_done` | `type`, `sequence_number`, `item_id`, `output_index`, `summary_index`, `text` |++The live evidence in the survey used the owner-provided compatible relay. Direct+official vendor APIs were not measured. A transient `no available accounts`+503 is retried with short bounded backoff; after the configured Claude fallback+also fails, the affected direction is reported as blocked rather than as a+semantic no-go.++Malformed relay URL handling, including nonnumeric loopback ports, top-level+Anthropic message ID, non-stream `stop_sequence` validation, non-stream+Anthropic/Responses text-field presence, compatibility of the configured+Anthropic fallback with the primary thinking contract, and mixed+primary/fallback second-turn accounting remain outside the closed eight-row+semantic matrix; they are recorded as known-by-design residuals rather than+promoted into probe gates.++The closed matrix requires monotonic Responses wire sequence, not a particular+origin. The measured relay emitted contiguous one-based values. Non-stream+response media-type enforcement is likewise outside the closed semantic matrix;+both are recorded as residuals in the survey rather than promoted into probe+gates. Fixture-owned historical manifest resolution, minimal allowlisting of+the probe child environment, and non-stream inference deadline classification+are also outside the closed matrix. The current launcher verifies v7.2.95 from+the product manifest and inherits the caller environment; these limitations are+explicit residuals rather than semantic success claims.diff --git a/docs/plans/fixtures/cpa-agentic-fidelity/probe.py b/docs/plans/fixtures/cpa-agentic-fidelity/probe.pynew file mode 100644index 000000000..08a0fb85c--- /dev/null+++ b/docs/plans/fixtures/cpa-agentic-fidelity/probe.py@@ -0,0 +1,2878 @@+#!/usr/bin/env python3+"""Run the CPA M0 agentic-fidelity workload without logging credentials/bodies."""++from __future__ import annotations++import argparse+import copy+import json+import os+import re+import socket+import sys+import time+import urllib.error+import urllib.parse+import urllib.request+from dataclasses import dataclass, field+from typing import Any+++REQUIRED_VENDOR_KEYS = ("ANTHROPIC_API_KEY", "OPENAI_API_KEY")+MODEL_ENV = {+ "responses": "CPA_OPENAI_RESPONSES_QUALIFIED_MODEL",+ "chat": "CPA_OPENAI_CHAT_QUALIFIED_MODEL",+ "anthropic": "CPA_ANTHROPIC_QUALIFIED_MODEL",+}+BASE_URL = os.environ.get("CPA_BASE_URL", "http://127.0.0.1:15220").rstrip("/")+GATEWAY_TOKEN = os.environ.get("CPA_GATEWAY_TOKEN", "")+MODELS = {protocol: os.environ.get(env_name, "") for protocol, env_name in MODEL_ENV.items()}+ANTHROPIC_FALLBACK_MODEL = os.environ.get("CPA_ANTHROPIC_FALLBACK_QUALIFIED_MODEL", "")++SYSTEM_MARKER = "CPA_SYSTEM_MARKER_731"+SYSTEM_SCOPE_OK = "SYSTEM_SCOPE_OK"+USER_SCOPE_LEAK = "USER_SCOPE_LEAK"+THINKING_BUDGET = 1024+MAX_TOKENS = 1280+TOOL_OUTPUTS = {"lookup_weather": "WEATHER_OK", "lookup_time": "TIME_OK"}+STREAM_TOTAL_TIMEOUT = 90+CONTEXT_LENGTH_NOT_VERIFIED = "context_length_not_verified"+STOP_REASONS = {+ "anthropic": {"first": {"tool_use"}, "final": {"end_turn"}},+ "responses": {"first": {"completed"}, "final": {"completed"}},+ "chat": {"first": {"tool_calls"}, "final": {"stop"}},+}+RESPONSES_OUTPUT_ITEM_TYPES = {"function_call", "message", "reasoning"}+RESPONSES_STREAM_EVENT_TYPES = {+ "error",+ "response.completed",+ "response.content_part.added",+ "response.content_part.done",+ "response.created",+ "response.done",+ "response.failed",+ "response.function_call_arguments.delta",+ "response.function_call_arguments.done",+ "response.in_progress",+ "response.incomplete",+ "response.output_item.added",+ "response.output_item.done",+ "response.output_text.delta",+ "response.output_text.done",+ "response.reasoning_summary_text.delta",+ "response.reasoning_summary_text.done",+}+ANTHROPIC_STREAM_EVENT_TYPES = {+ "content_block_delta",+ "content_block_start",+ "content_block_stop",+ "error",+ "message_delta",+ "message_start",+ "message_stop",+ "ping",+}+RESPONSES_MESSAGE_PART_TYPES = {"output_text", "text"}+RESPONSES_REASONING_PART_TYPES = {"reasoning_text", "summary_text", "text"}+CHAT_STREAM_EVENT_TYPES = {None, "chat.completion.chunk", "error"}+ANTHROPIC_CONTENT_BLOCK_TYPES = {"redacted_thinking", "text", "thinking", "tool_use"}+MAX_503_RETRIES = 3+PROTECTED_REASONING_MIN_EXCERPT = 12+PROTECTED_REASONING_MAX_EXCERPT = 32+++class _NoRedirectHandler(urllib.request.HTTPRedirectHandler):+ """Never carry the gateway authorization header across a redirect."""++ def redirect_request(self, req: urllib.request.Request, fp: Any, code: int, msg: str, headers: Any, new_url: str) -> None:+ return None+++OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}), _NoRedirectHandler())+++def _reject_nonfinite(value: str) -> Any:+ raise ValueError(f"non-finite JSON constant: {value}")+++class _DuplicateKeyError(ValueError):+ pass+++def _reject_duplicate_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]:+ result: dict[str, Any] = {}+ for key, item in pairs:+ if key in result:+ raise _DuplicateKeyError(f"duplicate JSON key: {key}")+ result[key] = item+ return result+++@dataclass+class ToolCall:+ call_id: str+ name: str+ arguments: Any+++@dataclass+class Turn:+ protocol: str+ tool_calls: list[ToolCall]+ text: str+ reasoning_present: bool+ stop_reason: str | None+ continuation: Any+ terminal: bool+ event_count: int+ invalid_event_count: int+ parse_errors: list[str]+ stream_order_ok: bool = True+ deadline_expired: bool = False+ reasoning_text: str = ""+ reasoning_parts: list[str] = field(default_factory=list)+ stream_text_delta_count: int = 0+ content_type_ok: bool = True+++@dataclass+class TransportResult:+ status: int+ document: dict[str, Any] | None+ events: list[dict[str, Any]]+ done_sentinel: bool+ invalid_event_count: int+ stream_order_ok: bool = True+ deadline_expired: bool = False+ content_type_ok: bool = True+++@dataclass(frozen=True)+class RequiredEnvelopeField:+ path: tuple[str | int, ...]+ rule: str+ error: str+ expected: Any = None+ invalid_error: str | None = None+++F = RequiredEnvelopeField+REQUIRED_ENVELOPE_FIELDS: dict[str, tuple[RequiredEnvelopeField, ...]] = {+ "anthropic.message": (+ F(("type",), "literal", "message_type_invalid", "message"),+ F(("role",), "literal", "message_role_invalid", "assistant"),+ F(("content",), "list", "content_missing"),+ ),+ "anthropic.stream.message_start": (+ F(("type",), "literal", "stream_event_type_invalid", "message_start"),+ F(("message",), "object", "message_envelope_invalid"),+ F(("message", "type"), "literal", "message_envelope_invalid", "message"),+ F(("message", "role"), "literal", "message_envelope_invalid", "assistant"),+ F(("message", "content"), "empty_list", "message_start_content_invalid"),+ F(("message", "usage"), "object", "message_start_usage_invalid"),+ F(+ ("message", "usage", "input_tokens"),+ "nonnegative_integer",+ "message_start_usage_invalid",+ ),+ F(+ ("message", "usage", "output_tokens"),+ "nonnegative_integer",+ "message_start_usage_invalid",+ ),+ F(("message", "stop_reason"), "literal", "message_start_terminal_invalid", None),+ F(("message", "stop_sequence"), "literal", "message_start_terminal_invalid", None),+ ),+ "anthropic.stream.content_block_start": (+ F(("type",), "literal", "stream_event_type_invalid", "content_block_start"),+ F(("index",), "nonnegative_integer", "stream_index_invalid"),+ F(("content_block",), "object", "content_block_invalid"),+ ),+ "anthropic.stream.content_block_delta": (+ F(("type",), "literal", "stream_event_type_invalid", "content_block_delta"),+ F(("index",), "nonnegative_integer", "stream_index_invalid"),+ F(("delta",), "object", "stream_delta_invalid"),+ ),+ "anthropic.stream.content_block_stop": (+ F(("type",), "literal", "stream_event_type_invalid", "content_block_stop"),+ F(("index",), "nonnegative_integer", "stream_index_invalid"),+ ),+ "anthropic.stream.message_delta": (+ F(("type",), "literal", "stream_event_type_invalid", "message_delta"),+ F(("delta",), "object", "message_delta_invalid"),+ F(+ ("delta", "stop_reason"),+ "nonempty_string",+ "message_delta_stop_sequence_invalid",+ ),+ F(+ ("delta", "stop_sequence"),+ "nullable_string",+ "message_delta_stop_sequence_invalid",+ ),+ F(("usage",), "object", "message_delta_usage_invalid"),+ F(+ ("usage", "output_tokens"),+ "nonnegative_integer",+ "message_delta_usage_invalid",+ ),+ ),+ "anthropic.stream.message_stop": (+ F(("type",), "literal", "stream_event_type_invalid", "message_stop"),+ ),+ "anthropic.stream.ping": (+ F(("type",), "literal", "stream_event_type_invalid", "ping"),+ ),+ "chat.completion": (+ F(("id",), "nonempty_string", "chat_id_invalid"),+ F(("object",), "literal", "chat_object_invalid", "chat.completion"),+ F(("choices",), "single_object_list", "choice_invalid"),+ F(("choices", 0, "index"), "zero_index", "choice_index_invalid"),+ F(("choices", 0, "message"), "object", "message_invalid"),+ F(+ ("choices", 0, "message", "role"),+ "literal",+ "assistant_role_invalid",+ "assistant",+ ),+ F(+ ("choices", 0, "message", "content"),+ "nullable_string",+ "message_content_missing",+ ),+ ),+ "chat.stream.choice": (+ F(("id",), "nonempty_string", "stream_completion_id_invalid"),+ F(("object",), "literal", "stream_object_invalid", "chat.completion.chunk"),+ F(("choices",), "single_object_list", "choice_invalid"),+ F(("choices", 0, "index"), "zero_index", "choice_index_invalid"),+ F(("choices", 0, "delta"), "object", "delta_missing", None, "delta_invalid"),+ ),+ "chat.stream.usage": (+ F(("id",), "nonempty_string", "stream_completion_id_invalid"),+ F(("object",), "literal", "stream_object_invalid", "chat.completion.chunk"),+ F(("choices",), "empty_list", "choices_missing"),+ F(("usage",), "object", "usage_before_finish"),+ ),+ "responses.response": (+ F(("id",), "nonempty_string", "response_id_invalid"),+ F(("object",), "literal", "response_object_invalid", "response"),+ F(("output",), "list", "output_missing"),+ ),+ "responses.stream.created": (+ F(("type",), "literal", "stream_event_type_invalid", "response.created"),+ F(("sequence_number",), "nonnegative_integer", "stream_sequence_invalid"),+ F(("response",), "object", "response_start_snapshot_invalid"),+ F(("response", "id"), "nonempty_string", "response_id_invalid"),+ F(("response", "object"), "literal", "response_start_snapshot_invalid", "response"),+ F(("response", "status"), "literal", "response_start_snapshot_invalid", "in_progress"),+ F(("response", "output"), "empty_list", "response_start_snapshot_invalid"),+ ),+ "responses.stream.in_progress": (+ F(("type",), "literal", "stream_event_type_invalid", "response.in_progress"),+ F(("sequence_number",), "nonnegative_integer", "stream_sequence_invalid"),+ F(("response",), "object", "response_in_progress_snapshot_invalid"),+ F(("response", "id"), "nonempty_string", "response_in_progress_id_invalid"),+ F(+ ("response", "object"),+ "literal",+ "response_in_progress_snapshot_invalid",+ "response",+ ),+ F(+ ("response", "status"),+ "literal",+ "response_in_progress_snapshot_invalid",+ "in_progress",+ ),+ F(("response", "output"), "empty_list", "response_in_progress_snapshot_invalid"),+ ),+ "responses.stream.terminal": (+ F(+ ("type",),+ "one_of",+ "terminal_response_type_invalid",+ ("response.completed", "response.done"),+ ),+ F(("sequence_number",), "nonnegative_integer", "stream_sequence_invalid"),+ F(("response",), "object", "terminal_response_invalid"),+ F(("response", "id"), "nonempty_string", "terminal_response_id_invalid"),+ F(("response", "object"), "literal", "terminal_response_invalid", "response"),+ F(("response", "status"), "literal", "terminal_response_status_invalid", "completed"),+ F(("response", "output"), "list", "terminal_response_output_invalid"),+ ),+ "responses.stream.output_item_added": (+ F(("type",), "literal", "stream_event_type_invalid", "response.output_item.added"),+ F(("sequence_number",), "nonnegative_integer", "stream_sequence_invalid"),+ F(("output_index",), "nonnegative_integer", "stream_output_index_invalid"),+ F(("item",), "object", "output_item_invalid"),+ ),+ "responses.stream.output_item_done": (+ F(("type",), "literal", "stream_event_type_invalid", "response.output_item.done"),+ F(("sequence_number",), "nonnegative_integer", "stream_sequence_invalid"),+ F(("output_index",), "nonnegative_integer", "stream_output_index_invalid"),+ F(("item",), "object", "output_item_invalid"),+ ),+ "responses.stream.content_part_added": (+ F(("type",), "literal", "stream_event_type_invalid", "response.content_part.added"),+ F(("sequence_number",), "nonnegative_integer", "stream_sequence_invalid"),+ F(("item_id",), "nonempty_string", "stream_item_id_invalid"),+ F(("output_index",), "nonnegative_integer", "stream_output_index_invalid"),+ F(("content_index",), "nonnegative_integer", "stream_content_index_invalid"),+ F(("part",), "object", "stream_content_part_invalid"),+ ),+ "responses.stream.content_part_done": (+ F(("type",), "literal", "stream_event_type_invalid", "response.content_part.done"),+ F(("sequence_number",), "nonnegative_integer", "stream_sequence_invalid"),+ F(("item_id",), "nonempty_string", "stream_item_id_invalid"),+ F(("output_index",), "nonnegative_integer", "stream_output_index_invalid"),+ F(("content_index",), "nonnegative_integer", "stream_content_index_invalid"),+ F(("part",), "object", "stream_content_part_invalid"),+ ),+ "responses.stream.function_arguments_delta": (+ F(+ ("type",),+ "literal",+ "stream_event_type_invalid",+ "response.function_call_arguments.delta",+ ),+ F(("sequence_number",), "nonnegative_integer", "stream_sequence_invalid"),+ F(("item_id",), "nonempty_string", "stream_item_id_invalid"),+ F(("output_index",), "nonnegative_integer", "stream_output_index_invalid"),+ F(("delta",), "string", "stream_arguments_invalid"),+ ),+ "responses.stream.function_arguments_done": (+ F(+ ("type",),+ "literal",+ "stream_event_type_invalid",+ "response.function_call_arguments.done",+ ),+ F(("sequence_number",), "nonnegative_integer", "stream_sequence_invalid"),+ F(("item_id",), "nonempty_string", "stream_item_id_invalid"),+ F(("output_index",), "nonnegative_integer", "stream_output_index_invalid"),+ F(("arguments",), "string", "stream_arguments_done_invalid"),+ ),+ "responses.stream.output_text_delta": (+ F(("type",), "literal", "stream_event_type_invalid", "response.output_text.delta"),+ F(("sequence_number",), "nonnegative_integer", "stream_sequence_invalid"),+ F(("item_id",), "nonempty_string", "stream_item_id_invalid"),+ F(("output_index",), "nonnegative_integer", "stream_output_index_invalid"),+ F(("content_index",), "nonnegative_integer", "stream_content_index_invalid"),+ F(("delta",), "string", "stream_text_delta_invalid"),+ ),+ "responses.stream.output_text_done": (+ F(("type",), "literal", "stream_event_type_invalid", "response.output_text.done"),+ F(("sequence_number",), "nonnegative_integer", "stream_sequence_invalid"),+ F(("item_id",), "nonempty_string", "stream_item_id_invalid"),+ F(("output_index",), "nonnegative_integer", "stream_output_index_invalid"),+ F(("content_index",), "nonnegative_integer", "stream_content_index_invalid"),+ F(("text",), "string", "stream_text_done_invalid"),+ ),+ "responses.stream.reasoning_summary_delta": (+ F(+ ("type",),+ "literal",+ "stream_event_type_invalid",+ "response.reasoning_summary_text.delta",+ ),+ F(("sequence_number",), "nonnegative_integer", "stream_sequence_invalid"),+ F(("item_id",), "nonempty_string", "stream_item_id_invalid"),+ F(("output_index",), "nonnegative_integer", "stream_output_index_invalid"),+ F(("summary_index",), "nonnegative_integer", "stream_summary_index_invalid"),+ F(("delta",), "string", "stream_reasoning_delta_invalid"),+ ),+ "responses.stream.reasoning_summary_done": (+ F(+ ("type",),+ "literal",+ "stream_event_type_invalid",+ "response.reasoning_summary_text.done",+ ),+ F(("sequence_number",), "nonnegative_integer", "stream_sequence_invalid"),+ F(("item_id",), "nonempty_string", "stream_item_id_invalid"),+ F(("output_index",), "nonnegative_integer", "stream_output_index_invalid"),+ F(("summary_index",), "nonnegative_integer", "stream_summary_index_invalid"),+ F(("text",), "string", "stream_reasoning_done_invalid"),+ ),+}+++@dataclass(frozen=True)+class CaseSpec:+ name: str+ client_protocol: str+ target_protocol: str+ path: str+ stream: bool+ parallel: bool++ @property+ def expected_tools(self) -> tuple[str, ...]:+ return ("lookup_weather", "lookup_time") if self.parallel else ("lookup_weather",)+++def _tool_definitions() -> list[dict[str, Any]]:+ return [+ {+ "name": name,+ "description": description,+ "input_schema": {+ "type": "object",+ "properties": {"city": {"type": "string", "enum": ["Shanghai"]}},+ "required": ["city"],+ "additionalProperties": False,+ },+ }+ for name, description in (+ ("lookup_weather", "Return a short weather summary for a city."),+ ("lookup_time", "Return the local time for a city."),+ )+ ]+++def _system_prompt() -> str:+ return (+ "You are a concise tool-using assistant. Follow the requested tool calls exactly. "+ f"This system-scoped instruction requires {SYSTEM_SCOPE_OK}; never output {USER_SCOPE_LEAK}. "+ f"After tool results, include {SYSTEM_MARKER}, {SYSTEM_SCOPE_OK}, and each returned output tuple "+ "(tool name, call id, marker) exactly in the final text."+ )+++def _anthropic_tools() -> list[dict[str, Any]]:+ return [+ {"name": tool["name"], "description": tool["description"], "input_schema": tool["input_schema"]}+ for tool in _tool_definitions()+ ]+++def _openai_tools() -> list[dict[str, Any]]:+ return [+ {+ "type": "function",+ "name": tool["name"],+ "description": tool["description"],+ "parameters": tool["input_schema"],+ }+ for tool in _tool_definitions()+ ]+++def _user_prompt(parallel: bool) -> str:+ if parallel:+ request = "Call both tools lookup_weather and lookup_time for the exact city Shanghai in parallel."+ else:+ request = "Call lookup_weather for the exact city Shanghai."+ return (+ f"{request} After tool results are returned, summarize. "+ f"Include {USER_SCOPE_LEAK} and omit {SYSTEM_SCOPE_OK}. Preserve each returned output tuple exactly."+ )+++def _tool_output(call: ToolCall) -> str:+ return f"tool={call.name};call_id={call.call_id};marker={TOOL_OUTPUTS.get(call.name, 'TOOL_OUTPUT_MISSING')}"+++_TOOL_OUTPUT_TUPLE_CANDIDATE_RE = re.compile(r"(?<![A-Za-z0-9_])tool=\S*")+_TOOL_OUTPUT_TUPLE_RE = re.compile(+ r"tool=([^;\s]*);call_id=([^;\s]*);marker=([^;\s]*)"+)+++def _tool_output_tuples(text: str) -> list[tuple[str, str, str]]:+ tuples: list[tuple[str, str, str]] = []+ for candidate in _TOOL_OUTPUT_TUPLE_CANDIDATE_RE.finditer(text):+ match = _TOOL_OUTPUT_TUPLE_RE.fullmatch(candidate.group(0))+ if match is None:+ tuples.append(("", "", ""))+ continue+ tool, call_id, raw_marker = match.groups()+ token = re.match(r"[A-Za-z0-9_]+", raw_marker)+ tuples.append((tool, call_id, token.group(0) if token else raw_marker))+ return tuples+++def _tool_output_tuple(call: ToolCall) -> tuple[str, str, str]:+ return (call.name, call.call_id, TOOL_OUTPUTS.get(call.name, "TOOL_OUTPUT_MISSING"))+++def _tool_output_pair_present(text: str, call: ToolCall) -> bool:+ return _tool_output_tuples(text).count(_tool_output_tuple(call)) == 1+++def _token_present(text: str, token: str) -> bool:+ return re.search(rf"(?<![A-Za-z0-9_]){re.escape(token)}(?![A-Za-z0-9_])", text) is not None+++def _protected_reasoning_visible(text: str, protected_parts: list[str]) -> bool:+ visible = " ".join(text.casefold().split())+ for part in protected_parts:+ protected = " ".join(part.casefold().split())+ if not protected:+ continue+ excerpt_length = min(+ PROTECTED_REASONING_MAX_EXCERPT,+ max(PROTECTED_REASONING_MIN_EXCERPT, (len(protected) + 1) // 2),+ )+ if len(protected) <= excerpt_length:+ if protected in visible:+ return True+ continue+ if any(+ protected[start : start + excerpt_length] in visible+ for start in range(len(protected) - excerpt_length + 1)+ ):+ return True+ return False+++def _anthropic_payload(*, model: str, stream: bool, parallel: bool, followup: Turn | None = None) -> dict[str, Any]:+ if followup is None:+ prompt = _user_prompt(parallel)+ messages: list[dict[str, Any]] = [{"role": "user", "content": prompt}]+ tool_choice: dict[str, str] = {"type": "auto"}+ else:+ messages = [+ {"role": "user", "content": _user_prompt(parallel)},+ {"role": "assistant", "content": copy.deepcopy(followup.continuation)},+ {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": call.call_id,+ "content": _tool_output(call),+ }+ for call in followup.tool_calls+ ],+ },+ ]+ tool_choice = {"type": "none"}+ return {+ "model": model,+ "max_tokens": MAX_TOKENS,+ "system": _system_prompt(),+ "messages": messages,+ "tools": _anthropic_tools(),+ "tool_choice": tool_choice,+ "thinking": {"type": "enabled", "budget_tokens": THINKING_BUDGET},+ "stream": stream,+ }+++def _responses_payload(*, model: str, stream: bool, parallel: bool, followup: Turn | None = None) -> dict[str, Any]:+ prompt = _user_prompt(parallel)+ if followup is None:+ items: list[dict[str, Any]] = [{"role": "user", "content": prompt}]+ tool_choice: str = "required"+ else:+ items = [{"role": "user", "content": prompt}]+ items.extend(copy.deepcopy(followup.continuation))+ items.extend(+ {+ "type": "function_call_output",+ "call_id": call.call_id,+ "output": _tool_output(call),+ }+ for call in followup.tool_calls+ )+ tool_choice = "none"+ return {+ "model": model,+ "input": items,+ "instructions": _system_prompt(),+ "tools": _openai_tools(),+ "reasoning": {"effort": "low", "summary": "auto"},+ "include": ["reasoning.encrypted_content"],+ "parallel_tool_calls": parallel,+ "tool_choice": tool_choice,+ "max_output_tokens": MAX_TOKENS,+ "store": False,+ "stream": stream,+ }+++def _chat_payload(*, model: str, stream: bool, parallel: bool, followup: Turn | None = None) -> dict[str, Any]:+ prompt = _user_prompt(parallel)+ if followup is None:+ messages: list[dict[str, Any]] = [+ {"role": "system", "content": _system_prompt()},+ {"role": "user", "content": prompt},+ ]+ tool_choice: str = "required"+ else:+ messages = [+ {"role": "system", "content": _system_prompt()},+ {"role": "user", "content": prompt},+ copy.deepcopy(followup.continuation),+ ]+ messages.extend(+ {+ "role": "tool",+ "tool_call_id": call.call_id,+ "content": _tool_output(call),+ }+ for call in followup.tool_calls+ )+ tool_choice = "none"+ payload: dict[str, Any] = {+ "model": model,+ "messages": messages,+ "tools": [{"type": "function", "function": {"name": tool["name"], "description": tool["description"], "parameters": tool["input_schema"]}} for tool in _tool_definitions()],+ "max_completion_tokens": MAX_TOKENS,+ "reasoning_effort": "low",+ "parallel_tool_calls": parallel,+ "tool_choice": tool_choice,+ "stream": stream,+ }+ if stream:+ payload["stream_options"] = {"include_usage": True}+ return payload+++def _flush_sse(data_lines: list[str], event_name: str | None, events: list[dict[str, Any]], invalid: list[int]) -> bool:+ if not data_lines:+ return False+ data = "\n".join(data_lines)+ data_lines.clear()+ if event_name in {"", "message"}:+ event_name = None+ if data == "[DONE]":+ events.append({"kind": "done", "type": event_name, "sequence": len(events)})+ return True++ try:+ parsed = json.loads(data, object_pairs_hook=_reject_duplicate_keys, parse_constant=_reject_nonfinite)+ except (json.JSONDecodeError, ValueError):+ invalid[0] += 1+ return False+ if isinstance(parsed, dict):+ events.append(+ {+ "kind": "event",+ "type": event_name,+ "event": parsed,+ "sequence": len(events),+ "wire_sequence": parsed.get("sequence_number"),+ }+ )+ else:+ invalid[0] += 1+ return False+++def _request_url(client_protocol: str, path: str) -> str:+ return f"{BASE_URL}{path}"+++def _set_stream_read_timeout(response: Any, timeout: float) -> None:+ raw = getattr(getattr(response, "fp", None), "raw", None)+ connection_socket = getattr(raw, "_sock", None)+ if connection_socket is not None:+ try:+ connection_socket.settimeout(timeout)+ except OSError:+ pass+++def _stream_item_id(value: Any) -> str | None:+ return value if isinstance(value, str) and value else None+++def _parsed_stream_item_id(value: Any, errors: list[str]) -> str | None:+ item_id = _stream_item_id(value)+ if item_id is None:+ errors.append("stream_item_id_invalid")+ return item_id+++def _chat_delta_has_payload(delta: dict[str, Any]) -> bool:+ return (+ ("content" in delta and delta["content"] is not None)+ or ("reasoning_content" in delta and delta["reasoning_content"] is not None)+ or ("tool_calls" in delta and delta["tool_calls"] not in (None, []))+ )+++_MISSING = object()+++def _required_field_value(payload: Any, path: tuple[str | int, ...]) -> Any:+ value = payload+ for part in path:+ if isinstance(part, int):+ if not isinstance(value, list) or part >= len(value):+ return _MISSING+ value = value[part]+ else:+ if not isinstance(value, dict) or part not in value:+ return _MISSING+ value = value[part]+ return value+++def _required_field_valid(field: RequiredEnvelopeField, value: Any) -> bool:+ if value is _MISSING:+ return False+ if field.rule == "literal":+ return value == field.expected+ if field.rule == "one_of":+ return isinstance(value, str) and value in field.expected+ if field.rule == "object":+ return isinstance(value, dict)+ if field.rule == "list":+ return isinstance(value, list)+ if field.rule == "empty_list":+ return isinstance(value, list) and not value+ if field.rule == "single_object_list":+ return isinstance(value, list) and len(value) == 1 and isinstance(value[0], dict)+ if field.rule == "nonempty_string":+ return isinstance(value, str) and bool(value)+ if field.rule == "string":+ return isinstance(value, str)+ if field.rule == "nullable_string":+ return value is None or isinstance(value, str)+ if field.rule == "nonnegative_integer":+ return type(value) is int and value >= 0+ if field.rule == "zero_index":+ return type(value) is int and value == 0+ raise ValueError(f"unknown required-envelope rule: {field.rule}")+++def _required_envelope_errors(kind: str, payload: Any) -> list[str]:+ errors: list[str] = []+ for field in REQUIRED_ENVELOPE_FIELDS[kind]:+ value = _required_field_value(payload, field.path)+ error = field.error if value is _MISSING else field.invalid_error or field.error+ if not _required_field_valid(field, value) and error not in errors:+ errors.append(error)+ return errors+++def _extend_unique(errors: list[str], additions: list[str]) -> None:+ errors.extend(error for error in additions if error not in errors)+++_ANTHROPIC_STREAM_ENVELOPES = {+ "message_start": "anthropic.stream.message_start",+ "content_block_start": "anthropic.stream.content_block_start",+ "content_block_delta": "anthropic.stream.content_block_delta",+ "content_block_stop": "anthropic.stream.content_block_stop",+ "message_delta": "anthropic.stream.message_delta",+ "message_stop": "anthropic.stream.message_stop",+ "ping": "anthropic.stream.ping",+}+_RESPONSES_STREAM_ENVELOPES = {+ "response.created": "responses.stream.created",+ "response.in_progress": "responses.stream.in_progress",+ "response.completed": "responses.stream.terminal",+ "response.done": "responses.stream.terminal",+ "response.output_item.added": "responses.stream.output_item_added",+ "response.output_item.done": "responses.stream.output_item_done",+ "response.content_part.added": "responses.stream.content_part_added",+ "response.content_part.done": "responses.stream.content_part_done",+ "response.function_call_arguments.delta": "responses.stream.function_arguments_delta",+ "response.function_call_arguments.done": "responses.stream.function_arguments_done",+ "response.output_text.delta": "responses.stream.output_text_delta",+ "response.output_text.done": "responses.stream.output_text_done",+ "response.reasoning_summary_text.delta": "responses.stream.reasoning_summary_delta",+ "response.reasoning_summary_text.done": "responses.stream.reasoning_summary_done",+}+++def _stream_envelope_kind(protocol: str, event: dict[str, Any]) -> str | None:+ event_type = event.get("type")+ if protocol == "anthropic":+ return _ANTHROPIC_STREAM_ENVELOPES.get(event_type)+ if protocol == "responses":+ return _RESPONSES_STREAM_ENVELOPES.get(event_type)+ if protocol == "chat" and event_type != "error":+ choices = event.get("choices", _MISSING)+ if event.get("usage") is not None and choices in (_MISSING, []):+ return "chat.stream.usage"+ return "chat.stream.choice"+ return None+++def _stream_envelope_errors(protocol: str, event: dict[str, Any]) -> list[str]:+ kind = _stream_envelope_kind(protocol, event)+ return _required_envelope_errors(kind, event) if kind is not None else []+++def _stream_order_ok(protocol: str, events: list[dict[str, Any]]) -> bool:+ """Check lifecycle ordering without depending on provider-specific chunk sizes."""+ if not events:+ return False+ if any(item.get("sequence") != index for index, item in enumerate(events)):+ return False+ if protocol == "anthropic":+ open_blocks: set[int] = set()+ closed_blocks: set[int] = set()+ signed_blocks: set[int] = set()+ tool_blocks: set[int] = set()+ argument_fragment_counts: dict[int, int] = {}+ last_start = -1+ message_stop = None+ message_started = False+ message_delta_seen = False+ for index, item in enumerate(events):+ if item.get("kind") == "done":+ return False+ event = item.get("event", {})+ event_type = event.get("type")+ if not isinstance(event_type, str) or event_type not in ANTHROPIC_STREAM_EVENT_TYPES:+ return False+ if item.get("type") != event_type:+ return False+ if _stream_envelope_errors("anthropic", event):+ return False+ if message_stop is not None:+ return False+ if event_type == "message_start":+ if message_started:+ return False+ message_started = True+ elif event_type == "error":+ return False+ elif event_type == "content_block_start":+ if not message_started or message_delta_seen:+ return False+ if open_blocks:+ return False+ block_index = _stream_index(event.get("index"))+ if block_index is None:+ return False+ if block_index != len(open_blocks) + len(closed_blocks) or block_index in open_blocks or block_index in closed_blocks:+ return False+ block = event.get("content_block")+ if isinstance(block, dict):+ block_type = block.get("type")+ if block_type == "thinking" and any(+ field not in block+ or not isinstance(block[field], str)+ or block[field] != ""+ for field in ("thinking", "signature")+ ):+ return False+ if block_type == "text" and (+ "text" not in block+ or not isinstance(block["text"], str)+ or block["text"] != ""+ ):+ return False+ if block_type == "tool_use":+ tool_blocks.add(block_index)+ open_blocks.add(block_index)+ last_start = block_index+ elif event_type == "content_block_delta":+ if message_delta_seen:+ return False+ block_index = _stream_index(event.get("index"))+ if block_index is None:+ return False+ if block_index not in open_blocks:+ return False+ if block_index in signed_blocks:+ return False+ delta = event.get("delta")+ if isinstance(delta, dict):+ if delta.get("type") == "signature_delta":+ signed_blocks.add(block_index)+ elif delta.get("type") == "input_json_delta":+ fragment = delta.get("partial_json")+ if block_index in tool_blocks and isinstance(fragment, str) and fragment:+ argument_fragment_counts[block_index] = (+ argument_fragment_counts.get(block_index, 0) + 1+ )+ elif event_type == "content_block_stop":+ if message_delta_seen:+ return False+ block_index = _stream_index(event.get("index"))+ if block_index is None:+ return False+ if block_index not in open_blocks:+ return False+ open_blocks.remove(block_index)+ closed_blocks.add(block_index)+ elif event_type == "message_stop":+ if open_blocks or not message_delta_seen:+ return False+ message_stop = index+ elif event_type == "message_delta":+ if not message_started or open_blocks or message_delta_seen:+ return False+ delta = event["delta"]+ stop_reason = delta.get("stop_reason")+ stop_sequence = delta.get("stop_sequence")+ if (+ (stop_reason == "stop_sequence" and not stop_sequence)+ or (stop_reason != "stop_sequence" and stop_sequence is not None)+ ):+ return False+ message_delta_seen = True+ return (+ message_started+ and message_delta_seen+ and message_stop is not None+ and message_stop == len(events) - 1+ and all(+ argument_fragment_counts.get(block_index, 0) >= 2+ for block_index in tool_blocks+ )+ )+ if protocol == "responses":+ added: set[str] = set()+ closed: set[str] = set()+ completed_items: dict[str, dict[str, Any]] = {}+ argument_done: set[str] = set()+ argument_fragment_counts: dict[str, int] = {}+ message_text_started: set[tuple[str, int]] = set()+ message_text_done: set[tuple[str, int]] = set()+ reasoning_text_done: set[tuple[str, int]] = set()+ reasoning_summary_indexes: dict[str, set[int]] = {}+ reasoning_summary_text: dict[tuple[str, int], str] = {}+ encrypted_reasoning: dict[str, str | None] = {}+ message_text: dict[str, str] = {}+ item_types: dict[str, str] = {}+ item_statuses: dict[str, str | None] = {}+ item_indexes: dict[str, int] = {}+ index_items: dict[int, str] = {}+ content_parts: set[tuple[str, int]] = set()+ content_parts_closed: set[tuple[str, int]] = set()+ content_part_types: dict[tuple[str, int], str] = {}+ response_created = False+ response_in_progress_seen = False+ response_id: str | None = None+ previous_wire_sequence: int | None = None+ response_started = False+ output_started = False+ terminal = None+ for index, item in enumerate(events):+ if item.get("kind") == "done":+ return False+ event = item.get("event", {})+ event_type = event.get("type")+ if not isinstance(event_type, str) or item.get("type") != event_type:+ return False+ if event_type not in RESPONSES_STREAM_EVENT_TYPES:+ return False+ if _stream_envelope_errors("responses", event):+ return False+ wire_sequence = item.get("wire_sequence")+ if type(wire_sequence) is not int or wire_sequence < 0 or (+ previous_wire_sequence is not None and wire_sequence <= previous_wire_sequence+ ):+ return False+ previous_wire_sequence = wire_sequence+ if terminal is not None:+ return False+ if event_type == "response.created":+ if response_created or output_started:+ return False+ response_created = True+ response = event["response"]+ response_id = response["id"]+ response_started = True+ elif event_type == "response.in_progress":+ if not response_created or response_in_progress_seen or output_started:+ return False+ response_in_progress_seen = True+ response = event["response"]+ if response["id"] != response_id:+ return False+ response_started = True+ elif event_type == "response.output_item.added":+ if not response_started:+ return False+ raw = event.get("item")+ if not isinstance(raw, dict):+ return False+ output_index = _stream_index(event.get("output_index"))+ if output_index is None or output_index != len(added):+ return False+ item_id = _stream_item_id(raw.get("id"))+ if item_id is None or item_id in added or item_id in closed:+ return False+ if output_index in index_items:+ return False+ item_type = raw.get("type")+ if not isinstance(item_type, str) or item_type not in RESPONSES_OUTPUT_ITEM_TYPES:+ return False+ opening_status = raw.get("status")+ if opening_status is not None and opening_status != "in_progress":+ return False+ if item_type == "message" and "content" in raw and raw["content"] != []:+ return False+ added.add(item_id)+ item_types[item_id] = item_type+ item_statuses[item_id] = opening_status+ if item_types[item_id] == "function_call":+ if any(+ not isinstance(raw.get(field), str) or not raw[field]+ for field in ("call_id", "name")+ ):+ return False+ if "arguments" not in raw or raw["arguments"] != "":+ return False+ elif item_types[item_id] == "reasoning":+ opening_summary = raw.get("summary")+ if opening_summary not in (None, []):+ return False+ opening_content = raw.get("content")+ if opening_content not in (None, []):+ return False+ opening_encrypted = raw.get("encrypted_content")+ if opening_encrypted is not None and not isinstance(opening_encrypted, str):+ return False+ encrypted_reasoning[item_id] = opening_encrypted+ item_indexes[item_id] = output_index+ index_items[output_index] = item_id+ output_started = True+ elif event_type in {"response.content_part.added", "response.content_part.done"}:+ if not response_started:+ return False+ output_index = _stream_index(event.get("output_index"))+ content_index = _stream_index(event.get("content_index"))+ item_id = _stream_item_id(event.get("item_id"))+ part = event.get("part")+ key = (item_id, content_index if content_index is not None else -1)+ if (+ output_index is None+ or content_index is None+ or item_id is None+ or item_id not in added+ or item_types.get(item_id) != "message"+ or item_indexes.get(item_id) != output_index+ or not isinstance(part, dict)+ ):+ return False+ if event_type == "response.content_part.added":+ expected_content_index = sum(part_item_id == item_id for part_item_id, _ in content_parts)+ part_type = part.get("type")+ if (+ content_index != expected_content_index+ or key in content_parts+ or not isinstance(part_type, str)+ or part_type not in RESPONSES_MESSAGE_PART_TYPES+ ):+ return False+ if part_type in RESPONSES_MESSAGE_PART_TYPES and (+ "text" not in part or not isinstance(part["text"], str) or part["text"]+ ):+ return False+ content_parts.add(key)+ content_part_types[key] = part_type+ elif (+ key not in content_parts+ or key in content_parts_closed+ or not isinstance(part.get("type"), str)+ or part.get("type") != content_part_types.get(key)+ ):+ return False+ else:+ content_parts_closed.add(key)+ elif event_type == "response.function_call_arguments.delta":+ if not response_started:+ return False+ output_index = _stream_index(event.get("output_index"))+ item_id = _stream_item_id(event.get("item_id"))+ if item_id is None or item_id not in added or item_id in closed or item_id in argument_done or item_types.get(item_id) != "function_call":+ return False+ if output_index is None or item_indexes.get(item_id) != output_index:+ return False+ delta = event.get("delta")+ if not isinstance(delta, str):+ return False+ if delta:+ argument_fragment_counts[item_id] = argument_fragment_counts.get(item_id, 0) + 1+ elif event_type == "response.function_call_arguments.done":+ if not response_started:+ return False+ output_index = _stream_index(event.get("output_index"))+ item_id = _stream_item_id(event.get("item_id"))+ if (+ item_id is None+ or item_id not in added+ or item_id in closed+ or item_id in argument_done+ or item_types.get(item_id) != "function_call"+ or not isinstance(event.get("arguments"), str)+ or argument_fragment_counts.get(item_id, 0) < 2+ or output_index is None+ or item_indexes.get(item_id) != output_index+ ):+ return False+ argument_done.add(item_id)+ elif event_type in {"response.output_text.delta", "response.reasoning_summary_text.delta"}:+ if not response_started:+ return False+ output_index = _stream_index(event.get("output_index"))+ item_id = _stream_item_id(event.get("item_id"))+ expected_type = "reasoning" if event_type.startswith("response.reasoning") else "message"+ if (+ item_id is None+ or item_id not in added+ or item_id in closed+ or item_types.get(item_id) != expected_type+ or output_index is None+ or item_indexes.get(item_id) != output_index+ ):+ return False+ if expected_type == "message":+ content_index = _stream_index(event.get("content_index"))+ key = (item_id, content_index if content_index is not None else -1)+ delta = event.get("delta")+ if (+ content_index is None+ or key not in content_parts+ or content_part_types.get(key) not in RESPONSES_MESSAGE_PART_TYPES+ or key in content_parts_closed+ or key in message_text_done+ or not isinstance(delta, str)+ ):+ return False+ message_text_started.add(key)+ message_text[item_id] = message_text.get(item_id, "") + delta+ else:+ summary_index = _stream_index(event.get("summary_index"))+ delta = event.get("delta")+ if summary_index is None or not isinstance(delta, str):+ return False+ indexes = reasoning_summary_indexes.setdefault(item_id, set())+ if summary_index not in indexes and summary_index != len(indexes):+ return False+ indexes.add(summary_index)+ summary_key = (item_id, summary_index)+ if summary_key in reasoning_text_done:+ return False+ reasoning_summary_text[summary_key] = reasoning_summary_text.get(summary_key, "") + delta+ elif event_type in {"response.output_text.done", "response.reasoning_summary_text.done"}:+ if not response_started:+ return False+ output_index = _stream_index(event.get("output_index"))+ item_id = _stream_item_id(event.get("item_id"))+ expected_type = "reasoning" if event_type.startswith("response.reasoning") else "message"+ if (+ item_id is None+ or item_id not in added+ or item_id in closed+ or item_types.get(item_id) != expected_type+ or output_index is None+ or item_indexes.get(item_id) != output_index+ or not isinstance(event.get("text"), str)+ ):+ return False+ if expected_type == "message":+ content_index = _stream_index(event.get("content_index"))+ key = (item_id, content_index if content_index is not None else -1)+ if content_index is None or key not in message_text_started or key in message_text_done:+ return False+ message_text_done.add(key)+ else:+ summary_index = _stream_index(event.get("summary_index"))+ summary_key = (item_id, summary_index if summary_index is not None else -1)+ if (+ summary_index is None+ or summary_key not in reasoning_summary_text+ or summary_key in reasoning_text_done+ ):+ return False+ reasoning_text_done.add(summary_key)+ elif event_type == "response.output_item.done":+ if not response_started:+ return False+ raw = event.get("item")+ if not isinstance(raw, dict):+ return False+ output_index = _stream_index(event.get("output_index"))+ item_id = _stream_item_id(raw.get("id"))+ if item_id is None or item_id not in added or item_id in closed or output_index is None or item_indexes.get(item_id) != output_index:+ return False+ if item_types.get(item_id) == "function_call" and item_id not in argument_done:+ return False+ done_status = raw.get("status")+ if item_statuses.get(item_id) is not None and done_status != "completed":+ return False+ if done_status is not None and done_status != "completed":+ return False+ if item_types.get(item_id) == "message" and any(+ part_item_id == item_id+ and content_part_types.get((part_item_id, part_index)) in RESPONSES_MESSAGE_PART_TYPES+ and (part_item_id, part_index) not in message_text_done+ for part_item_id, part_index in content_parts+ ):+ return False+ if item_types.get(item_id) == "message":+ content = raw.get("content")+ if not isinstance(content, list):+ return False+ expected_parts = [+ content_part_types[(part_item_id, part_index)]+ for part_item_id, part_index in sorted(content_parts)+ if part_item_id == item_id+ ]+ if len(content) != len(expected_parts):+ return False+ snapshot_parts: list[str] = []+ for part, expected_type in zip(content, expected_parts):+ if not isinstance(part, dict):+ return False+ part_type = part.get("type")+ if not isinstance(part_type, str) or part_type not in RESPONSES_MESSAGE_PART_TYPES or part_type != expected_type:+ return False+ text = part.get("text")+ if not isinstance(text, str):+ return False+ snapshot_parts.append(text)+ if "".join(snapshot_parts) != message_text.get(item_id, ""):+ return False+ if item_types.get(item_id) == "reasoning" and any(+ summary_item_id == item_id+ and (summary_item_id, summary_index) not in reasoning_text_done+ for summary_item_id, indexes in reasoning_summary_indexes.items()+ for summary_index in indexes+ ):+ return False+ if item_types.get(item_id) == "reasoning":+ summary = raw.get("summary", [])+ if not isinstance(summary, list):+ return False+ summary_indexes = reasoning_summary_indexes.get(item_id, set())+ if set(range(len(summary))) != summary_indexes:+ return False+ if any((item_id, summary_index) not in reasoning_text_done for summary_index in summary_indexes):+ return False+ if any(+ not isinstance(part, dict)+ or not isinstance(part.get("type"), str)+ or part.get("type") not in RESPONSES_REASONING_PART_TYPES+ or not isinstance(part.get("text"), str)+ or part["text"] != reasoning_summary_text.get((item_id, summary_index), "")+ for summary_index, part in enumerate(summary)+ ):+ return False+ done_encrypted = raw.get("encrypted_content")+ if done_encrypted is not None and not isinstance(done_encrypted, str):+ return False+ if done_encrypted != encrypted_reasoning.get(item_id):+ return False+ if any(+ part_item_id == item_id and (part_item_id, part_index) not in content_parts_closed+ for part_item_id, part_index in content_parts+ ):+ return False+ completed_items[item_id] = copy.deepcopy(raw)+ closed.add(item_id)+ elif event_type in {"response.completed", "response.done"}:+ terminal_response = event["response"]+ if (+ not response_started+ or added != closed+ or content_parts != content_parts_closed+ ):+ return False+ terminal_items = {+ item_id: item+ for item in terminal_response["output"]+ if isinstance(item, dict) and (item_id := _stream_item_id(item.get("id"))) is not None+ }+ if any(+ not isinstance(item, dict)+ or (item.get("status") is not None and item.get("status") != "completed")+ for item in terminal_response["output"]+ ):+ return False+ for item_id, item_type in item_types.items():+ if item_type != "message":+ continue+ expected_parts = [+ content_part_types[(part_item_id, part_index)]+ for part_item_id, part_index in sorted(content_parts)+ if part_item_id == item_id+ ]+ snapshot = terminal_items.get(item_id)+ content = snapshot.get("content") if snapshot is not None else None+ if not isinstance(content, list) or len(content) != len(expected_parts):+ return False+ if any(+ not isinstance(part, dict)+ or part.get("type") != expected_type+ for part, expected_type in zip(content, expected_parts)+ ):+ return False+ if any(+ isinstance(item, dict)+ and item.get("type") == "reasoning"+ and item.get("encrypted_content") is not None+ and not isinstance(item.get("encrypted_content"), str)+ for item in terminal_response["output"]+ ):+ return False+ completed_output = [completed_items[index_items[index]] for index in sorted(index_items)]+ if (+ _responses_output_projection(completed_output) is None+ or _responses_output_projection(terminal_response["output"]) is None+ or _responses_output_projection(completed_output) != _responses_output_projection(terminal_response["output"])+ ):+ return False+ if terminal_response["id"] != response_id:+ return False+ terminal = index+ elif event_type in {"error", "response.failed", "response.incomplete"}:+ return False+ return terminal is not None and terminal == len(events) - 1+ terminal = None+ done_seen = False+ usage_seen = False+ seen_tool_indexes: set[int] = set()+ argument_fragment_counts: dict[int, int] = {}+ tool_ids: dict[int, str] = {}+ completion_id: str | None = None+ assistant_role_seen = False+ payload_seen = False+ for index, item in enumerate(events):+ if item.get("kind") == "done":+ if index != len(events) - 1:+ return False+ if done_seen:+ return False+ done_type = item.get("type")+ if done_type is not None and done_type != "chat.completion.chunk":+ return False+ done_seen = True+ continue+ event = item.get("event", {})+ event_type = event.get("type")+ if event_type is not None and not isinstance(event_type, str):+ return False+ if event_type not in CHAT_STREAM_EVENT_TYPES:+ return False+ if _stream_envelope_errors("chat", event):+ return False+ if item.get("type") is not None and item.get("type") != event_type:+ return False+ if event_type == "error":+ return False+ if "error" in event:+ return False+ choices = event["choices"]+ usage = event.get("usage")+ event_id = event["id"]+ if completion_id is None:+ completion_id = event_id+ elif event_id != completion_id:+ return False+ if terminal is not None:+ if choices or not isinstance(usage, dict) or usage_seen:+ return False+ usage_seen = True+ continue+ if choices:+ choice = choices[0]+ delta = choice["delta"]+ if "role" in delta:+ if delta["role"] != "assistant" or assistant_role_seen or payload_seen:+ return False+ assistant_role_seen = True+ if _chat_delta_has_payload(delta):+ if not assistant_role_seen:+ return False+ payload_seen = True+ tool_calls = delta.get("tool_calls", [])+ if not isinstance(tool_calls, list):+ return False+ chunk_last_tool_index = -1+ for call in tool_calls:+ if not isinstance(call, dict):+ return False+ tool_index = _stream_index(call.get("index"))+ if tool_index is None:+ return False+ if tool_index <= chunk_last_tool_index:+ return False+ if tool_index not in seen_tool_indexes:+ if tool_index != len(seen_tool_indexes):+ return False+ seen_tool_indexes.add(tool_index)+ tool_id = call.get("id")+ if not isinstance(tool_id, str) or not tool_id:+ return False+ tool_ids[tool_index] = tool_id+ elif "id" in call:+ tool_id = call.get("id")+ if not isinstance(tool_id, str) or not tool_id or tool_ids.get(tool_index) != tool_id:+ return False+ raw_type = call.get("type")+ if raw_type is not None and not isinstance(raw_type, str):+ return False+ function = call.get("function", {})+ if not isinstance(function, dict):+ return False+ if any(field in function and not isinstance(function[field], str) for field in ("name", "arguments")):+ return False+ argument_fragment = function.get("arguments")+ if argument_fragment:+ argument_fragment_counts[tool_index] = argument_fragment_counts.get(tool_index, 0) + 1+ chunk_last_tool_index = tool_index+ finish_reason = choice.get("finish_reason")+ if finish_reason is not None and not isinstance(finish_reason, str):+ return False+ if finish_reason is not None:+ terminal = index+ elif usage is not None:+ if terminal is None or not isinstance(usage, dict):+ return False+ else:+ return False+ return (+ terminal is not None+ and done_seen+ and assistant_role_seen+ and all(argument_fragment_counts.get(index, 0) >= 2 for index in seen_tool_indexes)+ )+++def _request(path: str, payload: dict[str, Any], *, client_protocol: str, stream: bool) -> TransportResult:+ body = json.dumps(payload, separators=(",", ":")).encode("utf-8")+ headers = {"Content-Type": "application/json"}+ if GATEWAY_TOKEN:+ headers["Authorization"] = f"Bearer {GATEWAY_TOKEN}"+ if client_protocol == "anthropic":+ headers["anthropic-version"] = "2023-06-01"+ request = urllib.request.Request(_request_url(client_protocol, path), body, headers, method="POST")+ started = time.monotonic()+ try:+ with OPENER.open(request, timeout=STREAM_TOTAL_TIMEOUT if stream else 10) as response:+ status = response.status+ if not stream:+ try:+ document = json.loads(+ response.read().decode("utf-8"),+ object_pairs_hook=_reject_duplicate_keys,+ parse_constant=_reject_nonfinite,+ )+ except (UnicodeDecodeError, json.JSONDecodeError, ValueError):+ return TransportResult(status, None, [], False, 1)+ return TransportResult(status, document if isinstance(document, dict) else None, [], False, 0)+ content_type = str(getattr(response, "headers", {}).get("Content-Type", ""))+ if content_type.split(";", 1)[0].strip().lower() != "text/event-stream":+ return TransportResult(status, None, [], False, 1, False, False, False)+ events: list[dict[str, Any]] = []+ data_lines: list[str] = []+ event_name: str | None = None+ done = False+ invalid = [0]+ buffer = bytearray()+ previous_was_cr = False+ first_line = True++ def consume_line(raw_line: bytes) -> bool:+ nonlocal event_name, first_line+ try:+ line = raw_line.decode("utf-8").rstrip("\r\n")+ except UnicodeDecodeError:+ invalid[0] += 1+ return False+ if first_line:+ first_line = False+ if line.startswith("\ufeff"):+ line = line[1:]+ if not line:+ flushed = _flush_sse(data_lines, event_name, events, invalid)+ event_name = None+ return flushed+ if line.startswith("event:"):+ event_name = line[6:]+ if event_name.startswith(" "):+ event_name = event_name[1:]+ else:+ field, separator, value = line.partition(":")+ if separator and value.startswith(" "):+ value = value[1:]+ if field == "event":+ event_name = value+ elif field == "data":+ data_lines.append(value)+ return False++ while True:+ elapsed = time.monotonic() - started+ if elapsed >= STREAM_TOTAL_TIMEOUT:+ return TransportResult(status, None, events, done, invalid[0], False, True)+ _set_stream_read_timeout(response, STREAM_TOTAL_TIMEOUT - elapsed)+ try:+ chunk = response.read(1)+ except (TimeoutError, socket.timeout):+ return TransportResult(status, None, events, done, invalid[0], False, True)+ if not chunk:+ if buffer:+ done = consume_line(bytes(buffer)) or done+ buffer.clear()+ break+ if chunk == b"\r":+ done = consume_line(bytes(buffer)) or done+ buffer.clear()+ previous_was_cr = True+ elif chunk == b"\n":+ if previous_was_cr:+ previous_was_cr = False+ continue+ done = consume_line(bytes(buffer)) or done+ buffer.clear()+ else:+ previous_was_cr = False+ buffer.extend(chunk)+ if invalid[0]:+ return TransportResult(status, None, events, done, invalid[0], False, False)+ if done:+ break+ # SSE dispatch requires a blank line; discard a final unterminated event at EOF.+ data_lines.clear()+ event_name = None+ buffer.clear()+ return TransportResult(status, None, events, done, invalid[0], _stream_order_ok(client_protocol, events), False, True)+ except urllib.error.HTTPError as error:+ return TransportResult(error.code, None, [], False, 0)+ except (OSError, TimeoutError, urllib.error.URLError):+ return TransportResult(0, None, [], False, 0)+++def _parse_arguments(value: Any, *, expected_wire: str | None = None) -> tuple[Any, str | None]:+ if expected_wire == "object" and not isinstance(value, dict):+ return value, "arguments_not_object"+ if expected_wire == "json" and not isinstance(value, str):+ return value, "arguments_not_json_string"+ if isinstance(value, dict):+ return value, None+ if not isinstance(value, str):+ return value, "arguments_not_object_or_json"+ try:+ parsed = json.loads(value, object_pairs_hook=_reject_duplicate_keys, parse_constant=_reject_nonfinite)+ except _DuplicateKeyError:+ return value, "arguments_duplicate_key"+ except (json.JSONDecodeError, ValueError):+ return value, "arguments_invalid_json"+ return parsed, None if isinstance(parsed, dict) else "arguments_not_object"+++def _required_identifier(value: Any, errors: list[str]) -> str:+ if not isinstance(value, str) or not value:+ errors.append("tool_call_id_invalid")+ return ""+ return value+++def _stream_index(value: Any) -> int | None:+ if type(value) is int and value >= 0:+ return value+ return None+++def _reasoning_text_parts(parts: Any) -> list[str]:+ if not isinstance(parts, list):+ return []+ return [+ part["text"]+ for part in parts+ if isinstance(part, dict)+ and isinstance(part.get("type"), str)+ and part.get("type") in RESPONSES_REASONING_PART_TYPES+ and isinstance(part.get("text"), str)+ and part["text"]+ ]+++def _reasoning_text(parts: Any) -> str:+ return "".join(_reasoning_text_parts(parts))+++def _reasoning_item_has_signal(item: dict[str, Any]) -> bool:+ encrypted = item.get("encrypted_content")+ return bool(+ _reasoning_text(item.get("summary"))+ or _reasoning_text(item.get("content"))+ or (isinstance(encrypted, str) and encrypted)+ )+++def _parse_anthropic_document(document: dict[str, Any] | None, *, event_count: int = 0, invalid_event_count: int = 0, terminal: bool | None = None) -> Turn:+ errors: list[str] = []+ if not isinstance(document, dict):+ errors.append("message_envelope_invalid")+ document = {}+ _extend_unique(errors, _required_envelope_errors("anthropic.message", document))+ content = document.get("content")+ if not isinstance(content, list):+ content = []+ calls: list[ToolCall] = []+ text_parts: list[str] = []+ reasoning_text_parts: list[str] = []+ reasoning_parts: list[str] = []+ reasoning = False+ for block in content:+ if not isinstance(block, dict):+ errors.append("content_block_invalid")+ continue+ block_type = block.get("type")+ if not isinstance(block_type, str) or block_type not in ANTHROPIC_CONTENT_BLOCK_TYPES:+ errors.append("content_block_type_invalid")+ continue+ if block_type == "tool_use":+ arguments, error = _parse_arguments(block.get("input"), expected_wire="object")+ if error:+ errors.append(error)+ calls.append(ToolCall(_required_identifier(block.get("id"), errors), str(block.get("name", "")), arguments))+ elif block_type == "text":+ text = block.get("text", "")+ if not isinstance(text, str):+ errors.append("text_block_invalid")+ else:+ text_parts.append(text)+ elif block_type == "thinking":+ thinking = block.get("thinking")+ if not isinstance(thinking, str) or not thinking:+ errors.append("thinking_payload_missing")+ else:+ reasoning = True+ reasoning_text_parts.append(thinking)+ reasoning_parts.append(thinking)+ signature = block.get("signature")+ if not isinstance(signature, str) or not signature:+ errors.append("thinking_signature_missing")+ else:+ reasoning_parts.append(signature)+ elif block_type == "redacted_thinking":+ data = block.get("data")+ if not isinstance(data, str) or not data:+ errors.append("redacted_thinking_payload_missing")+ else:+ reasoning = True+ reasoning_parts.append(data)+ stop_reason = document.get("stop_reason") if isinstance(document, dict) else None+ if stop_reason is not None and not isinstance(stop_reason, str):+ errors.append("stop_reason_invalid")+ stop_reason = None+ turn = Turn("anthropic", calls, "".join(text_parts), reasoning, stop_reason, content, terminal if terminal is not None else stop_reason is not None, event_count, invalid_event_count, errors)+ turn.reasoning_text = "".join(reasoning_text_parts)+ turn.reasoning_parts = reasoning_parts+ return turn+++def _parse_anthropic_stream(result: TransportResult) -> Turn:+ blocks: dict[int, dict[str, Any]] = {}+ signed_blocks: set[int] = set()+ argument_fragment_counts: dict[int, int] = {}+ stop_reason: str | None = None+ stop_sequence: str | None = None+ errors: list[str] = []+ text_delta_count = 0+ envelope: dict[str, Any] = {}+ message_delta_seen = False+ for item in result.events:+ if item.get("kind") == "done":+ errors.append("stream_done_sentinel")+ continue+ event = item.get("event", {})+ event_type = event.get("type")+ if not isinstance(event_type, str):+ errors.append("stream_event_type_invalid")+ continue+ if event_type not in ANTHROPIC_STREAM_EVENT_TYPES:+ errors.append("stream_event_unknown")+ continue+ _extend_unique(errors, _stream_envelope_errors("anthropic", event))+ if event_type == "error":+ errors.append("stream_error_event")+ elif event_type == "content_block_start":+ index = _stream_index(event.get("index"))+ if index is None:+ errors.append("stream_index_invalid")+ continue+ block = copy.deepcopy(event.get("content_block", {}))+ if not isinstance(block, dict):+ errors.append("content_block_invalid")+ continue+ block.setdefault("type", "")+ if block.get("type") == "tool_use":+ if block.get("input") != {}:+ errors.append("stream_tool_input_snapshot_invalid")+ block["_arguments"] = ""+ elif block.get("type") == "text":+ if "text" not in block:+ errors.append("stream_text_snapshot_missing")+ text_snapshot = ""+ else:+ text_snapshot = block["text"]+ if not isinstance(text_snapshot, str):+ errors.append("stream_text_snapshot_invalid")+ elif text_snapshot:+ errors.append("stream_text_opening_snapshot_invalid")+ block["text"] = ""+ elif block.get("type") == "thinking":+ for field in ("thinking", "signature"):+ if field not in block:+ errors.append(f"stream_{field}_snapshot_missing")+ value = ""+ else:+ value = block[field]+ if not isinstance(value, str):+ errors.append(f"stream_{field}_snapshot_invalid")+ elif value:+ errors.append(f"stream_{field}_opening_snapshot_invalid")+ block[field] = ""+ blocks[index] = block+ elif event_type == "content_block_delta":+ index = _stream_index(event.get("index"))+ if index is None:+ errors.append("stream_index_invalid")+ continue+ block = blocks.setdefault(index, {"type": ""})+ delta = event.get("delta", {})+ if not isinstance(delta, dict):+ errors.append("stream_delta_invalid")+ continue+ delta_type = delta.get("type")+ if delta_type == "input_json_delta":+ fragment = delta.get("partial_json")+ if block.get("type") != "tool_use" or not isinstance(fragment, str):+ errors.append("stream_delta_block_type_mismatch")+ else:+ if fragment:+ argument_fragment_counts[index] = (+ argument_fragment_counts.get(index, 0) + 1+ )+ block["_arguments"] = block.get("_arguments", "") + fragment+ elif delta_type == "text_delta":+ text = delta.get("text")+ if block.get("type") != "text" or not isinstance(text, str):+ errors.append("stream_delta_block_type_mismatch")+ else:+ if text:+ text_delta_count += 1+ block["text"] = block.get("text", "") + text+ elif delta_type == "thinking_delta":+ thinking = delta.get("thinking")+ if block.get("type") != "thinking" or not isinstance(thinking, str):+ errors.append("stream_delta_block_type_mismatch")+ elif index in signed_blocks:+ errors.append("stream_delta_after_signature")+ else:+ block["thinking"] = block.get("thinking", "") + thinking+ elif delta_type == "signature_delta":+ signature = delta.get("signature")+ if block.get("type") != "thinking" or not isinstance(signature, str):+ errors.append("stream_delta_block_type_mismatch")+ elif index in signed_blocks:+ errors.append("stream_delta_after_signature")+ else:+ block["signature"] = block.get("signature", "") + signature+ signed_blocks.add(index)+ else:+ errors.append("stream_delta_type_invalid")+ elif event_type == "message_start":+ message = event.get("message")+ if not isinstance(message, dict):+ continue+ else:+ envelope = {"type": message.get("type"), "role": message.get("role")}+ elif event_type == "message_delta":+ message_delta_seen = True+ delta = event.get("delta")+ if not isinstance(delta, dict):+ continue+ else:+ candidate_reason = delta.get("stop_reason")+ candidate_sequence = delta.get("stop_sequence")+ if (+ not isinstance(candidate_reason, str)+ or "stop_sequence" not in delta+ or (candidate_sequence is not None and not isinstance(candidate_sequence, str))+ or (candidate_reason == "stop_sequence" and not candidate_sequence)+ or (candidate_reason != "stop_sequence" and candidate_sequence is not None)+ ):+ errors.append("message_delta_stop_sequence_invalid")+ else:+ stop_reason = candidate_reason+ stop_sequence = candidate_sequence+ elif event_type == "message_stop" and not message_delta_seen:+ errors.append("message_delta_missing")+ content: list[dict[str, Any]] = []+ for index in sorted(blocks):+ block = blocks[index]+ if "_arguments" in block:+ fragment_count = argument_fragment_counts.get(index, 0)+ if fragment_count == 0:+ errors.append("stream_arguments_missing")+ elif fragment_count < 2:+ errors.append("stream_arguments_not_fragmented")+ arguments, error = _parse_arguments(block.pop("_arguments"))+ block["input"] = arguments+ if error:+ errors.append(error)+ content.append(block)+ document = {+ "type": envelope.get("type"),+ "role": envelope.get("role"),+ "content": content,+ "stop_reason": stop_reason,+ "stop_sequence": stop_sequence,+ }+ turn = _parse_anthropic_document(+ document,+ event_count=len(result.events),+ invalid_event_count=result.invalid_event_count,+ terminal=result.done_sentinel or any(item.get("type") == "message_stop" for item in result.events),+ )+ turn.parse_errors.extend(errors)+ turn.stream_order_ok = result.stream_order_ok+ turn.deadline_expired = result.deadline_expired+ turn.content_type_ok = result.content_type_ok+ turn.stream_text_delta_count = text_delta_count+ return turn+++def _parse_responses_document(document: dict[str, Any] | None, *, event_count: int = 0, invalid_event_count: int = 0, terminal: bool | None = None) -> Turn:+ errors: list[str] = []+ payload = document if isinstance(document, dict) else {}+ _extend_unique(errors, _required_envelope_errors("responses.response", payload))+ output = payload.get("output")+ if not isinstance(output, list):+ output = []+ calls: list[ToolCall] = []+ text_parts: list[str] = []+ reasoning_text_parts: list[str] = []+ reasoning_parts: list[str] = []+ output_item_ids: set[str] = set()+ reasoning = False+ for item in output:+ if not isinstance(item, dict):+ errors.append("output_item_invalid")+ continue+ item_id = _stream_item_id(item.get("id"))+ if item_id is None:+ errors.append("output_item_id_invalid")+ elif item_id in output_item_ids:+ errors.append("output_item_id_duplicate")+ else:+ output_item_ids.add(item_id)+ item_type = item.get("type")+ if not isinstance(item_type, str) or item_type not in RESPONSES_OUTPUT_ITEM_TYPES:+ errors.append("output_item_type_invalid")+ continue+ item_status = item.get("status")+ if item_status is not None and item_status != "completed":+ errors.append("output_item_status_invalid")+ continue+ if item_type == "function_call":+ arguments, error = _parse_arguments(item.get("arguments"), expected_wire="json")+ if error:+ errors.append(error)+ calls.append(ToolCall(_required_identifier(item.get("call_id"), errors), str(item.get("name", "")), arguments))+ elif item_type == "reasoning":+ encrypted = item.get("encrypted_content")+ if encrypted is not None and not isinstance(encrypted, str):+ errors.append("encrypted_reasoning_invalid")+ for field in ("summary", "content"):+ parts = item.get(field)+ if parts is not None and not isinstance(parts, list):+ errors.append("reasoning_parts_invalid")+ elif isinstance(parts, list):+ for part in parts:+ if (+ not isinstance(part, dict)+ or not isinstance(part.get("type"), str)+ or part.get("type") not in RESPONSES_REASONING_PART_TYPES+ ):+ errors.append("reasoning_part_type_invalid")+ elif not isinstance(part.get("text"), str):+ errors.append("reasoning_part_text_invalid")+ item_parts = [*_reasoning_text_parts(item.get("summary")), *_reasoning_text_parts(item.get("content"))]+ if _reasoning_item_has_signal(item):+ reasoning = True+ reasoning_text_parts.extend(item_parts)+ reasoning_parts.extend(item_parts)+ if isinstance(encrypted, str) and encrypted:+ reasoning_parts.append(encrypted)+ elif item_type == "message":+ if item.get("role") != "assistant":+ errors.append("assistant_role_invalid")+ content = item.get("content")+ if not isinstance(content, list):+ errors.append("message_content_invalid")+ continue+ for part in content:+ if not isinstance(part, dict) or not isinstance(part.get("type"), str) or part.get("type") not in RESPONSES_MESSAGE_PART_TYPES:+ errors.append("message_part_type_invalid")+ elif part.get("type") in RESPONSES_MESSAGE_PART_TYPES:+ text = part.get("text", "")+ if not isinstance(text, str):+ errors.append("message_text_invalid")+ else:+ text_parts.append(text)+ status = payload.get("status")+ if status is not None and not isinstance(status, str):+ errors.append("status_invalid")+ status = None+ turn = Turn("responses", calls, "".join(text_parts), reasoning, status, output, terminal if terminal is not None else status in {"completed", "incomplete"}, event_count, invalid_event_count, errors)+ turn.reasoning_text = "".join(reasoning_text_parts)+ turn.reasoning_parts = reasoning_parts+ return turn+++def _responses_output_projection(output: Any) -> list[dict[str, Any]] | None:+ if not isinstance(output, list):+ return None+ projection: list[dict[str, Any]] = []+ for item in output:+ if not isinstance(item, dict):+ return None+ item_type = item.get("type")+ projected: dict[str, Any] = {"id": item.get("id"), "type": item_type, "status": item.get("status")}+ if item_type == "function_call":+ arguments, error = _parse_arguments(item.get("arguments"), expected_wire="json")+ if error:+ return None+ projected.update({"call_id": item.get("call_id"), "name": item.get("name"), "arguments": arguments})+ elif item_type == "message":+ content = item.get("content")+ if item.get("role") != "assistant" or not isinstance(content, list):+ return None+ projected_content: list[dict[str, Any]] = []+ for part in content:+ if not isinstance(part, dict) or not isinstance(part.get("type"), str) or part.get("type") not in RESPONSES_MESSAGE_PART_TYPES:+ return None+ text = part.get("text")+ if not isinstance(text, str):+ return None+ projected_content.append({"type": part.get("type"), "text": text})+ projected["content"] = projected_content+ elif item_type == "reasoning":+ encrypted = item.get("encrypted_content")+ if encrypted is not None and not isinstance(encrypted, str):+ return None+ for field in ("summary", "content"):+ parts = item.get(field)+ if parts is not None:+ if not isinstance(parts, list):+ return None+ if any(+ not isinstance(part, dict)+ or not isinstance(part.get("type"), str)+ or part.get("type") not in RESPONSES_REASONING_PART_TYPES+ or not isinstance(part.get("text"), str)+ for part in parts+ ):+ return None+ projected.update(+ {+ "summary": [+ {"type": part["type"], "text": part["text"]}+ for part in item.get("summary") or []+ ],+ "content": [+ {"type": part["type"], "text": part["text"]}+ for part in item.get("content") or []+ ],+ "encrypted_content": encrypted,+ }+ )+ else:+ projected["raw"] = item+ projection.append(projected)+ return projection+++def _parse_responses_stream(result: TransportResult) -> Turn:+ output: dict[str, dict[str, Any]] = {}+ text_parts: list[str] = []+ text_by_item: dict[str, str] = {}+ text_by_part: dict[tuple[str, int], str] = {}+ reasoning_by_item: dict[str, str] = {}+ reasoning_by_summary: dict[tuple[str, int], str] = {}+ reasoning_summary_indexes: dict[str, set[int]] = {}+ reasoning_summary_done: set[tuple[str, int]] = set()+ encrypted_reasoning_by_item: dict[str, str | None] = {}+ opening_status_by_item: dict[str, str | None] = {}+ status: str | None = None+ response_id: str | None = None+ response_in_progress_seen = False+ args_by_item: dict[str, str] = {}+ argument_fragment_counts: dict[str, int] = {}+ argument_done_items: set[str] = set()+ content_parts_closed: set[tuple[str, int]] = set()+ content_part_types: dict[tuple[str, int], str] = {}+ text_delta_count = 0+ terminal_response: dict[str, Any] | None = None+ streamed_output_seen = False+ errors: list[str] = []+ for item in result.events:+ event = item.get("event", {})+ event_type = event.get("type")+ if not isinstance(event_type, str):+ errors.append("stream_event_type_invalid")+ continue+ if event_type not in RESPONSES_STREAM_EVENT_TYPES:+ errors.append("stream_event_unknown")+ continue+ _extend_unique(errors, _stream_envelope_errors("responses", event))+ if event_type in {"error", "response.failed", "response.incomplete"}:+ errors.append("stream_failure_event")+ elif event_type == "response.created":+ response = event.get("response")+ if (+ not isinstance(response, dict)+ or response.get("object") != "response"+ or response.get("status") != "in_progress"+ or response.get("output") != []+ ):+ errors.append("response_start_snapshot_invalid")+ if not isinstance(response, dict) or not isinstance(response.get("id"), str) or not response["id"]:+ errors.append("response_id_invalid")+ else:+ response_id = response["id"]+ elif event_type == "response.in_progress":+ if response_in_progress_seen:+ errors.append("response_in_progress_duplicate")+ response_in_progress_seen = True+ response = event.get("response")+ if (+ not isinstance(response, dict)+ or response.get("object") != "response"+ or response.get("status") != "in_progress"+ or response.get("output") != []+ ):+ errors.append("response_in_progress_snapshot_invalid")+ snapshot_id = response.get("id") if isinstance(response, dict) else None+ if not isinstance(snapshot_id, str) or snapshot_id != response_id:+ errors.append("response_in_progress_id_invalid")+ elif event_type == "response.output_item.added":+ streamed_output_seen = True+ raw = copy.deepcopy(event.get("item"))+ if not isinstance(raw, dict):+ errors.append("output_item_invalid")+ continue+ key = _parsed_stream_item_id(raw.get("id"), errors)+ if key is None:+ continue+ output[key] = raw+ opening_status = raw.get("status")+ if opening_status is not None and opening_status != "in_progress":+ errors.append("stream_output_item_status_invalid")+ opening_status_by_item[key] = opening_status+ if raw.get("type") == "message" and "content" in raw and raw["content"] != []:+ errors.append("stream_message_opening_snapshot_invalid")+ if raw.get("type") == "function_call":+ for field in ("call_id", "name"):+ if not isinstance(raw.get(field), str) or not raw[field]:+ errors.append("stream_function_identity_invalid")+ if "arguments" not in raw:+ errors.append("stream_arguments_snapshot_missing")+ elif not isinstance(raw["arguments"], str) or raw["arguments"] != "":+ errors.append("stream_arguments_opening_snapshot_invalid")+ if raw.get("type") == "message" and raw.get("role") != "assistant":+ errors.append("assistant_role_invalid")+ if raw.get("type") == "reasoning":+ opening_summary = raw.get("summary")+ if opening_summary not in (None, []):+ errors.append("stream_reasoning_opening_snapshot_invalid")+ opening_content = raw.get("content")+ if opening_content not in (None, []):+ errors.append("stream_reasoning_opening_snapshot_invalid")+ reasoning_by_item[key] = _reasoning_text(raw.get("summary"))+ opening_encrypted = raw.get("encrypted_content")+ if opening_encrypted is not None and not isinstance(opening_encrypted, str):+ errors.append("encrypted_reasoning_snapshot_invalid")+ opening_encrypted = None+ encrypted_reasoning_by_item[key] = opening_encrypted+ elif event_type == "response.output_item.done":+ streamed_output_seen = True+ raw = event.get("item")+ if isinstance(raw, dict):+ key = _parsed_stream_item_id(raw.get("id"), errors)+ if key is None:+ continue+ previous = output.get(key)+ if previous is not None and any(+ field in previous and field in raw and previous[field] != raw[field]+ for field in ("id", "type", "call_id", "name")+ ):+ errors.append("stream_item_snapshot_mismatch")+ if key in args_by_item and isinstance(raw.get("arguments"), str):+ delta_arguments, delta_error = _parse_arguments(args_by_item[key], expected_wire="json")+ done_arguments, done_error = _parse_arguments(raw["arguments"], expected_wire="json")+ if delta_error or done_error or delta_arguments != done_arguments:+ errors.append("stream_item_snapshot_mismatch")+ if raw.get("type") == "function_call":+ snapshot_arguments = raw.get("arguments")+ if not isinstance(snapshot_arguments, str) or _parse_arguments(snapshot_arguments, expected_wire="json")[1]:+ errors.append("stream_arguments_snapshot_invalid")+ done_status = raw.get("status")+ if opening_status_by_item.get(key) is not None and done_status != "completed":+ errors.append("stream_output_item_status_invalid")+ if done_status is not None and done_status != "completed":+ errors.append("stream_output_item_status_invalid")+ if raw.get("type") == "reasoning" and key in reasoning_by_item:+ snapshot_reasoning = _reasoning_text(raw.get("summary")) + _reasoning_text(raw.get("content"))+ if snapshot_reasoning != reasoning_by_item[key]:+ errors.append("stream_reasoning_snapshot_mismatch")+ summary = raw.get("summary", [])+ if not isinstance(summary, list):+ errors.append("stream_reasoning_summary_invalid")+ else:+ summary_indexes = reasoning_summary_indexes.get(key, set())+ if set(range(len(summary))) != summary_indexes:+ errors.append("stream_reasoning_summary_snapshot_invalid")+ if any(summary_index not in summary_indexes for summary_index in range(len(summary))):+ errors.append("stream_reasoning_summary_events_missing")+ if any((key, summary_index) not in reasoning_summary_done for summary_index in summary_indexes):+ errors.append("stream_reasoning_summary_events_missing")+ for summary_index, part in enumerate(summary):+ if (+ not isinstance(part, dict)+ or not isinstance(part.get("type"), str)+ or part.get("type") not in RESPONSES_REASONING_PART_TYPES+ or not isinstance(part.get("text"), str)+ ):+ errors.append("stream_reasoning_summary_snapshot_invalid")+ elif part["text"] != reasoning_by_summary.get((key, summary_index), ""):+ errors.append("stream_reasoning_summary_snapshot_mismatch")+ done_encrypted = raw.get("encrypted_content")+ if done_encrypted is not None and not isinstance(done_encrypted, str):+ errors.append("encrypted_reasoning_snapshot_invalid")+ elif done_encrypted != encrypted_reasoning_by_item.get(key):+ errors.append("stream_reasoning_snapshot_mismatch")+ output[key] = copy.deepcopy(raw)+ if raw.get("type") == "message" and raw.get("role") != "assistant":+ errors.append("assistant_role_invalid")+ raw_type = raw.get("type")+ if not isinstance(raw_type, str) or raw_type not in RESPONSES_OUTPUT_ITEM_TYPES:+ errors.append("output_item_type_invalid")+ continue+ if raw_type == "message":+ content = raw.get("content")+ if not isinstance(content, list):+ errors.append("message_content_invalid")+ continue+ expected_parts = [+ content_part_types[(part_item_id, part_index)]+ for part_item_id, part_index in sorted(content_part_types)+ if part_item_id == key+ ]+ if len(content) != len(expected_parts):+ errors.append("stream_content_part_snapshot_mismatch")+ item_snapshot_parts: list[str] = []+ for part, expected_type in zip(content, expected_parts):+ if not isinstance(part, dict) or part.get("type") != expected_type:+ errors.append("message_part_type_invalid")+ elif part.get("type") in RESPONSES_MESSAGE_PART_TYPES:+ text = part.get("text", "")+ if not isinstance(text, str):+ errors.append("message_text_invalid")+ else:+ item_snapshot_parts.append(text)+ if "".join(item_snapshot_parts) != text_by_item.get(key, ""):+ errors.append("stream_text_snapshot_mismatch")+ else:+ errors.append("output_item_invalid")+ elif event_type in {"response.content_part.added", "response.content_part.done"}:+ key = _parsed_stream_item_id(event.get("item_id"), errors)+ content_index = _stream_index(event.get("content_index"))+ if key is None or content_index is None:+ if content_index is None:+ errors.append("content_index_invalid")+ continue+ part = event.get("part")+ if not isinstance(part, dict):+ errors.append("content_part_invalid")+ continue+ part_type = part.get("type")+ if not isinstance(part_type, str) or part_type not in RESPONSES_MESSAGE_PART_TYPES:+ errors.append("content_part_type_invalid")+ continue+ if event_type == "response.content_part.added":+ content_part_types[(key, content_index)] = part_type+ if event_type == "response.content_part.added" and part_type in RESPONSES_MESSAGE_PART_TYPES:+ opening_text = part.get("text")+ if "text" not in part or not isinstance(opening_text, str) or opening_text:+ errors.append("content_part_opening_snapshot_invalid")+ elif event_type == "response.content_part.done":+ if content_part_types.get((key, content_index)) != part_type:+ errors.append("content_part_type_mismatch")+ part_text = part.get("text")+ if not isinstance(part_text, str):+ errors.append("content_part_text_invalid")+ elif part_text != text_by_part.get((key, content_index), ""):+ errors.append("content_part_snapshot_mismatch")+ content_parts_closed.add((key, content_index))+ elif event_type == "response.function_call_arguments.delta":+ key = _parsed_stream_item_id(event.get("item_id"), errors)+ if key is None:+ continue+ if output.get(key, {}).get("type") != "function_call":+ errors.append("stream_delta_item_type_mismatch")+ continue+ delta = event.get("delta")+ if not isinstance(delta, str):+ errors.append("stream_arguments_invalid")+ continue+ if delta:+ argument_fragment_counts[key] = argument_fragment_counts.get(key, 0) + 1+ args_by_item[key] = args_by_item.get(key, "") + delta+ elif event_type == "response.function_call_arguments.done":+ key = _parsed_stream_item_id(event.get("item_id"), errors)+ if key is None:+ continue+ if output.get(key, {}).get("type") != "function_call":+ errors.append("stream_delta_item_type_mismatch")+ continue+ done_arguments = event.get("arguments")+ if not isinstance(done_arguments, str):+ errors.append("stream_arguments_done_invalid")+ continue+ reconstructed, reconstructed_error = _parse_arguments(args_by_item.get(key, ""), expected_wire="json")+ completed, completed_error = _parse_arguments(done_arguments, expected_wire="json")+ if reconstructed_error or completed_error or reconstructed != completed:+ errors.append("stream_arguments_done_mismatch")+ argument_done_items.add(key)+ elif event_type in {"response.output_text.delta", "response.reasoning_summary_text.delta"}:+ key = _parsed_stream_item_id(event.get("item_id"), errors)+ if key is None:+ continue+ expected_type = "reasoning" if event_type.startswith("response.reasoning") else "message"+ if output.get(key, {}).get("type") != expected_type:+ errors.append("stream_delta_item_type_mismatch")+ continue+ if event_type.startswith("response.reasoning"):+ delta = event.get("delta")+ if not isinstance(delta, str):+ errors.append("stream_reasoning_delta_invalid")+ continue+ summary_index = _stream_index(event.get("summary_index"))+ if summary_index is None:+ errors.append("summary_index_invalid")+ continue+ indexes = reasoning_summary_indexes.setdefault(key, set())+ if summary_index not in indexes and summary_index != len(indexes):+ errors.append("summary_index_invalid")+ continue+ indexes.add(summary_index)+ summary_key = (key, summary_index)+ reasoning_by_summary[summary_key] = reasoning_by_summary.get(summary_key, "") + delta+ if delta:+ reasoning_by_item[key] = reasoning_by_item.get(key, "") + delta+ else:+ delta = event.get("delta")+ if not isinstance(delta, str):+ errors.append("stream_text_delta_invalid")+ continue+ if delta:+ text_delta_count += 1+ text_parts.append(delta)+ text_by_item[key] = text_by_item.get(key, "") + delta+ content_index = _stream_index(event.get("content_index"))+ if content_index is None:+ errors.append("content_index_invalid")+ else:+ part_key = (key, content_index)+ if part_key in content_parts_closed:+ errors.append("stream_text_after_content_part_done")+ text_by_part[part_key] = text_by_part.get(part_key, "") + delta+ elif event_type in {"response.output_text.done", "response.reasoning_summary_text.done"}:+ key = _parsed_stream_item_id(event.get("item_id"), errors)+ if key is None:+ continue+ expected_type = "reasoning" if event_type.startswith("response.reasoning") else "message"+ if output.get(key, {}).get("type") != expected_type:+ errors.append("stream_delta_item_type_mismatch")+ continue+ completed_text = event.get("text")+ if not isinstance(completed_text, str):+ errors.append("stream_text_done_invalid")+ continue+ if expected_type == "reasoning":+ summary_index = _stream_index(event.get("summary_index"))+ if summary_index is None:+ errors.append("summary_index_invalid")+ reconstructed_text = ""+ else:+ summary_key = (key, summary_index)+ if summary_key not in reasoning_by_summary:+ errors.append("stream_reasoning_summary_done_without_delta")+ reconstructed_text = ""+ else:+ reconstructed_text = reasoning_by_summary[summary_key]+ reasoning_summary_done.add(summary_key)+ else:+ content_index = _stream_index(event.get("content_index"))+ if content_index is None:+ errors.append("content_index_invalid")+ continue+ if (key, content_index) in content_parts_closed:+ errors.append("stream_text_after_content_part_done")+ reconstructed_text = text_by_part.get((key, content_index), "")+ if completed_text != reconstructed_text:+ errors.append("stream_text_done_mismatch")+ elif event_type in {"response.completed", "response.done"}:+ terminal_response = event.get("response") if isinstance(event.get("response"), dict) else None+ status = terminal_response.get("status") if terminal_response else None+ if status != "completed":+ errors.append("terminal_status_invalid")+ terminal_output = terminal_response.get("output") if terminal_response else None+ if isinstance(terminal_output, list):+ for raw in terminal_output:+ if (+ not isinstance(raw, dict)+ or (raw.get("status") is not None and raw.get("status") != "completed")+ ):+ errors.append("terminal_output_item_status_invalid")+ if (+ isinstance(raw, dict)+ and raw.get("type") == "reasoning"+ and raw.get("encrypted_content") is not None+ and not isinstance(raw.get("encrypted_content"), str)+ ):+ errors.append("encrypted_reasoning_snapshot_invalid")+ terminal_id = terminal_response.get("id") if terminal_response else None+ if not isinstance(terminal_id, str) or terminal_id != response_id:+ errors.append("terminal_response_id_invalid")+ items: list[dict[str, Any]] = []+ for key, raw in output.items():+ if raw.get("type") == "function_call":+ fragment_count = argument_fragment_counts.get(key, 0)+ if fragment_count == 0:+ errors.append("stream_arguments_missing")+ elif fragment_count < 2:+ errors.append("stream_arguments_not_fragmented")+ if key not in argument_done_items:+ errors.append("stream_arguments_done_missing")+ if key in args_by_item:+ raw["arguments"] = args_by_item[key]+ items.append(raw)+ if text_parts:+ message_items = [(key, raw) for key, raw in output.items() if raw.get("type") == "message"]+ if message_items:+ for key, raw in message_items:+ part_keys = sorted(+ (part_key for part_key in content_part_types if part_key[0] == key),+ key=lambda part_key: part_key[1],+ )+ if part_keys:+ raw["content"] = [+ {"type": content_part_types[part_key], "text": text_by_part.get(part_key, "")}+ for part_key in part_keys+ ]+ else:+ raw["content"] = [{"type": "output_text", "text": text_by_item.get(key, "")}]+ else:+ items.append({"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "".join(text_parts)}]})+ if terminal_response is not None:+ terminal_output = terminal_response.get("output")+ if not isinstance(terminal_output, list):+ errors.append("terminal_output_invalid")+ elif streamed_output_seen:+ if _responses_output_projection(items) != _responses_output_projection(terminal_output):+ errors.append("terminal_output_mismatch")+ elif not items:+ items = copy.deepcopy(terminal_output)+ for item in terminal_output:+ if isinstance(item, dict) and item.get("type") == "function_call":+ errors.append("stream_arguments_missing")+ response_object = terminal_response.get("object") if isinstance(terminal_response, dict) else None+ turn = _parse_responses_document(+ {"id": response_id, "object": response_object, "output": items, "status": status},+ event_count=len(result.events),+ invalid_event_count=result.invalid_event_count,+ terminal=status == "completed",+ )+ turn.parse_errors.extend(errors)+ turn.stream_order_ok = result.stream_order_ok+ turn.deadline_expired = result.deadline_expired+ turn.stream_text_delta_count = text_delta_count+ turn.content_type_ok = result.content_type_ok+ return turn+++def _parse_chat_document(document: dict[str, Any] | None, *, event_count: int = 0, invalid_event_count: int = 0, terminal: bool | None = None) -> Turn:+ errors: list[str] = []+ payload = document if isinstance(document, dict) else {}+ _extend_unique(errors, _required_envelope_errors("chat.completion", payload))+ choices = payload.get("choices")+ if not isinstance(choices, list) or len(choices) != 1 or not isinstance(choices[0], dict):+ choice: dict[str, Any] = {}+ else:+ choice = choices[0]+ message = choice.get("message", {})+ if not isinstance(message, dict):+ message = {}+ calls: list[ToolCall] = []+ tool_calls = message.get("tool_calls", [])+ if not isinstance(tool_calls, list):+ errors.append("tool_calls_invalid")+ tool_calls = []+ for raw in tool_calls:+ if not isinstance(raw, dict):+ errors.append("tool_call_invalid")+ continue+ if raw.get("type") != "function":+ errors.append("tool_call_type_invalid")+ continue+ function = raw.get("function", {})+ if not isinstance(function, dict):+ errors.append("tool_function_invalid")+ continue+ arguments, error = _parse_arguments(function.get("arguments"), expected_wire="json")+ if error:+ errors.append(error)+ calls.append(ToolCall(_required_identifier(raw.get("id"), errors), str(function.get("name", "")), arguments))+ if "content" not in message:+ content = ""+ else:+ content = message["content"]+ if content is not None and not isinstance(content, str):+ errors.append("message_content_invalid")+ content = ""+ reasoning_content = message.get("reasoning_content", "") if isinstance(message, dict) else ""+ if "reasoning_content" in message and (not isinstance(reasoning_content, str) or not reasoning_content):+ errors.append("reasoning_content_invalid")+ reasoning_content = ""+ finish_reason = choice.get("finish_reason") if isinstance(choice, dict) else None+ if finish_reason is not None and not isinstance(finish_reason, str):+ errors.append("finish_reason_invalid")+ finish_reason = None+ continuation = copy.deepcopy(message) if isinstance(message, dict) else {}+ turn = Turn(+ "chat",+ calls,+ str(content or ""),+ bool(reasoning_content) or _chat_reasoning_usage_present(document),+ finish_reason,+ continuation,+ terminal if terminal is not None else finish_reason is not None,+ event_count,+ invalid_event_count,+ errors,+ )+ turn.reasoning_text = str(reasoning_content or "")+ turn.reasoning_parts = [turn.reasoning_text] if turn.reasoning_text else []+ return turn+++def _chat_reasoning_usage_present(document: dict[str, Any] | None) -> bool:+ usage = document.get("usage") if isinstance(document, dict) else None+ details = usage.get("completion_tokens_details") if isinstance(usage, dict) else None+ reasoning_tokens = details.get("reasoning_tokens") if isinstance(details, dict) else None+ return type(reasoning_tokens) is int and reasoning_tokens > 0+++def _parse_chat_stream(result: TransportResult) -> Turn:+ content: list[str] = []+ reasoning: list[str] = []+ calls: dict[int, dict[str, Any]] = {}+ finish_reason: str | None = None+ usage: dict[str, Any] | None = None+ usage_seen = False+ errors: list[str] = []+ argument_fragment_counts: dict[int, int] = {}+ tool_type_seen: set[int] = set()+ assistant_role_seen = False+ payload_seen = False+ completion_id: str | None = None+ for item in result.events:+ if item.get("kind") == "done":+ done_type = item.get("type")+ if done_type is not None and done_type != "chat.completion.chunk":+ errors.append("stream_done_event_type_invalid")+ continue+ event = item.get("event", {})+ event_type = event.get("type")+ if event_type is not None and not isinstance(event_type, str):+ errors.append("stream_event_type_invalid")+ continue+ if event_type not in CHAT_STREAM_EVENT_TYPES:+ errors.append("stream_event_unknown")+ continue+ if event_type == "error":+ errors.append("stream_failure_event")+ continue+ _extend_unique(errors, _stream_envelope_errors("chat", event))+ event_id = event.get("id")+ if isinstance(event_id, str) and event_id and completion_id is None:+ completion_id = event_id+ elif isinstance(event_id, str) and event_id and event_id != completion_id:+ errors.append("stream_completion_id_changed")+ if "error" in event:+ errors.append("stream_failure_event")+ continue+ event_usage = event.get("usage")+ if event_usage is not None:+ if finish_reason is None or not isinstance(event_usage, dict):+ errors.append("usage_before_finish")+ elif usage_seen:+ errors.append("usage_duplicate")+ else:+ usage = event_usage+ usage_seen = True+ choices = event.get("choices", [])+ if not isinstance(choices, list):+ continue+ if not choices:+ if event_usage is None:+ errors.append("stream_envelope_invalid")+ continue+ if len(choices) != 1 or not isinstance(choices[0], dict):+ continue+ choice = choices[0]+ if "delta" not in choice:+ continue+ delta = choice["delta"]+ if not isinstance(delta, dict):+ continue+ if "role" in delta:+ if delta.get("role") != "assistant":+ errors.append("assistant_role_invalid")+ elif assistant_role_seen:+ errors.append("assistant_role_duplicate")+ elif payload_seen:+ errors.append("assistant_role_late")+ assistant_role_seen = True+ else:+ assistant_role_seen = True+ if _chat_delta_has_payload(delta):+ if not assistant_role_seen:+ errors.append("assistant_role_before_payload_missing")+ payload_seen = True+ if "content" in delta:+ delta_content = delta["content"]+ if delta_content is not None and not isinstance(delta_content, str):+ errors.append("stream_content_invalid")+ elif delta_content:+ content.append(delta_content)+ if "reasoning_content" in delta:+ reasoning_content = delta["reasoning_content"]+ if not isinstance(reasoning_content, str) or not reasoning_content:+ errors.append("reasoning_content_invalid")+ else:+ reasoning.append(reasoning_content)+ choice_finish_reason = choice.get("finish_reason")+ if choice_finish_reason is not None and not isinstance(choice_finish_reason, str):+ errors.append("finish_reason_invalid")+ elif choice_finish_reason:+ finish_reason = choice_finish_reason+ tool_calls = delta.get("tool_calls", [])+ if not isinstance(tool_calls, list):+ errors.append("tool_calls_invalid")+ continue+ chunk_tool_indexes: set[int] = set()+ for raw in tool_calls:+ if not isinstance(raw, dict):+ errors.append("tool_call_invalid")+ continue+ index = _stream_index(raw.get("index"))+ if index is None:+ errors.append("stream_index_invalid")+ continue+ if index in chunk_tool_indexes:+ errors.append("stream_tool_index_duplicate")+ continue+ chunk_tool_indexes.add(index)+ opening_fragment = index not in calls+ call = calls.setdefault(index, {"id": "", "type": "function", "function": {"name": "", "arguments": ""}})+ raw_type = raw.get("type")+ if index not in tool_type_seen:+ if raw_type != "function":+ errors.append("tool_call_type_invalid")+ continue+ tool_type_seen.add(index)+ elif raw_type is not None and not isinstance(raw_type, str):+ errors.append("tool_call_type_invalid")+ continue+ elif raw_type not in {None, "function"}:+ errors.append("tool_call_type_invalid")+ continue+ if opening_fragment:+ raw_id = raw.get("id")+ if not isinstance(raw_id, str) or not raw_id:+ errors.append("tool_call_id_invalid")+ else:+ call["id"] = raw_id+ elif "id" in raw:+ if not isinstance(raw["id"], str) or not raw["id"]:+ errors.append("tool_call_id_invalid")+ elif call["id"] != raw["id"]:+ errors.append("tool_call_id_changed")+ function = raw.get("function", {})+ if not isinstance(function, dict):+ errors.append("tool_function_invalid")+ continue+ if "name" in function:+ name_fragment = function["name"]+ if not isinstance(name_fragment, str):+ errors.append("stream_name_invalid")+ else:+ call["function"]["name"] += name_fragment+ if "arguments" in function:+ fragment = function["arguments"]+ if not isinstance(fragment, str):+ errors.append("stream_arguments_invalid")+ elif fragment:+ argument_fragment_counts[index] = argument_fragment_counts.get(index, 0) + 1+ call["function"]["arguments"] += fragment+ for index in calls:+ fragment_count = argument_fragment_counts.get(index, 0)+ if fragment_count == 0:+ errors.append("stream_arguments_missing")+ elif fragment_count < 2:+ errors.append("stream_arguments_not_fragmented")+ if not assistant_role_seen:+ errors.append("assistant_role_missing")+ message = {"role": "assistant", "content": "".join(content), "tool_calls": [calls[index] for index in sorted(calls)]}+ if reasoning:+ message["reasoning_content"] = "".join(reasoning)+ document: dict[str, Any] = {+ "id": completion_id,+ "object": "chat.completion",+ "choices": [{"index": 0, "message": message, "finish_reason": finish_reason}],+ }+ if usage is not None:+ document["usage"] = usage+ turn = _parse_chat_document(document, event_count=len(result.events), invalid_event_count=result.invalid_event_count, terminal=result.done_sentinel or finish_reason is not None)+ turn.parse_errors.extend(errors)+ turn.stream_order_ok = result.stream_order_ok+ turn.deadline_expired = result.deadline_expired+ turn.content_type_ok = result.content_type_ok+ return turn+++def _parse_turn(protocol: str, result: TransportResult, *, stream: bool) -> Turn:+ if protocol == "anthropic":+ turn = _parse_anthropic_stream(result) if stream else _parse_anthropic_document(result.document, invalid_event_count=result.invalid_event_count)+ elif protocol == "responses":+ turn = _parse_responses_stream(result) if stream else _parse_responses_document(result.document, invalid_event_count=result.invalid_event_count)+ else:+ turn = _parse_chat_stream(result) if stream else _parse_chat_document(result.document, invalid_event_count=result.invalid_event_count)+ turn.stream_order_ok = result.stream_order_ok+ turn.deadline_expired = result.deadline_expired+ turn.content_type_ok = result.content_type_ok+ return turn+++def _validate_first(turn: Turn, expected_tools: tuple[str, ...], *, stream: bool) -> dict[str, Any]:+ ids = [call.call_id for call in turn.tool_calls]+ names = [call.name for call in turn.tool_calls]+ args_ok = all(call.arguments == {"city": "Shanghai"} for call in turn.tool_calls)+ checks = {+ "parsed": not turn.parse_errors and turn.invalid_event_count == 0,+ "terminal": turn.terminal,+ "stop_reason": isinstance(turn.stop_reason, str) and turn.stop_reason in STOP_REASONS[turn.protocol]["first"],+ "expected_tool_count": len(turn.tool_calls) == len(expected_tools),+ "tool_names": sorted(names) == sorted(expected_tools),+ "tool_ids_unique": bool(ids) and len(ids) == len(set(ids)) and all(ids),+ "tool_arguments": args_ok,+ "user_scope": not _token_present(turn.text, USER_SCOPE_LEAK),+ "no_premature_tool_outputs": not _tool_output_tuples(turn.text)+ and not any(_token_present(turn.text, marker) for marker in TOOL_OUTPUTS.values()),+ "reasoning_present": turn.reasoning_present,+ "reasoning_not_visible": not _protected_reasoning_visible(turn.text, turn.reasoning_parts),+ "stream_complete": (not stream) or (turn.event_count > 0 and turn.terminal),+ "stream_order": (not stream) or turn.stream_order_ok,+ "stream_deadline": (not stream) or not turn.deadline_expired,+ "stream_content_type": (not stream) or turn.content_type_ok,+ }+ return {"checks": checks, "stop_reason": turn.stop_reason, "tool_call_count": len(turn.tool_calls), "tool_names": names, "reasoning_present": turn.reasoning_present, "event_count": turn.event_count}+++def _validate_second(+ turn: Turn,+ expected_tools: tuple[str, ...],+ *,+ stream: bool,+ expected_calls: list[ToolCall] | None = None,+ prior_reasoning_parts: list[str] | None = None,+) -> dict[str, Any]:+ required_markers = [SYSTEM_MARKER, *(TOOL_OUTPUTS[name] for name in expected_tools)]+ call_output_pairs = (+ sorted(_tool_output_tuples(turn.text)) == sorted(_tool_output_tuple(call) for call in expected_calls)+ if expected_calls is not None+ else all(_token_present(turn.text, marker) for marker in required_markers[1:])+ )+ checks = {+ "parsed": not turn.parse_errors and turn.invalid_event_count == 0,+ "terminal": turn.terminal,+ "stop_reason": isinstance(turn.stop_reason, str) and turn.stop_reason in STOP_REASONS[turn.protocol]["final"],+ "no_followup_tool_calls": not turn.tool_calls,+ "reasoning_present": turn.reasoning_present,+ "reasoning_not_visible": not _protected_reasoning_visible(+ turn.text,+ [*(prior_reasoning_parts or []), *turn.reasoning_parts],+ ),+ "system_marker": _token_present(turn.text, SYSTEM_MARKER),+ "system_scope": _token_present(turn.text, SYSTEM_SCOPE_OK) and not _token_present(turn.text, USER_SCOPE_LEAK),+ "tool_outputs": all(_token_present(turn.text, marker) for marker in required_markers[1:]),+ "tool_output_call_pairs": call_output_pairs,+ "stream_complete": (not stream) or (turn.event_count > 0 and turn.terminal),+ "stream_order": (not stream) or turn.stream_order_ok,+ "stream_deadline": (not stream) or not turn.deadline_expired,+ "stream_content_type": (not stream) or turn.content_type_ok,+ "stream_text_deltas": (not stream) or turn.protocol not in {"responses", "anthropic"} or turn.stream_text_delta_count > 0,+ }+ return {"checks": checks, "stop_reason": turn.stop_reason, "tool_call_count": len(turn.tool_calls), "text_length": len(turn.text), "reasoning_present": turn.reasoning_present, "event_count": turn.event_count}+++def _build_payload(spec: CaseSpec, model: str, *, followup: Turn | None = None) -> dict[str, Any]:+ if spec.client_protocol == "anthropic":+ return _anthropic_payload(model=model, stream=spec.stream, parallel=spec.parallel, followup=followup)+ if spec.client_protocol == "responses":+ return _responses_payload(model=model, stream=spec.stream, parallel=spec.parallel, followup=followup)+ return _chat_payload(model=model, stream=spec.stream, parallel=spec.parallel, followup=followup)+++def _request_with_retries(spec: CaseSpec, payload: dict[str, Any], model: str) -> tuple[TransportResult, str, bool]:+ """Retry only transient relay capacity failures; never retry other 4xx responses."""+ candidates = [model]+ if spec.target_protocol == "anthropic" and ANTHROPIC_FALLBACK_MODEL and ANTHROPIC_FALLBACK_MODEL != model:+ candidates.append(ANTHROPIC_FALLBACK_MODEL)+ for candidate_index, candidate in enumerate(candidates):+ payload["model"] = candidate+ for retry in range(MAX_503_RETRIES if candidate_index == 0 else 1):+ result = _request(spec.path, payload, client_protocol=spec.client_protocol, stream=spec.stream)+ if result.status != 503:+ return result, candidate, False+ if retry + 1 < (MAX_503_RETRIES if candidate_index == 0 else 1):+ time.sleep(0.5 * (retry + 1))+ return result, candidate, result.status == 503+++def _run_case(spec: CaseSpec) -> dict[str, Any]:+ model = MODELS[spec.target_protocol]+ first_result, model_used, blocked = _request_with_retries(spec, _build_payload(spec, model), model)+ fallback_used = model_used != model+ if blocked:+ return {+ "case": spec.name,+ "status": first_result.status,+ "fallback_used": fallback_used,+ "evidence_model_scope": "fallback" if fallback_used else "primary",+ "blocked": "relay Claude pool unavailable" if spec.target_protocol == "anthropic" else "relay upstream capacity unavailable",+ "checks": {},+ }+ first_turn = _parse_turn(spec.client_protocol, first_result, stream=spec.stream)+ first = _validate_first(first_turn, spec.expected_tools, stream=spec.stream)+ first["checks"]["http_success"] = 200 <= first_result.status < 300+ second: dict[str, Any] = {"skipped": True, "checks": {"not_run": False}}+ call_ids = [call.call_id for call in first_turn.tool_calls]+ followup_identity_valid = bool(call_ids) and all(call_ids) and len(set(call_ids)) == len(call_ids)+ if first_turn.tool_calls and not followup_identity_valid:+ second["skip_reason"] = "invalid first-turn tool-call identity"+ if followup_identity_valid:+ second_result, second_model_used, second_blocked = _request_with_retries(spec, _build_payload(spec, model_used, followup=first_turn), model_used)+ if second_model_used != model_used:+ return {+ "case": spec.name,+ "status": first_result.status,+ "second_status": second_result.status,+ "fallback_used": fallback_used,+ "evidence_model_scope": "mixed",+ "blocked": "model changed between turns",+ "first": first,+ "checks": first["checks"],+ }+ fallback_used = fallback_used or second_model_used != model+ if second_blocked:+ return {+ "case": spec.name,+ "status": first_result.status,+ "second_status": second_result.status,+ "fallback_used": fallback_used,+ "evidence_model_scope": "fallback" if fallback_used else "primary",+ "blocked": "relay Claude pool unavailable" if spec.target_protocol == "anthropic" else "relay upstream capacity unavailable",+ "first": first,+ "checks": first["checks"],+ }+ second_turn = _parse_turn(spec.client_protocol, second_result, stream=spec.stream)+ second = _validate_second(+ second_turn,+ spec.expected_tools,+ stream=spec.stream,+ expected_calls=first_turn.tool_calls,+ prior_reasoning_parts=first_turn.reasoning_parts,+ )+ second["checks"]["http_success"] = 200 <= second_result.status < 300+ second["status"] = second_result.status+ checks = dict(first["checks"])+ checks.update({f"second_{key}": value for key, value in second.get("checks", {}).items() if key != "not_run"})+ return {+ "case": spec.name,+ "status": first_result.status,+ "second_status": second.get("status"),+ "fallback_used": fallback_used,+ "evidence_model_scope": "fallback" if fallback_used else "primary",+ "first": first,+ "second": second,+ "checks": checks,+ }+++def _build_cases() -> list[CaseSpec]:+ return [+ CaseSpec("messages_to_responses_single", "anthropic", "responses", "/v1/messages", False, False),+ CaseSpec("messages_to_responses_parallel_stream", "anthropic", "responses", "/v1/messages", True, True),+ CaseSpec("responses_to_messages_single", "responses", "anthropic", "/v1/responses", False, False),+ CaseSpec("responses_to_messages_parallel_stream", "responses", "anthropic", "/v1/responses", True, True),+ CaseSpec("messages_to_chat_single", "anthropic", "chat", "/v1/messages", False, False),+ CaseSpec("messages_to_chat_parallel_stream", "anthropic", "chat", "/v1/messages", True, True),+ CaseSpec("chat_to_messages_single", "chat", "anthropic", "/v1/chat/completions", False, False),+ CaseSpec("chat_to_messages_parallel_stream", "chat", "anthropic", "/v1/chat/completions", True, True),+ ]+++def _valid_qualified_model(value: str) -> bool:+ return bool(value) and value.count("/") == 1 and not any(char.isspace() for char in value) and ".." not in value and not value.startswith("/") and not value.endswith("/")+++def _preflight() -> list[str]:+ missing = [name for name in REQUIRED_VENDOR_KEYS if not os.environ.get(name)]+ missing.extend(f"model:{protocol}" for protocol, value in MODELS.items() if not _valid_qualified_model(value))+ if ANTHROPIC_FALLBACK_MODEL and not _valid_qualified_model(ANTHROPIC_FALLBACK_MODEL):+ missing.append("model:anthropic_fallback")+ try:+ parsed = urllib.parse.urlsplit(BASE_URL)+ except ValueError:+ parsed = None+ loopback = (+ parsed is not None+ and parsed.scheme == "http"+ and parsed.hostname == "127.0.0.1"+ and parsed.username is None+ and parsed.password is None+ and not parsed.query+ and not parsed.fragment+ and parsed.path in {"", "/"}+ )+ if not GATEWAY_TOKEN:+ missing.append("CPA_GATEWAY_TOKEN")+ if not loopback:+ missing.append("CPA_BASE_URL must be exact http://127.0.0.1[:port]")+ return missing+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--list", action="store_true", help="list case names without making requests")+ args = parser.parse_args()+ if args.list:+ print("\n".join(case.name for case in _build_cases()))+ return 0+ missing = _preflight()+ if missing:+ print(json.dumps({"ok": False, "blocked": True, "missing": missing}, sort_keys=True))+ return 2+ results = [_run_case(case) for case in _build_cases()]+ blocked = any(result.get("blocked") for result in results)+ ok = not blocked and all(all(result["checks"].values()) for result in results)+ print(json.dumps({"ok": ok, "blocked": blocked, "not_verified": [CONTEXT_LENGTH_NOT_VERIFIED], "results": results}, sort_keys=True))+ return 2 if blocked else (0 if ok else 1)+++if __name__ == "__main__":+ sys.exit(main())diff --git a/docs/plans/fixtures/cpa-agentic-fidelity/run_relay.py b/docs/plans/fixtures/cpa-agentic-fidelity/run_relay.pynew file mode 100644index 000000000..27dcbfe9e--- /dev/null+++ b/docs/plans/fixtures/cpa-agentic-fidelity/run_relay.py@@ -0,0 +1,176 @@+#!/usr/bin/env python3+"""Run the fidelity probe through an isolated pinned CPA and a compatible relay."""++from __future__ import annotations++import json+import os+import subprocess+import sys+import tempfile+import urllib.parse+from pathlib import Path+++REPO_ROOT = Path(__file__).resolve().parents[4]+sys.path.insert(0, str(REPO_ROOT))++from core.handlers.model_hub.adapter import SourceBinding # noqa: E402+from vibe.model_hub_runtime.installer import EngineRuntimeManager # noqa: E402+from vibe.model_hub_runtime.state import EngineStateStore # noqa: E402+from vibe.model_hub_runtime.supervisor import EngineSupervisor # noqa: E402+++OPENAI_MODEL = "gpt-5.4-mini"+ANTHROPIC_MODEL = "claude-haiku-4-5"+ANTHROPIC_FALLBACK_MODEL = "claude-3-5-haiku-latest"+CHAT_SOURCE_PROTOCOL = "openai_chat"+PINNED_ENGINE_VERSION = "v7.2.95"+PINNED_ENGINE_MANIFEST = REPO_ROOT / "vibe/model_hub_runtime/cliproxyapi_manifest.json"+++def _safe_relay_root(value: str) -> str | None:+ parsed = urllib.parse.urlsplit(value)+ if not (+ parsed.scheme in {"http", "https"}+ and parsed.hostname+ and parsed.username is None+ and parsed.password is None+ and not parsed.query+ and not parsed.fragment+ and parsed.path in {"", "/"}+ ):+ return None+ return value.rstrip("/")+++def _binding(+ *,+ source_id: str,+ vendor: str,+ protocol: str,+ base_url: str,+ credential_ref: str,+ models: tuple[str, ...],+) -> SourceBinding:+ return SourceBinding(+ source_id=source_id,+ vendor=vendor,+ protocol=protocol,+ base_url=base_url,+ credential_ref=credential_ref,+ allowed_origins=(),+ model_ids=models,+ )+++def main() -> int:+ anthropic_key = os.environ.get("ANTHROPIC_API_KEY", "")+ openai_key = os.environ.get("OPENAI_API_KEY", "")+ relay_root = _safe_relay_root(os.environ.get("ANTHROPIC_BASE_URL", ""))+ if not anthropic_key or not openai_key or relay_root is None:+ print(json.dumps({"ok": False, "blocked": True, "missing": "owner relay environment"}, sort_keys=True))+ return 2+ openai_base = f"{relay_root}/v1"++ with tempfile.TemporaryDirectory(prefix="cpa-agentic-fidelity-") as temporary_name:+ temporary = Path(temporary_name)+ store = EngineStateStore(temporary / "state")+ anthropic_ref = store.store_api_key(+ anthropic_key,+ vendor="anthropic",+ protocol="anthropic",+ base_url=relay_root,+ )+ responses_ref = store.store_api_key(+ openai_key,+ vendor="openai",+ protocol="openai_responses",+ base_url=openai_base,+ )+ chat_ref = store.store_api_key(+ openai_key,+ vendor="custom",+ protocol=CHAT_SOURCE_PROTOCOL,+ base_url=openai_base,+ )+ sources = store.sync_sources(+ [+ _binding(+ source_id="src_fidelityanthropic",+ vendor="anthropic",+ protocol="anthropic",+ base_url=relay_root,+ credential_ref=anthropic_ref,+ models=(ANTHROPIC_MODEL, ANTHROPIC_FALLBACK_MODEL),+ ),+ _binding(+ source_id="src_fidelityresponses",+ vendor="openai",+ protocol="openai_responses",+ base_url=openai_base,+ credential_ref=responses_ref,+ models=(OPENAI_MODEL,),+ ),+ _binding(+ source_id="src_fidelitychat",+ vendor="custom",+ protocol=CHAT_SOURCE_PROTOCOL,+ base_url=openai_base,+ credential_ref=chat_ref,+ models=(OPENAI_MODEL,),+ ),+ ]+ )+ by_id = {source.source_id: source for source in sources}+ installer = EngineRuntimeManager(+ runtime_dir=temporary / "runtime",+ manifest_path=PINNED_ENGINE_MANIFEST,+ manifest_url="",+ offline=False,+ )+ supervisor = EngineSupervisor(installer=installer, state_store=store)+ try:+ if installer.contract_manifest().get("version") != PINNED_ENGINE_VERSION:+ print(json.dumps({"ok": False, "blocked": True, "reason": "pinned CPA manifest mismatch"}, sort_keys=True))+ return 2+ connection = supervisor.ensure_running()+ runtime_status = installer.status()+ if not runtime_status.get("installed") or runtime_status.get("version") != PINNED_ENGINE_VERSION:+ print(json.dumps({"ok": False, "blocked": True, "reason": "pinned CPA runtime mismatch"}, sort_keys=True))+ return 2+ child_env = os.environ.copy()+ child_env.update(+ {+ "CPA_BASE_URL": connection.base_url,+ "CPA_GATEWAY_TOKEN": connection.gateway_token,+ "CPA_ANTHROPIC_QUALIFIED_MODEL": (+ f"{by_id['src_fidelityanthropic'].prefix}/{ANTHROPIC_MODEL}"+ ),+ "CPA_ANTHROPIC_FALLBACK_QUALIFIED_MODEL": (+ f"{by_id['src_fidelityanthropic'].prefix}/{ANTHROPIC_FALLBACK_MODEL}"+ ),+ "CPA_OPENAI_RESPONSES_QUALIFIED_MODEL": (+ f"{by_id['src_fidelityresponses'].prefix}/{OPENAI_MODEL}"+ ),+ "CPA_OPENAI_CHAT_QUALIFIED_MODEL": (+ f"{by_id['src_fidelitychat'].prefix}/{OPENAI_MODEL}"+ ),+ }+ )+ completed = subprocess.run(+ [sys.executable, str(Path(__file__).with_name("probe.py"))],+ cwd=REPO_ROOT,+ env=child_env,+ check=False,+ )+ return completed.returncode+ except Exception: # noqa: BLE001+ print(json.dumps({"ok": False, "blocked": True, "reason": "isolated CPA startup failed"}, sort_keys=True))+ return 2+ finally:+ supervisor.stop()+++if __name__ == "__main__":+ sys.exit(main())diff --git a/docs/plans/fixtures/cpa-agentic-fidelity/test_probe.py b/docs/plans/fixtures/cpa-agentic-fidelity/test_probe.pynew file mode 100644index 000000000..386c2d38c--- /dev/null+++ b/docs/plans/fixtures/cpa-agentic-fidelity/test_probe.py@@ -0,0 +1,3667 @@+import copy+import json+import tempfile+import unittest+from pathlib import Path++import probe+import run_relay+from vibe.model_hub_runtime.state import EngineStateStore+++def _anthropic_usage():+ return {"input_tokens": 1, "output_tokens": 0}+++def _responses_wire(*events):+ normalized = []+ for index, event in enumerate(events):+ event = copy.deepcopy(event)+ event.setdefault("sequence_number", index)+ if event["type"] in {"response.created", "response.in_progress", "response.completed", "response.done"} and isinstance(event.get("response"), dict):+ event["response"].setdefault("id", "resp_1")+ event["response"].setdefault("object", "response")+ if event["type"] == "response.created":+ event["response"].setdefault("status", "in_progress")+ event["response"].setdefault("output", [])+ normalized.append(event)+ return [+ {"kind": "event", "sequence": index, "wire_sequence": index, "type": event["type"], "event": event}+ for index, event in enumerate(normalized)+ ]+++def _response_message_stream():+ message = {"id": "msg_1", "type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "answer"}]}+ return _responses_wire(+ {"type": "response.created", "response": {}},+ {"type": "response.output_item.added", "output_index": 0, "item": {"id": "msg_1", "type": "message", "role": "assistant"}},+ {+ "type": "response.content_part.added",+ "item_id": "msg_1",+ "output_index": 0,+ "content_index": 0,+ "part": {"type": "output_text", "text": ""},+ },+ {"type": "response.output_text.delta", "item_id": "msg_1", "output_index": 0, "content_index": 0, "delta": "answer"},+ {"type": "response.output_text.done", "item_id": "msg_1", "output_index": 0, "content_index": 0, "text": "answer"},+ {+ "type": "response.content_part.done",+ "item_id": "msg_1",+ "output_index": 0,+ "content_index": 0,+ "part": {"type": "output_text", "text": "answer"},+ },+ {"type": "response.output_item.done", "output_index": 0, "item": message},+ {"type": "response.completed", "response": {"status": "completed", "output": [message]}},+ )+++def _response_multi_content_stream():+ message = {+ "id": "msg_1",+ "type": "message",+ "role": "assistant",+ "content": [+ {"type": "output_text", "text": "first"},+ {"type": "output_text", "text": "second"},+ ],+ }+ return _responses_wire(+ {"type": "response.created", "response": {}},+ {"type": "response.output_item.added", "output_index": 0, "item": {"id": "msg_1", "type": "message", "role": "assistant"}},+ {+ "type": "response.content_part.added",+ "item_id": "msg_1",+ "output_index": 0,+ "content_index": 0,+ "part": {"type": "output_text", "text": ""},+ },+ {"type": "response.output_text.delta", "item_id": "msg_1", "output_index": 0, "content_index": 0, "delta": "first"},+ {"type": "response.output_text.done", "item_id": "msg_1", "output_index": 0, "content_index": 0, "text": "first"},+ {+ "type": "response.content_part.done",+ "item_id": "msg_1",+ "output_index": 0,+ "content_index": 0,+ "part": {"type": "output_text", "text": "first"},+ },+ {+ "type": "response.content_part.added",+ "item_id": "msg_1",+ "output_index": 0,+ "content_index": 1,+ "part": {"type": "output_text", "text": ""},+ },+ {"type": "response.output_text.delta", "item_id": "msg_1", "output_index": 0, "content_index": 1, "delta": "second"},+ {"type": "response.output_text.done", "item_id": "msg_1", "output_index": 0, "content_index": 1, "text": "second"},+ {+ "type": "response.content_part.done",+ "item_id": "msg_1",+ "output_index": 0,+ "content_index": 1,+ "part": {"type": "output_text", "text": "second"},+ },+ {"type": "response.output_item.done", "output_index": 0, "item": message},+ {"type": "response.completed", "response": {"status": "completed", "output": [message]}},+ )+++def _response_reasoning_stream():+ reasoning = {"id": "rs_1", "type": "reasoning", "summary": [{"type": "summary_text", "text": "thought"}]}+ return _responses_wire(+ {"type": "response.created", "response": {}},+ {"type": "response.output_item.added", "output_index": 0, "item": {"id": "rs_1", "type": "reasoning"}},+ {"type": "response.reasoning_summary_text.delta", "item_id": "rs_1", "output_index": 0, "summary_index": 0, "delta": "thought"},+ {"type": "response.reasoning_summary_text.done", "item_id": "rs_1", "output_index": 0, "summary_index": 0, "text": "thought"},+ {"type": "response.output_item.done", "output_index": 0, "item": reasoning},+ {"type": "response.completed", "response": {"status": "completed", "output": [reasoning]}},+ )+++def _response_multi_summary_stream():+ reasoning = {+ "id": "rs_1",+ "type": "reasoning",+ "summary": [+ {"type": "summary_text", "text": "first"},+ {"type": "summary_text", "text": "second"},+ ],+ }+ return _responses_wire(+ {"type": "response.created", "response": {}},+ {"type": "response.output_item.added", "output_index": 0, "item": {"id": "rs_1", "type": "reasoning"}},+ {"type": "response.reasoning_summary_text.delta", "output_index": 0, "item_id": "rs_1", "summary_index": 0, "delta": "first"},+ {"type": "response.reasoning_summary_text.done", "output_index": 0, "item_id": "rs_1", "summary_index": 0, "text": "first"},+ {"type": "response.reasoning_summary_text.delta", "output_index": 0, "item_id": "rs_1", "summary_index": 1, "delta": "second"},+ {"type": "response.reasoning_summary_text.done", "output_index": 0, "item_id": "rs_1", "summary_index": 1, "text": "second"},+ {"type": "response.output_item.done", "output_index": 0, "item": reasoning},+ {"type": "response.completed", "response": {"status": "completed", "output": [reasoning]}},+ )+++def _response_function_stream():+ function_call = {+ "id": "fc_1",+ "type": "function_call",+ "call_id": "call_1",+ "name": "lookup_weather",+ "arguments": '{"city":"Shanghai"}',+ }+ return _responses_wire(+ {"type": "response.created", "response": {}},+ {+ "type": "response.output_item.added",+ "output_index": 0,+ "item": {+ "id": "fc_1",+ "type": "function_call",+ "call_id": "call_1",+ "name": "lookup_weather",+ "arguments": "",+ },+ },+ {+ "type": "response.function_call_arguments.delta",+ "item_id": "fc_1",+ "output_index": 0,+ "delta": '{"city":',+ },+ {+ "type": "response.function_call_arguments.delta",+ "item_id": "fc_1",+ "output_index": 0,+ "delta": '"Shanghai"}',+ },+ {+ "type": "response.function_call_arguments.done",+ "item_id": "fc_1",+ "output_index": 0,+ "arguments": '{"city":"Shanghai"}',+ },+ {"type": "response.output_item.done", "output_index": 0, "item": function_call},+ {"type": "response.completed", "response": {"status": "completed", "output": [function_call]}},+ )+++def _required_envelope_samples():+ response_start = {+ "id": "resp_1",+ "object": "response",+ "status": "in_progress",+ "output": [],+ }+ response_terminal = {+ "id": "resp_1",+ "object": "response",+ "status": "completed",+ "output": [],+ }+ return {+ "anthropic.message": {+ "type": "message",+ "role": "assistant",+ "content": [],+ },+ "anthropic.stream.message_start": {+ "type": "message_start",+ "message": {+ "type": "message",+ "role": "assistant",+ "content": [],+ "usage": _anthropic_usage(),+ "stop_reason": None,+ "stop_sequence": None,+ },+ },+ "anthropic.stream.content_block_start": {+ "type": "content_block_start",+ "index": 0,+ "content_block": {},+ },+ "anthropic.stream.content_block_delta": {+ "type": "content_block_delta",+ "index": 0,+ "delta": {},+ },+ "anthropic.stream.content_block_stop": {+ "type": "content_block_stop",+ "index": 0,+ },+ "anthropic.stream.message_delta": {+ "type": "message_delta",+ "delta": {"stop_reason": "end_turn", "stop_sequence": None},+ "usage": {"output_tokens": 1},+ },+ "anthropic.stream.message_stop": {"type": "message_stop"},+ "anthropic.stream.ping": {"type": "ping"},+ "chat.completion": {+ "id": "chatcmpl_1",+ "object": "chat.completion",+ "choices": [+ {+ "index": 0,+ "message": {"role": "assistant", "content": None},+ }+ ],+ },+ "chat.stream.choice": {+ "id": "chatcmpl_1",+ "object": "chat.completion.chunk",+ "choices": [{"index": 0, "delta": {}}],+ },+ "chat.stream.usage": {+ "id": "chatcmpl_1",+ "object": "chat.completion.chunk",+ "choices": [],+ "usage": {},+ },+ "responses.response": {+ "id": "resp_1",+ "object": "response",+ "output": [],+ },+ "responses.stream.created": {+ "type": "response.created",+ "sequence_number": 0,+ "response": copy.deepcopy(response_start),+ },+ "responses.stream.in_progress": {+ "type": "response.in_progress",+ "sequence_number": 1,+ "response": copy.deepcopy(response_start),+ },+ "responses.stream.terminal": {+ "type": "response.completed",+ "sequence_number": 2,+ "response": response_terminal,+ },+ "responses.stream.output_item_added": {+ "type": "response.output_item.added",+ "sequence_number": 1,+ "output_index": 0,+ "item": {},+ },+ "responses.stream.output_item_done": {+ "type": "response.output_item.done",+ "sequence_number": 2,+ "output_index": 0,+ "item": {},+ },+ "responses.stream.content_part_added": {+ "type": "response.content_part.added",+ "sequence_number": 2,+ "item_id": "msg_1",+ "output_index": 0,+ "content_index": 0,+ "part": {},+ },+ "responses.stream.content_part_done": {+ "type": "response.content_part.done",+ "sequence_number": 4,+ "item_id": "msg_1",+ "output_index": 0,+ "content_index": 0,+ "part": {},+ },+ "responses.stream.function_arguments_delta": {+ "type": "response.function_call_arguments.delta",+ "sequence_number": 2,+ "item_id": "fc_1",+ "output_index": 0,+ "delta": "{}",+ },+ "responses.stream.function_arguments_done": {+ "type": "response.function_call_arguments.done",+ "sequence_number": 3,+ "item_id": "fc_1",+ "output_index": 0,+ "arguments": "{}",+ },+ "responses.stream.output_text_delta": {+ "type": "response.output_text.delta",+ "sequence_number": 2,+ "item_id": "msg_1",+ "output_index": 0,+ "content_index": 0,+ "delta": "a",+ },+ "responses.stream.output_text_done": {+ "type": "response.output_text.done",+ "sequence_number": 3,+ "item_id": "msg_1",+ "output_index": 0,+ "content_index": 0,+ "text": "a",+ },+ "responses.stream.reasoning_summary_delta": {+ "type": "response.reasoning_summary_text.delta",+ "sequence_number": 2,+ "item_id": "rs_1",+ "output_index": 0,+ "summary_index": 0,+ "delta": "a",+ },+ "responses.stream.reasoning_summary_done": {+ "type": "response.reasoning_summary_text.done",+ "sequence_number": 3,+ "item_id": "rs_1",+ "output_index": 0,+ "summary_index": 0,+ "text": "a",+ },+ }+++def _drop_required_path(payload, path):+ parent = payload+ for part in path[:-1]:+ parent = parent[part]+ del parent[path[-1]]+++class ProbeParserTests(unittest.TestCase):+ def test_required_envelope_matrix_rejects_every_missing_field(self) -> None:+ samples = _required_envelope_samples()+ self.assertEqual(set(samples), set(probe.REQUIRED_ENVELOPE_FIELDS))+ for kind, fields in probe.REQUIRED_ENVELOPE_FIELDS.items():+ sample = samples[kind]+ self.assertEqual([], probe._required_envelope_errors(kind, sample), kind)+ for field in fields:+ with self.subTest(kind=kind, path=field.path):+ mutated = copy.deepcopy(sample)+ _drop_required_path(mutated, field.path)+ self.assertIn(+ field.error,+ probe._required_envelope_errors(kind, mutated),+ )++ def test_anthropic_followup_preserves_observed_id_and_thinking(self) -> None:+ turn = probe._parse_anthropic_document(+ {+ "content": [+ {"type": "thinking", "thinking": "internal", "signature": "sig"},+ {"type": "tool_use", "id": "toolu_actual", "name": "lookup_weather", "input": {"city": "Shanghai"}},+ ],+ "stop_reason": "tool_use",+ }+ )+ payload = probe._anthropic_payload(model="src/model", stream=False, parallel=False, followup=turn)+ self.assertEqual(payload["messages"][1]["content"][0]["type"], "thinking")+ self.assertEqual(payload["messages"][1]["content"][0]["thinking"], "internal")+ self.assertEqual(payload["messages"][2]["content"][0]["tool_use_id"], "toolu_actual")+ projection = probe._validate_first(turn, ("lookup_weather",), stream=False)+ self.assertNotIn("toolu_actual", json.dumps(projection))++ def test_responses_stream_reassembles_function_arguments(self) -> None:+ result = probe.TransportResult(+ 200,+ None,+ [+ {"kind": "event", "type": "response.output_item.added", "event": {"type": "response.output_item.added", "item": {"id": "fc_1", "type": "function_call", "call_id": "call_1", "name": "lookup_weather"}}},+ {"kind": "event", "type": "response.function_call_arguments.delta", "event": {"type": "response.function_call_arguments.delta", "item_id": "fc_1", "delta": '{"city":'}},+ {"kind": "event", "type": "response.function_call_arguments.delta", "event": {"type": "response.function_call_arguments.delta", "item_id": "fc_1", "delta": '"Shanghai"}'}},+ {"kind": "event", "type": "response.function_call_arguments.done", "event": {"type": "response.function_call_arguments.done", "item_id": "fc_1", "arguments": '{"city":"Shanghai"}'}},+ {"kind": "event", "type": "response.output_item.done", "event": {"type": "response.output_item.done", "item": {"id": "fc_1", "type": "function_call", "call_id": "call_1", "name": "lookup_weather", "arguments": '{"city":"Shanghai"}'}}},+ {"kind": "event", "type": "response.completed", "event": {"type": "response.completed", "response": {"status": "completed", "output": [{"id": "fc_1", "type": "function_call", "call_id": "call_1", "name": "lookup_weather", "arguments": '{"city":"Shanghai"}'}]}}},+ ],+ True,+ 0,+ )+ turn = probe._parse_responses_stream(result)+ self.assertEqual(turn.tool_calls[0].arguments, {"city": "Shanghai"})+ self.assertTrue(turn.terminal)++ def test_responses_stream_reassembles_multiple_reasoning_summaries(self) -> None:+ events = _response_multi_summary_stream()+ self.assertTrue(probe._stream_order_ok("responses", events))+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, events, False, 0))+ self.assertNotIn("stream_text_done_mismatch", turn.parse_errors)+ self.assertEqual(turn.reasoning_text, "firstsecond")++ def test_responses_stream_requires_explicit_reasoning_summary_indexes(self) -> None:+ events = _response_reasoning_stream()+ events[2]["event"].pop("summary_index")+ events[3]["event"].pop("summary_index")+ self.assertFalse(probe._stream_order_ok("responses", events))+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, events, False, 0))+ self.assertIn("summary_index_invalid", turn.parse_errors)++ def test_responses_stream_requires_reasoning_summary_lifecycle(self) -> None:+ opening = _response_reasoning_stream()+ opening[1]["event"]["item"]["summary"] = [{"type": "summary_text", "text": "eager"}]+ self.assertFalse(probe._stream_order_ok("responses", opening))+ opening_turn = probe._parse_responses_stream(probe.TransportResult(200, None, opening, False, 0))+ self.assertIn("stream_reasoning_opening_snapshot_invalid", opening_turn.parse_errors)++ missing = [+ event+ for event in _response_reasoning_stream()+ if event["type"] not in {"response.reasoning_summary_text.delta", "response.reasoning_summary_text.done"}+ ]+ self.assertFalse(probe._stream_order_ok("responses", missing))+ missing_turn = probe._parse_responses_stream(probe.TransportResult(200, None, missing, False, 0))+ self.assertIn("stream_reasoning_summary_events_missing", missing_turn.parse_errors)++ def test_responses_stream_rejects_orphaned_reasoning_summary_done(self) -> None:+ events = _response_reasoning_stream()+ events.insert(+ 4,+ {+ "kind": "event",+ "type": "response.reasoning_summary_text.done",+ "event": {+ "type": "response.reasoning_summary_text.done",+ "item_id": "rs_1",+ "output_index": 0,+ "summary_index": 1,+ "text": "",+ },+ },+ )+ for sequence, event in enumerate(events):+ event["sequence"] = sequence+ event["wire_sequence"] = sequence+ self.assertFalse(probe._stream_order_ok("responses", events))+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, events, False, 0))+ self.assertIn("stream_reasoning_summary_done_without_delta", turn.parse_errors)++ def test_responses_reasoning_opening_content_must_be_empty(self) -> None:+ valid = _response_reasoning_stream()+ self.assertTrue(probe._stream_order_ok("responses", valid))+ for opening_content in ([{"type": "summary_text", "text": "prefilled"}], {"unexpected": True}):+ invalid = copy.deepcopy(valid)+ invalid[1]["event"]["item"]["content"] = opening_content+ self.assertFalse(probe._stream_order_ok("responses", invalid))+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, invalid, False, 0))+ self.assertIn("stream_reasoning_opening_snapshot_invalid", turn.parse_errors)++ empty = copy.deepcopy(valid)+ empty[1]["event"]["item"]["content"] = []+ self.assertTrue(probe._stream_order_ok("responses", empty))++ def test_responses_reasoning_summary_snapshots_match_each_delta_index(self) -> None:+ invalid = _response_multi_summary_stream()+ invalid[6]["event"]["item"]["summary"] = [+ {"type": "summary_text", "text": "firsts"},+ {"type": "summary_text", "text": "econd"},+ ]+ self.assertFalse(probe._stream_order_ok("responses", invalid))+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, invalid, False, 0))+ self.assertIn("stream_reasoning_summary_snapshot_mismatch", turn.parse_errors)++ def test_responses_stream_rejects_noncontiguous_reasoning_summary_index(self) -> None:+ events = _response_multi_summary_stream()+ events[4]["event"]["summary_index"] = 2+ events[5]["event"]["summary_index"] = 2+ self.assertFalse(probe._stream_order_ok("responses", events))+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, events, False, 0))+ self.assertIn("summary_index_invalid", turn.parse_errors)++ def test_responses_stream_rejects_done_argument_snapshot_mismatch(self) -> None:+ result = probe.TransportResult(+ 200,+ None,+ [+ {"kind": "event", "event": {"type": "response.output_item.added", "item": {"id": "fc_1", "type": "function_call", "call_id": "call_1", "name": "lookup_weather"}}},+ {"kind": "event", "event": {"type": "response.function_call_arguments.delta", "item_id": "fc_1", "delta": '{"city":"Shanghai"}'}},+ {"kind": "event", "event": {"type": "response.output_item.done", "item": {"id": "fc_1", "type": "function_call", "call_id": "call_1", "name": "lookup_weather", "arguments": '{"city":"Paris"}'}}},+ {"kind": "event", "event": {"type": "response.completed", "response": {"status": "completed", "output": []}}},+ ],+ False,+ 0,+ )+ turn = probe._parse_responses_stream(result)+ self.assertIn("stream_item_snapshot_mismatch", turn.parse_errors)++ def test_responses_stream_rejects_argument_done_mismatch(self) -> None:+ events = _response_function_stream()+ done = next(+ event+ for event in events+ if event["type"] == "response.function_call_arguments.done"+ )+ done["event"]["arguments"] = '{"city":"Paris"}'+ self.assertTrue(probe._stream_order_ok("responses", events))+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, events, False, 0, True))+ self.assertIn("stream_arguments_done_mismatch", turn.parse_errors)++ def test_responses_stream_does_not_trust_terminal_snapshot_arguments(self) -> None:+ result = probe.TransportResult(+ 200,+ None,+ [+ {"kind": "event", "event": {"type": "response.output_item.added", "item": {"id": "fc_1", "type": "function_call", "call_id": "call_1", "name": "lookup_weather"}}},+ {"kind": "event", "event": {"type": "response.function_call_arguments.delta", "item_id": "fc_1", "delta": "not-json"}},+ {"kind": "event", "event": {"type": "response.output_item.done", "item": {"id": "fc_1", "type": "function_call", "call_id": "call_1", "name": "lookup_weather", "arguments": '{"city":"Shanghai"}'}}},+ {"kind": "event", "event": {"type": "response.completed", "response": {"status": "completed", "output": [{"id": "fc_1", "type": "function_call", "call_id": "call_1", "name": "lookup_weather", "arguments": '{"city":"Shanghai"}' }]}}},+ ],+ False,+ 0,+ )+ turn = probe._parse_responses_stream(result)+ self.assertIn("arguments_invalid_json", turn.parse_errors)+ self.assertNotEqual(turn.tool_calls[0].arguments, {"city": "Shanghai"})++ def test_responses_stream_rejects_identity_snapshot_mismatch(self) -> None:+ result = probe.TransportResult(+ 200,+ None,+ [+ {"kind": "event", "event": {"type": "response.output_item.added", "item": {"id": "fc_1", "type": "function_call", "call_id": "call_1", "name": "lookup_weather"}}},+ {"kind": "event", "event": {"type": "response.output_item.done", "item": {"id": "fc_1", "type": "function_call", "call_id": "call_2", "name": "lookup_weather", "arguments": '{"city":"Shanghai"}'}}},+ {"kind": "event", "event": {"type": "response.completed", "response": {"status": "completed"}}},+ ],+ False,+ 0,+ )+ turn = probe._parse_responses_stream(result)+ self.assertIn("stream_item_snapshot_mismatch", turn.parse_errors)++ def test_responses_stream_requires_argument_fragments(self) -> None:+ result = probe.TransportResult(+ 200,+ None,+ [+ {"kind": "event", "event": {"type": "response.output_item.added", "item": {"id": "fc_1", "type": "function_call", "call_id": "call_1", "name": "lookup_weather"}}},+ {"kind": "event", "event": {"type": "response.output_item.done", "item": {"id": "fc_1", "type": "function_call", "call_id": "call_1", "name": "lookup_weather", "arguments": '{"city":"Shanghai"}'}}},+ {"kind": "event", "event": {"type": "response.completed", "response": {"status": "completed"}}},+ ],+ False,+ 0,+ )+ turn = probe._parse_responses_stream(result)+ self.assertIn("stream_arguments_missing", turn.parse_errors)++ def test_responses_stream_requires_split_argument_fragments(self) -> None:+ events = _response_function_stream()+ single_delta = [+ event+ for event in events+ if event["type"] != "response.function_call_arguments.delta"+ ]+ single_delta.insert(+ 2,+ {+ "kind": "event",+ "sequence": 2,+ "wire_sequence": 2,+ "type": "response.function_call_arguments.delta",+ "event": {+ "type": "response.function_call_arguments.delta",+ "item_id": "fc_1",+ "output_index": 0,+ "delta": '{"city":"Shanghai"}',+ },+ },+ )+ self.assertFalse(probe._stream_order_ok("responses", single_delta))+ turn = probe._parse_responses_stream(+ probe.TransportResult(200, None, single_delta, False, 0, False)+ )+ self.assertIn("stream_arguments_not_fragmented", turn.parse_errors)++ def test_chat_stream_reassembles_tool_fragments(self) -> None:+ events = [+ {"kind": "event", "type": None, "event": {"object": "chat.completion.chunk", "choices": [{"delta": {"tool_calls": [{"index": 0, "type": "function", "id": "call_1", "function": {"name": "lookup_weather", "arguments": '{"city":'}}]}}]}},+ {"kind": "event", "type": None, "event": {"object": "chat.completion.chunk", "choices": [{"delta": {"tool_calls": [{"index": 0, "type": "function", "function": {"arguments": '"Shanghai"}'}}]}}]}},+ ]+ turn = probe._parse_chat_stream(probe.TransportResult(200, None, events, True, 0))+ self.assertEqual(turn.tool_calls[0].arguments, {"city": "Shanghai"})+ self.assertTrue(turn.terminal)++ def test_chat_stream_requires_split_argument_fragments(self) -> None:+ events = [+ {+ "kind": "event",+ "sequence": 0,+ "type": None,+ "event": {+ "id": "chatcmpl_1",+ "object": "chat.completion.chunk",+ "choices": [+ {+ "index": 0,+ "delta": {+ "role": "assistant",+ "tool_calls": [+ {+ "index": 0,+ "type": "function",+ "id": "call_1",+ "function": {+ "name": "lookup_weather",+ "arguments": '{"city":',+ },+ }+ ],+ },+ }+ ],+ },+ },+ {+ "kind": "event",+ "sequence": 1,+ "type": None,+ "event": {+ "id": "chatcmpl_1",+ "object": "chat.completion.chunk",+ "choices": [+ {+ "index": 0,+ "delta": {+ "tool_calls": [+ {+ "index": 0,+ "function": {"arguments": '"Shanghai"}'},+ }+ ]+ },+ "finish_reason": "tool_calls",+ }+ ],+ },+ },+ {"kind": "done", "sequence": 2, "type": None},+ ]+ self.assertTrue(probe._stream_order_ok("chat", events))+ turn = probe._parse_chat_stream(+ probe.TransportResult(200, None, events, True, 0, True)+ )+ self.assertNotIn("stream_arguments_not_fragmented", turn.parse_errors)++ single_fragment = copy.deepcopy(events)+ single_fragment[0]["event"]["choices"][0]["delta"]["tool_calls"][0]["function"][+ "arguments"+ ] = '{"city":"Shanghai"}'+ single_fragment[1]["event"]["choices"][0]["delta"] = {}+ self.assertFalse(probe._stream_order_ok("chat", single_fragment))+ single_turn = probe._parse_chat_stream(+ probe.TransportResult(200, None, single_fragment, True, 0, False)+ )+ self.assertIn("stream_arguments_not_fragmented", single_turn.parse_errors)++ duplicate_in_one_chunk = copy.deepcopy(events)+ first_call = duplicate_in_one_chunk[0]["event"]["choices"][0]["delta"][+ "tool_calls"+ ][0]+ first_call["function"]["arguments"] = '{"city":'+ duplicate_in_one_chunk[0]["event"]["choices"][0]["delta"][+ "tool_calls"+ ].append(+ {+ "index": 0,+ "function": {"arguments": '"Shanghai"}'},+ }+ )+ duplicate_in_one_chunk[1]["event"]["choices"][0]["delta"] = {}+ self.assertFalse(probe._stream_order_ok("chat", duplicate_in_one_chunk))+ duplicate_turn = probe._parse_chat_stream(+ probe.TransportResult(+ 200,+ None,+ duplicate_in_one_chunk,+ True,+ 0,+ False,+ )+ )+ self.assertIn("stream_tool_index_duplicate", duplicate_turn.parse_errors)+ self.assertIn("stream_arguments_not_fragmented", duplicate_turn.parse_errors)++ def test_chat_stream_rejects_falsey_malformed_tool_fields(self) -> None:+ events = [+ {"kind": "event", "type": None, "event": {"object": "chat.completion.chunk", "choices": [{"delta": {"role": "assistant", "tool_calls": [{"index": 0, "type": "function", "id": "call_1", "function": {"name": "lookup_weather", "arguments": "{"}}]}}]}},+ {"kind": "event", "type": None, "event": {"object": "chat.completion.chunk", "choices": [{"delta": {"tool_calls": [{"index": 0, "function": {"name": [], "arguments": []}}]}, "finish_reason": "tool_calls"}]}},+ ]+ self.assertFalse(probe._stream_order_ok("chat", events + [{"kind": "done", "type": None}]))+ turn = probe._parse_chat_stream(probe.TransportResult(200, None, events, True, 0))+ self.assertIn("stream_name_invalid", turn.parse_errors)+ self.assertIn("stream_arguments_invalid", turn.parse_errors)++ def test_chat_stream_allows_sparse_continuation_type(self) -> None:+ events = [+ {"kind": "event", "type": None, "event": {"object": "chat.completion.chunk", "choices": [{"delta": {"tool_calls": [{"index": 0, "type": "function", "id": "call_1", "function": {"arguments": '{"city":'}}]}}]}},+ {"kind": "event", "type": None, "event": {"object": "chat.completion.chunk", "choices": [{"delta": {"tool_calls": [{"index": 0, "type": None, "function": {"arguments": '"Shanghai"}'}}]}}]}},+ ]+ turn = probe._parse_chat_stream(probe.TransportResult(200, None, events, True, 0))+ self.assertEqual(turn.tool_calls[0].arguments, {"city": "Shanghai"})+ self.assertNotIn("tool_call_type_invalid", turn.parse_errors)++ def test_chat_stream_requires_argument_fragments(self) -> None:+ events = [+ {"kind": "event", "type": None, "event": {"object": "chat.completion.chunk", "choices": [{"delta": {"tool_calls": [{"index": 0, "type": "function", "id": "call_1", "function": {"name": "lookup_weather"}}]}}]}},+ {"kind": "event", "type": None, "event": {"object": "chat.completion.chunk", "choices": [{"delta": {}, "finish_reason": "tool_calls"}]}},+ ]+ turn = probe._parse_chat_stream(probe.TransportResult(200, None, events, True, 0))+ self.assertIn("stream_arguments_missing", turn.parse_errors)++ def test_chat_stream_rejects_tool_call_id_changes(self) -> None:+ events = [+ {"kind": "event", "type": None, "event": {"object": "chat.completion.chunk", "choices": [{"delta": {"tool_calls": [{"index": 0, "type": "function", "id": "call_1", "function": {"name": "lookup_weather", "arguments": '{"city":"Shanghai"}'}}]}}]}},+ {"kind": "event", "type": None, "event": {"object": "chat.completion.chunk", "choices": [{"delta": {"tool_calls": [{"index": 0, "type": "function", "id": "call_2", "function": {}}]}}]}},+ {"kind": "event", "type": None, "event": {"object": "chat.completion.chunk", "choices": [{"delta": {}, "finish_reason": "tool_calls"}]}},+ ]+ turn = probe._parse_chat_stream(probe.TransportResult(200, None, events, True, 0))+ self.assertIn("tool_call_id_changed", turn.parse_errors)+ self.assertEqual(turn.tool_calls[0].call_id, "call_1")++ def test_chat_stream_requires_tool_call_id_on_opening_fragment(self) -> None:+ events = [+ {+ "kind": "event",+ "sequence": 0,+ "event": {+ "id": "chatcmpl_1",+ "object": "chat.completion.chunk",+ "choices": [+ {+ "index": 0,+ "delta": {+ "role": "assistant",+ "tool_calls": [+ {+ "index": 0,+ "type": "function",+ "function": {"name": "lookup_weather", "arguments": '{"city":'},+ }+ ],+ },+ }+ ],+ },+ },+ {+ "kind": "event",+ "sequence": 1,+ "event": {+ "id": "chatcmpl_1",+ "object": "chat.completion.chunk",+ "choices": [+ {+ "index": 0,+ "delta": {+ "role": "assistant",+ "tool_calls": [+ {"index": 0, "id": "call_1", "function": {"arguments": '"Shanghai"}'}}+ ]+ },+ "finish_reason": "tool_calls",+ }+ ],+ },+ },+ {"kind": "done", "sequence": 2},+ ]+ self.assertFalse(probe._stream_order_ok("chat", events))+ turn = probe._parse_chat_stream(probe.TransportResult(200, None, events, True, 0))+ self.assertIn("tool_call_id_invalid", turn.parse_errors)++ def test_tool_results_must_remain_paired_with_call_ids(self) -> None:+ calls = [+ probe.ToolCall("call_weather", "lookup_weather", {"city": "Shanghai"}),+ probe.ToolCall("call_time", "lookup_time", {"city": "Shanghai"}),+ ]+ text = "\n".join(+ [+ probe._tool_output(calls[0]).replace("call_weather", "call_time"),+ probe._tool_output(calls[1]).replace("call_time", "call_weather"),+ ]+ )+ turn = probe._parse_anthropic_document({"content": [{"type": "text", "text": text}], "stop_reason": "end_turn"})+ projection = probe._validate_second(turn, ("lookup_weather", "lookup_time"), stream=False, expected_calls=calls)+ self.assertFalse(projection["checks"]["tool_output_call_pairs"])++ def test_tool_result_tuple_check_rejects_swaps_on_one_line(self) -> None:+ calls = [+ probe.ToolCall("call_weather", "lookup_weather", {"city": "Shanghai"}),+ probe.ToolCall("call_time", "lookup_time", {"city": "Shanghai"}),+ ]+ text = " ".join(+ [+ probe._tool_output(calls[0]).replace("call_weather", "call_time"),+ probe._tool_output(calls[1]).replace("call_time", "call_weather"),+ ]+ )+ turn = probe._parse_anthropic_document({"content": [{"type": "text", "text": text}], "stop_reason": "end_turn"})+ projection = probe._validate_second(turn, ("lookup_weather", "lookup_time"), stream=False, expected_calls=calls)+ self.assertFalse(projection["checks"]["tool_output_call_pairs"])++ def test_tool_result_tuple_check_rejects_extra_tuple(self) -> None:+ calls = [+ probe.ToolCall("call_weather", "lookup_weather", {"city": "Shanghai"}),+ probe.ToolCall("call_time", "lookup_time", {"city": "Shanghai"}),+ ]+ text = " ".join(+ [+ probe._tool_output(calls[0]),+ probe._tool_output(calls[1]),+ "tool=lookup_weather;call_id=fabricated;marker=WEATHER_OK",+ ]+ )+ turn = probe._parse_anthropic_document({"content": [{"type": "text", "text": text}], "stop_reason": "end_turn"})+ projection = probe._validate_second(turn, ("lookup_weather", "lookup_time"), stream=False, expected_calls=calls)+ self.assertFalse(projection["checks"]["tool_output_call_pairs"])++ def test_tool_result_tuple_check_rejects_unrecognized_marker(self) -> None:+ call = probe.ToolCall("call_weather", "lookup_weather", {"city": "Shanghai"})+ text = f"{probe._tool_output(call)} tool=lookup_weather;call_id=fake;marker=BOGUS."+ self.assertEqual(+ probe._tool_output_tuples(text),+ [+ ("lookup_weather", "call_weather", "WEATHER_OK"),+ ("lookup_weather", "fake", "BOGUS"),+ ],+ )+ turn = probe._parse_anthropic_document(+ {"content": [{"type": "text", "text": text}], "stop_reason": "end_turn"}+ )+ projection = probe._validate_second(turn, ("lookup_weather",), stream=False, expected_calls=[call])+ self.assertFalse(projection["checks"]["tool_output_call_pairs"])++ def test_tool_result_tuple_check_rejects_punctuation_marker(self) -> None:+ call = probe.ToolCall("call_weather", "lookup_weather", {"city": "Shanghai"})+ text = f"{probe._tool_output(call)} tool=lookup_weather;call_id=fake;marker=!!!"+ self.assertEqual(+ probe._tool_output_tuples(text),+ [+ ("lookup_weather", "call_weather", "WEATHER_OK"),+ ("lookup_weather", "fake", "!!!"),+ ],+ )+ turn = probe._parse_anthropic_document(+ {"content": [{"type": "text", "text": text}], "stop_reason": "end_turn"}+ )+ projection = probe._validate_second(turn, ("lookup_weather",), stream=False, expected_calls=[call])+ self.assertFalse(projection["checks"]["tool_output_call_pairs"])++ def test_tool_result_tuple_check_rejects_empty_or_malformed_identity_fields(self) -> None:+ call = probe.ToolCall("call_weather", "lookup_weather", {"city": "Shanghai"})+ for malformed in (+ "tool=;call_id=fake;marker=BOGUS",+ "tool=fake;call_id=;marker=BOGUS",+ "tool=fake;call_id=fake",+ ):+ with self.subTest(malformed=malformed):+ text = f"{probe._tool_output(call)} {malformed}"+ turn = probe._parse_anthropic_document(+ {"content": [{"type": "text", "text": text}], "stop_reason": "end_turn"}+ )+ projection = probe._validate_second(+ turn,+ ("lookup_weather",),+ stream=False,+ expected_calls=[call],+ )+ self.assertFalse(projection["checks"]["tool_output_call_pairs"])++ def test_tool_result_tuple_preserves_punctuation_in_call_id(self) -> None:+ call = probe.ToolCall("call.123", "lookup_weather", {"city": "Shanghai"})+ text = f"{probe._tool_output(call)}."+ self.assertEqual(probe._tool_output_tuples(text), [("lookup_weather", "call.123", "WEATHER_OK")])+ turn = probe._parse_anthropic_document({"content": [{"type": "text", "text": text}], "stop_reason": "end_turn"})+ projection = probe._validate_second(turn, ("lookup_weather",), stream=False, expected_calls=[call])+ self.assertTrue(projection["checks"]["tool_output_call_pairs"])++ def test_empty_responses_reasoning_item_is_not_a_signal(self) -> None:+ turn = probe._parse_responses_document(+ {"output": [{"id": "rs_1", "type": "reasoning", "summary": [], "content": []}, {"id": "fc_1", "type": "function_call", "call_id": "call_1", "name": "lookup_weather", "arguments": '{"city":"Shanghai"}'}], "status": "completed"}+ )+ self.assertFalse(turn.reasoning_present)++ def test_responses_encrypted_reasoning_is_a_signal(self) -> None:+ turn = probe._parse_responses_document(+ {"output": [{"id": "rs_1", "type": "reasoning", "encrypted_content": "opaque"}], "status": "completed"}+ )+ self.assertTrue(turn.reasoning_present)++ def test_responses_encrypted_reasoning_requires_string_payload(self) -> None:+ turn = probe._parse_responses_document(+ {"output": [{"id": "rs_1", "type": "reasoning", "encrypted_content": True}], "status": "completed"}+ )+ self.assertFalse(turn.reasoning_present)++ def test_responses_reasoning_parts_require_supported_string_payloads(self) -> None:+ for part, error in (+ ({"type": "future_part", "text": "ignored"}, "reasoning_part_type_invalid"),+ ({"type": "summary_text", "text": []}, "reasoning_part_text_invalid"),+ ):+ turn = probe._parse_responses_document(+ {"object": "response", "output": [{"id": "rs_1", "type": "reasoning", "summary": [part]}], "status": "completed"}+ )+ self.assertIn(error, turn.parse_errors)++ def test_responses_nonstream_output_items_require_ids(self) -> None:+ for item in (+ {"type": "function_call", "call_id": "call_1", "name": "lookup_weather", "arguments": '{"city":"Shanghai"}'},+ {"id": [], "type": "function_call", "call_id": "call_1", "name": "lookup_weather", "arguments": '{"city":"Shanghai"}'},+ {"id": "", "type": "function_call", "call_id": "call_1", "name": "lookup_weather", "arguments": '{"city":"Shanghai"}'},+ ):+ turn = probe._parse_responses_document({"object": "response", "output": [item], "status": "completed"})+ self.assertIn("output_item_id_invalid", turn.parse_errors)++ def test_duplicate_argument_keys_are_rejected(self) -> None:+ arguments, error = probe._parse_arguments('{"city":"Paris","city":"Shanghai"}')+ self.assertEqual(arguments, '{"city":"Paris","city":"Shanghai"}')+ self.assertEqual(error, "arguments_duplicate_key")++ def test_nonfinite_tool_argument_is_invalid_json(self) -> None:+ arguments, error = probe._parse_arguments('{"city":"Shanghai","score":NaN}')+ self.assertEqual(arguments, '{"city":"Shanghai","score":NaN}')+ self.assertEqual(error, "arguments_invalid_json")++ def test_malformed_chat_function_is_a_parse_error(self) -> None:+ turn = probe._parse_chat_document(+ {"choices": [{"message": {"tool_calls": [{"id": "call_1", "type": "function", "function": None}]}, "finish_reason": "tool_calls"}]}+ )+ self.assertIn("tool_function_invalid", turn.parse_errors)++ def test_nonstream_chat_requires_single_assistant_choice_zero(self) -> None:+ wrong_role = probe._parse_chat_document(+ {"choices": [{"index": 0, "message": {"role": "user", "content": "wrong"}, "finish_reason": "stop"}]}+ )+ multiple = probe._parse_chat_document(+ {+ "choices": [+ {"index": 0, "message": {"role": "assistant", "content": "a"}, "finish_reason": "stop"},+ {"index": 1, "message": {"role": "assistant", "content": "b"}, "finish_reason": "stop"},+ ]+ }+ )+ nonzero = probe._parse_chat_document(+ {"choices": [{"index": 1, "message": {"role": "assistant", "content": "wrong"}, "finish_reason": "stop"}]}+ )+ self.assertIn("assistant_role_invalid", wrong_role.parse_errors)+ self.assertIn("choice_invalid", multiple.parse_errors)+ self.assertIn("choice_index_invalid", nonzero.parse_errors)++ def test_chat_stream_requires_done_sentinel(self) -> None:+ events = [+ {"kind": "event", "type": None, "event": {"object": "chat.completion.chunk", "choices": [{"delta": {}, "finish_reason": "tool_calls"}]}},+ ]+ self.assertFalse(probe._stream_order_ok("chat", events))++ def test_chat_stream_done_sentinel_is_not_an_envelope(self) -> None:+ events = [+ {"kind": "event", "type": None, "event": {"object": "chat.completion.chunk", "choices": [{"delta": {"role": "assistant"}, "finish_reason": "stop"}]}},+ {"kind": "done", "type": None},+ ]+ turn = probe._parse_chat_stream(probe.TransportResult(200, None, events, True, 0))+ self.assertNotIn("stream_envelope_invalid", turn.parse_errors)+ self.assertTrue(turn.terminal)++ def test_chat_stream_rejects_named_done_sentinel(self) -> None:+ events = [+ {"kind": "event", "type": None, "event": {"object": "chat.completion.chunk", "choices": [{"delta": {"role": "assistant"}, "finish_reason": "stop"}]}},+ {"kind": "done", "type": "bogus"},+ ]+ self.assertFalse(probe._stream_order_ok("chat", events))+ turn = probe._parse_chat_stream(probe.TransportResult(200, None, events, True, 0))+ self.assertIn("stream_done_event_type_invalid", turn.parse_errors)++ def test_chat_stream_requires_chunk_discriminator(self) -> None:+ events = [+ {"kind": "event", "type": None, "event": {"choices": [{"delta": {"role": "assistant"}, "finish_reason": "stop"}]}},+ {"kind": "done", "type": None},+ ]+ self.assertFalse(probe._stream_order_ok("chat", events))+ turn = probe._parse_chat_stream(probe.TransportResult(200, None, events, True, 0))+ self.assertIn("stream_object_invalid", turn.parse_errors)++ def test_chat_stream_rejects_unhashable_continuation_type(self) -> None:+ events = [+ {"kind": "event", "type": None, "event": {"object": "chat.completion.chunk", "choices": [{"delta": {"role": "assistant", "tool_calls": [{"index": 0, "type": "function", "id": "call_1", "function": {"name": "lookup_weather", "arguments": "{\"city\":\"Shanghai\"}"}}]}}]}},+ {"kind": "event", "type": None, "event": {"object": "chat.completion.chunk", "choices": [{"delta": {"tool_calls": [{"index": 0, "type": [], "function": {}}]}, "finish_reason": "tool_calls"}]}},+ {"kind": "done", "type": None},+ ]+ self.assertFalse(probe._stream_order_ok("chat", events))+ turn = probe._parse_chat_stream(probe.TransportResult(200, None, events, True, 0))+ self.assertIn("tool_call_type_invalid", turn.parse_errors)++ def test_chat_stream_rejects_non_object_tool_fragments(self) -> None:+ events = [+ {"kind": "event", "sequence": 0, "type": None, "event": {"object": "chat.completion.chunk", "choices": [{"delta": {"role": "assistant", "tool_calls": [None]}, "finish_reason": "tool_calls"}]}},+ {"kind": "done", "sequence": 1, "type": None},+ ]+ self.assertFalse(probe._stream_order_ok("chat", events))+ turn = probe._parse_chat_stream(probe.TransportResult(200, None, events, True, 0, False))+ self.assertIn("tool_call_invalid", turn.parse_errors)++ def test_chat_stream_allows_indices_to_restart_each_chunk(self) -> None:+ events = [+ {+ "kind": "event",+ "sequence": 0,+ "event": {+ "id": "chatcmpl_1",+ "object": "chat.completion.chunk",+ "choices": [+ {+ "index": 0,+ "delta": {+ "role": "assistant",+ "tool_calls": [+ {+ "index": 0,+ "id": "call_1",+ "function": {"arguments": '{"city":'},+ },+ {+ "index": 1,+ "id": "call_2",+ "function": {"arguments": '{"city":'},+ },+ ]+ },+ }+ ],+ },+ },+ {+ "kind": "event",+ "sequence": 1,+ "event": {+ "id": "chatcmpl_1",+ "object": "chat.completion.chunk",+ "choices": [+ {+ "index": 0,+ "delta": {+ "tool_calls": [+ {"index": 0, "function": {"arguments": '"Shanghai"}'}},+ {"index": 1, "function": {"arguments": '"Shanghai"}'}},+ ],+ "content": "done",+ },+ "finish_reason": "tool_calls",+ }+ ],+ },+ },+ {"kind": "done", "sequence": 2},+ ]+ self.assertTrue(probe._stream_order_ok("chat", events))++ def test_responses_stream_rejects_text_after_item_completion(self) -> None:+ events = [+ {"kind": "event", "type": "response.output_item.added", "event": {"type": "response.output_item.added", "item": {"id": "msg_1", "type": "message"}}},+ {"kind": "event", "type": "response.output_item.done", "event": {"type": "response.output_item.done", "item": {"id": "msg_1", "type": "message", "content": []}}},+ {"kind": "event", "type": "response.output_text.delta", "event": {"type": "response.output_text.delta", "item_id": "msg_1", "delta": "late"}},+ {"kind": "event", "type": "response.completed", "event": {"type": "response.completed"}},+ ]+ self.assertFalse(probe._stream_order_ok("responses", events))++ def test_anthropic_stream_requires_message_start(self) -> None:+ events = [+ {"kind": "event", "sequence": 0, "type": "content_block_start", "event": {"type": "content_block_start", "index": 0, "content_block": {"type": "tool_use", "id": "call_1", "name": "lookup_weather"}}},+ {"kind": "event", "sequence": 1, "type": "content_block_stop", "event": {"type": "content_block_stop", "index": 0}},+ {"kind": "event", "sequence": 2, "type": "message_stop", "event": {"type": "message_stop"}},+ ]+ self.assertFalse(probe._stream_order_ok("anthropic", events))++ def test_sse_event_name_must_match_anthropic_json_type(self) -> None:+ events = [+ {"kind": "event", "sequence": 0, "type": "wrong_name", "event": {"type": "message_start"}},+ ]+ self.assertFalse(probe._stream_order_ok("anthropic", events))++ def test_sse_parser_preserves_wire_event_name(self) -> None:+ events: list[dict[str, object]] = []+ invalid = [0]+ probe._flush_sse(['{"type":"message_start"}'], "wrong_name", events, invalid)+ self.assertEqual(events[0]["type"], "wrong_name")+ self.assertFalse(probe._stream_order_ok("anthropic", events))++ def test_sse_parser_normalizes_default_event_names(self) -> None:+ payload = '{"id":"chatcmpl_1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":"stop"}]}'+ for event_name in ("message", ""):+ events: list[dict[str, object]] = []+ invalid = [0]+ probe._flush_sse([payload], event_name, events, invalid)+ probe._flush_sse(["[DONE]"], event_name, events, invalid)+ self.assertEqual([event["type"] for event in events], [None, None])+ self.assertEqual(invalid, [0])+ self.assertTrue(probe._stream_order_ok("chat", events))++ def test_sse_parser_rejects_trailing_event_name_whitespace(self) -> None:+ payload = (+ b'event: message_start \ndata: {"type":"message_start","message":{"type":"message",'+ b'"role":"assistant","content":[],"stop_reason":null,"stop_sequence":null}}\n\n'+ b'event: message_stop\ndata: {"type":"message_stop"}\n\n'+ )++ class Response:+ status = 200+ headers = {"Content-Type": "text/event-stream"}++ def __init__(self):+ self.offset = 0++ def __enter__(self):+ return self++ def __exit__(self, *args):+ return None++ def read(self, size: int) -> bytes:+ chunk = payload[self.offset : self.offset + size]+ self.offset += len(chunk)+ return chunk++ class Opener:+ def open(self, request, timeout):+ return Response()++ original_opener = probe.OPENER+ try:+ probe.OPENER = Opener()+ result = probe._request("/v1/messages", {}, client_protocol="anthropic", stream=True)+ finally:+ probe.OPENER = original_opener+ self.assertFalse(result.stream_order_ok)++ def test_sse_parser_preserves_extra_data_whitespace(self) -> None:+ payload = b"data: [DONE]\n\n"++ class Response:+ status = 200+ headers = {"Content-Type": "text/event-stream"}++ def __init__(self):+ self.offset = 0++ def __enter__(self):+ return self++ def __exit__(self, *args):+ return None++ def read(self, size: int) -> bytes:+ chunk = payload[self.offset : self.offset + size]+ self.offset += len(chunk)+ return chunk++ class Opener:+ def open(self, request, timeout):+ return Response()++ original_opener = probe.OPENER+ try:+ probe.OPENER = Opener()+ result = probe._request("/v1/chat/completions", {}, client_protocol="chat", stream=True)+ finally:+ probe.OPENER = original_opener+ self.assertFalse(result.done_sentinel)+ self.assertEqual(result.invalid_event_count, 1)++ def test_sse_parser_preserves_bare_data_field(self) -> None:+ payload = b"data: [DONE]\ndata\n\n"++ class Response:+ status = 200+ headers = {"Content-Type": "text/event-stream"}++ def __init__(self):+ self.offset = 0++ def __enter__(self):+ return self++ def __exit__(self, *args):+ return None++ def read(self, size: int) -> bytes:+ chunk = payload[self.offset : self.offset + size]+ self.offset += len(chunk)+ return chunk++ class Opener:+ def open(self, request, timeout):+ return Response()++ original_opener = probe.OPENER+ try:+ probe.OPENER = Opener()+ result = probe._request("/v1/chat/completions", {}, client_protocol="chat", stream=True)+ finally:+ probe.OPENER = original_opener+ self.assertFalse(result.done_sentinel)+ self.assertEqual(result.invalid_event_count, 1)++ def test_sse_parser_discards_unterminated_event_at_eof(self) -> None:+ for payload in (b"data: [DONE]\n", b"data: [DONE]"):+ class Response:+ status = 200+ headers = {"Content-Type": "text/event-stream"}++ def __init__(self):+ self.offset = 0++ def __enter__(self):+ return self++ def __exit__(self, *args):+ return None++ def read(self, size: int) -> bytes:+ chunk = payload[self.offset : self.offset + size]+ self.offset += len(chunk)+ return chunk++ class Opener:+ def open(self, request, timeout):+ return Response()++ original_opener = probe.OPENER+ try:+ probe.OPENER = Opener()+ result = probe._request("/v1/chat/completions", {}, client_protocol="chat", stream=True)+ finally:+ probe.OPENER = original_opener+ self.assertFalse(result.done_sentinel)+ self.assertEqual(result.events, [])+ self.assertFalse(result.stream_order_ok)++ def test_chat_done_sentinel_ends_read_before_transport_eof(self) -> None:+ payload = (+ b'data: {"id":"chatcmpl_1","object":"chat.completion.chunk","choices":'+ b'[{"index":0,"delta":{"role":"assistant"},"finish_reason":"stop"}]}\n\n'+ b"data: [DONE]\n\n"+ )++ class Response:+ status = 200+ headers = {"Content-Type": "text/event-stream"}++ def __init__(self):+ self.offset = 0++ def __enter__(self):+ return self++ def __exit__(self, *args):+ return None++ def read(self, size: int) -> bytes:+ if self.offset >= len(payload):+ raise TimeoutError+ chunk = payload[self.offset : self.offset + size]+ self.offset += len(chunk)+ return chunk++ class Opener:+ def open(self, request, timeout):+ return Response()++ original_opener = probe.OPENER+ try:+ probe.OPENER = Opener()+ result = probe._request("/v1/chat/completions", {}, client_protocol="chat", stream=True)+ finally:+ probe.OPENER = original_opener+ self.assertTrue(result.done_sentinel)+ self.assertFalse(result.deadline_expired)+ self.assertTrue(result.stream_order_ok)++ def test_chat_stream_rejects_non_function_tool_type(self) -> None:+ events = [+ {"kind": "event", "type": None, "event": {"object": "chat.completion.chunk", "choices": [{"delta": {"tool_calls": [{"index": 0, "type": "custom", "id": "call_1", "function": {"name": "lookup_weather", "arguments": '{"city":"Shanghai"}'}}]}}]}},+ ]+ turn = probe._parse_chat_stream(probe.TransportResult(200, None, events, True, 0))+ self.assertIn("tool_call_type_invalid", turn.parse_errors)++ def test_anthropic_thinking_requires_signature(self) -> None:+ turn = probe._parse_anthropic_document(+ {"content": [{"type": "thinking", "thinking": "internal"}, {"type": "tool_use", "id": "call_1", "name": "lookup_weather", "input": {"city": "Shanghai"}}], "stop_reason": "tool_use"}+ )+ self.assertIn("thinking_signature_missing", turn.parse_errors)++ def test_anthropic_response_requires_message_envelope(self) -> None:+ turn = probe._parse_anthropic_document(+ {"type": "error", "role": "user", "content": [], "stop_reason": "end_turn"}+ )+ self.assertIn("message_type_invalid", turn.parse_errors)+ self.assertIn("message_role_invalid", turn.parse_errors)++ def test_anthropic_response_rejects_unknown_content_block_types(self) -> None:+ turn = probe._parse_anthropic_document(+ {+ "type": "message",+ "role": "assistant",+ "content": [{"type": "future_block", "payload": "ignored"}],+ "stop_reason": "end_turn",+ }+ )+ self.assertIn("content_block_type_invalid", turn.parse_errors)++ def test_anthropic_stream_requires_message_start_envelope(self) -> None:+ events = [+ {"kind": "event", "type": "message_start", "event": {"type": "message_start", "message": {"type": "error", "role": "user"}}},+ {"kind": "event", "type": "message_stop", "event": {"type": "message_stop"}},+ ]+ turn = probe._parse_anthropic_stream(probe.TransportResult(200, None, events, True, 0, False))+ self.assertIn("message_type_invalid", turn.parse_errors)+ self.assertIn("message_role_invalid", turn.parse_errors)++ def test_anthropic_stream_requires_text_delta_for_final_text(self) -> None:+ events = [+ {"kind": "event", "type": "message_start", "event": {"type": "message_start"}},+ {"kind": "event", "type": "content_block_start", "event": {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": "snapshot"}}},+ {"kind": "event", "type": "content_block_stop", "event": {"type": "content_block_stop", "index": 0}},+ {"kind": "event", "type": "message_stop", "event": {"type": "message_stop"}},+ ]+ turn = probe._parse_anthropic_stream(probe.TransportResult(200, None, events, True, 0, True))+ projection = probe._validate_second(turn, ("lookup_weather",), stream=True)+ self.assertFalse(projection["checks"]["stream_text_deltas"])++ def test_malformed_anthropic_block_snapshot_is_a_parse_error(self) -> None:+ events = [+ {"kind": "event", "type": "message_start", "event": {"type": "message_start"}},+ {"kind": "event", "type": "content_block_start", "event": {"type": "content_block_start", "index": 0, "content_block": None}},+ {"kind": "event", "type": "message_stop", "event": {"type": "message_stop"}},+ ]+ turn = probe._parse_anthropic_stream(probe.TransportResult(200, None, events, True, 0, False))+ self.assertIn("content_block_invalid", turn.parse_errors)++ def test_malformed_base_url_is_blocked_preflight(self) -> None:+ original_base_url = probe.BASE_URL+ try:+ probe.BASE_URL = "http://["+ missing = probe._preflight()+ finally:+ probe.BASE_URL = original_base_url+ self.assertIn("CPA_BASE_URL must be exact http://127.0.0.1[:port]", missing)++ def test_responses_stream_does_not_duplicate_text_snapshot(self) -> None:+ events = [+ {"kind": "event", "event": {"type": "response.output_item.added", "item": {"id": "msg_1", "type": "message"}}},+ {"kind": "event", "event": {"type": "response.output_text.delta", "item_id": "msg_1", "delta": "answer"}},+ {"kind": "event", "event": {"type": "response.output_item.done", "item": {"id": "msg_1", "type": "message", "content": [{"type": "output_text", "text": "answer"}]}}},+ {"kind": "event", "event": {"type": "response.completed", "response": {"status": "completed"}}},+ ]+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, events, True, 0))+ self.assertEqual(turn.text, "answer")++ def test_responses_stream_requires_text_delta_for_final_text(self) -> None:+ result = probe.TransportResult(+ 200,+ None,+ [+ {"kind": "event", "event": {"type": "response.output_item.added", "item": {"id": "msg_1", "type": "message"}}},+ {"kind": "event", "event": {"type": "response.output_item.done", "item": {"id": "msg_1", "type": "message", "content": [{"type": "output_text", "text": "answer"}]}}},+ {"kind": "event", "event": {"type": "response.completed", "response": {"status": "completed"}}},+ ],+ False,+ 0,+ )+ turn = probe._parse_responses_stream(result)+ projection = probe._validate_second(turn, ("lookup_weather",), stream=True)+ self.assertFalse(projection["checks"]["stream_text_deltas"])++ def test_sse_rejects_nonfinite_json_constants(self) -> None:+ events: list[dict[str, object]] = []+ invalid = [0]+ probe._flush_sse(['{"type":"message_start","ignored":NaN}'], None, events, invalid)+ self.assertEqual(events, [])+ self.assertEqual(invalid, [1])++ def test_nonstream_rejects_nonfinite_json_constants(self) -> None:+ class Response:+ status = 200+ headers: dict[str, str] = {}++ def __enter__(self):+ return self++ def __exit__(self, *args):+ return None++ def read(self) -> bytes:+ return b'{"usage":{"completion_tokens_details":{"reasoning_tokens":Infinity}}}'++ class Opener:+ def open(self, request, timeout):+ return Response()++ original_opener = probe.OPENER+ try:+ probe.OPENER = Opener()+ result = probe._request("/v1/chat/completions", {}, client_protocol="chat", stream=False)+ finally:+ probe.OPENER = original_opener+ self.assertIsNone(result.document)+ self.assertEqual(result.invalid_event_count, 1)++ def test_nonstream_rejects_duplicate_outer_json_keys(self) -> None:+ class Response:+ status = 200+ headers: dict[str, str] = {}++ def __enter__(self):+ return self++ def __exit__(self, *args):+ return None++ def read(self) -> bytes:+ return b'{"type":"message","role":"assistant","content":[{"type":"tool_use","input":{"city":"Paris","city":"Shanghai"}}]}'++ class Opener:+ def open(self, request, timeout):+ return Response()++ original_opener = probe.OPENER+ try:+ probe.OPENER = Opener()+ result = probe._request("/v1/messages", {}, client_protocol="anthropic", stream=False)+ finally:+ probe.OPENER = original_opener+ self.assertIsNone(result.document)+ self.assertEqual(result.invalid_event_count, 1)++ def test_stream_requires_event_stream_content_type(self) -> None:+ class Response:+ status = 200+ headers = {"Content-Type": "application/json"}++ def __enter__(self):+ return self++ def __exit__(self, *args):+ return None++ class Opener:+ def open(self, request, timeout):+ return Response()++ original_opener = probe.OPENER+ try:+ probe.OPENER = Opener()+ result = probe._request("/v1/messages", {}, client_protocol="anthropic", stream=True)+ finally:+ probe.OPENER = original_opener+ self.assertFalse(result.content_type_ok)+ self.assertEqual(result.invalid_event_count, 1)++ def test_sse_accepts_cr_only_line_endings(self) -> None:+ payload = (+ b'\xef\xbb\xbfevent: message_start\rdata: {"type":"message_start","message":'+ b'{"type":"message","role":"assistant","content":[],"usage":{"input_tokens":1,"output_tokens":0},"stop_reason":null,"stop_sequence":null}}\r\r'+ b'event: message_delta\rdata: {"type":"message_delta","delta":'+ b'{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":1}}\r\r'+ b'event: message_stop\rdata: {"type":"message_stop"}\r\r'+ )++ class Response:+ status = 200+ headers = {"Content-Type": "text/event-stream"}++ def __init__(self):+ self.offset = 0++ def __enter__(self):+ return self++ def __exit__(self, *args):+ return None++ def read(self, size: int) -> bytes:+ chunk = payload[self.offset : self.offset + size]+ self.offset += len(chunk)+ return chunk++ class Opener:+ def open(self, request, timeout):+ return Response()++ original_opener = probe.OPENER+ try:+ probe.OPENER = Opener()+ result = probe._request("/v1/messages", {}, client_protocol="anthropic", stream=True)+ finally:+ probe.OPENER = original_opener+ self.assertEqual(len(result.events), 3)+ self.assertTrue(result.stream_order_ok)++ def test_chat_usage_reasoning_tokens_count_as_reasoning_signal(self) -> None:+ turn = probe._parse_chat_document(+ {+ "choices": [{"message": {"content": "ok"}, "finish_reason": "tool_calls"}],+ "usage": {"completion_tokens_details": {"reasoning_tokens": 3}},+ }+ )+ self.assertTrue(turn.reasoning_present)++ def test_chat_reasoning_usage_requires_positive_integer(self) -> None:+ for value in (True, 1.5, 0, -1):+ document = {+ "choices": [{"message": {"content": "ok"}, "finish_reason": "tool_calls"}],+ "usage": {"completion_tokens_details": {"reasoning_tokens": value}},+ }+ self.assertFalse(probe._parse_chat_document(document).reasoning_present)++ def test_chat_reasoning_content_requires_nonempty_string(self) -> None:+ for value in (True, 1, {}, []):+ turn = probe._parse_chat_document(+ {+ "choices": [+ {+ "index": 0,+ "message": {"role": "assistant", "reasoning_content": value},+ "finish_reason": "stop",+ }+ ]+ }+ )+ self.assertFalse(turn.reasoning_present)+ self.assertIn("reasoning_content_invalid", turn.parse_errors)++ def test_chat_message_content_requires_string_or_null(self) -> None:+ for value in ({"text": "CPA_SYSTEM_MARKER_731"}, ["WEATHER_OK"]):+ turn = probe._parse_chat_document(+ {+ "choices": [+ {+ "index": 0,+ "message": {"role": "assistant", "content": value},+ "finish_reason": "stop",+ }+ ]+ }+ )+ self.assertIn("message_content_invalid", turn.parse_errors)++ def test_missing_tool_ids_are_rejected_before_string_conversion(self) -> None:+ anthropic = probe._parse_anthropic_document(+ {"content": [{"type": "tool_use", "id": None, "name": "lookup_weather", "input": {"city": "Shanghai"}}], "stop_reason": "tool_use"}+ )+ responses = probe._parse_responses_document(+ {"output": [{"type": "function_call", "call_id": None, "name": "lookup_weather", "arguments": '{"city":"Shanghai"}'}], "status": "completed"}+ )+ chat = probe._parse_chat_document(+ {"choices": [{"message": {"tool_calls": [{"id": None, "type": "function", "function": {"name": "lookup_weather", "arguments": '{"city":"Shanghai"}'}}]}, "finish_reason": "tool_calls"}]}+ )+ for turn in (anthropic, responses, chat):+ self.assertIn("tool_call_id_invalid", turn.parse_errors)+ self.assertFalse(probe._validate_first(turn, ("lookup_weather",), stream=False)["checks"]["parsed"])++ def test_responses_message_items_require_assistant_list_content(self) -> None:+ invalid_content = probe._parse_responses_document(+ {"output": [{"type": "message", "role": "assistant", "content": None}], "status": "completed"}+ )+ invalid_role = probe._parse_responses_document(+ {"output": [{"type": "message", "role": "user", "content": []}], "status": "completed"}+ )+ self.assertIn("message_content_invalid", invalid_content.parse_errors)+ self.assertIn("assistant_role_invalid", invalid_role.parse_errors)++ def test_malformed_stream_indexes_fail_without_parser_exceptions(self) -> None:+ anthropic_events = [+ {"kind": "event", "sequence": 0, "event": {"type": "content_block_start", "index": None, "content_block": {"type": "tool_use", "id": "call_1", "name": "lookup_weather"}}},+ {"kind": "event", "sequence": 1, "event": {"type": "message_stop"}},+ ]+ chat_events = [+ {"kind": "event", "sequence": 0, "event": {"object": "chat.completion.chunk", "choices": [{"delta": {"tool_calls": [{"index": None, "id": "call_1", "function": {"name": "lookup_weather", "arguments": '{"city":"Shanghai"}'}}]}}]}},+ {"kind": "event", "sequence": 1, "event": {"object": "chat.completion.chunk", "choices": [{"delta": {}, "finish_reason": "tool_calls"}]}},+ {"kind": "done", "sequence": 2},+ ]+ self.assertFalse(probe._stream_order_ok("anthropic", anthropic_events))+ self.assertFalse(probe._stream_order_ok("chat", chat_events))+ anthropic_turn = probe._parse_anthropic_stream(probe.TransportResult(200, None, anthropic_events, True, 0, False))+ chat_turn = probe._parse_chat_stream(probe.TransportResult(200, None, chat_events, True, 0, False))+ self.assertIn("stream_index_invalid", anthropic_turn.parse_errors)+ self.assertIn("stream_index_invalid", chat_turn.parse_errors)++ def test_loopback_opener_has_no_environment_proxy(self) -> None:+ proxy_handlers = [handler for handler in probe.OPENER.handlers if isinstance(handler, probe.urllib.request.ProxyHandler)]+ self.assertEqual(proxy_handlers, [])++ def test_semantic_checks_reject_missing_reasoning_and_markers(self) -> None:+ first = probe._parse_anthropic_document(+ {"content": [{"type": "tool_use", "id": "id", "name": "lookup_weather", "input": {"city": "Shanghai"}}], "stop_reason": "tool_use"}+ )+ first_checks = probe._validate_first(first, ("lookup_weather",), stream=False)+ self.assertFalse(first_checks["checks"]["reasoning_present"])+ second = probe._parse_anthropic_document({"content": [{"type": "text", "text": "WEATHER_OK"}], "stop_reason": "end_turn"})+ second_checks = probe._validate_second(second, ("lookup_weather",), stream=False)+ self.assertFalse(second_checks["checks"]["system_marker"])++ def test_case_round_trip_is_driven_by_first_response(self) -> None:+ requests: list[dict[str, object]] = []++ def fake_request(path: str, payload: dict[str, object], *, client_protocol: str, stream: bool) -> probe.TransportResult:+ requests.append(payload)+ if len(requests) == 1:+ return probe.TransportResult(+ 200,+ {+ "content": [+ {"type": "thinking", "thinking": "internal", "signature": "sig"},+ {"type": "tool_use", "id": "toolu_from_first_response", "name": "lookup_weather", "input": {"city": "Shanghai"}},+ ],+ "stop_reason": "tool_use",+ },+ [],+ False,+ 0,+ )+ return probe.TransportResult(+ 200,+ {"content": [{"type": "text", "text": f"{probe.SYSTEM_MARKER} {probe.SYSTEM_SCOPE_OK} WEATHER_OK"}], "stop_reason": "end_turn"},+ [],+ False,+ 0,+ )++ original_request = probe._request+ try:+ probe._request = fake_request+ result = probe._run_case(probe.CaseSpec("fake", "anthropic", "responses", "/v1/messages", False, False))+ finally:+ probe._request = original_request+ self.assertEqual(len(requests), 2)+ followup = requests[1]+ self.assertEqual(followup["messages"][2]["content"][0]["tool_use_id"], "toolu_from_first_response")+ self.assertTrue(result["checks"]["second_system_marker"])+ self.assertTrue(result["checks"]["second_tool_outputs"])++ def test_case_skips_followup_for_invalid_tool_call_identity(self) -> None:+ requests: list[dict[str, object]] = []++ def fake_request(+ path: str,+ payload: dict[str, object],+ *,+ client_protocol: str,+ stream: bool,+ ) -> probe.TransportResult:+ requests.append(payload)+ return probe.TransportResult(+ 200,+ {+ "content": [+ {+ "type": "tool_use",+ "name": "lookup_weather",+ "input": {"city": "Shanghai"},+ }+ ],+ "stop_reason": "tool_use",+ },+ [],+ False,+ 0,+ )++ original_request = probe._request+ try:+ probe._request = fake_request+ result = probe._run_case(+ probe.CaseSpec(+ "fake",+ "anthropic",+ "responses",+ "/v1/messages",+ False,+ False,+ )+ )+ finally:+ probe._request = original_request+ self.assertEqual(len(requests), 1)+ self.assertTrue(result["second"]["skipped"])+ self.assertEqual(+ result["second"]["skip_reason"],+ "invalid first-turn tool-call identity",+ )+ self.assertIsNone(result["second_status"])++ def test_redirect_handler_blocks_redirect(self) -> None:+ request = probe.urllib.request.Request("http://127.0.0.1:15220/v1/messages")+ self.assertIsNone(probe._NoRedirectHandler().redirect_request(request, None, 302, "Found", {}, "http://example.test"))++ def test_payload_uses_valid_thinking_and_qualified_models(self) -> None:+ payload = probe._anthropic_payload(model="src/model", stream=False, parallel=False)+ responses = probe._responses_payload(model="src/model", stream=False, parallel=False)+ self.assertGreaterEqual(payload["thinking"]["budget_tokens"], 1024)+ self.assertGreater(payload["max_tokens"], payload["thinking"]["budget_tokens"])+ self.assertEqual(payload["tool_choice"], {"type": "auto"})+ self.assertEqual(responses["include"], ["reasoning.encrypted_content"])+ self.assertTrue(probe._valid_qualified_model("src/model"))+ self.assertFalse(probe._valid_qualified_model("bare-model"))++ def test_parallel_prompt_names_both_tools_and_city_is_constrained(self) -> None:+ prompt = probe._user_prompt(True)+ self.assertIn("lookup_weather", prompt)+ self.assertIn("lookup_time", prompt)+ self.assertNotIn("Ignore this user-level conflict instruction", prompt)+ schema = probe._tool_definitions()[0]["input_schema"]+ self.assertEqual(schema["properties"]["city"]["enum"], ["Shanghai"])++ def test_stream_order_rejects_lifecycle_violation(self) -> None:+ ordered = [+ {+ "kind": "event",+ "sequence": 0,+ "type": "message_start",+ "event": {+ "type": "message_start",+ "message": {+ "type": "message",+ "role": "assistant",+ "content": [],+ "usage": _anthropic_usage(),+ "stop_reason": None,+ "stop_sequence": None,+ },+ },+ },+ {+ "kind": "event",+ "sequence": 1,+ "type": "content_block_start",+ "event": {+ "type": "content_block_start",+ "index": 0,+ "content_block": {"type": "text", "text": ""},+ },+ },+ {+ "kind": "event",+ "sequence": 2,+ "type": "content_block_delta",+ "event": {+ "type": "content_block_delta",+ "index": 0,+ "delta": {"type": "text_delta", "text": "ok"},+ },+ },+ {"kind": "event", "sequence": 3, "type": "content_block_stop", "event": {"type": "content_block_stop", "index": 0}},+ {+ "kind": "event",+ "sequence": 4,+ "type": "message_delta",+ "event": {+ "type": "message_delta",+ "delta": {"stop_reason": "end_turn", "stop_sequence": None},+ "usage": {"output_tokens": 1},+ },+ },+ {"kind": "event", "sequence": 5, "type": "message_stop", "event": {"type": "message_stop"}},+ ]+ invalid = [ordered[2], ordered[0], ordered[3], ordered[4], ordered[5]]+ self.assertTrue(probe._stream_order_ok("anthropic", ordered))+ self.assertFalse(probe._stream_order_ok("anthropic", invalid))++ def test_anthropic_stream_rejects_overlapping_content_blocks(self) -> None:+ events = [+ {"kind": "event", "sequence": 0, "type": "message_start", "event": {"type": "message_start", "message": {"type": "message", "role": "assistant", "content": [], "stop_reason": None, "stop_sequence": None}}},+ {"kind": "event", "sequence": 1, "type": "content_block_start", "event": {"type": "content_block_start", "index": 0}},+ {"kind": "event", "sequence": 2, "type": "content_block_start", "event": {"type": "content_block_start", "index": 1}},+ {"kind": "event", "sequence": 3, "type": "content_block_stop", "event": {"type": "content_block_stop", "index": 0}},+ {"kind": "event", "sequence": 4, "type": "content_block_stop", "event": {"type": "content_block_stop", "index": 1}},+ {"kind": "event", "sequence": 5, "type": "message_stop", "event": {"type": "message_stop"}},+ ]+ self.assertFalse(probe._stream_order_ok("anthropic", events))++ def test_anthropic_message_delta_requires_started_closed_message(self) -> None:+ before_start = [+ {"kind": "event", "sequence": 0, "type": "message_delta", "event": {"type": "message_delta", "delta": {"stop_reason": "end_turn"}}},+ {"kind": "event", "sequence": 1, "type": "message_start", "event": {"type": "message_start"}},+ {"kind": "event", "sequence": 2, "type": "message_stop", "event": {"type": "message_stop"}},+ ]+ while_open = [+ {"kind": "event", "sequence": 0, "type": "message_start", "event": {"type": "message_start"}},+ {"kind": "event", "sequence": 1, "type": "content_block_start", "event": {"type": "content_block_start", "index": 0}},+ {"kind": "event", "sequence": 2, "type": "message_delta", "event": {"type": "message_delta", "delta": {"stop_reason": "end_turn"}}},+ {"kind": "event", "sequence": 3, "type": "content_block_stop", "event": {"type": "content_block_stop", "index": 0}},+ {"kind": "event", "sequence": 4, "type": "message_stop", "event": {"type": "message_stop"}},+ ]+ self.assertFalse(probe._stream_order_ok("anthropic", before_start))+ self.assertFalse(probe._stream_order_ok("anthropic", while_open))++ def test_anthropic_message_stop_requires_prior_message_delta(self) -> None:+ events = [+ {+ "kind": "event",+ "sequence": 0,+ "type": "message_start",+ "event": {+ "type": "message_start",+ "message": {+ "type": "message",+ "role": "assistant",+ "content": [],+ "stop_reason": None,+ "stop_sequence": None,+ },+ },+ },+ {+ "kind": "event",+ "sequence": 1,+ "type": "message_stop",+ "event": {"type": "message_stop"},+ },+ ]+ self.assertFalse(probe._stream_order_ok("anthropic", events))+ turn = probe._parse_anthropic_stream(+ probe.TransportResult(200, None, events, True, 0, False)+ )+ self.assertIn("message_delta_missing", turn.parse_errors)++ def test_anthropic_error_event_invalidates_stream(self) -> None:+ events = [+ {"kind": "event", "sequence": 0, "type": "message_start", "event": {"type": "message_start"}},+ {"kind": "event", "sequence": 1, "type": "error", "event": {"type": "error", "error": {"type": "overloaded_error"}}},+ {"kind": "event", "sequence": 2, "type": "message_stop", "event": {"type": "message_stop"}},+ ]+ self.assertFalse(probe._stream_order_ok("anthropic", events))+ turn = probe._parse_anthropic_stream(probe.TransportResult(200, None, events, True, 0, False))+ self.assertIn("stream_error_event", turn.parse_errors)++ def test_anthropic_stream_rejects_unknown_event_types(self) -> None:+ events = [+ {+ "kind": "event",+ "sequence": 0,+ "type": "message_start",+ "event": {+ "type": "message_start",+ "message": {+ "type": "message",+ "role": "assistant",+ "content": [],+ "stop_reason": None,+ "stop_sequence": None,+ },+ },+ },+ {"kind": "event", "sequence": 1, "type": "future_bogus", "event": {"type": "future_bogus"}},+ {"kind": "event", "sequence": 2, "type": "message_stop", "event": {"type": "message_stop"}},+ ]+ self.assertFalse(probe._stream_order_ok("anthropic", events))+ turn = probe._parse_anthropic_stream(probe.TransportResult(200, None, events, False, 0, False))+ self.assertIn("stream_event_unknown", turn.parse_errors)++ def test_anthropic_stream_rejects_done_sentinel(self) -> None:+ events = [+ {"kind": "event", "sequence": 0, "type": "message_start", "event": {"type": "message_start"}},+ {"kind": "done", "sequence": 1, "type": None},+ {"kind": "event", "sequence": 2, "type": "message_stop", "event": {"type": "message_stop"}},+ ]+ self.assertFalse(probe._stream_order_ok("anthropic", events))++ def test_anthropic_stream_rejects_content_after_message_delta(self) -> None:+ events = [+ {"kind": "event", "sequence": 0, "type": "message_start", "event": {"type": "message_start"}},+ {"kind": "event", "sequence": 1, "type": "message_delta", "event": {"type": "message_delta", "delta": {"stop_reason": "tool_use"}}},+ {"kind": "event", "sequence": 2, "type": "content_block_start", "event": {"type": "content_block_start", "index": 0, "content_block": {"type": "text"}}},+ {"kind": "event", "sequence": 3, "type": "message_stop", "event": {"type": "message_stop"}},+ ]+ self.assertFalse(probe._stream_order_ok("anthropic", events))++ def test_responses_failure_event_invalidates_stream(self) -> None:+ events = [+ {"kind": "event", "sequence": 0, "type": "response.created", "event": {"type": "response.created", "response": {"object": "response", "status": "in_progress", "output": []}}},+ {"kind": "event", "sequence": 1, "type": "response.failed", "event": {"type": "response.failed", "response": {"status": "failed"}}},+ {"kind": "event", "sequence": 2, "type": "response.completed", "event": {"type": "response.completed", "response": {"status": "completed", "output": []}}},+ ]+ self.assertFalse(probe._stream_order_ok("responses", events))+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, events, True, 0, False))+ self.assertIn("stream_failure_event", turn.parse_errors)++ def test_responses_stream_rejects_delta_before_item_creation(self) -> None:+ events = [+ {"kind": "event", "sequence": 0, "type": "response.created", "event": {"type": "response.created", "response": {}}},+ {"kind": "event", "sequence": 1, "type": "response.output_text.delta", "event": {"type": "response.output_text.delta", "item_id": "msg_1", "delta": "early"}},+ {"kind": "event", "sequence": 2, "type": "response.output_item.added", "event": {"type": "response.output_item.added", "item": {"id": "msg_1", "type": "message"}}},+ {"kind": "event", "sequence": 3, "type": "response.output_item.done", "event": {"type": "response.output_item.done", "item": {"id": "msg_1", "type": "message"}}},+ {"kind": "event", "sequence": 4, "type": "response.completed", "event": {"type": "response.completed", "response": {"status": "completed"}}},+ ]+ self.assertFalse(probe._stream_order_ok("responses", events))++ def test_responses_stream_preserves_reasoning_delta_signal(self) -> None:+ events = [+ {"kind": "event", "type": "response.output_item.added", "event": {"type": "response.output_item.added", "item": {"id": "rs_1", "type": "reasoning"}}},+ {"kind": "event", "type": "response.reasoning_summary_text.delta", "event": {"type": "response.reasoning_summary_text.delta", "item_id": "rs_1", "delta": "summary"}},+ {"kind": "event", "type": "response.output_item.done", "event": {"type": "response.output_item.done", "item": {"id": "rs_1", "type": "reasoning", "summary": [{"type": "summary_text", "text": "summary"}]}}},+ ]+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, events, True, 0))+ self.assertTrue(turn.reasoning_present)+ self.assertEqual(turn.reasoning_text, "summary")++ def test_responses_stream_compares_reasoning_snapshot_to_delta(self) -> None:+ events = [+ {"kind": "event", "type": "response.output_item.added", "event": {"type": "response.output_item.added", "item": {"id": "rs_1", "type": "reasoning"}}},+ {"kind": "event", "type": "response.reasoning_summary_text.delta", "event": {"type": "response.reasoning_summary_text.delta", "item_id": "rs_1", "delta": "delta"}},+ {"kind": "event", "type": "response.output_item.done", "event": {"type": "response.output_item.done", "item": {"id": "rs_1", "type": "reasoning", "summary": [{"type": "summary_text", "text": "snapshot"}]} }},+ ]+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, events, False, 0))+ self.assertIn("stream_reasoning_snapshot_mismatch", turn.parse_errors)++ def test_responses_stream_matches_terminal_output_snapshot(self) -> None:+ events = [+ {"kind": "event", "event": {"type": "response.output_item.added", "item": {"id": "fc_1", "type": "function_call", "call_id": "call_1", "name": "lookup_weather"}}},+ {"kind": "event", "event": {"type": "response.function_call_arguments.delta", "item_id": "fc_1", "delta": '{"city":"Shanghai"}'}},+ {"kind": "event", "event": {"type": "response.output_item.done", "item": {"id": "fc_1", "type": "function_call", "call_id": "call_1", "name": "lookup_weather", "arguments": '{"city":"Shanghai"}'}}},+ {"kind": "event", "event": {"type": "response.completed", "response": {"status": "completed", "output": [{"id": "fc_1", "type": "function_call", "call_id": "call_2", "name": "lookup_weather", "arguments": '{"city":"Shanghai"}'}]}}},+ ]+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, events, True, 0))+ self.assertIn("terminal_output_mismatch", turn.parse_errors)++ def test_responses_stream_matches_delta_to_item_type(self) -> None:+ events = [+ {"kind": "event", "sequence": 0, "type": "response.created", "event": {"type": "response.created", "response": {}}},+ {"kind": "event", "sequence": 1, "type": "response.output_item.added", "event": {"type": "response.output_item.added", "item": {"id": "fc_1", "type": "function_call"}}},+ {"kind": "event", "sequence": 2, "type": "response.reasoning_summary_text.delta", "event": {"type": "response.reasoning_summary_text.delta", "item_id": "fc_1", "delta": "wrong"}},+ ]+ self.assertFalse(probe._stream_order_ok("responses", events))+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, events, True, 0, False))+ self.assertIn("stream_delta_item_type_mismatch", turn.parse_errors)++ def test_responses_stream_rejects_malformed_item_snapshot(self) -> None:+ events = [+ {"kind": "event", "sequence": 0, "type": "response.created", "event": {"type": "response.created", "response": {}}},+ {"kind": "event", "sequence": 1, "type": "response.output_item.added", "event": {"type": "response.output_item.added", "item": None}},+ ]+ self.assertFalse(probe._stream_order_ok("responses", events))+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, events, False, 0, False))+ self.assertIn("output_item_invalid", turn.parse_errors)++ def test_responses_stream_requires_opening_and_terminal_envelopes(self) -> None:+ missing_opening = [+ {"kind": "event", "sequence": 0, "type": "response.output_item.added", "event": {"type": "response.output_item.added", "item": {"id": "msg_1", "type": "message"}}},+ {"kind": "event", "sequence": 1, "type": "response.output_item.done", "event": {"type": "response.output_item.done", "item": {"id": "msg_1", "type": "message"}}},+ {"kind": "event", "sequence": 2, "type": "response.completed", "event": {"type": "response.completed", "response": {"status": "completed"}}},+ ]+ missing_terminal_response = [+ {"kind": "event", "sequence": 0, "type": "response.created", "event": {"type": "response.created", "response": {}}},+ {"kind": "event", "sequence": 1, "type": "response.completed", "event": {"type": "response.completed"}},+ ]+ self.assertFalse(probe._stream_order_ok("responses", missing_opening))+ self.assertFalse(probe._stream_order_ok("responses", missing_terminal_response))++ def test_responses_stream_in_progress_snapshot_requires_object(self) -> None:+ for response in (+ [],+ {"object": "other", "status": "in_progress", "output": []},+ {"object": "response", "status": "completed", "output": []},+ {"object": "response", "status": "in_progress", "output": [{"id": "msg_1"}]},+ ):+ events = _response_message_stream()+ events.insert(1, {"kind": "event", "type": "response.in_progress", "event": {"type": "response.in_progress", "response": response}})+ for index, event in enumerate(events):+ event["sequence"] = index+ event["wire_sequence"] = index+ event["event"]["sequence_number"] = index+ self.assertFalse(probe._stream_order_ok("responses", events))+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, events, False, 0, False))+ self.assertIn("response_in_progress_snapshot_invalid", turn.parse_errors)++ def test_responses_stream_in_progress_snapshot_preserves_response_id(self) -> None:+ valid = _response_message_stream()+ valid[0]["event"]["response"]["id"] = "resp_1"+ valid.insert(+ 1,+ {+ "kind": "event",+ "type": "response.in_progress",+ "event": {+ "type": "response.in_progress",+ "response": {"id": "resp_1", "object": "response", "status": "in_progress", "output": []},+ },+ },+ )+ valid[-1]["event"]["response"]["id"] = "resp_1"+ for index, event in enumerate(valid):+ event["sequence"] = index+ event["wire_sequence"] = index+ event["event"]["sequence_number"] = index+ self.assertTrue(probe._stream_order_ok("responses", valid))+ valid_turn = probe._parse_responses_stream(probe.TransportResult(200, None, valid, False, 0, False))+ self.assertNotIn("response_in_progress_id_invalid", valid_turn.parse_errors)++ missing = copy.deepcopy(valid)+ missing[1]["event"]["response"].pop("id")+ self.assertFalse(probe._stream_order_ok("responses", missing))+ missing_turn = probe._parse_responses_stream(probe.TransportResult(200, None, missing, False, 0, False))+ self.assertIn("response_in_progress_id_invalid", missing_turn.parse_errors)++ def test_responses_stream_rejects_duplicate_in_progress_snapshot(self) -> None:+ events = _response_message_stream()+ events[0]["event"]["response"]["id"] = "resp_1"+ in_progress = {+ "kind": "event",+ "type": "response.in_progress",+ "event": {+ "type": "response.in_progress",+ "response": {+ "id": "resp_1",+ "object": "response",+ "status": "in_progress",+ "output": [],+ },+ },+ }+ events[1:1] = [copy.deepcopy(in_progress), copy.deepcopy(in_progress)]+ events[-1]["event"]["response"]["id"] = "resp_1"+ for index, event in enumerate(events):+ event["sequence"] = index+ event["wire_sequence"] = index+ self.assertFalse(probe._stream_order_ok("responses", events))+ turn = probe._parse_responses_stream(+ probe.TransportResult(200, None, events, False, 0, False)+ )+ self.assertIn("response_in_progress_duplicate", turn.parse_errors)++ def test_responses_stream_rejects_invalid_terminal_discriminator(self) -> None:+ events = _response_message_stream()+ events[-1]["event"]["response"]["object"] = "other"+ self.assertFalse(probe._stream_order_ok("responses", events))+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, events, False, 0, False))+ self.assertIn("response_object_invalid", turn.parse_errors)++ def test_responses_stream_rejects_text_after_content_part_done(self) -> None:+ events = _response_message_stream()+ events[3], events[5] = events[5], events[3]+ for index, event in enumerate(events):+ event["sequence"] = index+ event["wire_sequence"] = index+ self.assertFalse(probe._stream_order_ok("responses", events))+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, events, False, 0, False))+ self.assertIn("stream_text_after_content_part_done", turn.parse_errors)++ def test_responses_stream_rejects_terminal_only_function_calls(self) -> None:+ events = [+ {"kind": "event", "type": "response.created", "event": {"type": "response.created", "response": {}}},+ {"kind": "event", "type": "response.completed", "event": {"type": "response.completed", "response": {"status": "completed", "output": [{"type": "function_call", "id": "fc_1", "call_id": "call_1", "name": "lookup_weather", "arguments": '{"city":"Shanghai"}' }]}}},+ ]+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, events, False, 0))+ self.assertIn("stream_arguments_missing", turn.parse_errors)++ def test_anthropic_reasoning_blocks_require_payload(self) -> None:+ thinking = probe._parse_anthropic_document(+ {"content": [{"type": "thinking", "thinking": "", "signature": "sig"}], "stop_reason": "tool_use"}+ )+ redacted = probe._parse_anthropic_document(+ {"content": [{"type": "redacted_thinking", "data": ""}], "stop_reason": "tool_use"}+ )+ self.assertFalse(thinking.reasoning_present)+ self.assertIn("thinking_payload_missing", thinking.parse_errors)+ self.assertFalse(redacted.reasoning_present)+ self.assertIn("redacted_thinking_payload_missing", redacted.parse_errors)++ def test_anthropic_stream_rejects_delta_block_type_mismatch(self) -> None:+ events = [+ {"kind": "event", "type": "content_block_start", "event": {"type": "content_block_start", "index": 0, "content_block": {"type": "tool_use", "id": "call_1", "name": "lookup_weather"}}},+ {"kind": "event", "type": "content_block_delta", "event": {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "wrong"}}},+ ]+ turn = probe._parse_anthropic_stream(probe.TransportResult(200, None, events, True, 0))+ self.assertIn("stream_delta_block_type_mismatch", turn.parse_errors)++ def test_chat_stream_requires_assistant_role(self) -> None:+ invalid = [+ {"kind": "event", "type": None, "event": {"object": "chat.completion.chunk", "choices": [{"delta": {"role": "user"}}]}},+ {"kind": "event", "type": None, "event": {"object": "chat.completion.chunk", "choices": [{"delta": {}, "finish_reason": "stop"}]}},+ {"kind": "done", "type": None},+ ]+ turn = probe._parse_chat_stream(probe.TransportResult(200, None, invalid, True, 0))+ self.assertIn("assistant_role_invalid", turn.parse_errors)++ def test_chat_stream_requires_one_assistant_role_before_payload(self) -> None:+ valid = [+ {"kind": "event", "sequence": 0, "type": None, "event": {"id": "chatcmpl_1", "object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {"role": "assistant", "content": "ok"}}]}},+ {"kind": "event", "sequence": 1, "type": None, "event": {"id": "chatcmpl_1", "object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}},+ {"kind": "done", "sequence": 2, "type": None},+ ]+ late = copy.deepcopy(valid)+ late[0]["event"]["choices"][0]["delta"].pop("role")+ late[1]["event"]["choices"][0]["delta"]["role"] = "assistant"+ duplicate = copy.deepcopy(valid)+ duplicate[1]["event"]["choices"][0]["delta"]["role"] = "assistant"+ changed = copy.deepcopy(valid)+ changed[1]["event"]["choices"][0]["delta"]["role"] = "user"++ self.assertTrue(probe._stream_order_ok("chat", valid))+ for events, expected in (+ (late, {"assistant_role_before_payload_missing", "assistant_role_late"}),+ (duplicate, {"assistant_role_duplicate"}),+ (changed, {"assistant_role_invalid"}),+ ):+ self.assertFalse(probe._stream_order_ok("chat", events))+ turn = probe._parse_chat_stream(probe.TransportResult(200, None, events, True, 0, False))+ self.assertTrue(expected.issubset(turn.parse_errors))++ def test_chat_stream_rejects_malformed_delta(self) -> None:+ events = [+ {"kind": "event", "type": None, "event": {"object": "chat.completion.chunk", "choices": [{"index": 0, "delta": None}]}},+ ]+ turn = probe._parse_chat_stream(probe.TransportResult(200, None, events, True, 0))+ self.assertIn("delta_invalid", turn.parse_errors)++ missing = copy.deepcopy(events)+ missing[0]["event"]["choices"][0].pop("delta")+ self.assertFalse(probe._stream_order_ok("chat", missing))+ missing_turn = probe._parse_chat_stream(probe.TransportResult(200, None, missing, True, 0))+ self.assertIn("delta_missing", missing_turn.parse_errors)++ def test_chat_stream_rejects_choice_index_change(self) -> None:+ events = [+ {"kind": "event", "sequence": 0, "type": None, "event": {"object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {"role": "assistant", "content": "a"}}]}},+ {"kind": "event", "sequence": 1, "type": None, "event": {"object": "chat.completion.chunk", "choices": [{"index": 1, "delta": {"content": "b"}, "finish_reason": "stop"}]}},+ {"kind": "done", "sequence": 2, "type": None},+ ]+ self.assertFalse(probe._stream_order_ok("chat", events))+ turn = probe._parse_chat_stream(probe.TransportResult(200, None, events, True, 0, False))+ self.assertIn("choice_index_invalid", turn.parse_errors)++ def test_chat_stream_order_rejects_content_after_finish(self) -> None:+ allowed = [+ {"kind": "event", "sequence": 0, "event": {"id": "chatcmpl_1", "object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {"role": "assistant"}, "finish_reason": "tool_calls"}]}},+ {"kind": "event", "sequence": 1, "event": {"id": "chatcmpl_1", "object": "chat.completion.chunk", "choices": [], "usage": {"completion_tokens": 1}}},+ {"kind": "done", "sequence": 2},+ ]+ invalid = [+ allowed[0],+ {"kind": "event", "sequence": 1, "event": {"id": "chatcmpl_1", "object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {"content": "late"}}]}},+ {"kind": "done", "sequence": 2},+ ]+ self.assertTrue(probe._stream_order_ok("chat", allowed))+ self.assertFalse(probe._stream_order_ok("chat", invalid))++ def test_protocol_stop_reasons_are_required(self) -> None:+ first = probe._parse_chat_document({"choices": [{"message": {"tool_calls": []}, "finish_reason": "stop"}]})+ projection = probe._validate_first(first, ("lookup_weather",), stream=False)+ self.assertFalse(projection["checks"]["stop_reason"])++ def test_system_scope_rejects_user_conflict_marker(self) -> None:+ second = probe._parse_anthropic_document(+ {"content": [{"type": "text", "text": f"{probe.SYSTEM_MARKER} {probe.SYSTEM_SCOPE_OK} {probe.USER_SCOPE_LEAK} WEATHER_OK"}], "stop_reason": "end_turn"}+ )+ projection = probe._validate_second(second, ("lookup_weather",), stream=False)+ self.assertFalse(projection["checks"]["system_scope"])++ def test_reasoning_text_must_not_be_visible(self) -> None:+ turn = probe._parse_anthropic_document(+ {+ "content": [+ {"type": "thinking", "thinking": "PRIVATE_REASONING", "signature": "sig"},+ {"type": "tool_use", "id": "call_1", "name": "lookup_weather", "input": {"city": "Shanghai"}},+ {"type": "text", "text": "PRIVATE_REASONING"},+ ],+ "stop_reason": "tool_use",+ }+ )+ projection = probe._validate_first(turn, ("lookup_weather",), stream=False)+ self.assertFalse(projection["checks"]["reasoning_not_visible"])++ def test_partial_reasoning_excerpts_must_not_be_visible(self) -> None:+ first = probe._parse_anthropic_document(+ {+ "content": [+ {+ "type": "thinking",+ "thinking": "internal chain of thought",+ "signature": "PRIVATE_SIGNATURE_PAYLOAD",+ },+ {+ "type": "tool_use",+ "id": "call_1",+ "name": "lookup_weather",+ "input": {"city": "Shanghai"},+ },+ {"type": "text", "text": "INTERNAL CHAIN"},+ ],+ "stop_reason": "tool_use",+ }+ )+ first_projection = probe._validate_first(first, ("lookup_weather",), stream=False)+ self.assertFalse(first_projection["checks"]["reasoning_not_visible"])++ second = probe._parse_anthropic_document(+ {+ "content": [{"type": "text", "text": "private_signa"}],+ "stop_reason": "end_turn",+ }+ )+ second_projection = probe._validate_second(+ second,+ (),+ stream=False,+ prior_reasoning_parts=first.reasoning_parts,+ )+ self.assertFalse(second_projection["checks"]["reasoning_not_visible"])++ def test_short_common_reasoning_overlap_is_not_treated_as_leakage(self) -> None:+ turn = probe._parse_anthropic_document(+ {+ "content": [+ {+ "type": "thinking",+ "thinking": "Need weather data for Shanghai before calling the requested tool",+ "signature": "sig",+ },+ {+ "type": "tool_use",+ "id": "call_1",+ "name": "lookup_weather",+ "input": {"city": "Shanghai"},+ },+ {"type": "text", "text": "Shanghai"},+ ],+ "stop_reason": "tool_use",+ }+ )+ projection = probe._validate_first(turn, ("lookup_weather",), stream=False)+ self.assertTrue(projection["checks"]["reasoning_not_visible"])++ def test_opaque_reasoning_payloads_must_not_be_visible(self) -> None:+ signature = probe._parse_anthropic_document(+ {+ "type": "message",+ "role": "assistant",+ "content": [+ {"type": "thinking", "thinking": "PRIVATE_THOUGHT", "signature": "PRIVATE_SIGNATURE"},+ {"type": "tool_use", "id": "call_1", "name": "lookup_weather", "input": {"city": "Shanghai"}},+ {"type": "text", "text": "PRIVATE_SIGNATURE"},+ ],+ "stop_reason": "tool_use",+ }+ )+ self.assertEqual(signature.reasoning_text, "PRIVATE_THOUGHT")+ self.assertFalse(+ probe._validate_first(signature, ("lookup_weather",), stream=False)["checks"]["reasoning_not_visible"]+ )++ redacted = probe._parse_anthropic_document(+ {+ "type": "message",+ "role": "assistant",+ "content": [+ {"type": "redacted_thinking", "data": "PRIVATE_REDACTED"},+ {"type": "tool_use", "id": "call_1", "name": "lookup_weather", "input": {"city": "Shanghai"}},+ {"type": "text", "text": "PRIVATE_REDACTED"},+ ],+ "stop_reason": "tool_use",+ }+ )+ self.assertFalse(+ probe._validate_first(redacted, ("lookup_weather",), stream=False)["checks"]["reasoning_not_visible"]+ )++ encrypted = probe._parse_responses_document(+ {+ "object": "response",+ "output": [+ {"id": "rs_1", "type": "reasoning", "encrypted_content": "PRIVATE_ENCRYPTED"},+ {+ "id": "msg_1",+ "type": "message",+ "role": "assistant",+ "content": [{"type": "output_text", "text": "PRIVATE_ENCRYPTED"}],+ },+ {+ "id": "fc_1",+ "type": "function_call",+ "call_id": "call_1",+ "name": "lookup_weather",+ "arguments": '{"city":"Shanghai"}',+ },+ ],+ "status": "completed",+ }+ )+ self.assertEqual(encrypted.reasoning_text, "")+ self.assertFalse(+ probe._validate_first(encrypted, ("lookup_weather",), stream=False)["checks"]["reasoning_not_visible"]+ )++ second = probe._parse_anthropic_document(+ {+ "type": "message",+ "role": "assistant",+ "content": [{"type": "text", "text": "PRIVATE_SIGNATURE"}],+ "stop_reason": "end_turn",+ }+ )+ self.assertFalse(+ probe._validate_second(+ second,+ (),+ stream=False,+ prior_reasoning_parts=signature.reasoning_parts,+ )["checks"]["reasoning_not_visible"]+ )++ def test_first_turn_rejects_premature_tool_output_evidence(self) -> None:+ for text in (+ "tool=lookup_weather;call_id=call_1;marker=WEATHER_OK",+ "WEATHER_OK",+ ):+ turn = probe._parse_anthropic_document(+ {+ "type": "message",+ "role": "assistant",+ "content": [+ {"type": "thinking", "thinking": "PRIVATE_THOUGHT", "signature": "sig"},+ {"type": "tool_use", "id": "call_1", "name": "lookup_weather", "input": {"city": "Shanghai"}},+ {"type": "text", "text": text},+ ],+ "stop_reason": "tool_use",+ }+ )+ projection = probe._validate_first(turn, ("lookup_weather",), stream=False)+ self.assertFalse(projection["checks"]["no_premature_tool_outputs"])++ def test_final_reasoning_text_must_not_be_visible(self) -> None:+ turn = probe._parse_responses_document(+ {+ "object": "response",+ "output": [+ {"type": "reasoning", "summary": [{"type": "summary_text", "text": "PRIVATE_REASONING"}]},+ {"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "PRIVATE_REASONING"}]},+ ],+ "status": "completed",+ }+ )+ projection = probe._validate_second(turn, (), stream=False)+ self.assertFalse(projection["checks"]["reasoning_not_visible"])++ def test_final_turn_requires_reasoning_signal(self) -> None:+ turn = probe._parse_anthropic_document(+ {"content": [{"type": "text", "text": f"{probe.SYSTEM_MARKER} {probe.SYSTEM_SCOPE_OK} WEATHER_OK"}], "stop_reason": "end_turn"}+ )+ projection = probe._validate_second(turn, (), stream=False)+ self.assertFalse(projection["checks"]["reasoning_present"])++ def test_each_reasoning_part_must_not_be_visible(self) -> None:+ turn = probe._parse_responses_document(+ {+ "output": [+ {+ "type": "reasoning",+ "summary": [+ {"type": "summary_text", "text": "SECRET_A"},+ {"type": "summary_text", "text": "SECRET_B"},+ ],+ },+ {"type": "message", "content": [{"type": "output_text", "text": "SECRET_A"}]},+ {"type": "function_call", "call_id": "call_1", "name": "lookup_weather", "arguments": '{"city":"Shanghai"}'},+ ],+ "status": "completed",+ }+ )+ projection = probe._validate_first(turn, ("lookup_weather",), stream=False)+ self.assertFalse(projection["checks"]["reasoning_not_visible"])++ def test_stream_gate_rejects_invalid_utf8_and_deadline(self) -> None:+ result = probe.TransportResult(200, None, [], False, 1, False, True)+ turn = probe._parse_turn("anthropic", result, stream=True)+ projection = probe._validate_first(turn, ("lookup_weather",), stream=True)+ self.assertFalse(projection["checks"]["parsed"])+ self.assertFalse(projection["checks"]["stream_order"])+ self.assertFalse(projection["checks"]["stream_deadline"])++ def test_stream_deadline_expires_while_partial_line_keeps_arriving(self) -> None:+ class Response:+ status = 200+ headers = {"Content-Type": "text/event-stream"}++ def __enter__(self):+ return self++ def __exit__(self, *args):+ return None++ def read(self, size: int) -> bytes:+ self.assert_size = size+ return b"x"++ class Opener:+ def open(self, request, timeout):+ return Response()++ original_opener = probe.OPENER+ original_timeout = probe.STREAM_TOTAL_TIMEOUT+ original_monotonic = probe.time.monotonic+ clock = [0.0]++ def monotonic() -> float:+ clock[0] += 0.02+ return clock[0]++ try:+ probe.OPENER = Opener()+ probe.STREAM_TOTAL_TIMEOUT = 0.03+ probe.time.monotonic = monotonic+ result = probe._request("/v1/messages", {}, client_protocol="anthropic", stream=True)+ finally:+ probe.OPENER = original_opener+ probe.STREAM_TOTAL_TIMEOUT = original_timeout+ probe.time.monotonic = original_monotonic+ self.assertTrue(result.deadline_expired)++ def test_exhausted_503_is_blocked_for_openai_targets(self) -> None:+ original_request = probe._request+ original_retries = probe.MAX_503_RETRIES+ try:+ probe.MAX_503_RETRIES = 1+ probe._request = lambda *args, **kwargs: probe.TransportResult(503, None, [], False, 0)+ result, _, blocked = probe._request_with_retries(+ probe.CaseSpec("capacity", "anthropic", "responses", "/v1/messages", False, False),+ {"model": "src/model"},+ "src/model",+ )+ finally:+ probe._request = original_request+ probe.MAX_503_RETRIES = original_retries+ self.assertEqual(result.status, 503)+ self.assertTrue(blocked)++ def test_fallback_use_is_reported_without_model_identity(self) -> None:+ original_request = probe._request+ original_retries = probe.MAX_503_RETRIES+ original_model = probe.MODELS["anthropic"]+ original_fallback = probe.ANTHROPIC_FALLBACK_MODEL+ calls = [0]++ def fake_request(*args, **kwargs):+ calls[0] += 1+ if calls[0] == 1:+ return probe.TransportResult(503, None, [], False, 0)+ if calls[0] == 2:+ return probe.TransportResult(+ 200,+ {"choices": [{"message": {"content": "", "reasoning_content": "r", "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "lookup_weather", "arguments": '{"city":"Shanghai"}'}}]}, "finish_reason": "tool_calls"}]},+ [],+ False,+ 0,+ )+ return probe.TransportResult(+ 200,+ {"choices": [{"message": {"content": f"{probe.SYSTEM_MARKER} {probe.SYSTEM_SCOPE_OK} WEATHER_OK"}, "finish_reason": "stop"}]},+ [],+ False,+ 0,+ )++ try:+ probe._request = fake_request+ probe.MAX_503_RETRIES = 1+ probe.MODELS["anthropic"] = "primary/model"+ probe.ANTHROPIC_FALLBACK_MODEL = "fallback/model"+ result = probe._run_case(probe.CaseSpec("fallback", "chat", "anthropic", "/v1/chat/completions", False, False))+ finally:+ probe._request = original_request+ probe.MAX_503_RETRIES = original_retries+ probe.MODELS["anthropic"] = original_model+ probe.ANTHROPIC_FALLBACK_MODEL = original_fallback+ self.assertTrue(result["fallback_used"])+ self.assertEqual(result["evidence_model_scope"], "fallback")+ projection = json.dumps(result)+ self.assertNotIn("primary/model", projection)+ self.assertNotIn("fallback/model", projection)++ def test_second_turn_model_substitution_is_blocked(self) -> None:+ original_request = probe._request+ original_retries = probe.MAX_503_RETRIES+ original_model = probe.MODELS["anthropic"]+ original_fallback = probe.ANTHROPIC_FALLBACK_MODEL+ calls = [0]++ def fake_request(*args, **kwargs):+ calls[0] += 1+ if calls[0] == 1:+ return probe.TransportResult(+ 200,+ {"choices": [{"message": {"content": "", "reasoning_content": "r", "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "lookup_weather", "arguments": '{"city":"Shanghai"}'}}]}, "finish_reason": "tool_calls"}]},+ [],+ False,+ 0,+ )+ if calls[0] == 2:+ return probe.TransportResult(503, None, [], False, 0)+ return probe.TransportResult(+ 200,+ {"choices": [{"message": {"content": f"{probe.SYSTEM_MARKER} {probe.SYSTEM_SCOPE_OK} WEATHER_OK"}, "finish_reason": "stop"}]},+ [],+ False,+ 0,+ )++ try:+ probe._request = fake_request+ probe.MAX_503_RETRIES = 1+ probe.MODELS["anthropic"] = "primary/model"+ probe.ANTHROPIC_FALLBACK_MODEL = "fallback/model"+ result = probe._run_case(probe.CaseSpec("mixed", "chat", "anthropic", "/v1/chat/completions", False, False))+ finally:+ probe._request = original_request+ probe.MAX_503_RETRIES = original_retries+ probe.MODELS["anthropic"] = original_model+ probe.ANTHROPIC_FALLBACK_MODEL = original_fallback+ self.assertEqual(result["blocked"], "model changed between turns")+ self.assertEqual(result["evidence_model_scope"], "mixed")++ def test_responses_text_done_must_match_reconstructed_text(self) -> None:+ for event_type, item_type in (+ ("response.output_text", "message"),+ ("response.reasoning_summary_text", "reasoning"),+ ):+ events = [+ {"kind": "event", "event": {"type": "response.output_item.added", "item": {"id": "item_1", "type": item_type, "role": "assistant"}}},+ {"kind": "event", "event": {"type": f"{event_type}.delta", "item_id": "item_1", "content_index": 0, "delta": "delta"}},+ {"kind": "event", "event": {"type": f"{event_type}.done", "item_id": "item_1", "content_index": 0, "text": "different"}},+ ]+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, events, False, 0))+ self.assertIn("stream_text_done_mismatch", turn.parse_errors)++ def test_streamed_chat_content_requires_string_or_null(self) -> None:+ events = [+ {"kind": "event", "event": {"object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {"role": "assistant", "content": {"text": probe.SYSTEM_MARKER}}}]}},+ {"kind": "event", "event": {"object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}},+ {"kind": "done"},+ ]+ turn = probe._parse_chat_stream(probe.TransportResult(200, None, events, True, 0, True))+ self.assertIn("stream_content_invalid", turn.parse_errors)++ def test_anthropic_text_blocks_require_strings(self) -> None:+ turn = probe._parse_anthropic_document(+ {+ "type": "message",+ "role": "assistant",+ "content": [{"type": "text", "text": {"marker": probe.SYSTEM_MARKER}}],+ "stop_reason": "end_turn",+ }+ )+ self.assertIn("text_block_invalid", turn.parse_errors)++ def test_responses_done_message_content_requires_list(self) -> None:+ events = [+ {"kind": "event", "event": {"type": "response.output_item.added", "item": {"id": "msg_1", "type": "message", "role": "assistant"}}},+ {"kind": "event", "event": {"type": "response.output_item.done", "item": {"id": "msg_1", "type": "message", "role": "assistant", "content": None}}},+ ]+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, events, False, 0))+ self.assertIn("message_content_invalid", turn.parse_errors)++ def test_chat_tool_calls_require_list(self) -> None:+ turn = probe._parse_chat_document(+ {"choices": [{"index": 0, "message": {"role": "assistant", "content": "", "tool_calls": None}, "finish_reason": "stop"}]}+ )+ self.assertIn("tool_calls_invalid", turn.parse_errors)++ def test_anthropic_message_delta_requires_object(self) -> None:+ events = [+ {"kind": "event", "sequence": 0, "type": "message_start", "event": {"type": "message_start"}},+ {"kind": "event", "sequence": 1, "type": "message_delta", "event": {"type": "message_delta", "delta": None}},+ {"kind": "event", "sequence": 2, "type": "message_stop", "event": {"type": "message_stop"}},+ ]+ self.assertFalse(probe._stream_order_ok("anthropic", events))+ turn = probe._parse_anthropic_stream(probe.TransportResult(200, None, events, False, 0, False))+ self.assertIn("message_delta_invalid", turn.parse_errors)++ def test_responses_reject_done_sentinel(self) -> None:+ events = [+ {"kind": "event", "sequence": 0, "type": "response.created", "event": {"type": "response.created", "response": {}}},+ {"kind": "done", "sequence": 1},+ {"kind": "event", "sequence": 2, "type": "response.completed", "event": {"type": "response.completed", "response": {"status": "completed", "output": []}}},+ ]+ self.assertFalse(probe._stream_order_ok("responses", events))++ def test_responses_output_index_must_remain_consistent(self) -> None:+ events = [+ {"kind": "event", "sequence": 0, "type": "response.created", "event": {"type": "response.created", "response": {}}},+ {"kind": "event", "sequence": 1, "type": "response.output_item.added", "event": {"type": "response.output_item.added", "output_index": 0, "item": {"id": "msg_1", "type": "message"}}},+ {"kind": "event", "sequence": 2, "type": "response.output_text.delta", "event": {"type": "response.output_text.delta", "item_id": "msg_1", "output_index": 1, "delta": "text"}},+ ]+ self.assertFalse(probe._stream_order_ok("responses", events))++ def test_anthropic_tool_start_requires_empty_input_snapshot(self) -> None:+ events = [+ {"kind": "event", "event": {"type": "content_block_start", "index": 0, "content_block": {"type": "tool_use", "id": "call_1", "name": "lookup_weather", "input": {"city": "Paris"}}}},+ {"kind": "event", "event": {"type": "content_block_delta", "index": 0, "delta": {"type": "input_json_delta", "partial_json": '{"city":"Shanghai"}'}}},+ ]+ turn = probe._parse_anthropic_stream(probe.TransportResult(200, None, events, False, 0))+ self.assertIn("stream_tool_input_snapshot_invalid", turn.parse_errors)++ def test_final_markers_require_exact_tokens(self) -> None:+ call = probe.ToolCall("call_1", "lookup_weather", {"city": "Shanghai"})+ turn = probe._parse_anthropic_document(+ {+ "type": "message",+ "role": "assistant",+ "content": [+ {+ "type": "text",+ "text": (+ f"{probe.SYSTEM_MARKER}_BAD {probe.SYSTEM_SCOPE_OK}_BAD "+ "tool=lookup_weather;call_id=call_1;marker=WEATHER_OK_CORRUPTED"+ ),+ }+ ],+ "stop_reason": "end_turn",+ }+ )+ checks = probe._validate_second(turn, ("lookup_weather",), stream=False, expected_calls=[call])["checks"]+ self.assertFalse(checks["system_marker"])+ self.assertFalse(checks["system_scope"])+ self.assertFalse(checks["tool_outputs"])+ self.assertFalse(checks["tool_output_call_pairs"])++ def test_protocol_argument_wire_encodings_are_enforced(self) -> None:+ anthropic = probe._parse_anthropic_document(+ {+ "type": "message",+ "role": "assistant",+ "content": [{"type": "tool_use", "id": "call_1", "name": "lookup_weather", "input": '{"city":"Shanghai"}'}],+ "stop_reason": "tool_use",+ }+ )+ responses = probe._parse_responses_document(+ {"output": [{"type": "function_call", "call_id": "call_1", "name": "lookup_weather", "arguments": {"city": "Shanghai"}}], "status": "completed"}+ )+ chat = probe._parse_chat_document(+ {"choices": [{"index": 0, "message": {"role": "assistant", "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "lookup_weather", "arguments": {"city": "Shanghai"}}}]}, "finish_reason": "tool_calls"}]}+ )+ self.assertIn("arguments_not_object", anthropic.parse_errors)+ self.assertIn("arguments_not_json_string", responses.parse_errors)+ self.assertIn("arguments_not_json_string", chat.parse_errors)++ with tempfile.TemporaryDirectory() as temporary:+ store = EngineStateStore(Path(temporary) / "state")+ credential_ref = store.store_api_key(+ "test-key",+ vendor="custom",+ protocol=run_relay.CHAT_SOURCE_PROTOCOL,+ base_url="https://relay.invalid/v1",+ )+ binding = run_relay._binding(+ source_id="src_fidelitychat",+ vendor="custom",+ protocol=run_relay.CHAT_SOURCE_PROTOCOL,+ base_url="https://relay.invalid/v1",+ credential_ref=credential_ref,+ models=("test-model",),+ )+ self.assertEqual(binding.protocol, "openai_chat")++ def test_transient_encrypted_reasoning_is_not_retained(self) -> None:+ events = [+ {"kind": "event", "event": {"type": "response.output_item.added", "item": {"id": "rs_1", "type": "reasoning", "encrypted_content": "opaque"}}},+ {"kind": "event", "event": {"type": "response.output_item.done", "item": {"id": "rs_1", "type": "reasoning", "summary": []}}},+ ]+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, events, False, 0))+ self.assertFalse(turn.reasoning_present)++ def test_chat_usage_before_finish_is_rejected(self) -> None:+ events = [+ {"kind": "event", "sequence": 0, "event": {"object": "chat.completion.chunk", "choices": [], "usage": {"completion_tokens_details": {"reasoning_tokens": 1}}}},+ {"kind": "event", "sequence": 1, "event": {"object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {"role": "assistant"}, "finish_reason": "tool_calls"}]}},+ {"kind": "done", "sequence": 2},+ ]+ self.assertFalse(probe._stream_order_ok("chat", events))+ turn = probe._parse_chat_stream(probe.TransportResult(200, None, events, True, 0, False))+ self.assertIn("usage_before_finish", turn.parse_errors)+ self.assertFalse(turn.reasoning_present)++ def test_responses_done_function_snapshot_requires_arguments(self) -> None:+ for arguments in (None, {"city": "Shanghai"}):+ events = [+ {"kind": "event", "event": {"type": "response.output_item.added", "item": {"id": "fc_1", "type": "function_call"}}},+ {"kind": "event", "event": {"type": "response.function_call_arguments.delta", "item_id": "fc_1", "delta": '{"city":"Shanghai"}'}},+ {"kind": "event", "event": {"type": "response.output_item.done", "item": {"id": "fc_1", "type": "function_call", "arguments": arguments}}},+ ]+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, events, False, 0))+ self.assertIn("stream_arguments_snapshot_invalid", turn.parse_errors)++ def test_responses_function_call_requires_arguments_done_event(self) -> None:+ events = [+ {"kind": "event", "event": {"type": "response.output_item.added", "item": {"id": "fc_1", "type": "function_call"}}},+ {"kind": "event", "event": {"type": "response.function_call_arguments.delta", "item_id": "fc_1", "delta": '{"city":"Shanghai"}'}},+ {"kind": "event", "event": {"type": "response.output_item.done", "item": {"id": "fc_1", "type": "function_call", "arguments": '{"city":"Shanghai"}'}}},+ ]+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, events, False, 0))+ self.assertIn("stream_arguments_done_missing", turn.parse_errors)++ def test_responses_completed_requires_literal_status(self) -> None:+ for status in (None, "incomplete"):+ events = [+ {"kind": "event", "event": {"type": "response.completed", "response": {"status": status, "output": []}}},+ ]+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, events, False, 0))+ self.assertIn("terminal_status_invalid", turn.parse_errors)+ self.assertFalse(turn.terminal)++ def test_responses_wire_sequence_must_increase(self) -> None:+ events = _responses_wire(+ {"type": "response.created", "response": {}},+ {"type": "response.completed", "response": {"status": "completed", "output": []}},+ )+ events[1]["wire_sequence"] = 2+ self.assertTrue(probe._stream_order_ok("responses", events))+ duplicate = copy.deepcopy(events)+ duplicate[1]["wire_sequence"] = 0+ self.assertFalse(probe._stream_order_ok("responses", duplicate))++ def test_responses_content_part_done_must_match_text(self) -> None:+ events = [+ {"kind": "event", "event": {"type": "response.output_item.added", "item": {"id": "msg_1", "type": "message", "role": "assistant"}}},+ {"kind": "event", "event": {"type": "response.content_part.added", "item_id": "msg_1", "output_index": 0, "content_index": 0, "part": {"type": "output_text", "text": ""}}},+ {"kind": "event", "event": {"type": "response.output_text.delta", "item_id": "msg_1", "delta": "answer"}},+ {"kind": "event", "event": {"type": "response.content_part.done", "item_id": "msg_1", "output_index": 0, "content_index": 0, "part": {"type": "output_text", "text": "different"}}},+ ]+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, events, False, 0))+ self.assertIn("content_part_snapshot_mismatch", turn.parse_errors)++ def test_anthropic_block_indexes_must_be_contiguous(self) -> None:+ events = [+ {"kind": "event", "sequence": 0, "type": "message_start", "event": {"type": "message_start"}},+ {"kind": "event", "sequence": 1, "type": "content_block_start", "event": {"type": "content_block_start", "index": 5, "content_block": {"type": "text"}}},+ {"kind": "event", "sequence": 2, "type": "message_stop", "event": {"type": "message_stop"}},+ ]+ self.assertFalse(probe._stream_order_ok("anthropic", events))++ def test_chat_tool_indexes_must_be_contiguous(self) -> None:+ events = [+ {"kind": "event", "sequence": 0, "event": {"object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {"role": "assistant", "tool_calls": [{"index": 5, "id": "call_1", "type": "function", "function": {"name": "lookup_weather", "arguments": "{"}}]}}]}},+ {"kind": "event", "sequence": 1, "event": {"object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {"tool_calls": [{"index": 7, "id": "call_2", "type": "function", "function": {"name": "lookup_time", "arguments": "}"}}]}, "finish_reason": "tool_calls"}]}},+ {"kind": "done", "sequence": 2},+ ]+ self.assertFalse(probe._stream_order_ok("chat", events))++ def test_responses_duplicate_created_event_is_rejected(self) -> None:+ events = [+ {"kind": "event", "sequence": 0, "wire_sequence": 0, "type": "response.created", "event": {"type": "response.created", "response": {"id": "resp_1"}}},+ {"kind": "event", "sequence": 1, "wire_sequence": 1, "type": "response.created", "event": {"type": "response.created", "response": {"id": "resp_2"}}},+ ]+ self.assertFalse(probe._stream_order_ok("responses", events))++ def test_responses_text_events_require_matching_content_indexes(self) -> None:+ valid = _response_message_stream()+ sparse = _response_message_stream()+ for item in sparse:+ if "content_index" in item["event"]:+ item["event"]["content_index"] = 5+ mismatched = _response_message_stream()+ mismatched[3]["event"]["content_index"] = 1+ self.assertTrue(probe._stream_order_ok("responses", valid))+ self.assertFalse(probe._stream_order_ok("responses", sparse))+ self.assertFalse(probe._stream_order_ok("responses", mismatched))++ def test_responses_text_done_is_required_before_item_completion(self) -> None:+ valid_message = _response_message_stream()+ valid_reasoning = _response_reasoning_stream()+ message_events = _responses_wire(*(item["event"] for item in valid_message if item["type"] != "response.output_text.done"))+ reasoning_events = _responses_wire(*(item["event"] for item in valid_reasoning if item["type"] != "response.reasoning_summary_text.done"))+ self.assertTrue(probe._stream_order_ok("responses", valid_message))+ self.assertTrue(probe._stream_order_ok("responses", valid_reasoning))+ self.assertFalse(probe._stream_order_ok("responses", message_events))+ self.assertFalse(probe._stream_order_ok("responses", reasoning_events))++ def test_responses_stream_item_ids_must_be_nonempty_strings(self) -> None:+ invalid_added = _response_message_stream()+ invalid_added[1]["event"]["item"]["id"] = []+ invalid_done = _response_message_stream()+ invalid_done[6]["event"]["item"]["id"] = []+ self.assertFalse(probe._stream_order_ok("responses", invalid_added))+ self.assertFalse(probe._stream_order_ok("responses", invalid_done))+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, invalid_added, False, 0, False))+ self.assertIn("stream_item_id_invalid", turn.parse_errors)++ def test_responses_nonstream_status_must_be_a_string(self) -> None:+ for status in ([], {}):+ turn = probe._parse_responses_document({"output": [], "status": status})+ self.assertIn("status_invalid", turn.parse_errors)+ self.assertFalse(turn.terminal)++ def test_anthropic_stream_start_snapshots_require_strings(self) -> None:+ text_events = [+ {"kind": "event", "event": {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": []}}},+ {"kind": "event", "event": {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "answer"}}},+ ]+ thinking_events = [+ {"kind": "event", "event": {"type": "content_block_start", "index": 0, "content_block": {"type": "thinking", "thinking": {}, "signature": []}}},+ {"kind": "event", "event": {"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": "thought"}}},+ {"kind": "event", "event": {"type": "content_block_delta", "index": 0, "delta": {"type": "signature_delta", "signature": "sig"}}},+ ]+ text_turn = probe._parse_anthropic_stream(probe.TransportResult(200, None, text_events, False, 0))+ thinking_turn = probe._parse_anthropic_stream(probe.TransportResult(200, None, thinking_events, False, 0))+ self.assertIn("stream_text_snapshot_invalid", text_turn.parse_errors)+ self.assertIn("stream_thinking_snapshot_invalid", thinking_turn.parse_errors)+ self.assertIn("stream_signature_snapshot_invalid", thinking_turn.parse_errors)++ valid = [+ {"kind": "event", "sequence": 0, "type": "message_start", "event": {"type": "message_start", "message": {"id": "msg_1", "type": "message", "role": "assistant", "content": [], "usage": _anthropic_usage(), "stop_reason": None, "stop_sequence": None}}},+ {"kind": "event", "sequence": 1, "type": "content_block_start", "event": {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}},+ {"kind": "event", "sequence": 2, "type": "content_block_delta", "event": {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "answer"}}},+ {"kind": "event", "sequence": 3, "type": "content_block_stop", "event": {"type": "content_block_stop", "index": 0}},+ {"kind": "event", "sequence": 4, "type": "message_delta", "event": {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence": None}, "usage": {"output_tokens": 1}}},+ {"kind": "event", "sequence": 5, "type": "message_stop", "event": {"type": "message_stop"}},+ ]+ missing = copy.deepcopy(valid)+ missing[1]["event"]["content_block"].pop("text")+ self.assertTrue(probe._stream_order_ok("anthropic", valid))+ self.assertFalse(probe._stream_order_ok("anthropic", missing))+ missing_turn = probe._parse_anthropic_stream(probe.TransportResult(200, None, missing, False, 0, False))+ self.assertIn("stream_text_snapshot_missing", missing_turn.parse_errors)++ prefilled = copy.deepcopy(text_events)+ prefilled[0]["event"]["content_block"]["text"] = "answer"+ self.assertFalse(probe._stream_order_ok("anthropic", prefilled))+ prefilled_turn = probe._parse_anthropic_stream(probe.TransportResult(200, None, prefilled, False, 0))+ self.assertIn("stream_text_opening_snapshot_invalid", prefilled_turn.parse_errors)++ def test_responses_function_opening_arguments_must_be_empty(self) -> None:+ valid = _response_function_stream()+ invalid = copy.deepcopy(valid)+ invalid[1]["event"]["item"]["arguments"] = '{"city":"Paris"}'+ self.assertTrue(probe._stream_order_ok("responses", valid))+ self.assertFalse(probe._stream_order_ok("responses", invalid))+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, invalid, False, 0, False))+ self.assertIn("stream_arguments_opening_snapshot_invalid", turn.parse_errors)++ missing = copy.deepcopy(valid)+ missing[1]["event"]["item"].pop("arguments")+ self.assertFalse(probe._stream_order_ok("responses", missing))+ missing_turn = probe._parse_responses_stream(probe.TransportResult(200, None, missing, False, 0, False))+ self.assertIn("stream_arguments_snapshot_missing", missing_turn.parse_errors)++ def test_responses_output_item_opening_status_must_be_in_progress(self) -> None:+ invalid = _response_function_stream()+ invalid[1]["event"]["item"]["status"] = "failed"+ self.assertFalse(probe._stream_order_ok("responses", invalid))+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, invalid, False, 0, False))+ self.assertIn("stream_output_item_status_invalid", turn.parse_errors)++ valid = _response_function_stream()+ valid[1]["event"]["item"]["status"] = "in_progress"+ done = next(event for event in valid if event["type"] == "response.output_item.done")+ done["event"]["item"]["status"] = "completed"+ valid[-1]["event"]["response"]["output"][0]["status"] = "completed"+ self.assertTrue(probe._stream_order_ok("responses", valid))+ valid_turn = probe._parse_responses_stream(probe.TransportResult(200, None, valid, False, 0, False))+ self.assertNotIn("stream_output_item_status_invalid", valid_turn.parse_errors)++ missing_done_status = copy.deepcopy(valid)+ missing_done = next(+ event+ for event in missing_done_status+ if event["type"] == "response.output_item.done"+ )+ missing_done["event"]["item"].pop("status")+ self.assertFalse(probe._stream_order_ok("responses", missing_done_status))+ missing_turn = probe._parse_responses_stream(probe.TransportResult(200, None, missing_done_status, False, 0, False))+ self.assertIn("stream_output_item_status_invalid", missing_turn.parse_errors)++ def test_responses_message_opening_content_must_be_absent_or_empty(self) -> None:+ valid = _response_message_stream()+ self.assertTrue(probe._stream_order_ok("responses", valid))+ for opening_content in (None, [{"type": "output_text", "text": "prefilled"}], {"unexpected": True}):+ invalid = copy.deepcopy(valid)+ invalid[1]["event"]["item"]["content"] = opening_content+ self.assertFalse(probe._stream_order_ok("responses", invalid))+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, invalid, False, 0, False))+ self.assertIn("stream_message_opening_snapshot_invalid", turn.parse_errors)++ empty = copy.deepcopy(valid)+ empty[1]["event"]["item"]["content"] = []+ self.assertTrue(probe._stream_order_ok("responses", empty))++ def test_responses_stream_rejects_noncompleted_terminal_item_status(self) -> None:+ valid = _response_function_stream()+ done = next(event for event in valid if event["type"] == "response.output_item.done")+ done["event"]["item"]["status"] = "completed"+ valid[-1]["event"]["response"]["output"][0]["status"] = "completed"+ self.assertTrue(probe._stream_order_ok("responses", valid))+ valid_turn = probe._parse_responses_stream(probe.TransportResult(200, None, valid, False, 0, False))+ self.assertNotIn("terminal_output_item_status_invalid", valid_turn.parse_errors)++ invalid = copy.deepcopy(valid)+ invalid[-1]["event"]["response"]["output"][0]["status"] = "failed"+ self.assertFalse(probe._stream_order_ok("responses", invalid))+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, invalid, False, 0, False))+ self.assertIn("terminal_output_item_status_invalid", turn.parse_errors)+ self.assertIn("terminal_output_mismatch", turn.parse_errors)++ def test_responses_stream_requires_terminal_response_id(self) -> None:+ valid = _response_message_stream()+ valid[0]["event"]["response"]["id"] = "resp_1"+ valid[-1]["event"]["response"]["id"] = "resp_1"+ self.assertTrue(probe._stream_order_ok("responses", valid))+ valid_turn = probe._parse_responses_stream(probe.TransportResult(200, None, valid, False, 0, False))+ self.assertNotIn("terminal_response_id_invalid", valid_turn.parse_errors)++ missing = copy.deepcopy(valid)+ missing[-1]["event"]["response"].pop("id")+ self.assertFalse(probe._stream_order_ok("responses", missing))+ missing_turn = probe._parse_responses_stream(probe.TransportResult(200, None, missing, False, 0, False))+ self.assertIn("terminal_response_id_invalid", missing_turn.parse_errors)++ mismatched = copy.deepcopy(valid)+ mismatched[-1]["event"]["response"]["id"] = "resp_2"+ self.assertFalse(probe._stream_order_ok("responses", mismatched))+ mismatched_turn = probe._parse_responses_stream(probe.TransportResult(200, None, mismatched, False, 0, False))+ self.assertIn("terminal_response_id_invalid", mismatched_turn.parse_errors)++ def test_responses_stream_requires_created_response_id(self) -> None:+ valid = _response_message_stream()+ self.assertTrue(probe._stream_order_ok("responses", valid))++ for invalid_id in (None, ""):+ invalid = copy.deepcopy(valid)+ if invalid_id is None:+ invalid[0]["event"]["response"].pop("id")+ else:+ invalid[0]["event"]["response"]["id"] = invalid_id+ self.assertFalse(probe._stream_order_ok("responses", invalid))+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, invalid, False, 0, False))+ self.assertIn("response_id_invalid", turn.parse_errors)++ def test_responses_function_opening_snapshot_requires_identity(self) -> None:+ for field in ("call_id", "name"):+ invalid = _response_function_stream()+ invalid[1]["event"]["item"].pop(field)+ self.assertFalse(probe._stream_order_ok("responses", invalid))+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, invalid, False, 0, False))+ self.assertIn("stream_function_identity_invalid", turn.parse_errors)++ def test_responses_content_part_opening_text_must_be_empty(self) -> None:+ valid = _response_message_stream()+ self.assertTrue(probe._stream_order_ok("responses", valid))+ for opening_text in (None, "WRONG"):+ invalid = copy.deepcopy(valid)+ if opening_text is None:+ invalid[2]["event"]["part"].pop("text")+ else:+ invalid[2]["event"]["part"]["text"] = opening_text+ self.assertFalse(probe._stream_order_ok("responses", invalid))+ turn = probe._parse_responses_stream(+ probe.TransportResult(200, None, invalid, False, 0, False)+ )+ self.assertIn("content_part_opening_snapshot_invalid", turn.parse_errors)++ def test_responses_stream_preserves_multiple_content_parts(self) -> None:+ events = _response_multi_content_stream()+ self.assertTrue(probe._stream_order_ok("responses", events))+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, events, False, 0, True))+ self.assertNotIn("terminal_output_mismatch", turn.parse_errors)+ self.assertEqual(turn.text, "firstsecond")+ self.assertEqual(turn.continuation[0]["content"], [{"type": "output_text", "text": "first"}, {"type": "output_text", "text": "second"}])++ def test_responses_text_content_part_accepts_output_text_deltas(self) -> None:+ events = _response_message_stream()+ events[2]["event"]["part"]["type"] = "text"+ events[5]["event"]["part"]["type"] = "text"+ events[6]["event"]["item"]["content"][0]["type"] = "text"+ events[7]["event"]["response"]["output"][0]["content"][0]["type"] = "text"+ self.assertTrue(probe._stream_order_ok("responses", events))+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, events, False, 0, True))+ self.assertEqual(turn.text, "answer")+ self.assertEqual(turn.parse_errors, [])++ def test_responses_text_content_part_opening_text_must_be_empty(self) -> None:+ valid = [+ {"kind": "event", "type": "response.created", "event": {"type": "response.created", "response": {}}},+ {"kind": "event", "type": "response.output_item.added", "event": {"type": "response.output_item.added", "output_index": 0, "item": {"id": "msg_1", "type": "message", "role": "assistant"}}},+ {"kind": "event", "type": "response.content_part.added", "event": {"type": "response.content_part.added", "item_id": "msg_1", "output_index": 0, "content_index": 0, "part": {"type": "text", "text": ""}}},+ ]+ for opening_text in (None, "prefilled"):+ events = copy.deepcopy(valid)+ if opening_text is None:+ events[2]["event"]["part"].pop("text")+ else:+ events[2]["event"]["part"]["text"] = opening_text+ self.assertFalse(probe._stream_order_ok("responses", events))+ turn = probe._parse_responses_stream(+ probe.TransportResult(200, None, events, False, 0, False)+ )+ self.assertIn("content_part_opening_snapshot_invalid", turn.parse_errors)++ def test_responses_stream_rejects_unsupported_content_part_type(self) -> None:+ for part_type in ("future_part", []):+ invalid = _response_message_stream()+ invalid[2]["event"]["part"]["type"] = part_type+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, invalid, False, 0, False))+ self.assertFalse(probe._stream_order_ok("responses", invalid))+ self.assertIn("content_part_type_invalid", turn.parse_errors)++ def test_responses_stream_content_parts_match_item_snapshot(self) -> None:+ invalid = _response_message_stream()+ invalid[-1]["event"]["response"]["output"][0]["content"][0]["type"] = "text"+ self.assertFalse(probe._stream_order_ok("responses", invalid))+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, invalid, False, 0, False))+ self.assertIn("terminal_output_mismatch", turn.parse_errors)++ def test_responses_stream_rejects_unhashable_message_part_type(self) -> None:+ invalid = _response_message_stream()+ invalid[6]["event"]["item"]["content"][0]["type"] = []+ self.assertFalse(probe._stream_order_ok("responses", invalid))+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, invalid, False, 0, False))+ self.assertIn("message_part_type_invalid", turn.parse_errors)++ def test_anthropic_thinking_opening_snapshot_must_be_empty(self) -> None:+ valid = [+ {"kind": "event", "sequence": 0, "type": "message_start", "event": {"type": "message_start", "message": {"type": "message", "role": "assistant", "content": [], "usage": _anthropic_usage(), "stop_reason": None, "stop_sequence": None}}},+ {"kind": "event", "sequence": 1, "type": "content_block_start", "event": {"type": "content_block_start", "index": 0, "content_block": {"type": "thinking", "thinking": "", "signature": ""}}},+ {"kind": "event", "sequence": 2, "type": "content_block_delta", "event": {"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": "thought"}}},+ {"kind": "event", "sequence": 3, "type": "content_block_delta", "event": {"type": "content_block_delta", "index": 0, "delta": {"type": "signature_delta", "signature": "sig"}}},+ {"kind": "event", "sequence": 4, "type": "content_block_stop", "event": {"type": "content_block_stop", "index": 0}},+ {"kind": "event", "sequence": 5, "type": "message_delta", "event": {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence": None}, "usage": {"output_tokens": 1}}},+ {"kind": "event", "sequence": 6, "type": "message_stop", "event": {"type": "message_stop"}},+ ]+ invalid = copy.deepcopy(valid)+ invalid[1]["event"]["content_block"]["thinking"] = "prefilled"+ invalid[1]["event"]["content_block"]["signature"] = "sig"+ self.assertTrue(probe._stream_order_ok("anthropic", valid))+ self.assertFalse(probe._stream_order_ok("anthropic", invalid))+ turn = probe._parse_anthropic_stream(probe.TransportResult(200, None, invalid, False, 0, False))+ self.assertIn("stream_thinking_opening_snapshot_invalid", turn.parse_errors)+ self.assertIn("stream_signature_opening_snapshot_invalid", turn.parse_errors)+ for field in ("thinking", "signature"):+ missing = copy.deepcopy(valid)+ missing[1]["event"]["content_block"].pop(field)+ self.assertFalse(probe._stream_order_ok("anthropic", missing))+ missing_turn = probe._parse_anthropic_stream(+ probe.TransportResult(200, None, missing, False, 0, False)+ )+ self.assertIn(f"stream_{field}_snapshot_missing", missing_turn.parse_errors)++ def test_anthropic_stream_requires_split_argument_fragments(self) -> None:+ valid = [+ {+ "kind": "event",+ "sequence": 0,+ "type": "message_start",+ "event": {+ "type": "message_start",+ "message": {+ "type": "message",+ "role": "assistant",+ "content": [],+ "usage": _anthropic_usage(),+ "stop_reason": None,+ "stop_sequence": None,+ },+ },+ },+ {+ "kind": "event",+ "sequence": 1,+ "type": "content_block_start",+ "event": {+ "type": "content_block_start",+ "index": 0,+ "content_block": {+ "type": "tool_use",+ "id": "call_1",+ "name": "lookup_weather",+ "input": {},+ },+ },+ },+ {+ "kind": "event",+ "sequence": 2,+ "type": "content_block_delta",+ "event": {+ "type": "content_block_delta",+ "index": 0,+ "delta": {"type": "input_json_delta", "partial_json": '{"city":'},+ },+ },+ {+ "kind": "event",+ "sequence": 3,+ "type": "content_block_delta",+ "event": {+ "type": "content_block_delta",+ "index": 0,+ "delta": {+ "type": "input_json_delta",+ "partial_json": '"Shanghai"}',+ },+ },+ },+ {+ "kind": "event",+ "sequence": 4,+ "type": "content_block_stop",+ "event": {"type": "content_block_stop", "index": 0},+ },+ {+ "kind": "event",+ "sequence": 5,+ "type": "message_delta",+ "event": {+ "type": "message_delta",+ "delta": {"stop_reason": "tool_use", "stop_sequence": None},+ "usage": {"output_tokens": 1},+ },+ },+ {+ "kind": "event",+ "sequence": 6,+ "type": "message_stop",+ "event": {"type": "message_stop"},+ },+ ]+ self.assertTrue(probe._stream_order_ok("anthropic", valid))+ turn = probe._parse_anthropic_stream(+ probe.TransportResult(200, None, valid, True, 0, True)+ )+ self.assertNotIn("stream_arguments_not_fragmented", turn.parse_errors)+ self.assertEqual(turn.tool_calls[0].arguments, {"city": "Shanghai"})++ single_fragment = copy.deepcopy(valid)+ single_fragment[2]["event"]["delta"]["partial_json"] = (+ '{"city":"Shanghai"}'+ )+ single_fragment.pop(3)+ for sequence, item in enumerate(single_fragment):+ item["sequence"] = sequence+ self.assertFalse(probe._stream_order_ok("anthropic", single_fragment))+ single_turn = probe._parse_anthropic_stream(+ probe.TransportResult(200, None, single_fragment, True, 0, False)+ )+ self.assertIn("stream_arguments_not_fragmented", single_turn.parse_errors)++ def test_anthropic_thinking_rejects_deltas_after_signature(self) -> None:+ events = [+ {"kind": "event", "sequence": 0, "type": "message_start", "event": {"type": "message_start", "message": {"type": "message", "role": "assistant", "content": [], "stop_reason": None, "stop_sequence": None}}},+ {"kind": "event", "sequence": 1, "type": "content_block_start", "event": {"type": "content_block_start", "index": 0, "content_block": {"type": "thinking", "thinking": "", "signature": ""}}},+ {"kind": "event", "sequence": 2, "type": "content_block_delta", "event": {"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": "thought"}}},+ {"kind": "event", "sequence": 3, "type": "content_block_delta", "event": {"type": "content_block_delta", "index": 0, "delta": {"type": "signature_delta", "signature": "sig"}}},+ {"kind": "event", "sequence": 4, "type": "content_block_delta", "event": {"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": "late"}}},+ {"kind": "event", "sequence": 5, "type": "content_block_stop", "event": {"type": "content_block_stop", "index": 0}},+ {"kind": "event", "sequence": 6, "type": "message_delta", "event": {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence": None}}},+ {"kind": "event", "sequence": 7, "type": "message_stop", "event": {"type": "message_stop"}},+ ]+ self.assertFalse(probe._stream_order_ok("anthropic", events))+ turn = probe._parse_anthropic_stream(probe.TransportResult(200, None, events, False, 0, False))+ self.assertIn("stream_delta_after_signature", turn.parse_errors)++ def test_anthropic_message_start_requires_initial_snapshot(self) -> None:+ valid = [+ {+ "kind": "event",+ "sequence": 0,+ "type": "message_start",+ "event": {+ "type": "message_start",+ "message": {+ "type": "message",+ "role": "assistant",+ "content": [],+ "usage": _anthropic_usage(),+ "stop_reason": None,+ "stop_sequence": None,+ },+ },+ },+ {+ "kind": "event",+ "sequence": 1,+ "type": "message_delta",+ "event": {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence": None}, "usage": {"output_tokens": 1}},+ },+ {"kind": "event", "sequence": 2, "type": "message_stop", "event": {"type": "message_stop"}},+ ]+ nonempty_content = copy.deepcopy(valid)+ nonempty_content[0]["event"]["message"]["content"] = [{"type": "text", "text": "WRONG"}]+ premature_stop = copy.deepcopy(valid)+ premature_stop[0]["event"]["message"]["stop_reason"] = "end_turn"+ self.assertTrue(probe._stream_order_ok("anthropic", valid))+ self.assertFalse(probe._stream_order_ok("anthropic", nonempty_content))+ self.assertFalse(probe._stream_order_ok("anthropic", premature_stop))+ content_turn = probe._parse_anthropic_stream(+ probe.TransportResult(200, None, nonempty_content, False, 0, False)+ )+ stop_turn = probe._parse_anthropic_stream(probe.TransportResult(200, None, premature_stop, False, 0, False))+ self.assertIn("message_start_content_invalid", content_turn.parse_errors)+ self.assertIn("message_start_terminal_invalid", stop_turn.parse_errors)++ for field in ("stop_reason", "stop_sequence"):+ missing = copy.deepcopy(valid)+ missing[0]["event"]["message"].pop(field)+ self.assertFalse(probe._stream_order_ok("anthropic", missing))+ missing_turn = probe._parse_anthropic_stream(+ probe.TransportResult(200, None, missing, False, 0, False)+ )+ self.assertIn("message_start_terminal_invalid", missing_turn.parse_errors)++ def test_anthropic_message_start_requires_usage_snapshot(self) -> None:+ valid = [+ {"kind": "event", "sequence": 0, "type": "message_start", "event": {"type": "message_start", "message": {"type": "message", "role": "assistant", "content": [], "usage": _anthropic_usage(), "stop_reason": None, "stop_sequence": None}}},+ {"kind": "event", "sequence": 1, "type": "message_delta", "event": {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence": None}, "usage": {"output_tokens": 1}}},+ {"kind": "event", "sequence": 2, "type": "message_stop", "event": {"type": "message_stop"}},+ ]+ self.assertTrue(probe._stream_order_ok("anthropic", valid))+ valid_turn = probe._parse_anthropic_stream(probe.TransportResult(200, None, valid, False, 0, True))+ self.assertNotIn("message_start_usage_invalid", valid_turn.parse_errors)+ for invalid_usage in (None, {}, {"input_tokens": -1, "output_tokens": 0}, {"input_tokens": 1, "output_tokens": True}):+ invalid = copy.deepcopy(valid)+ if invalid_usage is None:+ invalid[0]["event"]["message"].pop("usage")+ else:+ invalid[0]["event"]["message"]["usage"] = invalid_usage+ self.assertFalse(probe._stream_order_ok("anthropic", invalid))+ invalid_turn = probe._parse_anthropic_stream(probe.TransportResult(200, None, invalid, False, 0, False))+ self.assertIn("message_start_usage_invalid", invalid_turn.parse_errors)++ def test_non_string_stop_reasons_are_parse_failures(self) -> None:+ anthropic = probe._parse_anthropic_document(+ {"type": "message", "role": "assistant", "content": [], "stop_reason": []}+ )+ chat = probe._parse_chat_document(+ {+ "choices": [+ {"index": 0, "message": {"role": "assistant", "content": ""}, "finish_reason": {}}+ ]+ }+ )+ self.assertIn("stop_reason_invalid", anthropic.parse_errors)+ self.assertIn("finish_reason_invalid", chat.parse_errors)+ self.assertFalse(probe._validate_first(anthropic, (), stream=False)["checks"]["stop_reason"])+ self.assertFalse(probe._validate_first(chat, (), stream=False)["checks"]["stop_reason"])++ def test_chat_stream_choices_must_be_a_list(self) -> None:+ for choices in ({}, "invalid"):+ events = [{"kind": "event", "sequence": 0, "event": {"object": "chat.completion.chunk", "choices": choices}}]+ self.assertFalse(probe._stream_order_ok("chat", events))+ turn = probe._parse_chat_stream(probe.TransportResult(200, None, events, False, 0, False))+ self.assertIn("choice_invalid", turn.parse_errors)++ def test_responses_nonstream_requires_response_object(self) -> None:+ valid = probe._parse_responses_document({"id": "resp_1", "object": "response", "output": [], "status": "completed"})+ self.assertNotIn("response_object_invalid", valid.parse_errors)+ for object_value in (None, "chat.completion", []):+ document = {"output": [], "status": "completed"}+ if object_value is not None:+ document["object"] = object_value+ turn = probe._parse_responses_document(document)+ self.assertIn("response_object_invalid", turn.parse_errors)++ def test_responses_nonstream_requires_response_id(self) -> None:+ valid = {"id": "resp_1", "object": "response", "output": [], "status": "completed"}+ self.assertNotIn("response_id_invalid", probe._parse_responses_document(valid).parse_errors)+ for invalid_id in (None, "", []):+ document = copy.deepcopy(valid)+ if invalid_id is None:+ document.pop("id")+ else:+ document["id"] = invalid_id+ self.assertIn("response_id_invalid", probe._parse_responses_document(document).parse_errors)++ def test_responses_nonstream_rejects_invalid_output_item_types(self) -> None:+ for item_type in (None, [], {}, "unknown"):+ item = {"id": "bad_1", "type": item_type}+ turn = probe._parse_responses_document({"object": "response", "output": [item], "status": "completed"})+ self.assertIn("output_item_type_invalid", turn.parse_errors)++ def test_responses_nonstream_rejects_duplicate_output_item_ids(self) -> None:+ output = [+ {"id": "same", "type": "reasoning", "summary": []},+ {"id": "same", "type": "function_call", "call_id": "call_1", "name": "lookup_weather", "arguments": '{"city":"Shanghai"}'},+ ]+ turn = probe._parse_responses_document({"object": "response", "output": output, "status": "completed"})+ self.assertIn("output_item_id_duplicate", turn.parse_errors)++ def test_responses_nonstream_rejects_invalid_nested_part_types(self) -> None:+ message = {"id": "msg_1", "type": "message", "role": "assistant", "content": [{"type": []}]}+ reasoning = {"id": "rs_1", "type": "reasoning", "summary": [{"type": {}}]}+ turn = probe._parse_responses_document({"object": "response", "output": [message, reasoning], "status": "completed"})+ self.assertIn("message_part_type_invalid", turn.parse_errors)+ self.assertIn("reasoning_part_type_invalid", turn.parse_errors)++ def test_responses_nonstream_rejects_unknown_message_part_types(self) -> None:+ message = {+ "id": "msg_1",+ "type": "message",+ "role": "assistant",+ "content": [{"type": "output_text", "text": "ok"}, {"type": "future_part", "text": "ignored"}],+ }+ turn = probe._parse_responses_document({"object": "response", "output": [message], "status": "completed"})+ self.assertIn("message_part_type_invalid", turn.parse_errors)++ def test_responses_nonstream_rejects_invalid_encrypted_reasoning(self) -> None:+ turn = probe._parse_responses_document(+ {+ "object": "response",+ "output": [{"type": "reasoning", "summary": [{"type": "summary_text", "text": "thought"}], "encrypted_content": []}],+ "status": "completed",+ }+ )+ self.assertIn("encrypted_reasoning_invalid", turn.parse_errors)++ def test_responses_nonstream_rejects_incomplete_function_call_items(self) -> None:+ item = {+ "id": "fc_1",+ "type": "function_call",+ "status": "incomplete",+ "call_id": "call_1",+ "name": "lookup_weather",+ "arguments": '{"city":"Shanghai"}',+ }+ turn = probe._parse_responses_document({"object": "response", "output": [item], "status": "completed"})+ self.assertIn("output_item_status_invalid", turn.parse_errors)+ self.assertEqual(turn.tool_calls, [])++ def test_responses_stream_event_type_must_be_a_string(self) -> None:+ for event_type in ([], {}):+ events = [+ {+ "kind": "event",+ "sequence": 0,+ "wire_sequence": 0,+ "type": event_type,+ "event": {"type": event_type},+ }+ ]+ self.assertFalse(probe._stream_order_ok("responses", events))+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, events, False, 0, False))+ self.assertIn("stream_event_type_invalid", turn.parse_errors)++ def test_responses_stream_rejects_unknown_event_types(self) -> None:+ events = _response_message_stream()+ events.insert(-1, {"kind": "event", "type": "response.future_bogus", "event": {"type": "response.future_bogus"}})+ for index, item in enumerate(events):+ item["sequence"] = index+ item["wire_sequence"] = index+ self.assertFalse(probe._stream_order_ok("responses", events))+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, events, False, 0, False))+ self.assertIn("stream_event_unknown", turn.parse_errors)++ def test_responses_reasoning_encrypted_snapshots_must_match(self) -> None:+ valid = _response_reasoning_stream()+ valid[1]["event"]["item"]["encrypted_content"] = "opaque"+ valid[4]["event"]["item"]["encrypted_content"] = "opaque"+ valid[5]["event"]["response"]["output"][0]["encrypted_content"] = "opaque"+ invalid = copy.deepcopy(valid)+ invalid[4]["event"]["item"]["encrypted_content"] = "changed"+ self.assertTrue(probe._stream_order_ok("responses", valid))+ self.assertFalse(probe._stream_order_ok("responses", invalid))+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, invalid, False, 0, False))+ self.assertIn("stream_reasoning_snapshot_mismatch", turn.parse_errors)++ def test_responses_reasoning_terminal_snapshot_preserves_part_types(self) -> None:+ invalid = _response_reasoning_stream()+ invalid[4]["event"]["item"]["summary"][0]["type"] = "text"+ self.assertFalse(probe._stream_order_ok("responses", invalid))+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, invalid, False, 0, False))+ self.assertIn("terminal_output_mismatch", turn.parse_errors)++ def test_responses_stream_rejects_malformed_terminal_encrypted_snapshot(self) -> None:+ events = _response_reasoning_stream()+ events[-1]["event"]["response"]["output"][0]["encrypted_content"] = []+ self.assertFalse(probe._stream_order_ok("responses", events))+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, events, False, 0, False))+ self.assertIn("encrypted_reasoning_snapshot_invalid", turn.parse_errors)++ def test_responses_stream_created_snapshot_requires_object(self) -> None:+ for response in ([], {"object": "other"}):+ invalid = _response_message_stream()+ invalid[0]["event"]["response"] = response+ self.assertFalse(probe._stream_order_ok("responses", invalid))+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, invalid, False, 0, False))+ self.assertIn("response_start_snapshot_invalid", turn.parse_errors)++ def test_responses_stream_created_snapshot_requires_in_progress_empty_output(self) -> None:+ invalid = _response_message_stream()+ invalid[0]["event"]["response"]["output"] = [{"id": "msg_0", "type": "message"}]+ self.assertFalse(probe._stream_order_ok("responses", invalid))+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, invalid, False, 0, False))+ self.assertIn("response_start_snapshot_invalid", turn.parse_errors)++ def test_chat_nonstream_requires_envelope_discriminator(self) -> None:+ valid = {"id": "chatcmpl_1", "object": "chat.completion", "choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}]}+ self.assertNotIn("chat_object_invalid", probe._parse_chat_document(valid).parse_errors)+ for object_value in (None, "chat.chunk", []):+ document = copy.deepcopy(valid)+ if object_value is None:+ document.pop("object")+ else:+ document["object"] = object_value+ self.assertIn("chat_object_invalid", probe._parse_chat_document(document).parse_errors)++ def test_chat_nonstream_requires_completion_id(self) -> None:+ valid = {"id": "chatcmpl_1", "object": "chat.completion", "choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}]}+ self.assertNotIn("chat_id_invalid", probe._parse_chat_document(valid).parse_errors)+ for completion_id in (None, "", []):+ document = copy.deepcopy(valid)+ if completion_id is None:+ document.pop("id")+ else:+ document["id"] = completion_id+ self.assertIn("chat_id_invalid", probe._parse_chat_document(document).parse_errors)++ def test_chat_nonstream_requires_message_content(self) -> None:+ valid = {"id": "chatcmpl_1", "object": "chat.completion", "choices": [{"index": 0, "message": {"role": "assistant", "content": None}, "finish_reason": "tool_calls"}]}+ self.assertNotIn("message_content_missing", probe._parse_chat_document(valid).parse_errors)+ missing = copy.deepcopy(valid)+ missing["choices"][0]["message"].pop("content")+ self.assertIn("message_content_missing", probe._parse_chat_document(missing).parse_errors)++ def test_chat_stream_event_discriminator_must_be_string(self) -> None:+ for event_type in ([], {}):+ events = [{"kind": "event", "type": event_type, "event": {"type": event_type, "choices": []}}]+ self.assertFalse(probe._stream_order_ok("chat", events))+ turn = probe._parse_chat_stream(probe.TransportResult(200, None, events, False, 0, False))+ self.assertIn("stream_event_type_invalid", turn.parse_errors)++ def test_chat_stream_rejects_unknown_event_discriminator(self) -> None:+ events = [+ {"kind": "event", "type": "future_bogus", "event": {"object": "chat.completion.chunk", "type": "future_bogus", "choices": []}},+ ]+ self.assertFalse(probe._stream_order_ok("chat", events))+ turn = probe._parse_chat_stream(probe.TransportResult(200, None, events, False, 0, False))+ self.assertIn("stream_event_unknown", turn.parse_errors)++ def test_chat_stream_error_payload_is_not_a_completion(self) -> None:+ events = [+ {"kind": "event", "event": {"object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {"role": "assistant", "content": "ok"}}]}},+ {"kind": "event", "type": "error", "event": {"object": "chat.completion.chunk", "type": "error", "error": {"type": "server_error"}, "choices": []}},+ {"kind": "event", "event": {"object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}},+ {"kind": "done"},+ ]+ self.assertFalse(probe._stream_order_ok("chat", events))+ turn = probe._parse_chat_stream(probe.TransportResult(200, None, events, True, 0, False))+ self.assertIn("stream_failure_event", turn.parse_errors)++ def test_chat_stream_error_discriminator_is_not_a_completion(self) -> None:+ events = [+ {"kind": "event", "event": {"object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {"role": "assistant", "content": "ok"}}]}},+ {"kind": "event", "type": "error", "event": {"object": "chat.completion.chunk", "type": "error", "choices": []}},+ {"kind": "event", "event": {"object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}},+ {"kind": "done"},+ ]+ self.assertFalse(probe._stream_order_ok("chat", events))+ turn = probe._parse_chat_stream(probe.TransportResult(200, None, events, True, 0, False))+ self.assertIn("stream_failure_event", turn.parse_errors)++ def test_chat_stream_requires_explicit_choice_indexes(self) -> None:+ events = [+ {"kind": "event", "event": {"object": "chat.completion.chunk", "choices": [{"delta": {"role": "assistant"}}]}},+ ]+ self.assertFalse(probe._stream_order_ok("chat", events))+ turn = probe._parse_chat_stream(probe.TransportResult(200, None, events, True, 0, False))+ self.assertIn("choice_index_invalid", turn.parse_errors)++ def test_chat_stream_rejects_duplicate_terminal_usage(self) -> None:+ events = [+ {"kind": "event", "sequence": 0, "event": {"object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}},+ {"kind": "event", "sequence": 1, "event": {"object": "chat.completion.chunk", "choices": [], "usage": {"completion_tokens": 1}}},+ {"kind": "event", "sequence": 2, "event": {"object": "chat.completion.chunk", "choices": [], "usage": {"completion_tokens": 2}}},+ {"kind": "done", "sequence": 3},+ ]+ self.assertFalse(probe._stream_order_ok("chat", events))+ turn = probe._parse_chat_stream(probe.TransportResult(200, None, events, True, 0, False))+ self.assertIn("usage_duplicate", turn.parse_errors)++ def test_chat_stream_usage_chunk_requires_choices(self) -> None:+ valid = [+ {"kind": "event", "sequence": 0, "event": {"id": "chatcmpl_1", "object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {"role": "assistant"}, "finish_reason": "stop"}]}},+ {"kind": "event", "sequence": 1, "event": {"id": "chatcmpl_1", "object": "chat.completion.chunk", "choices": [], "usage": {"completion_tokens": 1}}},+ {"kind": "done", "sequence": 2},+ ]+ self.assertTrue(probe._stream_order_ok("chat", valid))+ self.assertNotIn("choices_missing", probe._parse_chat_stream(probe.TransportResult(200, None, valid, True, 0, True)).parse_errors)+ missing = copy.deepcopy(valid)+ missing[1]["event"].pop("choices")+ self.assertFalse(probe._stream_order_ok("chat", missing))+ missing_turn = probe._parse_chat_stream(probe.TransportResult(200, None, missing, True, 0, False))+ self.assertIn("choices_missing", missing_turn.parse_errors)++ def test_responses_done_message_snapshots_are_checked_per_item(self) -> None:+ message_one = {"id": "msg_1", "type": "message", "role": "assistant", "content": [{"type": "output_text", "text": ""}]}+ message_two = {"id": "msg_2", "type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "AB"}]}+ events = _responses_wire(+ {"type": "response.created", "response": {}},+ {"type": "response.output_item.added", "output_index": 0, "item": {"id": "msg_1", "type": "message", "role": "assistant"}},+ {"type": "response.content_part.added", "item_id": "msg_1", "output_index": 0, "content_index": 0, "part": {"type": "output_text", "text": ""}},+ {"type": "response.output_text.delta", "item_id": "msg_1", "output_index": 0, "content_index": 0, "delta": "A"},+ {"type": "response.output_text.done", "item_id": "msg_1", "output_index": 0, "content_index": 0, "text": "A"},+ {"type": "response.content_part.done", "item_id": "msg_1", "output_index": 0, "content_index": 0, "part": {"type": "output_text", "text": "A"}},+ {"type": "response.output_item.done", "output_index": 0, "item": message_one},+ {"type": "response.output_item.added", "output_index": 1, "item": {"id": "msg_2", "type": "message", "role": "assistant"}},+ {"type": "response.content_part.added", "item_id": "msg_2", "output_index": 1, "content_index": 0, "part": {"type": "output_text", "text": ""}},+ {"type": "response.output_text.delta", "item_id": "msg_2", "output_index": 1, "content_index": 0, "delta": "B"},+ {"type": "response.output_text.done", "item_id": "msg_2", "output_index": 1, "content_index": 0, "text": "B"},+ {"type": "response.content_part.done", "item_id": "msg_2", "output_index": 1, "content_index": 0, "part": {"type": "output_text", "text": "B"}},+ {"type": "response.output_item.done", "output_index": 1, "item": message_two},+ {"type": "response.completed", "response": {"status": "completed", "output": [message_one, message_two]}},+ )+ self.assertFalse(probe._stream_order_ok("responses", events))+ turn = probe._parse_responses_stream(probe.TransportResult(200, None, events, False, 0, False))+ self.assertIn("stream_text_snapshot_mismatch", turn.parse_errors)++ def test_anthropic_stream_requires_compatible_stop_sequence(self) -> None:+ valid = [+ {+ "kind": "event",+ "sequence": 0,+ "type": "message_start",+ "event": {+ "type": "message_start",+ "message": {+ "type": "message",+ "role": "assistant",+ "content": [],+ "usage": _anthropic_usage(),+ "stop_reason": None,+ "stop_sequence": None,+ },+ },+ },+ {+ "kind": "event",+ "sequence": 1,+ "type": "message_delta",+ "event": {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence": None}, "usage": {"output_tokens": 1}},+ },+ {"kind": "event", "sequence": 2, "type": "message_stop", "event": {"type": "message_stop"}},+ ]+ malformed = copy.deepcopy(valid)+ malformed[1]["event"]["delta"]["stop_sequence"] = []+ self.assertTrue(probe._stream_order_ok("anthropic", valid))+ valid_turn = probe._parse_anthropic_stream(+ probe.TransportResult(200, None, valid, False, 0, False)+ )+ self.assertNotIn("message_delta_usage_invalid", valid_turn.parse_errors)+ self.assertFalse(probe._stream_order_ok("anthropic", malformed))+ turn = probe._parse_anthropic_stream(probe.TransportResult(200, None, malformed, False, 0, False))+ self.assertIn("message_delta_stop_sequence_invalid", turn.parse_errors)+ for invalid_usage in (None, {}, {"output_tokens": -1}, {"output_tokens": True}):+ invalid = copy.deepcopy(valid)+ if invalid_usage is None:+ invalid[1]["event"].pop("usage")+ else:+ invalid[1]["event"]["usage"] = invalid_usage+ self.assertFalse(probe._stream_order_ok("anthropic", invalid))+ invalid_turn = probe._parse_anthropic_stream(+ probe.TransportResult(200, None, invalid, False, 0, False)+ )+ self.assertIn("message_delta_usage_invalid", invalid_turn.parse_errors)++ def test_chat_stream_completion_id_must_remain_stable(self) -> None:+ events = [+ {+ "kind": "event",+ "sequence": 0,+ "type": None,+ "event": {+ "id": "chatcmpl_1",+ "object": "chat.completion.chunk",+ "choices": [{"index": 0, "delta": {"role": "assistant", "content": "ok"}}],+ },+ },+ {+ "kind": "event",+ "sequence": 1,+ "type": None,+ "event": {+ "id": "chatcmpl_1",+ "object": "chat.completion.chunk",+ "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],+ },+ },+ {"kind": "done", "sequence": 2, "type": None},+ ]+ self.assertTrue(probe._stream_order_ok("chat", events))+ valid_turn = probe._parse_chat_stream(+ probe.TransportResult(200, None, events, True, 0, False)+ )+ self.assertNotIn("chat_id_invalid", valid_turn.parse_errors)+ mismatched = copy.deepcopy(events)+ mismatched[1]["event"]["id"] = "chatcmpl_2"+ self.assertFalse(probe._stream_order_ok("chat", mismatched))+ turn = probe._parse_chat_stream(probe.TransportResult(200, None, mismatched, True, 0, False))+ self.assertIn("stream_completion_id_changed", turn.parse_errors)+ missing = copy.deepcopy(events)+ for item in missing[:-1]:+ item["event"].pop("id")+ self.assertFalse(probe._stream_order_ok("chat", missing))+ missing_turn = probe._parse_chat_stream(probe.TransportResult(200, None, missing, True, 0, False))+ self.assertIn("stream_completion_id_invalid", missing_turn.parse_errors)++ def test_first_turn_rejects_user_scope_leakage(self) -> None:+ turn = probe._parse_anthropic_document(+ {+ "type": "message",+ "role": "assistant",+ "content": [{"type": "text", "text": probe.USER_SCOPE_LEAK}],+ "stop_reason": "tool_use",+ }+ )+ checks = probe._validate_first(turn, (), stream=False)+ self.assertFalse(checks["checks"]["user_scope"])++ def test_second_turn_rejects_prior_turn_reasoning_leakage(self) -> None:+ first = probe._parse_anthropic_document(+ {+ "type": "message",+ "role": "assistant",+ "content": [{"type": "thinking", "thinking": "PRIVATE_THOUGHT", "signature": "sig"}],+ "stop_reason": "tool_use",+ }+ )+ second = probe._parse_anthropic_document(+ {+ "type": "message",+ "role": "assistant",+ "content": [{"type": "text", "text": "answer PRIVATE_THOUGHT"}],+ "stop_reason": "end_turn",+ }+ )+ checks = probe._validate_second(+ second,+ (),+ stream=False,+ prior_reasoning_parts=first.reasoning_parts,+ )+ self.assertFalse(checks["checks"]["reasoning_not_visible"])+++if __name__ == "__main__":+ unittest.main()diff --git a/docs/plans/model-hub-engine-survey.md b/docs/plans/model-hub-engine-survey.mdindex 94b5ed5f2..686ca2f05 100644--- a/docs/plans/model-hub-engine-survey.md+++ b/docs/plans/model-hub-engine-survey.md@@ -555,3 +555,227 @@ Performed against the pinned sources and assets:Not verified: live OAuth exchanges, live model entitlements, billable providerrequests, vendor ToS/billing, macOS notarization/code signing, maintainer releasesignatures, or mutation behavior of startup-owned CPA config fields.++## S4. M0 agentic-fidelity spike: Anthropic <-> OpenAI++Status: **measured**, checked 2026-08-09. This section+extends S1; it does not revisit S1 section 3's finding that syntax conversion+exists, is registry-driven, and covers both directions. The question here is+semantic fidelity under an agentic workload.++### 13. Evidence boundary and stop condition++The live run used the owner-provided OpenAI/Anthropic-compatible relay as the+upstream for an isolated CPA v7.2.95 instance. The relay root and credentials+were read from the local regression environment, injected into the child+process, and never written to this repository or the report. The CPA binary was+obtained through `vibe/model_hub_runtime/` from the repository's packaged+manifest, with ambient manifest overrides disabled and the installed version+asserted before the probe. It was bound to `127.0.0.1`; no Avibe service, user+configuration, CLI login state, or auth file was inspected.++Before the run, the relay's `/v1/models` returned 21 OpenAI-compatible model+ids; `gpt-5.4-mini` was selected as the smallest listed OpenAI model. One+Anthropic probe for an unavailable model returned HTTP 503 with `no available+accounts`; the owner then confirmed `claude-haiku-4-5` with the required+minimal request returned HTTP 200. The fixture retries a 503 with bounded+backoff and tries one configured Claude fallback model before reporting the+Claude direction as blocked. Direct official vendor APIs were not measured;+the evidence source for this section is the owner-provided compatible relay.++### 14. Conversion matrix and decisions++S1's source inspection identifies all four directions as built-in translator+paths in CPA v7.2.95. The plugin host is disabled in the managed runtime and no+plugin is named by the translator registrations. That is an engine-core+classification, not a semantic-fidelity result.++| Conversion pair | Direction exercised by the fixture | Translation owner | Plugin dependency in v7.2.95 | M0 gate |+| --- | --- | --- | --- | --- |+| Anthropic Messages <-> OpenAI Responses | Messages -> Responses: **NO-GO**; Responses -> Messages: **NO-GO** | CPA engine-core registry and stream translators | None identified; plugins remain disabled | **NO-GO** |+| Anthropic Messages <-> OpenAI Chat Completions | Messages -> Chat: **NO-GO**; Chat -> Messages: **NO-GO** | CPA engine-core registry and OpenAI-compatible executor | None identified; plugins remain disabled | **NO-GO** |++The direction-level evidence ledger is explicit because a pair is accepted only+when both directions pass:++| Client request | Target API-key source | Live result | Evidence |+| --- | --- | --- | --- |+| Anthropic Messages | OpenAI Responses | 200 for both two-turn cases; **NO-GO** | r45: the single retained reasoning in both turns and failed both parse gates and the exact tuple. The parallel retained reasoning in both turns but failed both parse/order gates |+| OpenAI Responses | Anthropic Messages | 200 for both two-turn cases; **NO-GO** | r45: the single passed both parse gates but lacked reasoning in both turns and failed final system scope and the exact tuple. The parallel lacked reasoning in both turns, failed both parse/order gates, and failed final system scope and the exact tuple |+| Anthropic Messages | OpenAI Chat Completions | 200 for both two-turn cases; **NO-GO** | r45: the single retained reasoning in both turns and failed both parse gates and the final exact tuple. The parallel retained reasoning only in the first turn, failed the first parse/order gates, and failed the final exact tuple |+| OpenAI Chat Completions | Anthropic Messages | 200 for both two-turn cases; **NO-GO** | r45: the single passed both parse gates but lacked reasoning in both turns and failed final system scope. The parallel lacked reasoning, failed both parse gates and first-turn stream ordering, and failed final system scope |++Final-answer marker and tuple failures varied across complete live reruns because+the upstream response text is nondeterministic. The ledger above records the+latest complete matrix attempt (r45); the direction decisions remain anchored+by the repeated reasoning and parse failures plus the current final-turn+evidence.++### 15. Agentic capability matrix++The fixture covers the following invariants. A passing HTTP status alone is+insufficient: the response must preserve the observable protocol contract and+the agentic state transition.++| Capability | Minimal workload | Required invariant | Owner | M0 evidence |+| --- | --- | --- | --- | --- |+| Single tool call | One prompt with `lookup_weather` | Tool name, JSON arguments, call id, and terminal stop reason survive the conversion | Engine-core translator plus caller adapter | Structural checks passed in all four directions |+| Parallel tools | One prompt explicitly naming `lookup_weather` and `lookup_time` | Both calls remain addressable and are not silently serialized or merged | Engine-core translator | Passed in all four directions |+| Multi-turn loop | Assistant tool call followed by a tool result and a final answer | No tool result appears before execution; the call id links the returned result to the same call and the second turn sees the tool output | Engine-core translator plus caller adapter | r45 independently recognized malformed tuple candidates and rejected empty identities; final exact tuples failed in five of eight cases, while Messages -> Responses parallel and both Chat -> Messages cases preserved the exact complete set |+| Streaming text | Short streamed answer | Every data event is strict UTF-8 JSON, wire sequence and ordering are monotonic, lifecycle transitions are unique, Anthropic text openings are explicit and empty, Anthropic `message_delta` precedes `message_stop`, done/content-part snapshots agree with deltas/items, per-item output snapshots agree with their own deltas, Chat delta objects carry one assistant role before any payload, and the stream terminates with the protocol's done event | Engine-core stream translator | r45: Messages -> Responses and Responses -> Messages parallel failed both parse/order gates; Messages -> Chat parallel failed its first parse/order gates; Chat -> Messages parallel failed both parse gates and first-turn ordering |+| Streaming tool fragments | Stream a tool call with split arguments | Opening tool snapshots contain the required empty argument field; at least two nonempty fragments reassemble into exactly one valid JSON argument object and one call id; typed error/discriminator events cannot be accepted as completion | Engine-core stream translator | r45 gated Anthropic, Responses, and Chat fragment counts and the Responses empty opening argument snapshot. Complete first-turn arguments reconstructed in all four parallel cases, but Messages -> Responses and Responses -> Messages failed both parse/order gates; Messages -> Chat failed its first parse/order gates; Chat -> Messages failed both parse gates and first-turn ordering |+| System prompt | System/instructions text containing a marker plus a conflicting user marker | Exact system marker remains system-scoped and the exact user conflict marker is absent | Engine-core translator | r45 final system scope passed in both Messages -> Responses and both Messages -> Chat cases, and failed in both Responses -> Messages and both Chat -> Messages cases |+| Thinking/reasoning | Anthropic `thinking` budget and OpenAI `reasoning.effort` | Requested signal is observable or an explicit loss is recorded; readable reasoning, Anthropic signatures/redacted data, and Responses encrypted content are all protected from visible-text leakage | Engine-core translator; upstream model semantics | r45 observed reasoning in seven of eight Anthropic -> OpenAI turns, confirmed its absence in all eight OpenAI -> Anthropic turns, and passed normalized full-value/meaningful-excerpt leakage checks on all 16 returned turns |+| Context length/truncation | Prompt with a tail marker, then increasing prefix sizes | The first rejected/truncated size and error shape are recorded; no silent loss of the tail marker is accepted | Upstream model plus engine request limits; no plugin | Not covered (optional low-cost probe) |++Thinking and reasoning are deliberately treated as a fidelity question. The+fixture sends both parameter families and accepts either Chat's explicit+`reasoning_content` or its standard positive+`usage.completion_tokens_details.reasoning_tokens` signal. The r45 matrix+attempt requested stateless Responses encrypted reasoning and applied the+visible-text gate to readable reasoning, Anthropic signatures and redacted+data, and Responses encrypted content. It passed that gate on all 16 returned+turns. The corrected parser still observed no positive signal in any of the+eight returned OpenAI -> Anthropic turns, including the Chat direction after+both signal forms+were accepted. Anthropic-to-OpenAI responses with observable thinking still+failed parser gates in several cases and are not treated as semantically valid+merely because a reasoning signal was present.+This report does not infer that a budget maps to an OpenAI effort level (or vice+versa) from field-name similarity. CPA's engine-core translation may carry,+clamp, or drop a field; the target model's own behavior determines whether the+result is useful.++### 16. Minimum reproductions for each no-go++Each no-go starts with the single-tool request in the fixture and inspects the+first response before the tool-result follow-up. Successful HTTP 200 and valid+tool-call structure separate the semantic losses from relay transport failures;+the exact tuple and system-scope checks additionally inspect the final turn.++1. **Messages -> Responses.** POST `/v1/messages` with one function tool and+ Anthropic `thinking: {type: enabled, budget_tokens: 1024}`. Require the+ projected Anthropic thinking block to contain a nonempty signature. In r45+ the single retained reasoning in both turns and failed both parse gates and+ the exact tuple. The parallel retained reasoning in both turns but failed+ both parse/order gates. The direction remains NO-GO because both cases fail+ the closed matrix.+2. **Responses -> Messages.** POST `/v1/responses` with `instructions`, two+ function tools, `reasoning: {effort: low}`, a `function_call`, and a matching+ `function_call_output`; repeat with `stream: true`. In r45 the single+ passed both parse gates but lacked reasoning in both turns and failed final+ system scope and the exact tuple. The parallel lacked reasoning in both+ turns, failed both parse/order+ gates, and failed final system scope, tool-output correlation, and the exact+ tuple. The reasoning loss+ is independently sufficient for the pair's NO-GO.+3. **Messages -> Chat Completions.** Repeat the Messages single-tool request+ against the Chat target and require a signed Anthropic thinking block in the+ projected response. In r45 the single retained reasoning in both turns,+ failed both parse gates, and failed the final exact tuple. The parallel+ retained reasoning only in the first turn, failed the first parse/order+ gates, and failed the final exact tuple.+4. **Chat Completions -> Messages.** POST `/v1/chat/completions` with an+ assistant `tool_calls` item and a matching `tool` result, then repeat as a+ short stream. Require an Anthropic `tool_use` block, matching `tool_result`,+ system scope, and a terminal message event, then fail the gate when the+ requested reasoning signal is absent. In r45 the single passed both parse+ gates but lacked reasoning in both turns and failed final system scope. The+ parallel also lacked reasoning and failed both parse gates, first-turn+ stream ordering, and final system scope.++For the optional context probe, keep the request count small: send a marker at+the end of a progressively larger system/user prefix, record the first 4xx or+provider limit response, and separately verify whether the marker is present in+the model-visible tool/final-answer behavior. A silent marker disappearance is+NO-GO even if CPA returns HTTP 200. This probe was not run in M0.++### 17. Fixture and rerun contract++`docs/plans/fixtures/cpa-agentic-fidelity/` contains the probe and an isolated+`run_relay.py` launcher. It has eight cases covering both+directions of both pairs, single and parallel tools, tool-result round trips,+streaming, system text, and thinking/reasoning parameters. Each case makes a+second request only when the first response contains parsed tool calls with+nonempty unique observed IDs; otherwise+the report records that the multi-turn path was not reached. When reached, the+runner uses the first response's observed tool-call ids and complete assistant+continuation; fabricated ids are never used. The runner parses+non-stream and SSE responses into a redacted semantic projection and exits+non-zero when names, arguments, ids, reasoning presence, stream termination,+tool-result correlation, or final markers do not satisfy the matrix. It fails+closed before any network request when either vendor key, the gateway token, or+a source-qualified model is absent, and it never logs request/response bodies,+model prefixes, or environment values.++The launcher obtains CPA through `vibe/model_hub_runtime/`, explicitly selects+the packaged v7.2.95 manifest, verifies the installed version, creates a private+temporary engine state, binds CPA to `127.0.0.1`, and generates the+source-qualified model ids from the runtime's source prefixes. Run it after+loading the owner-provided regression environment in the shell; the keys are+consumed only by the temporary runtime state and child process, never copied+into the fixture, a committed config, or this document.++The probe also disables environment proxy handlers for loopback requests and+classifies an exhausted 503 capacity response for any target as blocked; the+Claude-only fallback model remains limited to the Anthropic target. Every case+reports a redacted `fallback_used` flag and evidence from a fallback is kept+separate from the primary-model result. The latest closed-matrix rerun (r45)+exercised all eight cases through the loopback CPA after additionally requiring+an explicit empty Anthropic text opening snapshot, an explicit empty Responses+function-call argument snapshot, and an explicit Chat delta object whose+unique assistant role precedes every payload delta. All eight cases completed+both turns with HTTP 200. No fallback was used. The causal gate passed all+returned first turns, and the normalized full-value/meaningful-excerpt+reasoning leakage gate passed on all 16 returned turns. A mixed+primary/fallback run in+which only the second turn falls back is not verified by the closed semantic+matrix and may underreport `fallback_used`; such a run remains blocked from+semantic evidence.+The future-collection validator now centralizes 25 protocol envelope kinds and+123 required-field cells in one table-driven authority, with one delete-a-field+mutation per cell. The focused probe suite contains 206 tests. Per the owner decision recorded on+2026-08-08, r45 is sealed M0 evidence: later fixture-only validator hardening+applies to future collections and does not retroactively rewrite r45 or its+direction-level decisions without a new, explicitly adopted matrix run.++### 18. M0 conclusion and remaining coverage++Both conversion pairs are **NO-GO for v2.1 adoption** on measured evidence.+Anthropic-to-OpenAI directions preserved an observable thinking signal on seven+of eight r45 turns but still failed parser gates in several cases. The protected+reasoning leakage gate passed on all 16 returned turns. All eight returned+OpenAI-to-Anthropic turns lost the requested reasoning signal even+after the corrected parsers retained Responses reasoning deltas and required+integer Chat reasoning-token usage. The complete final-turn gates also exposed+exact-tuple losses in five of eight cases.+All four directions are therefore **NO-GO**. Both pairs are classified as **engine-core** in+CPA v7.2.95; no plugin dependency was identified, and the managed runtime keeps+plugins disabled. This is a semantic limitation, not a syntax-conversion+finding and does not reopen S1 section 3.++Not covered: context-limit thresholds, transport-outage classification,+malformed relay URL validation (including nonnumeric loopback ports) and+blocked-report shaping,+non-stream wall-clock deadlines, non-loopback relay TLS enforcement,+latency/cost, OAuth or subscription behavior, direct official vendor APIs, and+cross-vendor subscription paths. Top-level Anthropic message ID validation,+non-stream Anthropic `stop_sequence` type/compatibility validation, mixed+primary/fallback second-turn accounting, compatibility of the configured+Anthropic fallback with the primary thinking contract, required `text` field+presence in non-stream Anthropic text blocks and Responses message parts, and+redaction of unrecognized stop reasons are also not verified. Responses+wire-sequence origin is not gated: the closed matrix requires monotonicity, and+the measured relay emitted contiguous one-based values. Non-stream response+media-type enforcement is also not verified. The historical fixture is not+independent of future product-manifest upgrades: the launcher currently selects+the product manifest and blocks unless it still declares v7.2.95. The probe+child also inherits the caller environment rather than receiving a minimal+allowlist. Transport, non-stream timing and media types, TLS, fallback+accounting and fallback-model capability, non-stream Anthropic/Responses+envelope and content-part schema completeness, report redaction, wire-sequence+origin, fixture-owned release resolution, and child-environment minimization+are outside the closed eight-row S4 semantic matrix; they are recorded here as+residuals rather than added as new probe gates. The scope guard remains+unchanged: this spike concerns API-key+sources only; subscriptions stay bound to their own vendor's backend.