fix(output-shaper): don't add Responses instructions to a body already steered in input (#4937)

## Problem

Some Responses upstreams reject the `instructions` field. Kiro's runtime
(Kiro CLI 3.x and the Kiro IDE, V3 harness) answers `400 "systemPrompt
field is not enabled for this user"`.

For those clients, the Kiro extension's `on_responses_create` hook puts
the output-steering block at the end of the user turns instead. Core's
Responses shaper runs after the hooks and appended a second copy as
`instructions`. With the output shaper on, every steered Kiro request
failed.

## Fix

`apply_openai_responses_verbosity_steering` now leaves a body alone when
a **user message ends with a steering block**. That is exactly where
`replace_or_append_steering_block` puts it.

Tool outputs and quoted text don't count. Devin pointed out that the
first version, which scanned the whole `input`, stopped steering a Codex
request whose tool output quoted `STEERING_SENTINEL` (for example, while
reading `output_verbosity_policy.py`). Nothing changes for clients that
aren't steered in `input`.

## Tests

New tests. Each fails before its fix and passes after:
- `test_openai_responses_steering_skips_a_body_already_steered_in_input`
-
`test_openai_responses_steering_skips_input_text_parts_already_steered`
-
`test_openai_responses_steering_ignores_the_marker_quoted_in_tool_output`
(Devin's example)
-
`test_openai_responses_steering_ignores_a_user_quoting_the_marker_mid_message`

Results:
- `tests/test_output_steering.py` and `tests/test_output_shaper*.py`: 97
passed.
- `pytest -k "steer or shaper or verbosity or responses"`: 673 passed,
14 skipped.
- Ruff 0.17.4 check and format: clean.

## Real behavior proof

**Setup:**
- macOS 27.2.1, Python 3.13.15, kiro-cli 3.5.0 (V3 harness, model
`auto`), a real Kiro account.
- Proxy: headroom-ai 0.44.0 with this PR's `output_steering.py` change
applied, plus headroom-kiro#7 (`ccbad4b`).
- Extensions:
`control_plane,kiro,lossless_guard,oauth2,observability,skill_search,tool_search`.
- `HEADROOM_OUTPUT_SHAPER=1 HEADROOM_VERBOSITY_LEVEL=3`.
- A logging relay between the proxy and `runtime.us-east-1.kiro.dev`
recorded each forwarded body and status.

**Steps:**
1. `kiro-cli settings api.krs.service
'{"endpoint":"http://127.0.0.1:8789","region":"us-east-1"}'`
2. Run a fixed 6-step coding task in an itsdangerous checkout with
`kiro-cli chat --v3 --no-interactive`: git log, pytest, grep, read
signer.py, list tests, write release notes.

**Observed after the fix** (relay record of what reached Kiro):
```
   4 /v1/responses 200
   2 / 200                      (KiroRuntimeService control calls)
   4 no-instructions steered    (every Responses turn: steering in the user prompt, no `instructions`)
   2 no-instructions unsteered  (control calls)
proxy errors=0; credits billed 0.3346 over 4 requests
```

**Before the fix**, same setup: the forwarded body carried
`instructions`, and Kiro answered `400 systemPrompt field is not enabled
for this user` on the first turn.

**Not tested:**
- Kiro IDE (same harness, not driven here).
- Codex live. The tool-output case is covered by the unit test, not a
live Codex session.
- Steering levels other than 3.
- Windows and Linux.

Part of the Kiro V3 POC set: headroom-kiro#7, tool-search#35,
skill-search#18, lossless-guard#16, partner-trial#47.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tejas Chopra
2026-11-19 06:44:05 -08:00
committed by GitHub
co-authored by Claude Opus 5.5
parent ec2ab21844
commit 3a8270b836
2 changed files with 102 additions and 1 deletions
+42 -1
View File
@@ -7,6 +7,9 @@ from typing import Any
from headroom.proxy.output_verbosity_policy import (
STEERING_SENTINEL as _STEERING_SENTINEL,
)
from headroom.proxy.output_verbosity_policy import (
STEERING_SUFFIX as _STEERING_SUFFIX,
)
from headroom.proxy.output_verbosity_policy import (
replace_or_append_steering_block,
steering_text,
@@ -113,14 +116,52 @@ def apply_openai_chat_verbosity_steering(
return False
def _input_already_steered(items: Any) -> bool:
"""True when a user message in a Responses ``input`` ends with a steering block.
Only user messages are read, and only a block at the very end counts: that is where
``replace_or_append_steering_block`` puts it. Tool outputs and quoted source can contain the
marker text (this module's own policy file does) without anything having been steered, and
must not switch core's steering off.
"""
if isinstance(items, str): # Responses accepts a bare string as one user message
items = [{"role": "user", "content": items}]
if not isinstance(items, list):
return False
for item in items:
if not isinstance(item, dict) or item.get("role") != "user":
continue
if item.get("type") not in (None, "message"):
continue
content = item.get("content")
parts = content if isinstance(content, list) else [{"text": content}]
for part in parts:
text = part.get("text") if isinstance(part, dict) else None
if not isinstance(text, str):
continue
stripped = text.rstrip()
if stripped.endswith(_STEERING_SUFFIX) and _STEERING_SENTINEL in stripped:
return True
return False
def apply_openai_responses_verbosity_steering(
body: dict[str, Any],
level: int,
) -> bool:
"""Append or replace steering in OpenAI Responses ``instructions``."""
"""Append or replace steering in OpenAI Responses ``instructions``.
Leaves the body alone when a steering block already rides in ``input``. A
client whose upstream rejects ``instructions`` (Kiro's runtime returns 400
for it) has its steering placed in the user turns by an extension's
``on_responses_create`` hook; adding a second copy here would break that
request outright.
"""
text = steering_text(level)
if text is None:
return False
if _input_already_steered(body.get("input")):
return False
instructions = body.get("instructions")
if instructions is None:
+60
View File
@@ -61,6 +61,66 @@ def test_openai_responses_steering_is_idempotent() -> None:
assert body == snapshot
def test_openai_responses_steering_skips_a_body_already_steered_in_input() -> None:
"""An upstream that rejects ``instructions`` gets its steering in the user turn
from an extension hook; core must not add ``instructions`` on top of it."""
steered = f"fix it\n\n{steering_text(3)}"
body = {"input": [{"role": "user", "content": steered}]}
assert apply_openai_responses_verbosity_steering(body, 3) is False
assert body == {"input": [{"role": "user", "content": steered}]}
def test_openai_responses_steering_ignores_the_marker_quoted_in_tool_output() -> None:
"""Reading this repo's own steering source puts the marker in a tool result; that is not a
steered body, so core must still steer it."""
body = {
"instructions": "You are Codex.",
"input": [
{"role": "user", "content": "show me the steering policy"},
{"type": "function_call", "call_id": "c1", "name": "read", "arguments": "{}"},
{
"type": "function_call_output",
"call_id": "c1",
"output": 'STEERING_SENTINEL = "<headroom_output_shaping>"\n'
'STEERING_SUFFIX = "</headroom_output_shaping>"',
},
],
}
assert apply_openai_responses_verbosity_steering(body, 2) is True
assert steering_text(2) in body["instructions"]
def test_openai_responses_steering_ignores_a_user_quoting_the_marker_mid_message() -> None:
body = {
"input": [{"role": "user", "content": "why does <headroom_output_shaping> appear here?"}]
}
assert apply_openai_responses_verbosity_steering(body, 2) is True
assert body["instructions"] == steering_text(2)
def test_openai_responses_steering_skips_input_text_parts_already_steered() -> None:
steered = f"fix it\n\n{steering_text(3)}"
body = {
"input": [
{
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": steered}],
}
]
}
assert apply_openai_responses_verbosity_steering(body, 3) is False
assert "instructions" not in body
def test_openai_responses_steering_skips_a_string_input_already_steered() -> None:
steered = f"fix it\n\n{steering_text(3)}"
body = {"input": steered}
assert apply_openai_responses_verbosity_steering(body, 3) is False
assert body == {"input": steered}
def test_openai_chat_steering_appends_to_system_message() -> None:
from headroom.proxy.output_steering import apply_openai_chat_verbosity_steering