The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui_gateway): keep a quoted prompt out of the turn-finished cause
Jack Lau4828b4a9e227
diff --git a/tests/tui_gateway/test_turn_finished_failure_cause.py b/tests/tui_gateway/test_turn_finished_failure_cause.pyindex 4a238f977a1..307b89a0202 100644--- a/tests/tui_gateway/test_turn_finished_failure_cause.py+++ b/tests/tui_gateway/test_turn_finished_failure_cause.py@@ -217,6 +217,56 @@ class TestContentDiscipline:# The diagnostic value survives the redaction — this is the point.assert "400 from provider" in msg+ SENTINEL = "the marmalade inventory for Q3 was discontinued in March"++ def test_a_prompt_the_provider_quotes_back_does_not_reach_the_record(+ self, turn_env, caplog+ ):+ """Secret redaction is not prompt omission, and this is the difference.++ A provider that rejects a request routinely quotes it back. The quoted+ material is the user's own prose: it matches no credential pattern, so+ ``redact_sensitive_text`` passes it through untouched, and adding the+ cause to this record would newly persist user content that #86865+ deliberately kept out of it. The sentinel here is deliberately benign+ for that reason: nothing about it looks like a secret.+ """+ session = _session(agent=_agent_returning({+ "final_response": "",+ "error": (+ "400 Bad Request from provider: messages[0].content was "+ "rejected: '" + self.SENTINEL + "'"+ ),+ "failed": True,+ }))++ with caplog.at_level(logging.INFO, logger="tui_gateway.server"):+ _run(session, "Summarise this: " + self.SENTINEL)++ msg = _finished(caplog)+ assert self.SENTINEL not in msg+ assert "marmalade" not in msg+ assert "<prompt>" in msg, "the removal should be visible, not silent"+ # The whole point of the cause survives the removal.+ assert "400 Bad Request from provider" in msg++ def test_a_provider_message_that_shares_nothing_is_untouched(+ self, turn_env, caplog+ ):+ """The echo strip must not eat diagnostics that merely sit near a prompt."""+ session = _session(agent=_agent_returning({+ "final_response": "",+ "error": "429 rate limited; retry after 30s",+ "failed": True,+ }))++ with caplog.at_level(logging.INFO, logger="tui_gateway.server"):+ _run(session, "Summarise this: " + self.SENTINEL)++ msg = _finished(caplog)+ assert "429 rate limited; retry after 30s" in msg+ assert "<prompt>" not in msg+def test_a_huge_provider_body_cannot_flood_the_log(self, turn_env, caplog):"""An HTML error page or a full request echo is a log-volume problem."""session = _session(agent=_agent_returning({@@ -272,6 +322,11 @@ class TestDetailHelperDirectly:def test_an_exception_with_no_message_still_names_its_type(self):assert "KeyError" in server._turn_failure_detail(KeyError())+ def test_the_prompt_argument_is_optional(self):+ """Callers without a prompt in scope still get the secret contract."""+ out = server._turn_failure_detail("Bearer sk-proj-supersecretvalue1234")+ assert "supersecretvalue1234" not in out+def test_a_broken_redactor_fails_closed(self, monkeypatch):"""If redaction cannot run, the raw message must not reach the log.@@ -288,3 +343,43 @@ class TestDetailHelperDirectly:out = server._turn_failure_detail("Bearer sk-proj-supersecretvalue")assert "supersecretvalue" not in outassert "unredactable" in out+++class TestPromptEchoStripping:+ """``_strip_prompt_echo`` in isolation: the boundaries of the guarantee."""++ def test_an_overlap_below_the_window_is_not_an_echo(self):+ """Short shared phrases are coincidence, and eating them costs detail."""+ out = server._strip_prompt_echo("400: invalid model", "invalid model")+ assert out == "400: invalid model"++ def test_a_json_escaped_echo_is_stripped_too(self):+ """A provider handing back its own request body often hands it escaped."""+ prompt = "please summarise the Q3 marmalade inventory memo for me"+ message = 'upstream body: {"messages": [{"content": "' + prompt + '"}]}'+ out = server._strip_prompt_echo(message, prompt)+ assert "marmalade" not in out+ assert "<prompt>" in out++ def test_an_echo_is_removed_before_the_length_cap_applies(self):+ """A quote must not survive by starting inside the kept prefix."""+ prompt = "the confidential merger memorandum for the northern division"+ error = ("x" * 200) + " echoed request: " + prompt+ out = server._turn_failure_detail(error, None, prompt)+ assert "merger memorandum" not in out+ assert "confidential" not in out++ def test_a_prompt_shorter_than_the_window_cannot_blank_the_message(self):+ """A one-word prompt must not turn every message into <prompt>."""+ out = server._strip_prompt_echo("provider said no", "hi")+ assert out == "provider said no"++ def test_whitespace_shape_does_not_hide_an_echo(self):+ """Both sides are collapsed, so a re-wrapped quote still matches."""+ prompt = "the marmalade inventory for Q3 was discontinued in March"+ error = (+ "rejected: the marmalade inventory\n"+ " for Q3 was discontinued in March"+ )+ out = server._turn_failure_detail(error, None, prompt)+ assert "marmalade" not in outdiff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex fddb1cbbd5e..a12fed006dd 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -9978,9 +9978,70 @@ def _fail_inflight_turn(_TURN_FAILURE_DETAIL_LIMIT = 240+# Shortest run of the submitted prompt that counts as the provider quoting it+# back. Long enough that shared boilerplate ("Invalid request for model ") does+# not trip it, short enough to catch a quoted sentence.+_TURN_PROMPT_ECHO_WINDOW = 24+# Ceiling on the prompt we shingle. An @-expanded prompt can carry a whole+# file; the failure path must stay cheap.+_TURN_PROMPT_ECHO_MAX_PROMPT = 65536+++def _strip_prompt_echo(message: str, prompt: Any) -> str:+ """Blank runs of the submitted prompt that ``message`` quotes back.++ Secret redaction and prompt omission are different contracts, and only the+ first one is pattern-based. A provider 4xx that echoes the request carries+ ordinary private prose -- a paragraph about a person, a pasted file from an+ ``@`` reference -- that matches no credential pattern and would otherwise+ reach the log intact. This closes that path directly: anything the message+ shares with the prompt for ``_TURN_PROMPT_ECHO_WINDOW`` characters or more+ becomes ``<prompt>``.++ Shingle-set matching, not a diff: cost is linear in both strings, which+ matters because this runs on every failed turn and an ``@`` reference can+ make the prompt arbitrarily long. The JSON-escaped form of the prompt is+ shingled too, since a provider that hands back its own request body often+ hands it back escaped.++ Verbatim echo is what this stops. A paraphrase, a re-encoding (base64, a+ different unicode normalization) or a summary of the prompt would survive,+ so this is a floor and not a proof; the guarantee it does give is that the+ prompt cannot reach the record by being quoted.+ """+ if not message or not prompt:+ return message+ needle = " ".join(str(prompt).split())[:_TURN_PROMPT_ECHO_MAX_PROMPT]+ window = _TURN_PROMPT_ECHO_WINDOW+ if len(needle) < window or len(message) < window:+ return message+ shingles = {needle[i:i + window] for i in range(len(needle) - window + 1)}+ try:+ escaped = json.dumps(needle)[1:-1]+ except Exception:+ escaped = ""+ if escaped and escaped != needle:+ shingles.update(+ escaped[i:i + window] for i in range(len(escaped) - window + 1)+ )+ out: list[str] = []+ i = 0+ n = len(message)+ while i <= n - window:+ if message[i:i + window] in shingles:+ j = i + window+ while j < n and message[j - window + 1:j + 1] in shingles:+ j += 1+ out.append("<prompt>")+ i = j+ else:+ out.append(message[i])+ i += 1+ out.append(message[i:])+ return "".join(out)-def _turn_failure_detail(error: Any, reason: Any = None) -> str:+def _turn_failure_detail(error: Any, reason: Any = None, prompt: Any = None) -> str:"""Render why a turn failed, for the ``tui turn finished`` bookend.Returns ``""`` when there is nothing to say, otherwise a fragment that@@ -9996,9 +10057,18 @@ def _turn_failure_detail(error: Any, reason: Any = None) -> str:emits no other log line at all; only the exception path prints to stderr,which is why the quiet failures are the ones that get filed.- Content discipline follows #86865's: the prompt is never logged, and the- provider's message is redacted and truncated before it reaches a log file,- because a 4xx body can quote the request that produced it.+ Content discipline follows #86865's, and it takes two separate steps+ because it is two separate contracts. ``redact_sensitive_text`` removes+ credentials, which are pattern-shaped. It does nothing about a 4xx body+ that quotes the request back, because ordinary private prose is not+ pattern-shaped -- so ``_strip_prompt_echo`` removes that separately, using+ the submitted ``prompt`` itself as the thing to look for. The invariant the+ two of them keep is: this record may gain failure classification and+ provider detail, and may not newly persist the user's own content.++ ``prompt`` is optional so the helper stays callable from a path that has no+ prompt in scope, but the turn paths always pass it; without it, only the+ secret contract is enforced."""reason_text = str(reason or "").strip()message = str(error or "").strip()@@ -10015,6 +10085,10 @@ def _turn_failure_detail(error: Any, reason: Any = None) -> str:# message into the log by failing open.message = "<unredactable>"message = " ".join(message.split())+ # After the collapse, so both sides are compared in the same shape, and+ # before the truncation, so a quote that starts inside the kept prefix+ # cannot survive by being cut mid-run.+ message = _strip_prompt_echo(message, prompt)if len(message) > _TURN_FAILURE_DETAIL_LIMIT:message = message[:_TURN_FAILURE_DETAIL_LIMIT] + "\u2026"out = ""@@ -13041,6 +13115,11 @@ def _run_prompt_submit(# exception is reliably in scope, so both failure paths stash their# cause here on the way past.turn_error_detail = ""+ # What this turn actually submitted, kept only so the cause can be+ # checked for quoting it back (see _strip_prompt_echo). Bound here+ # rather than read from the turn body because the exception path can+ # fire before the prompt is resolved.+ turn_prompt_text = ""# Durable crash marker: written before the turn runs, retired the# moment its outcome reaches the client (see _retire_turn_marker).# Any concluded turn — success, handled error, interrupt — retires@@ -13147,6 +13226,11 @@ def _run_prompt_submit(returnprompt = ctx.message+ # After @-expansion on purpose: an injected file's contents are+ # exactly the kind of private material a provider echo would carry+ # back, and they are not in `text`.+ turn_prompt_text = prompt if isinstance(prompt, str) else ""+# Decide image routing per-turn based on active provider/model.# "native" → pass pixels to the main model as OpenAI-style content# parts (adapters translate for Anthropic/Gemini/Bedrock/etc.).@@ -13563,6 +13647,7 @@ def _run_prompt_submit(turn_error_detail = _turn_failure_detail((result.get("error") if isinstance(result, dict) else raw),(result.get("failure_reason") if isinstance(result, dict) else None),+ turn_prompt_text,)else:_clear_inflight_turn(session)@@ -13792,7 +13877,9 @@ def _run_prompt_submit(retire_marker=terminal_receipt_committed,)turn_error_retained = True- turn_error_detail = _turn_failure_detail(e, type(e).__name__)+ turn_error_detail = _turn_failure_detail(+ e, type(e).__name__, turn_prompt_text+ )except Exception as emit_exc:print(f"[gateway-turn] terminal error emit failed: "