Skip to content

FIX: Escape control characters in console printer output - #2694

Merged
Richard Lundeen (richlundeen) merged 2 commits into
microsoft:mainfrom
v0ropaev:fix/escape-control-characters-in-printers
Sep 21, 2026
Merged

Richard Lundeen (richlundeen) merged 2 commits into
microsoft:mainfrom
v0ropaev:fix/escape-control-characters-in-printers

Conversation

@v0ropaev

Copy link
Copy Markdown
Contributor

Description

Closes #2693. Follow-up to #2683 / #2688: those add scorers that detect ANSI escape sequences in target output; this makes it safe to print such output.

The pretty printers put text the target controls into their output as-is - response text, original/converted prompt values, partial_content from blocked responses, reasoning summaries, score rationales, the objective, outcome_reason, metadata - and _PrettyPrinterMixin._format_colored only adds PyRIT's colour codes around it. A target that answers with escape sequences therefore drives the operator's terminal: cursor movement and erase (rewriting the outcome or score lines just printed), SGR conceal, window-title changes, OSC 8 links whose label differs from the URL, OSC 52 clipboard writes on permissive terminals, plus the C1 introducers \x9b / \x9d and \r. Eliciting exactly that is the point of the ansi_attack technique, which is in foundry.red_team_agent's default EASY set, and AnsiAttackConverter.LIVE_PAYLOADS put raw ESC into the user turn as well, so the payload is replayed even when the model refuses. The target under test is untrusted by definition, so this is defence-in-depth for whoever is running PyRIT.

Changes:

  • pyrit/common/text_helper.py - new escape_control_characters(text): C0 except \t/\n, DEL and the whole C1 range are replaced by their repr form (\x1b, \r, \x9b). Non-ASCII text is untouched, and the docstring records that Unicode format characters (the bidirectional controls in particular) are deliberately out of scope. Not added to pyrit/common/__init__.py, following the lazy-export contract (read_txt/write_txt in the same module are not exported either); callers import it by module path.
  • pyrit/output/_formatting.py - _format_colored escapes before adding colours. Every line the pretty printers emit goes through this one function, so this covers the conversation, attack-result, score, scorer and scenario-result printers. Escaping first means PyRIT's own SGR codes still work exactly as before.
  • pyrit/output/score/pretty.py - the rationale is escaped before textwrap runs, and the two remaining raw appends (the Scorer: line and the Rationale: label) now go through _format_colored too, so the choke point has no exceptions. Output is byte-identical: _format_colored with no colour arguments returns f"{text}\n".
  • pyrit/output/conversation/pretty.py - escape before textwrap runs and treat \r\n as a newline. Wrapping on the raw text would under-count the width, and TextWrapper(drop_whitespace=True) silently drops a lone \r sitting at a wrap boundary, so the escape would never be shown; the CRLF normalisation keeps a literal \r off the end of every line of a CRLF response.
  • pyrit/executor/promptgen/fuzzer/fuzzer.py - the same helper in FuzzerResultPrinter._print_colored, in _print_wrapped_text (which wraps first, and textwrap.wrap defaults to replace_whitespace=True, so a lone \r in a template would otherwise become a space), and in the one print() inside print_templates_only that bypasses _print_colored.

Display only. No new parameters or flags. Memory, the database, JSON/markdown exports and the markdown printers are unchanged - stored values stay raw, and only rendered output is escaped. Note that the printers accept a sink=, so a FileSink artefact gets the escaped text too, which seems like the right side of the trade: the file is what someone later cats.

Out of scope on purpose, happy to follow up on either: logging (the INFO stdout handler and the full-response logs in azure_ml_chat_target / executor/workflow/xpia), and pyrit/cli/_output.py, which prints retry/error lines and the raw objective at line 463 on the scenario-results --view conversations path - #2508 is already changing that file.

Two open questions, also in the issue:

  1. \x1b makes a raw ESC look identical to a model that literally typed \x1b - the raw-vs-escaped split the scorers in FEAT: Add ANSI escape output scorers #2688 make. Unicode control pictures (␛[32m) would disambiguate and keep the line width, at the cost of still needing a \x9b-style form for C1. Tell me which you prefer and I'll change it.
  2. The C0/C1 class leaves the Unicode bidirectional controls that PyRIT's own BidiConverter emits (U+202E … U+202C) untouched; they can still reorder a displayed line. I did not widen the class because repr escapes the whole Cf category, which mangles legitimate text (a family emoji becomes emoji‍emoji) and breaks the isolates that correctly embed LTR runs in RTL text. Say the word and I'll add a narrow set (overrides/embeddings/isolates only).

