The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): stale-call watchdog prices images at the learned per-image cost, not base64 length (salvage #76471)
crdesign8922c0d670cf4
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.pyindex a24eb1dd1e1..88c2ee0c764 100644--- a/agent/chat_completion_helpers.py+++ b/agent/chat_completion_helpers.py@@ -323,14 +323,42 @@ def _provider_stream_error_from_text(text: str, finish_reason: Optional[str], *,return None+_IMAGE_PART_TYPES = frozenset({"image_url", "input_image", "image"})+++def _image_part_chars(part: Dict[str, Any], image_cost: int) -> int:+ """Char-equivalent of one image content part: the per-image cost learned from provider usage+ (x4 chars/token), never the base64 payload length. A single native screenshot priced as text+ read as ~100K+ tokens and selected the giant-conversation watchdog tiers (#63871, #76411)."""+ text = part.get("text")+ return image_cost * 4 + (len(text) if isinstance(text, str) else 0)+++def _payload_chars(value: Any, image_cost: int) -> int:+ """``len(str(value))`` with image content parts priced at ``image_cost`` tokens each."""+ if value is None:+ return 0+ if isinstance(value, dict):+ if value.get("type") in _IMAGE_PART_TYPES and any(k in value for k in ("image_url", "image", "source", "file_id")):+ return _image_part_chars(value, image_cost)+ return sum(len(str(k)) + 6 + _payload_chars(v, image_cost) for k, v in value.items())+ if isinstance(value, list):+ return sum(_payload_chars(item, image_cost) for item in value) + 2 * len(value)+ return len(str(value))++def estimate_request_context_tokens(api_payload: Any) -> int:"""Cheap char/4 context estimate for the stale-call detectors. Handles bothwire shapes so Codex turns don't report ~0 tokens: list -> Chat ``messages``;dict with ``messages`` (+``tools``); dict with ``input`` (Responses API,- +``instructions``/``tools``); any other dict -> sum of its values."""+ +``instructions``/``tools``); any other dict -> sum of its values. Image parts+ cost the learned per-image price, not their base64 length."""+ from agent.image_token_cost import current_image_token_cost++ image_cost = current_image_token_cost()def _chars(value: Any) -> int:- return 0 if value is None else len(str(value))+ return _payload_chars(value, image_cost)if isinstance(api_payload, list):return sum(_chars(item) for item in api_payload) // 4diff --git a/tests/agent/test_context_estimator_multimodal.py b/tests/agent/test_context_estimator_multimodal.pynew file mode 100644index 00000000000..8a320f4eee6--- /dev/null+++ b/tests/agent/test_context_estimator_multimodal.py@@ -0,0 +1,33 @@+"""Stale-call watchdog estimator prices images at the learned per-image cost, not their base64+length (#63871 / #76411; salvage of #76471 by @crdesign8). A single native screenshot read as+~100K+ tokens and selected the 600-1200s giant-conversation watchdog tiers while the provider's+real prompt was a fraction of that."""++from agent.chat_completion_helpers import estimate_request_context_tokens, openai_codex_stale_timeout_floor+from agent.image_token_cost import DEFAULT_IMAGE_TOKEN_COST, image_cost_context++_B64 = "data:image/png;base64," + "A" * 400_000+++def _chat(*parts):+ return {"messages": [{"role": "user", "content": list(parts)}], "tools": [{"type": "function", "function": {"name": "t"}}]}+++def test_image_parts_cost_the_learned_price_on_both_wire_shapes():+ chat = _chat({"type": "text", "text": "look"}, {"type": "image_url", "image_url": {"url": _B64}})+ responses = {"input": [{"role": "user", "content": [{"type": "input_image", "image_url": _B64}]}], "instructions": "i" * 400}+ default = estimate_request_context_tokens(chat)+ assert DEFAULT_IMAGE_TOKEN_COST <= default < DEFAULT_IMAGE_TOKEN_COST + 200+ assert DEFAULT_IMAGE_TOKEN_COST <= estimate_request_context_tokens(responses) < DEFAULT_IMAGE_TOKEN_COST + 200+ with image_cost_context(4_000):+ assert 4_000 <= estimate_request_context_tokens(chat) < 4_200+ # The watchdog tier follows: one screenshot no longer buys the 100K+ (1200s) floor.+ assert openai_codex_stale_timeout_floor(default) == 0.0+++def test_text_payloads_and_tool_schemas_keep_the_legacy_estimate():+ """A base64-looking STRING is text; tool schemas mentioning ``image`` are not images."""+ payload = {"messages": [{"role": "user", "content": _B64}],+ "tools": [{"type": "function", "function": {"name": "vision", "parameters": {"type": "image"}}}]}+ legacy = (sum(len(str(m)) for m in payload["messages"]) + len(str(payload["tools"]))) // 4+ assert abs(estimate_request_context_tokens(payload) - legacy) < legacy * 0.02