The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(data-use): route connector results that need no-training to qualifying Nous endpoints
Siddharth Balyan22fc8098691e
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.pyindex 243b7fbf7b0..1b905dda718 100644--- a/agent/chat_completion_helpers.py+++ b/agent/chat_completion_helpers.py@@ -42,7 +42,7 @@ from agent.gemini_native_adapter import is_native_gemini_base_url# misidentify and, without an api_key, return 401 on every leg (issue #89863).from agent.model_metadata import is_local_endpointfrom agent.message_content import flatten_message_text-from agent.message_metadata import PERSISTENCE_ONLY_MESSAGE_FIELDS, append_message, stamp_message_timestamp+from agent.message_metadata import PERSISTENCE_ONLY_MESSAGE_FIELDS, append_message, data_use_requirement, stamp_message_timestampfrom agent.message_sanitization import (_sanitize_messages_surrogates, _sanitize_surrogates, _repair_tool_call_arguments,normalize_finish_reason as _normalize_finish_reason, sanitize_outbound_kwargs, strip_images_for_rejecting_model,@@ -499,18 +499,18 @@ def _prompt_cache_scope_for_agent(agent) -> str | None:return None-def _merge_nous_portal_messages_extra_body(agent, anthropic_kwargs: dict) -> dict:- """Merge Portal ``tags`` / ``session_id`` onto an Anthropic Messages kwargs dict.- The Nous profile is only consulted by the OpenAI-wire transport; ``session_id``- only — never ``provider_preferences`` (an OpenAI-wire routing object)."""+def _merge_nous_portal_messages_extra_body(agent, anthropic_kwargs: dict, api_messages: list) -> dict:+ """Merge Portal ``tags`` / ``session_id`` / data-use ``provider`` onto an Anthropic Messages kwargs+ dict. The Nous profile is only consulted by the OpenAI-wire transport; never+ ``provider_preferences`` (an OpenAI-wire routing object)."""if getattr(agent, "provider", None) not in {"nous", "nous-portal", "nousresearch"}:return anthropic_kwargstry:from providers import get_provider_profilenous_profile = get_provider_profile("nous")if nous_profile is not None:- anthropic_kwargs.setdefault("extra_body", {}).update(- nous_profile.build_extra_body(session_id=getattr(agent, "session_id", None)))+ anthropic_kwargs.setdefault("extra_body", {}).update(nous_profile.build_extra_body(+ session_id=getattr(agent, "session_id", None), data_use=data_use_requirement(api_messages)))except Exception as exc:logger.debug("Nous Portal extra_body merge failed: %s", exc)return anthropic_kwargs@@ -1390,7 +1390,7 @@ def _build_anthropic_kwargs(agent, api_messages, tools_for_api, reasoning_configdrop_context_1m_beta=bool(getattr(agent, "_oauth_1m_beta_disabled", False)))# Portal reads ``tags`` / ``session_id`` on its Messages route too, but the profile hook# is only consulted by the OpenAI-wire transport — merge here to keep sticky routing.- return _merge_nous_portal_messages_extra_body(agent, anthropic_kwargs)+ return _merge_nous_portal_messages_extra_body(agent, anthropic_kwargs, api_messages)def _build_bedrock_kwargs(agent, api_messages, tools_for_api, reasoning_config):@@ -2245,7 +2245,7 @@ def _anthropic_summary_attempt(agent, api_messages: list, api_request_id: str):model=agent.model, messages=api_messages, tools=None, max_tokens=agent.max_tokens,reasoning_config=agent.reasoning_config, is_oauth=agent._is_anthropic_oauth,preserve_dots=agent._anthropic_preserve_dots(), base_url=getattr(agent, "_anthropic_base_url", None))- ant_kw = _merge_nous_portal_messages_extra_body(agent, ant_kw)+ ant_kw = _merge_nous_portal_messages_extra_body(agent, ant_kw, api_messages)response = _managed_summary_call(agent, api_request_id, ant_kw, agent._interruptible_api_call, retry_count=retry_count)return _summary_text(agent, response, strip_tool_prefix=agent._is_anthropic_oauth)diff --git a/agent/error_classifier.py b/agent/error_classifier.pyindex addf3917fe8..f6b63eb6df2 100644--- a/agent/error_classifier.py+++ b/agent/error_classifier.py@@ -49,6 +49,7 @@ class FailoverReason(enum.Enum):image_corrupt = "image_corrupt" # Provider can't decode image bytes — strip and retry (shrinking won't help)model_not_found = "model_not_found" # 404 or invalid model — fallback to different modelprovider_policy_blocked = "provider_policy_blocked" # Aggregator account data/privacy policy excluded the only endpoint+ data_policy_denied = "data_policy_denied" # Context holds a connector result needing a no-training model; none serves itcontent_policy_blocked = "content_policy_blocked" # Provider safety filter rejected this prompt — deterministic per-request, don't retry unchangedmodel_entitlement = "model_entitlement" # This account cannot use the requested model — rotate credential (model-scoped), else fall backincomplete_response = "incomplete_response" # Codex/Responses turn stuck emitting reasoning only (no answer, no tool call) after replay + nudge — hand to a different provider@@ -862,6 +863,10 @@ def _nous_welcome_tier(c: _Ctx) -> Optional[Verdict]:def _provider_special_cases(c: _Ctx) -> Optional[Verdict]:"""Highest-priority provider-specific shapes that a status code would misroute."""msg, status = c.msg, c.status_code+ # Nous API: the request's data-use requirement (from a connector result) has no qualifying endpoint.+ # Deterministic for this context on any provider, so no retry and no fallback.+ if c.code == "data_policy_denied":+ return _v(_R.data_policy_denied, retryable=False, should_fallback=False)welcome = _nous_welcome_tier(c)if welcome is not None:return welcomediff --git a/agent/error_surface.py b/agent/error_surface.pyindex 2b25512b1ef..6f9d16d6206 100644--- a/agent/error_surface.py+++ b/agent/error_surface.py@@ -54,7 +54,7 @@ _FREE_TIER_RETRYABLE_KINDS = {"rate_limited", "at_capacity", "outage"}# Kept in sync with ``classify_api_error``'s retryable=False verdicts._NON_RETRYABLE_REASONS = {"auth", "auth_permanent", "billing", "billing_unverified", "content_policy_blocked",- "provider_policy_blocked", "model_not_found", "format_error", "ssl_cert_verification",+ "provider_policy_blocked", "data_policy_denied", "model_not_found", "format_error", "ssl_cert_verification","context_overflow", "interpreter_shutdown", "upstream_blocked",}diff --git a/agent/message_metadata.py b/agent/message_metadata.pyindex 14e0bd82a6d..c588a5e19b3 100644--- a/agent/message_metadata.py+++ b/agent/message_metadata.py@@ -50,10 +50,37 @@ PERSISTENCE_ONLY_MESSAGE_FIELDS = frozenset() | REPAIR_BOOKKEEPING_FIELDS+# A tool message's connector data-use requirement (``no_training`` / ``zero_retention``): set from the+# gateway's ``dataUse``, persisted inside ``display_metadata``, read by the Nous profile, stripped by the transport.+DATA_USE = "data_use"+++def data_use_requirement(messages: Any) -> frozenset[str]:+ """The union of ``data_use`` over *messages*: what the model receiving them must guarantee."""+ return frozenset(r for m in messages or () if isinstance(m, Mapping) for r in m.get(DATA_USE) or ())+++def stamp_data_use(message: MutableMapping[str, Any], requires: list[str]) -> None:+ """Mark a tool message with its requirement. The ``display_metadata`` copy is the durable one: that+ column already rides every writer, branch and compaction copy, and replay lifts it back (SessionDB)."""+ if not requires:+ return+ message[DATA_USE] = list(requires)+ metadata = message.get("display_metadata")+ message["display_metadata"] = {**(metadata if isinstance(metadata, dict) else {}), DATA_USE: list(requires)}+++def lift_data_use(message: MutableMapping[str, Any]) -> None:+ """Restore a replayed row's ``data_use`` key from its durable ``display_metadata`` copy."""+ metadata = message.get("display_metadata")+ if isinstance(metadata, dict) and metadata.get(DATA_USE):+ message[DATA_USE] = list(metadata[DATA_USE])++# Replay carriers the preflight estimate prices at 0, exactly as the compaction tail walk does (opaque signatures,# duplicate reasoning copies, ordered sidecars); a mismatch between the two estimates loops compaction.UNPRICED_REPLAY_FIELDS = frozenset({"_anthropic_content_blocks", "reasoning_details", "extra_content",- "reasoning_opaque", "reasoning_text", "bedrock_content_blocks"})+ "reasoning_opaque", "reasoning_text", "bedrock_content_blocks", DATA_USE})def without_persistence_fields(msg: Mapping[str, Any]) -> Mapping[str, Any]:diff --git a/agent/tool_executor.py b/agent/tool_executor.pyindex da36c6a2d13..5209cbf477c 100644--- a/agent/tool_executor.py+++ b/agent/tool_executor.py@@ -43,6 +43,7 @@ from agent.inline_tool_executors import (emit_terminal_post_tool_call,tool_hook_ids,)+from agent.message_metadata import stamp_data_usefrom agent.tool_dispatch_helpers import (_NEVER_PARALLEL_TOOLS,_is_destructive_command,@@ -1161,6 +1162,8 @@ def _commit_tool_result(tool_message["display_metadata"] = metadataexcept Exception as callback_error:logging.debug("Tool result metadata callback error: %s", callback_error)+ from tools.connectors.data_use import take_data_use+ stamp_data_use(tool_message, take_data_use(getattr(agent, "_current_turn_id", "") or "", tool_call_id))messages.append(tool_message)if not _flush_session_db_after_tool_progress(agent, messages, stage=f"tool result {function_name}"):return Nonediff --git a/agent/transports/chat_completions.py b/agent/transports/chat_completions.pyindex 9dad438e46c..9e4ef960801 100644--- a/agent/transports/chat_completions.py+++ b/agent/transports/chat_completions.py@@ -15,7 +15,7 @@ from agent.reasoning_effort import (GEMINI4_THINKING_LEVELS, KIMI_K3_EFFORTS, KIMI_K3_OVERRIDES, OPENAI_COMPAT_WIRE_EFFORTS, clamp_effort,clamp_reasoning_config, kimi_supported_efforts, requested_effort, tokenhub_effort,)-from agent.message_metadata import MESSAGE_UID+from agent.message_metadata import DATA_USE, MESSAGE_UID, data_use_requirementfrom agent.message_sanitization import coalesce_tool_call_id, normalize_finish_reason as _normalize_finish_reasonfrom agent.moonshot_schema import is_moonshot_model, sanitize_moonshot_toolsfrom agent.prompt_builder import DEVELOPER_ROLE_MODELS@@ -41,7 +41,7 @@ _STRIP_MSG_KEYS = (# ``platform_message_id`` is persisted as-is and comes back from replay as ``message_id``# (JSONL transcript compat); both are delivery bookkeeping, never model input."platform_message_id", "message_id", "api_content", "anthropic_content_blocks", "bedrock_content_blocks",- MESSAGE_UID,+ MESSAGE_UID, DATA_USE,)_STRIP_TC_KEYS = ("call_id", "response_item_id")_HIGH_EFFORTS = {"high", "xhigh", "max", "ultra"}@@ -559,6 +559,8 @@ class ChatCompletionsTransport(ProviderTransport):path below (is_kimi, is_openrouter, ...) is only reached for unregistered providers."""_profile = params.get("provider_profile")+ # Read before convert_messages strips the key; only a profile that asks for it consumes it.+ params["data_use"] = data_use_requirement(messages)sanitized = self.convert_messages(messages, model=model, base_url=params.get("base_url"), provider_profile=_profile,provider=params.get("provider_name"),@@ -658,7 +660,7 @@ class ChatCompletionsTransport(ProviderTransport):profile_body = profile.build_extra_body(session_id=params.get("session_id"), provider_preferences=params.get("provider_preferences"), model=model,base_url=params.get("base_url"), reasoning_config=reasoning_config,- openrouter_min_coding_score=params.get("openrouter_min_coding_score"),+ openrouter_min_coding_score=params.get("openrouter_min_coding_score"), data_use=params.get("data_use"),)for part in (profile_body, extra_body_from_profile, params.get("extra_body_additions")):if part:diff --git a/agent/turn_failure_copy.py b/agent/turn_failure_copy.pyindex 2f3b32924d6..f6b466c0cd4 100644--- a/agent/turn_failure_copy.py+++ b/agent/turn_failure_copy.py@@ -216,6 +216,12 @@ _NONRETRYABLE_COPY: dict[str, str] = {"didn't answer and retrying won't help. Check the account with the provider, or switch ""models with /model."),+ FailoverReason.data_policy_denied.value: (+ "This conversation contains a result from a connected app that may only be sent to a model "+ "that does not train on your data, and '{model}' on {label} can't guarantee that. Switch to "+ "another model with /model, run /compress to summarize the result away, or start a new "+ "session with /new."+ ),FailoverReason.upstream_blocked.value: ("A firewall/CDN in front of {label} blocked the request before it reached the model, so ""your key is probably fine. Set a custom User-Agent via the provider's extra_headers, check "@@ -261,6 +267,9 @@ FAILURE_CAUSE_GLOSS: dict[str, str] = {FailoverReason.provider_policy_blocked.value: ("the AI model service refused the request because of a policy on the account"),+ FailoverReason.data_policy_denied.value: (+ "{possessive} context holds a connected-app result that needs a model that does not train on data"+ ),"context_overflow": "{possessive} request grew too large for the model","payload_too_large": "{possessive} request grew too large for the model",}diff --git a/gateway/slash_commands_session.py b/gateway/slash_commands_session.pyindex 189804f8bb9..8dfb87502a0 100644--- a/gateway/slash_commands_session.py+++ b/gateway/slash_commands_session.py@@ -36,7 +36,7 @@ _DM_CHAT_TYPES = {"dm", "direct", "private", ""}_BRANCH_COPIED_FIELDS = ("content", "tool_calls", "tool_call_id", "finish_reason", "reasoning","reasoning_content", "reasoning_details", "codex_reasoning_items",- "codex_message_items", "timestamp")+ "codex_message_items", "timestamp", "data_use")def _sattr(obj, name: str) -> str:diff --git a/hermes_cli/cli_commands_mixin.py b/hermes_cli/cli_commands_mixin.pyindex 21ed6c44c95..d90337b4f38 100644--- a/hermes_cli/cli_commands_mixin.py+++ b/hermes_cli/cli_commands_mixin.py@@ -120,7 +120,7 @@ _WORKTREE_SUBCOMMANDS = {# Message fields copied verbatim onto a /branch row (plus role / tool_name / api_content)._BRANCH_COPY_KEYS = ("content", "tool_calls", "tool_call_id", "reasoning", "reasoning_content", "reasoning_details",- "codex_reasoning_items", "codex_message_items", "timestamp")+ "codex_reasoning_items", "codex_message_items", "timestamp", "data_use")# /hatch progress event -> catalog key (``cli.commands.hatch.*``)._HATCH_PROGRESS = {"compose": "hatch.progress_compose", "save": "hatch.progress_save"}diff --git a/hermes_state_messages.py b/hermes_state_messages.pyindex dd1319e52b8..614e3262dd7 100644--- a/hermes_state_messages.py+++ b/hermes_state_messages.py@@ -15,7 +15,7 @@ from agent.context_compressor import (_newest_checkpoint_carrier, split_user_originated_turn)from agent.memory_context import sanitize_contextfrom agent.message_metadata import (- CANONICAL_ROW, DB_ROW_SNAPSHOT, MESSAGE_UID, TOOL_CALL_UID, TOOL_CALL_UIDS,+ CANONICAL_ROW, DATA_USE, DB_ROW_SNAPSHOT, lift_data_use, MESSAGE_UID, TOOL_CALL_UID, TOOL_CALL_UIDS,index_tool_call_uids, message_uid_or_none, resolve_tool_call_uid, mint_uid, stamp_message_uid)from agent.message_sanitization import _sanitize_surrogates, coalesce_tool_call_idfrom hermes_cli.timefmt import coerce_epoch@@ -276,7 +276,11 @@ class SessionMessagesMixin(SessionDetachedResultsMixin, SessionTodoResultMixin):encoded_content = self._encode_content(msg.get("content"))encoded_tool_calls = json.dumps(tool_calls) if tool_calls else Noneencoded_tool_name = _scrub_surrogates(msg.get("tool_name"))- display_metadata = self._encode_display_metadata(msg.get("display_metadata"))+ display_metadata = msg.get("display_metadata")+ if msg.get(DATA_USE) and isinstance(display_metadata, (dict, type(None))):+ # Writers that copy a fixed field list (/branch) carry the key, not display_metadata.+ display_metadata = {**(display_metadata or {}), DATA_USE: list(msg[DATA_USE])}+ display_metadata = self._encode_display_metadata(display_metadata)identity_row = {"role": role, "content": encoded_content, "timestamp": message_timestamp,"tool_call_id": msg.get("tool_call_id"), "tool_calls": encoded_tool_calls,@@ -1581,6 +1585,7 @@ class SessionMessagesMixin(SessionDetachedResultsMixin, SessionTodoResultMixin):msg.update((col, row[col]) for col in ("api_content", "display_kind") if row[col])if row["display_metadata"] and (decoded := self._decode_display_metadata(row["display_metadata"])) is not None:msg["display_metadata"] = decoded+ lift_data_use(msg)if include_summary_markers and row["_compressed_summary"]:msg["_compressed_summary"] = Truemsg.update(diff --git a/hermes_state_runtime.py b/hermes_state_runtime.pyindex 60aaf594952..516e3ea4615 100644--- a/hermes_state_runtime.py+++ b/hermes_state_runtime.py@@ -9,7 +9,7 @@ from typing import NamedTuple, Optionalfrom agent.conversation_compression_archive import ABSORBED_ROW_IDSfrom agent.message_metadata import (- CANONICAL_ROW, DB_ROW_SNAPSHOT, MESSAGE_UID, PERSISTENCE_ONLY_MESSAGE_FIELDS, TOOL_CALL_UID, TOOL_CALL_UIDS,+ CANONICAL_ROW, DATA_USE, DB_ROW_SNAPSHOT, MESSAGE_UID, PERSISTENCE_ONLY_MESSAGE_FIELDS, TOOL_CALL_UID, TOOL_CALL_UIDS,)from hermes_state_keys import admission_fingerprint@@ -797,7 +797,7 @@ _MESSAGE_FIELDS = frozenset({'finish_reason', 'reasoning', 'reasoning_content', 'reasoning_details','codex_reasoning_items', 'codex_message_items', 'platform_message_id', 'message_id','observed', 'effect_disposition', '_compressed_summary', 'timestamp', 'api_content',- 'display_kind', 'display_metadata', '_row_id', '_canonical_content', DB_ROW_SNAPSHOT, CANONICAL_ROW,+ 'display_kind', 'display_metadata', '_row_id', '_canonical_content', DB_ROW_SNAPSHOT, CANONICAL_ROW, DATA_USE,# Main's durable message identity (message_uid / merge witness / tool-call uids) and the alternation# repair's row counts ride every persisted dict; the owner's insert and coverage read them.}) | PERSISTENCE_ONLY_MESSAGE_FIELDS | {ABSORBED_ROW_IDS}diff --git a/plugins/model-providers/nous/__init__.py b/plugins/model-providers/nous/__init__.pyindex 2e37e3d4a3f..e30d2456aa3 100644--- a/plugins/model-providers/nous/__init__.py+++ b/plugins/model-providers/nous/__init__.py@@ -20,7 +20,9 @@ class NousProfile(ProviderProfile):except Exception:return ""- def build_extra_body(self, *, session_id: str | None = None, **context) -> dict[str, Any]:+ def build_extra_body(+ self, *, session_id: str | None = None, data_use: frozenset[str] = frozenset(), **context,+ ) -> dict[str, Any]:body: dict[str, Any] = {"tags": nous_portal_tags(session_id=session_id)}# Top-level session_id = sticky routing key, so Anthropic-style cache# breakpoints stay warm on one upstream instance. Resolved like the@@ -29,10 +31,10 @@ class NousProfile(ProviderProfile):sticky_key = _cache_scope_from_session_id(get_affinity_scope() or get_conversation_context() or session_id)if sticky_key:body["session_id"] = sticky_key- # Nous Portal inference rejects caller-supplied provider routing prefs- # (only/ignore/order/sort/data_collection/zdr/require_parameters) with- # HTTP 400 — routing is decided centrally per model. provider_routing- # from config.yaml is OpenRouter-only, so it is not forwarded here.+ # The Portal routes centrally and 400s on caller routing fields, except data_collection and+ # zdr: sent only when an outgoing connector result requires them (``data_use``), never from config.+ if data_use:+ body["provider"] = {"data_collection": "deny", **({"zdr": True} if "zero_retention" in data_use else {})}return body@staticmethoddiff --git a/tests/agent/test_error_classifier_data_policy.py b/tests/agent/test_error_classifier_data_policy.pynew file mode 100644index 00000000000..9b7cda502ce--- /dev/null+++ b/tests/agent/test_error_classifier_data_policy.py@@ -0,0 +1,18 @@+"""A Nous 403 ``data_policy_denied`` is deterministic for this context: no retry, no rotation, no fallback."""++from agent.error_classifier import FailoverReason, classify_api_error+++class _ForbiddenError(Exception):+ def __init__(self, body):+ super().__init__("Forbidden")+ self.status_code = 403+ self.body = body+++def test_403_data_policy_denied_never_retries_or_falls_back():+ body = {"error": {"code": "data_policy_denied", "type": "data_policy_denied", "message": "No endpoint qualifies.",+ "requirement": ["no_training"], "sources": ["request"], "suggested_action": "switch_model"}}+ result = classify_api_error(_ForbiddenError(body), provider="nous")+ assert result.reason == FailoverReason.data_policy_denied+ assert (result.retryable, result.should_fallback, result.should_rotate_credential) == (False, False, False)diff --git a/tests/agent/test_nous_portal_anthropic_wire.py b/tests/agent/test_nous_portal_anthropic_wire.pyindex 9aeb5982c94..0451986fc88 100644--- a/tests/agent/test_nous_portal_anthropic_wire.py+++ b/tests/agent/test_nous_portal_anthropic_wire.py@@ -326,7 +326,7 @@ class TestPortalBodyFields:kwargs = {"model": "claude-opus-4-8", "messages": []}agent = SimpleNamespace(provider="anthropic", session_id="s")- assert _merge_nous_portal_messages_extra_body(agent, kwargs) is kwargs+ assert _merge_nous_portal_messages_extra_body(agent, kwargs, []) is kwargsassert "extra_body" not in kwargsdiff --git a/tests/agent/test_provider_parity.py b/tests/agent/test_provider_parity.pyindex b9e9a1d0d43..d80fa02d320 100644--- a/tests/agent/test_provider_parity.py+++ b/tests/agent/test_provider_parity.py@@ -358,6 +358,35 @@ class TestBuildApiKwargsNousPortal:extra = kwargs.get("extra_body", {})assert extra.get("tags") == nous_portal_tags(session_id=agent.session_id)+ @pytest.mark.parametrize("data_use,provider", [+ (None, None),+ (["no_training"], {"data_collection": "deny"}),+ (["zero_retention"], {"data_collection": "deny", "zdr": True}),+ ])+ def test_connector_data_use_asks_for_a_no_training_route_and_never_reaches_the_wire(+ self, monkeypatch, data_use, provider):+ agent = _make_agent(monkeypatch, "nous", base_url="https://inference-api.nousresearch.com/v1", model="gpt-5")+ tool = {"role": "tool", "tool_call_id": "c1", "content": "inbox"}+ messages = [+ {"role": "user", "content": "read my mail"},+ {"role": "assistant", "content": "", "tool_calls": [+ {"id": "c1", "type": "function", "function": {"name": "tool_call", "arguments": "{}"}}]},+ {**tool, **({"data_use": data_use} if data_use else {})},+ ]+ kwargs = agent._build_api_kwargs(messages)+ assert kwargs["extra_body"].get("provider") == provider+ assert kwargs["messages"][-1] == tool++ def test_connector_data_use_is_not_sent_to_other_providers(self, monkeypatch):+ agent = _make_agent(monkeypatch, "openrouter")+ messages = [{"role": "user", "content": "hi"},+ {"role": "assistant", "content": "", "tool_calls": [+ {"id": "c1", "type": "function", "function": {"name": "tool_call", "arguments": "{}"}}]},+ {"role": "tool", "tool_call_id": "c1", "content": "inbox", "data_use": ["no_training"]}]+ kwargs = agent._build_api_kwargs(messages)+ assert "provider" not in kwargs.get("extra_body", {})+ assert "data_use" not in kwargs["messages"][-1]+class TestBuildApiKwargsCustomEndpoint:diff --git a/tests/agent/test_tool_call_incremental_persistence.py b/tests/agent/test_tool_call_incremental_persistence.pyindex 7eaf2da776d..9e10dc624c0 100644--- a/tests/agent/test_tool_call_incremental_persistence.py+++ b/tests/agent/test_tool_call_incremental_persistence.py@@ -502,6 +502,39 @@ def test_tool_result_is_durable_before_ui_completion_on_abnormal_exit(assert durable[2]["content"] == "repository result"+def test_connector_data_use_rides_the_tool_message_and_survives_a_reload(tmp_path):+ """The requirement dispatch recorded lands on the tool message as metadata (content untouched)+ and comes back from the session DB on resume."""+ from tools.connectors.data_use import record_data_use++ agent = _make_agent()+ db_path = tmp_path / "state.db"+ db = _attach_real_session_db(agent, db_path, "data-use")+ agent._current_turn_id = "turn-1"+ messages = [{"role": "user", "content": "read my mail"},+ {"role": "assistant", "content": "", "tool_calls": [+ {"id": "mail-call", "type": "function", "function": {"name": "web_search", "arguments": "{}"}}]}]+ agent._flush_messages_to_session_db(messages)++ def _dispatch(name, args, task_id, **kwargs):+ record_data_use(kwargs["turn_id"], kwargs["tool_call_id"], ["no_training"])+ return '{"results": [{"response": "inbox"}]}'++ try:+ with (patch("model_tools.handle_function_call", side_effect=_dispatch),+ patch("agent.tool_executor.maybe_persist_tool_result", side_effect=lambda **kw: kw["content"])):+ agent._execute_tool_calls_sequential(+ SimpleNamespace(content="", tool_calls=[_mock_tool_call(call_id="mail-call")]), messages, "task-1")+ finally:+ db.close()++ plain = make_tool_result_message("web_search", '{"results": [{"response": "inbox"}]}', "mail-call")+ assert messages[-1]["content"] == plain["content"]+ assert messages[-1]["data_use"] == ["no_training"]+ durable = _durable_messages(db_path, "data-use")[-1]+ assert (durable["content"], durable["data_use"]) == (messages[-1]["content"], ["no_training"])++@pytest.mark.parametrize("executor_mode", ["sequential", "concurrent"])def test_failed_tool_result_persist_blocks_completion_projection(executor_mode):agent = _make_agent()diff --git a/tests/tools/test_connector_dispatch_policy.py b/tests/tools/test_connector_dispatch_policy.pyindex 1bfd24ecb2c..d3b496108a0 100644--- a/tests/tools/test_connector_dispatch_policy.py+++ b/tests/tools/test_connector_dispatch_policy.py@@ -121,3 +121,31 @@ def test_disabled_connections_cannot_be_called_through_a_stale_schema(monkeypatclambda **_: (_ for _ in ()).throw(AssertionError("disabled connector attempted I/O")))result = json.loads(registry.dispatch("manage_connections", {"action": "connect", "connectors": ["gmail"]}))assert "not available" in result["error"]+++def test_a_connector_batch_records_the_union_of_data_use_and_keeps_it_out_of_the_result(monkeypatch):+ import model_tools+ from tools.connectors import take_data_use+ from tools.connectors.gateway import bridge, config+ from tools.registry import invalidate_check_fn_cache++ monkeypatch.setattr(config, "connectors_available", lambda: True)+ monkeypatch.setattr(bridge, "connectors_available", lambda: True)+ invalidate_check_fn_cache()+ requires = {"gmail": ["no_training"], "googledrive": ["zero_retention"], "slack": None}++ class Client:+ def execute(self, planned, **_):+ return [{"data": "row", "error": None, **({"data_use": requires[p.connector]} if requires[p.connector] else {})}+ for p in planned]++ monkeypatch.setattr(bridge, "_default_client_factory", lambda call=None: Client())+ calls = [{"name": f"connectors__{c}__READ", "arguments": {}} for c in requires]+ raw = model_tools.handle_function_call(+ "tool_call", {"calls": calls}, enabled_toolsets=["connections"], session_id="s", tool_call_id="batch-1",+ turn_id="turn-1", skip_pre_tool_call_hook=True, skip_tool_request_middleware=True,+ skip_tool_execution_middleware=True)++ assert "data_use" not in raw+ assert [r["response"] for r in json.loads(raw)["results"]] == ["row", "row", "row"]+ assert take_data_use("turn-1", "batch-1") == ["no_training", "zero_retention"]diff --git a/tests/tools/test_connectors_gateway_client.py b/tests/tools/test_connectors_gateway_client.pyindex 18220a0eed3..416382bd107 100644--- a/tests/tools/test_connectors_gateway_client.py+++ b/tests/tools/test_connectors_gateway_client.py@@ -114,6 +114,17 @@ def test_execute_sends_one_single_call_request_per_call_with_its_own_key():]+def test_execute_result_carries_the_gateway_data_use_requirement():+ gmail = single_result("gmail", "GMAIL_FETCH_EMAILS", {"id": "m1"})+ gmail["result"]["dataUse"] = {"requires": ["no_training"]}+ transport = FakeTransport(FakeResponse(200, gmail), FakeResponse(200, single_result("slack", "SLACK_POST_MESSAGE", "ok")))++ results = make_client(transport).execute(planned())++ assert results == [{"data": {"id": "m1"}, "error": None, "data_use": ["no_training"]},+ {"data": "ok", "error": None}]++def test_retry_on_5xx_reuses_the_same_idempotency_key():transport = FakeTransport(FakeResponse(502, {"error": {"code": "BAD_GATEWAY", "message": "upstream"}}),diff --git a/tools/connectors/__init__.py b/tools/connectors/__init__.pyindex 51f4ce054b2..379c65e4d36 100644--- a/tools/connectors/__init__.py+++ b/tools/connectors/__init__.py@@ -23,6 +23,7 @@ _LAZY_EXPORTS: dict[str, str] = {"ensure_guest_identity": "tools.connectors.gateway.config","guest_identity_pending": "tools.connectors.gateway.config","is_connector_name": "tools.connectors.gateway.names",+ "take_data_use": "tools.connectors.data_use","manage_connections": "tools.connectors.tool",}diff --git a/tools/connectors/data_use.py b/tools/connectors/data_use.pynew file mode 100644index 00000000000..5cb706bb1f0--- /dev/null+++ b/tools/connectors/data_use.py@@ -0,0 +1,35 @@+"""Data-use requirements of connector results, handed from dispatch to the tool message.++The result string the model reads never carries them: dispatch records the requirement here under the+call's ``(turn_id, tool_call_id)`` and the agent's tool executor takes it when it builds the tool message,+storing it as that message's ``data_use`` metadata (``agent.message_metadata.DATA_USE``).+"""++from __future__ import annotations++import threading+from typing import Iterable, Optional++_LOCK = threading.Lock()+_PENDING: dict[tuple[str, str], frozenset[str]] = {}+# Callers outside the agent's tool executor (execute_code RPC, MCP serve) never take; keep that bounded.+_MAX_PENDING = 512+++def record_data_use(turn_id: Optional[str], tool_call_id: Optional[str], requires: Iterable[str]) -> None:+ wanted = frozenset(requires)+ if not tool_call_id or not wanted:+ return+ with _LOCK:+ key = (turn_id or "", tool_call_id)+ _PENDING[key] = _PENDING.pop(key, frozenset()) | wanted+ while len(_PENDING) > _MAX_PENDING:+ _PENDING.pop(next(iter(_PENDING)))+++def take_data_use(turn_id: Optional[str], tool_call_id: Optional[str]) -> list[str]:+ """The requirement recorded for this call (sorted), removing it; ``[]`` when none was recorded."""+ if not tool_call_id:+ return []+ with _LOCK:+ return sorted(_PENDING.pop((turn_id or "", tool_call_id), ()))diff --git a/tools/connectors/dispatch.py b/tools/connectors/dispatch.pyindex af04ad5d476..9e52d41ef6c 100644--- a/tools/connectors/dispatch.py+++ b/tools/connectors/dispatch.py@@ -9,12 +9,14 @@ from tools.connectors.gateway.merge import assemble_results, fill_remote_failuredef dispatch_connector_call(name, arguments, tool_call_id, turn_id=None, task_id=None):+ from tools.connectors.data_use import record_data_usefrom tools.connectors.gateway.bridge import run_remotepartition = partition_calls([{"name": name, "arguments": arguments}])entries = run_remote(partition.remote, tool_call_id, availability=None, client_factory=None, turn_id=turn_id,task_id=task_id)entry = entries[0]+ record_data_use(turn_id, tool_call_id, entry.get("data_use") or ())return json.dumps({key: value for key, value in entry.items() if key in {"response", "error", "account"}},ensure_ascii=False)@@ -24,6 +26,7 @@ def dispatch_connector_batch(calls, ids, *, user_task, enabled_tools,from dataclasses import replacefrom model_tools import handle_function_call, suppress_post_tool_call_hook+ from tools.connectors.data_use import record_data_use, take_data_usefrom tools.interrupt import is_interruptedif len(calls) > MAX_CALLS_PER_DISPATCH:@@ -34,6 +37,7 @@ def dispatch_connector_batch(calls, ids, *, user_task, enabled_tools,from tools.tool_search_validation import local_batch_errorreturn tool_error(local_batch_error(calls))entries = list(partition.errors)+ requires: set[str] = set()for offset, plan in enumerate(partition.remote):if is_interrupted():# Check before every entry so /stop prevents unstarted remote side effects.@@ -52,6 +56,8 @@ def dispatch_connector_batch(calls, ids, *, user_task, enabled_tools,skip_tool_execution_middleware=False,enabled_toolsets=enabled_toolsets, disabled_toolsets=disabled_toolsets,)+ # The batch is one tool message: it carries the union of its entries' requirements.+ requires.update(take_data_use(entry_ids.turn_id, entry_ids.tool_call_id))try:value = json.loads(payload) if isinstance(payload, str) else payloadexcept ValueError:@@ -65,4 +71,5 @@ def dispatch_connector_batch(calls, ids, *, user_task, enabled_tools,if isinstance(value, dict) and value.get("account"):entry["account"] = value["account"]entries.append(entry)+ record_data_use(ids.turn_id, ids.tool_call_id, requires)return json.dumps(assemble_results(len(calls), entries), ensure_ascii=False)diff --git a/tools/connectors/gateway/client.py b/tools/connectors/gateway/client.pyindex 31f9a688d29..4c2485643b1 100644--- a/tools/connectors/gateway/client.py+++ b/tools/connectors/gateway/client.py@@ -319,10 +319,7 @@ class ConnectorClient:if 200 <= status < 300:reply = _Reply(payload, status, request_id, _EXECUTE_ROUTE)parsed = self._checked(wire.ConnectorExecuteSingleResponse, reply, "connector execute result")- entry = {"data": parsed.result.data, "error": None}- if parsed.result.account:- entry["account"] = parsed.result.account- return entry+ return _result_dict(parsed.result)headers = getattr(response, "headers", None)failure = _call_failure(payload)code = failure.code if failure else parse_gateway_error(status, payload, headers).code@@ -476,13 +473,13 @@ def _route_key(path: str) -> str:return ".".join(parts) or path-def _result_dict(result: wire.ConnectorExecuteResult) -> dict[str, Any]:- error = None- if result.error is not None:- error = _error_dict(result.error)- entry = {"data": result.data, "error": error}+def _result_dict(result: wire.ConnectorExecuteResult | wire.ConnectorExecuteSingleResult) -> dict[str, Any]:+ error = getattr(result, "error", None)+ entry = {"data": result.data, "error": _error_dict(error) if error is not None else None}if result.account:entry["account"] = result.account+ if result.data_use is not None and result.data_use.requires:+ entry["data_use"] = list(result.data_use.requires)return entrydiff --git a/tools/connectors/gateway/merge.py b/tools/connectors/gateway/merge.pyindex da8b58a1102..3fc2d4bfd28 100644--- a/tools/connectors/gateway/merge.py+++ b/tools/connectors/gateway/merge.py@@ -91,7 +91,11 @@ def render_remote_entry(planned: PlannedCall, remote: Mapping[str, Any]) -> dictaccount = _opt_str(remote.get("account")) if isinstance(remote, Mapping) else Noneif not isinstance(error, Mapping):data = remote.get("data") if isinstance(remote, Mapping) else None- return _with_account({"index": planned.position, "name": planned.name, "response": data}, account)+ entry = _with_account({"index": planned.position, "name": planned.name, "response": data}, account)+ # Message metadata, never model content: dispatch lifts it off before the result is rendered.+ if isinstance(remote, Mapping) and remote.get("data_use"):+ entry["data_use"] = list(remote["data_use"])+ return entrycode = str(error.get("code") or "PROVIDER_ERROR")message = str(error.get("message") or "The gateway reported an error.")diff --git a/tools/connectors/gateway/wire.py b/tools/connectors/gateway/wire.pyindex cfb2b845814..c4b39c70d37 100644--- a/tools/connectors/gateway/wire.py+++ b/tools/connectors/gateway/wire.py@@ -191,11 +191,20 @@ class ConnectorExecuteSingleRequest(_Wire):op: Optional[str] = Field(default=None, min_length=1, max_length=128)+# What a model receiving this result must guarantee; absent when the connector asks nothing.+DataUseRequirement = Literal["no_training", "zero_retention"]+++class ConnectorDataUse(_Wire):+ requires: list[DataUseRequirement]++class ConnectorExecuteSingleResult(_Wire):connector: str = ""tool: str = ""data: Any = Noneaccount: Optional[str] = None+ data_use: Optional[ConnectorDataUse] = Field(default=None, alias="dataUse")class ConnectorExecuteSingleResponse(_Wire):@@ -211,6 +220,7 @@ class ConnectorExecuteResult(_Wire):error: Optional[ConnectorToolError] = None# The alias of the account the call ran under; null when that account has no alias.account: Optional[str] = None+ data_use: Optional[ConnectorDataUse] = Field(default=None, alias="dataUse")class ConnectorExecuteResponse(_Wire):