If you would rather operators could turn this off, an escape_control_characters: bool = True parameter on the printers (or a setting) is additive and I'm happy to add it in this PR - I left it out to keep the surface small.

Tests and Documentation

79 new tests, all of which fail on main and pass with this change (verified in a dedicated worktree at the base commit with only the test files applied: 69 assertion failures plus 10 that cannot even collect, against 3 pre-existing passes):

  • tests/unit/common/test_text_helper.py - parametrized: CSI/OSC/OSC-52, the C1 forms \x9b/\x9d/\x9c, lone \r, NUL/DEL/BS are escaped; plain text, \n, \t, non-ASCII (é, 中文, ␛) and an already-escaped literal \x1b[2J are returned unchanged.
  • tests/unit/output/test_formatting.py - exact _format_colored output with colours on and off: the OSC sequence is escaped, tab and newline survive, and the colour wrapper is intact.
  • tests/unit/output/test_control_characters.py (new) - each of the 7 AnsiAttackConverter.LIVE_PAYLOADS, with colours on and off, through the conversation printer (user piece with original != converted, assistant response, inline score), the score printer, and the attack-result summary (objective, outcome_reason, metadata). With colours off the assertion allows no control character at all in the raw output; with colours on it strips only PyRIT's own SGR first. One test states the requirement positively - a target's \x1b[32m must appear escaped and must not appear raw - so an implementation that passed colour codes through, or that stripped the bytes instead of escaping them, would fail. Another covers carriage returns with the lone \r past the wrap width, which is the only place the pre-wrap escaping is observable.
  • tests/unit/executor/promptgen/fuzzer/test_fuzzer_result_printer.py (new) - the same payload sweep through print_result (colours on and off) and print_templates_only over capsys, plus a non-ESC payload that pins the _print_wrapped_text fix.

Existing tests that assert PyRIT's own colour codes are present still pass, because escaping happens before colouring.

Commands run (macOS 27.0, Python 3.12.13, arm64):

  • uv sync --frozen --extra all --python 3.12
  • uv run --frozen pytest tests/unit/output tests/unit/common tests/unit/executor/promptgen -q -n 2 → 1052 passed
  • uv run --frozen pytest tests/unit/cli -q -n 2 → 514 passed, 1 skipped (the CLI thin client renders through PrettyConversationPrinter)
  • uv run --frozen pytest tests/unit/docs tests/unit/test_garak_license_compliance.py -q → 10 passed
  • full unit suite, make unit-test with 2 workers (pytest -n 2 --dist=loadfile tests/unit) → 18119 passed, 10 skipped
  • uv run --frozen -m ty check pyrit → all checks passed
  • pre-commit run --files <the 9 changed files> → all matching hooks passed (ruff-format, ruff-check, ty, async-suffix, no-reST-roles, …)

Not run, for transparency: only macOS / Python 3.12 (CI covers the matrix); -n 2 instead of the Makefile's -n 4; pre-commit run --files rather than --all-files; no integration, end-to-end or JupyText runs.

No documentation changes: the behaviour adds no API surface, and .github/copilot-instructions.md asks for minimal documentation, so no notebooks were touched and JupyText was not re-run. Happy to add a note to doc/code/output/0_output.py if you'd like one.

The pretty printers write target-controlled text (responses, prompts,
score rationales, objectives, outcome reasons, metadata) to the operator's
terminal as-is, so a target that emits ANSI/OSC sequences can move the
cursor, hide or rewrite lines, set the window title, forge OSC 8 links or
write the clipboard. Eliciting exactly that is the point of the
ansi_attack technique, which is part of red_team_agent's default EASY set.

Add escape_control_characters to pyrit/common/text_helper.py and call it
from _PrettyPrinterMixin._format_colored, which every pretty-printed line
now goes through, plus the three places that wrap text before formatting
it (the conversation printer, the score rationale and FuzzerResultPrinter).
Tab and newline are kept, PyRIT's own colors are added after escaping, and
memory, the database and the exports are unchanged. Unicode format
characters such as the bidirectional controls stay out of scope.
@v0ropaev
Dmitry Voropaev (v0ropaev) force-pushed the fix/escape-control-characters-in-printers branch from 8645f21 to 4e96ae6 Compare September 19, 2026 09:22
@richlundeen
Richard Lundeen (richlundeen) added this pull request to the merge queue Sep 21, 2026
Merged via the queue into microsoft:main with commit 3f005eb Sep 21, 2026
49 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BUG Console printers write ANSI/OSC sequences from target responses straight to the terminal

2 participants