Repository navigation
FIX: Escape control characters in console printer output - #2694
Merged
Richard Lundeen (richlundeen) merged 2 commits intoSep 21, 2026
Merged
Richard Lundeen (richlundeen) merged 2 commits into
Richard Lundeen (richlundeen) merged 2 commits into
Conversation
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.
…aracters-in-printers
Dmitry Voropaev (v0ropaev)
force-pushed
the
fix/escape-control-characters-in-printers
branch
from
September 19, 2026 09:22
8645f21 to
4e96ae6
Compare
Richard Lundeen (richlundeen)
approved these changes
Sep 21, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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_contentfrom blocked responses, reasoning summaries, score rationales, the objective,outcome_reason, metadata - and_PrettyPrinterMixin._format_coloredonly 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/\x9dand\r. Eliciting exactly that is the point of theansi_attacktechnique, which is infoundry.red_team_agent's defaultEASYset, andAnsiAttackConverter.LIVE_PAYLOADSput 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- newescape_control_characters(text): C0 except\t/\n, DEL and the whole C1 range are replaced by theirreprform (\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 topyrit/common/__init__.py, following the lazy-export contract (read_txt/write_txtin the same module are not exported either); callers import it by module path.pyrit/output/_formatting.py-_format_coloredescapes 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 beforetextwrapruns, and the two remaining raw appends (theScorer:line and theRationale:label) now go through_format_coloredtoo, so the choke point has no exceptions. Output is byte-identical:_format_coloredwith no colour arguments returnsf"{text}\n".pyrit/output/conversation/pretty.py- escape beforetextwrapruns and treat\r\nas a newline. Wrapping on the raw text would under-count the width, andTextWrapper(drop_whitespace=True)silently drops a lone\rsitting at a wrap boundary, so the escape would never be shown; the CRLF normalisation keeps a literal\roff the end of every line of a CRLF response.pyrit/executor/promptgen/fuzzer/fuzzer.py- the same helper inFuzzerResultPrinter._print_colored, in_print_wrapped_text(which wraps first, andtextwrap.wrapdefaults toreplace_whitespace=True, so a lone\rin a template would otherwise become a space), and in the oneprint()insideprint_templates_onlythat 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 aFileSinkartefact gets the escaped text too, which seems like the right side of the trade: the file is what someone latercats.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), andpyrit/cli/_output.py, which prints retry/error lines and the rawobjectiveat line 463 on thescenario-results --view conversationspath - #2508 is already changing that file.Two open questions, also in the issue:
\x1bmakes 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.BidiConverteremits (U+202E … U+202C) untouched; they can still reorder a displayed line. I did not widen the class becausereprescapes the wholeCfcategory, which mangles legitimate text (a family emoji becomesemojiemoji) 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 = Trueparameter 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
mainand 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[2Jare returned unchanged.tests/unit/output/test_formatting.py- exact_format_coloredoutput 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 7AnsiAttackConverter.LIVE_PAYLOADS, with colours on and off, through the conversation printer (user piece withoriginal != 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[32mmust 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\rpast 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 throughprint_result(colours on and off) andprint_templates_onlyovercapsys, plus a non-ESC payload that pins the_print_wrapped_textfix.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.12uv run --frozen pytest tests/unit/output tests/unit/common tests/unit/executor/promptgen -q -n 2→ 1052 passeduv run --frozen pytest tests/unit/cli -q -n 2→ 514 passed, 1 skipped (the CLI thin client renders throughPrettyConversationPrinter)uv run --frozen pytest tests/unit/docs tests/unit/test_garak_license_compliance.py -q→ 10 passedmake unit-testwith 2 workers (pytest -n 2 --dist=loadfile tests/unit) → 18119 passed, 10 skippeduv run --frozen -m ty check pyrit→ all checks passedpre-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 2instead of the Makefile's-n 4;pre-commit run --filesrather than--all-files; no integration, end-to-end or JupyText runs.No documentation changes: the behaviour adds no API surface, and
.github/copilot-instructions.mdasks for minimal documentation, so no notebooks were touched and JupyText was not re-run. Happy to add a note todoc/code/output/0_output.pyif you'd like one.