All 22 apps

CandyAnsiInspect

ANSI escape-sequence inspector

inspired by charmbracelet/sequin ansi debugging inspector

CandyAnsiInspect code coverage

candy-ansi-inspect decodes terminal escape sequences into labeled lines. Pipe styled output through it, or name a saved capture, and each SGR, CSI, OSC, DCS, APC and SS3 sequence becomes one line that says what it does, next to the raw bytes it was sent as. It is a PHP port of charmbracelet/sequin, reimplemented for PHP 8.3 with the sequin core behavior and a narrower flag surface. The tool and the library share one parser, so the CLI report and Inspector::report() produce the same text.

Install

composer require sugarcraft/candy-ansi-inspect   # binary lands in vendor/bin/candy-ansi-inspect

Requires PHP 8.3 or newer. From a project root the examples below type the bare command, so either prefix it with vendor/bin/ or put vendor/bin on your PATH. composer global require installs it the same way.

A self-contained phar is the other option. The build seals the app with its published vendor/ into one file, and refuses a linked-mode vendor or a dirty tree:

php -d phar.readonly=0 tools/build-phar.php --out=dist/candy-ansi-inspect.phar

A downloaded archive, even one renamed to drop the suffix, boots through its own frozen autoload and answers --version with the stamp it was built under. A source checkout reports dev-master rather than an invented semver.

Quickstart

$ printf '\e[31mhello\e[0m world\n' | candy-ansi-inspect
ESC[31m  SGR foreground red
hello
ESC[0m  SGR reset
 world
LF  C0 LF (line feed)

$ printf '\e]0;new title\e\\' | candy-ansi-inspect
ESC]0;new titleBEL  set window title to "new title"

$ printf '\e[?2026h' | candy-ansi-inspect
ESC[?2026h  enable synchronized output

The display column prints named tokens (BEL, LF, ESC) wherever a raw control byte was sent. A captured sequence therefore cannot beep, retitle your window or move the cursor while you read the report, and the transcript diffs cleanly against od output.

Concepts

The tool is a parser with a label table. Input is split into segments. A TextSegment holds visible text between escapes, and a SequenceSegment holds one escape sequence, its raw bytes and its decoded label. Each segment records the byte offset where it started in the source stream, so a report can point at the exact position of a sequence in a multi-megabyte capture.

Anything the decoder does not recognize falls back to a generic CSI/OSC/... descriptor. No sequence that reaches the segmenter is dropped without a report. Bytes can still disappear upstream, inside the parser's state table. The byte-fidelity contract below lists exactly where that happens.

Reports are live and byte-stable

A pipe is reported as it arrives. Stdin is read chunk by chunk, and each segment's line is written as soon as its sequence completes, so tail -f log | candy-ansi-inspect emits per sequence instead of waiting for the writer to close. The live report and the file report produce the same bytes.

Exec mode runs a program

Exec mode starts a command on a fresh pseudo-terminal and reports every sequence it prints the instant it completes, then exits with the child's status. Everything after -- belongs to the command, including its own flags. The PTY work is done by sugar-pty.

Tasks

Inspect a saved capture

printf '\e[31merror: disk full\e[0m\n' > capture.ansi
candy-ansi-inspect capture.ansi
candy-ansi-inspect --show-offsets capture.ansi   # prefix each line with its byte position as @hex

A saved capture works exactly like a pipe: the file argument produces the same report. --show-offsets adds the position column. Offsets count from zero across the whole source, and a normal segment's offset plus its reported bytes lands exactly on the next segment's offset.

Get the report as JSON

candy-ansi-inspect --json capture.ansi | jq '.[] | select(.type == "sequence") | .description'

--json prints a JSON array with one object per segment. Each object carries type (text or sequence), the raw content bytes, the human description and the byteOffset. JSON is never live. A partial array is not parseable, so --json on a pipe collects every segment and prints the array when the source ends. The flag works before or after the file operand.

Run a program and label what it prints

candy-ansi-inspect -- ls --color=always
candy-ansi-inspect -- git -c color.ui=always status

The child runs on a PTY, so it sees a terminal and writes the sequences a real session would. The tool's exit status is the child's.

Label sequences from PHP

use SugarCraft\AnsiInspect\Inspector;

echo Inspector::report("\e[1;31mboom\e[0m");   // the three report lines, as the CLI prints them

For a chunked source such as a log file or a live process, use StreamingInspector. See the Examples section for a worked chunk split.

Read a hostile capture safely

The report never replays a control byte. Control bytes are printed as named tokens, so a capture that contains a title change or a clipboard write shows only its label and cannot move your cursor or retitle your window.

API reference

The library lives in SugarCraft\AnsiInspect\. The tables below list the classes a caller uses directly. AnsiHandler, the parser callback behind both entry points, is described in the Architecture section, and Lang, the message catalog, under Configuration, in the Locale subsection. Neither is repeated here. The CLI is a thin layer over these.

Inspector and reports

ClassMethodDescription
Inspectorparse(string $input)Parse ANSI bytes into a list of Segment values.
Inspectorreport(string $input, bool $showOffsets = false)One-shot labeled report text, the exact lines the CLI prints. Pass true for the offset column.
InspectorreportAsJson(string $input)The JSON array the --json flag prints.
InspectorencodeSegmentsJson(iterable $segments)Render any segment list as that JSON array.
InspectorformatSegment(Segment $seg, bool $showOffsets = false)Format one segment as a single report line.
InspectordescribeCsi(string $params, string $final), describeOsc(string $payload), describeDcs(string $payload, int $final = 0), describeSs3(string $final), describeEsc(string $byte, string $intermediate = '')Label one sequence family. Each returns the human description for that payload.
InspectorsanitizeLabelBytes(string $s)Tokenize control bytes so a label can be shown without replaying them.
C0C1c0Name(int $byte), c1Name(int $byte)The name of a C0 or C1 control byte, such as BEL or LF.

Segments

ClassMemberDescription
Segmentraw(), describe(), byteOffset()The abstract base. raw() returns the bytes, describe() the report text, byteOffset() the source offset or null.
TextSegment__construct(string $value, ?int $offset = null)Visible text between escape sequences. The text is $value.
SequenceSegment__construct(string $bytes, string $label, ?int $offset = null), printable(string $bytes)One escape sequence. $bytes is the raw sequence and $label the decoded label, such as SGR reset.

Streaming, exec and version

ClassMethodDescription
StreamingInspectorfeed(string $data)Consume a chunk and return the segments it completed. A half sequence is held until its next bytes arrive.
StreamingInspectorfinish()Flush the held text and any unterminated sequence, so a dangling ESC arrives as its own segment.
Exec\ExecRunnerrun(array $cmd, callable $emitLine, ...)Run a command on a PTY, stream its report lines to $emitLine, and return the child's exit status. Returns ExecRunner::EXIT_UNAVAILABLE (1) when no PTY can be opened.
Support\Versionline(), current(), fromPharMetadata(string $path)The --version line, the version this build reports, and the version stamped into a phar.

Only methods declared in candy-ansi-inspect/src, or inherited from a parent declared there, are listed. A type that extends a class outside that tree, such as \RuntimeException, does not show the methods of that class.

SugarCraft\AnsiInspect

AnsiHandler final class

Collects ANSI parse events into a flat list of Segments.

MethodSummary
parse(string $input): arrayParse a complete input in one shot: feed every byte, then finalise.
feed(string $input): voidFeed bytes through the state machine, accumulating segments.
finish(): voidEnd of stream: force any in-flight string sequence to dispatch and finalise the dangling tail.
reset(): voidReset all accumulated state (segments, text buffer, flags). Used by StreamingInspector between sessions.
drainSegments(): arrayReturn all segments produced since the last drain (or since reset). Does NOT call flushText() — pending text is only flushed when a sequence dispatch auto-flushes (csiDispatch / oscDispatch / etc.) or when finish() is called. This preserves the streaming invariant that text is returned only when a sequence is completed or the stream ends.
flushText(): void
printChar(string $rune): void
execute(int $byte): void
csiDispatch(int $final, array $params, int $prefix, int $intermediate): void
escDispatch(int $final, int $intermediate): void
oscDispatch(string $data): void
dcsDispatch(int $final, array $params, int $prefix, int $intermediate, string $data): void
sosPmApcDispatch(string $kind, string $data): void

C0C1 final class

Lookup tables for C0 (0x00–0x1F) and C1 (0x80–0x9F) control codes. Descriptions follow ANSI/ISO standards and common terminal conventions.

MethodSummary
static c0Name(int $byte): string
static c1Name(int $byte): string

Inspector final class

Walk a string of mixed text + ANSI escape sequences and split it into Segments. The decoder labels SGR codes (foreground, background, attributes), CSI cursor moves, CSI erase/mode toggles, OSC titles, and bracketed-paste / focus / mouse mode sequences. Anything it doesn't recognise still gets a Segment with a generic "CSI" / "OSC" / "SS3" label, so no sequence that reaches the segmenter is dropped without a report. Bytes can still vanish further upstream, inside sugar-ansi-parser, before this code ever sees a dispatch — README.md keeps the closed list of every known case and ByteFidelityTest pins each one.

MethodSummary
static parse(string $input): arrayParse $input into a list of segments. Plain text becomes TextSegment; escape sequences become SequenceSegment.
static report(string $input, bool $showOffsets = false): stringRender parsed segments as a sequin-style report (one per line).
static formatSegment(Segment $seg, bool $showOffsets = false): stringOne report line for a segment: its describe() rendering, prefixed with the hex byte offset when $showOffsets is set and the segment carries a stream position (segments hand-constructed outside a parse are untracked and render without a prefix).
static reportAsJson(string $input): stringRender parsed segments as a machine-readable JSON array.
static encodeSegmentsJson(iterable $segments): stringJSON projection of an already-parsed segment list — the shared body of reportAsJson() and the bin's --json streaming arm (finding 005: a pipe under --json collects segments and encodes the same array shape).
static describeCsi(string $params, string $final): string
static describeMouseX10(string $payload): stringX10 mouse event (finding 006): the three raw bytes that trail ESC[M, each offset by 32. Low bits 0-2 select button (3 = release), bit 4 shift, bit 8 meta, bit 16 ctrl, bit 5 drag, the 64 band wheels; coordinates are byte-minus-31 (1-based).
static describeOsc(string $payload): string
static describeDcs(string $payload, int $final = 0): stringDecode DCS payloads — XTVERSION reply, DECRQSS, DECRPSS, sixel, tmux passthrough.
static describeDcsParts(int $final, array $params, int $prefix, int $intermediate, string $data, string $rawPayload = ''): stringClassify a DCS body from the parser's true dispatch fields using the shared Dcs decoder, rendering the label in this inspector's house spelling: attacker-controlled payload bytes go through sanitizeLabelBytes() (named C0/C1 tokens), the same discipline as the OSC/APC labels, so a captured reply can't inject control bytes into the inspector's own output.
static describeApc(string $payload): stringDecode APC payloads — CandyZone markers, kitty graphics.
static describeSs3(string $final): string
static describeEsc(string $byte, string $intermediate = ''): stringNames a two- or three-byte ESC sequence. The intermediate byte (the 0x20–0x2F the EscapeIntermediate state collects, finding 014) changes the final byte's meaning entirely — ESC 8 is DECRC while ESC # 8 is DECALN — so the bare-ESC arms are gated on its absence and an unexpected intermediate never borrows a bare label.
static describeTruncated(string $bytes): stringLabel a sequence the stream never terminated (ECMA-48 §5.6 escape sequences run introducer → parameters → intermediates → final byte, and the final byte is what completes them).
static sanitizeLabelBytes(string $s): stringReplace C0, DEL and C1 control bytes in a label interpolation with visible tokens.

Lang final class

Per-library translation facade for candy-ansi-inspect.

Segment abstract class

Base class for the chunks produced by Inspector::parse(). Every segment can both render itself verbatim (raw()) and produce a human-readable description (describe()).

MethodSummary
abstract raw(): string
abstract describe(): string
abstract byteOffset(): ?intAbsolute byte offset where this segment starts in the parsed input, or null for a segment that was hand-constructed and therefore carries no stream position (finding 019 — the location sequin prints beside every decoded entry).

SequenceSegment final class

One ANSI escape sequence — its raw bytes paired with a decoded label (e.g. "SGR foreground red"). The label is what makes CandyAnsiInspect useful as a debugging tool: you can pipe styled output in and see exactly which sequence produced what effect.

MethodSummary
__construct(public readonly string $bytes, public readonly string $label, public readonly ?int $offset = null)The raw bytes are stored verbatim; the report renders them through printable(), which tokenizes every control byte.
raw(): string
byteOffset(): ?int
describe(): string
static printable(string $bytes): stringRender bytes with control bytes replaced by visible tokens: \x1b becomes ESC, every C0/DEL/C1 byte becomes its named token (CR, BEL, RI, …), and printable ASCII plus well-formed UTF-8 runes survive verbatim.

StreamingInspector final class

Streaming incremental parser for ANSI escape sequences.

MethodSummary
__construct()
feed(string $data): arrayFeed a chunk of input. Segments completed by this chunk are returned; incomplete sequences are held in the parser state for the next chunk.
finish(): arrayFlush any remaining buffered text and finalise pending sequences.

TextSegment final class

Visible text between escape sequences. describe() returns the payload verbatim so it shows up unmodified in inspector reports.

MethodSummary
__construct(public readonly string $value, public readonly ?int $offset = null)
raw(): string
describe(): string
byteOffset(): ?int

SugarCraft\AnsiInspect\Exec

ExecRunner final class

Executes a command on a fresh pseudo-terminal and reports the raw bytes it prints, segment by segment, as they dispatch.

MethodSummary
static run(array $cmd, callable $emitLine, ?callable $sessionFactory = null, $errorStream = STDERR, bool $showOffsets = false): int

SugarCraft\AnsiInspect\Support

Version final class

The version string this tool reports on --version.

MethodSummary
static line(): stringThe --version line: plain text, newline-terminated, produced by no state and no host probe — the flag must answer anywhere.
static current(): stringThe version this process reports: the archive stamp when running from a stamped phar, self::CURRENT everywhere else.
static fromPharMetadata(string $path): ?stringThe version a phar archive at $path was built to carry, or null when it names none (unreadable archive, wrong metadata shape, the dev-build sentinel, or an empty stamp). Every refusal is a null, never an exception — --version must answer on a machine whose phar cannot be opened.
static versionFromMetadata(mixed $metadata): ?stringThe judgement on the stamp itself, split out because the archive-open leg is unreachable from a suite that must not build phars: the release namespace strip, the dev-build refusal, and the wrong-type nulls are a pure function over what getMetadata() answers.
static hostArchive(): stringThe filesystem path of the phar this process was launched from, or '' when it was not launched from one — the two-identity law measured on candy-code's real builds and pinned by the bin autoload guard: inside archive-loaded code Phar::running(false) answers the archive path, while the stub context answers '' and there a '.phar'-suffixed __DIR__ is the enclosing archive.

Configuration

The tool has no configuration file. Its behavior is set by flags and by the locale of the environment.

Flags

FlagEffect
--jsonPrint the report as a JSON array. Collects segments, so it is not live.
--show-offsetsPrefix every line-mode report line with its segment's byte position as @hex. Off by default, so the default transcript stays byte-stable for diffs.
-- cmd [args…]Exec mode. Everything after -- is the command and its arguments.
-h, --helpPrint usage on stdout and exit 0. Checked before any path is considered.
--versionPrint the version line and exit 0.

Exit status

SituationPrintsStreamExit status
Readable file argument or piped stdinreportstdout0
--help or -husagestdout0
--versionversion linestdout0
Exec mode (-- cmd [args…])reportstdoutthe child's exit status
No source: no operand and stdin is a terminalusagestderr1
More than one source namedusagestderr1
Operand is not a readable regular filerefusalstderr1

Locale

Messages the tool prints itself, such as usage and refusals, are translated. The locale is read from LC_ALL, then LC_MESSAGES, then LANG, and the first usable value wins. fr_FR.UTF-8 resolves to fr, and an unknown locale falls back to English. The labels inside a report are always English, so report bytes never depend on the caller's locale. Seventeen locale catalogs ship in lang/.

Keys and input

The tool has no keyboard handling and no key bindings. Its input is bytes: a file operand, a pipe on stdin, or the output of a command after --. Pass exactly one source. Naming two files is refused with usage, rather than reporting the first and silently dropping the other.

A path that carries a scheme such as php:// or data:// is refused as a stream wrapper. Pipe those bytes on stdin instead. Process substitution (<(cmd)), FIFOs and other special files are not readable regular files either, so pipe them as well.

Theming

There is no theme. The report is intentionally uncolored: an ANSI-colored inspector would have to escape its own output, and the point of this tool is a byte-trustworthy transcript. Vocabulary lives in the labels themselves. The sequin option that reads SEQUIN_THEME has no counterpart here.

Examples

The examples/ directory holds one shell script and three PHP programs. The PHP examples load the Composer autoloader, so run them from a checkout after composer install.

  • examples/inspect.sh is a guided tour of common sequences through the CLI: SGR colors, DEC private modes, OSC clipboard writes and OSC 8 hyperlinks. It is the program behind the demo GIF below.
  • examples/inspect-string.php labels a byte string with Inspector::parse(), printing each segment's kind, offset and description, and then the full Inspector::report() text.
  • examples/streaming-chunks.php feeds StreamingInspector three chunks, one of which ends inside ESC[31m. The held half sequence arrives only with the chunk that completes it, and finish() reports the dangling ESC[ as truncated.
  • examples/json-report.php prints Inspector::reportAsJson() and reads it back with json_decode() to show the fields a script would use.
./examples/inspect.sh
php examples/inspect-string.php
php examples/streaming-chunks.php
php examples/json-report.php

Testing

The suite runs under PHPUnit 10. Run it once from the package root, with stdin redirected so a test that reads stdin cannot hang:

cd candy-ansi-inspect && composer install && vendor/bin/phpunit < /dev/null

The suite pins the behavior in several ways. ReadmeTranscriptGoldenTest checks that the transcripts in this README still come out byte for byte. ByteFidelityTest and ByteOffsetTest check the byte-fidelity contract. C1ClassificationSweepTest pins the C1 control roster byte for byte. StreamingInspectorTest covers chunk boundaries, and CliTest and ExecRunnerTest cover the command line and exec mode. LangParityTest checks that the locale catalogs match. PerfGuardTest keeps the report's cost growing no faster than its input, so a large capture cannot turn into a stall.

Troubleshooting

Exit 1 with "cannot read"

The operand is not a readable regular file. A directory, a FIFO, a process substitution and a stream wrapper all refuse the same way. For a wrapper such as data:// the message adds a hint line. Pipe the bytes on stdin instead: cmd | candy-ansi-inspect.

Exit 1 with a usage message and nothing to read

With no operand and a terminal on stdin, there is no source. Name a file or pipe something in. A pipe is always a source, even an empty one, and an empty source prints an empty report and exits 0.

A sequence is missing from the report

Most such cases are documented byte-fidelity deviations, pinned by named tests. A cancel byte (CAN or SUB) inside a string such as an OSC is consumed as the terminator, so it appears nowhere in the report. An invalid UTF-8 byte in the middle of text is dropped with its position. An OSC closed by ESC \ is re-emitted with a BEL terminator, because terminals accept that spelling everywhere. The full list is in the byte-fidelity section below.

Output appears late under --json

That is by design. A partial JSON array cannot be parsed, so --json collects every segment and prints the array when the source ends. For a live feed, drop --json and read the line-mode report, which prints each sequence as it completes.

Exec mode exits 1 and says no pseudo-terminal is available

Exec mode needs a PTY. When one cannot be opened, the run exits with ExecRunner::EXIT_UNAVAILABLE (1) and names the reason on stderr. Use a pipe or a file in that environment.

Offsets look wrong after a multi-byte character

Offsets are positions in the input bytes, not in characters. A text segment's offset is the byte where its first character starts. Use byteOffset() with raw() when you need exact positions, and not the length of a decoded string.

Byte-fidelity contract

Reported bytes are the bytes that were sent, in four respects. Parameters keep the separator the sender used, so ESC[4;3m is never reported as ESC[4:3m. A dispatched CSI replays its own bytes verbatim, including stacked private markers and the 8-bit 0x9B spelling. A string's ESC \ terminator is reported once, inside the sequence it closed. A truncated sequence still arrives, as a truncated … segment carrying its raw bytes.

Every known deviation is pinned by a named test rather than hidden. Anything else that loses a byte is a bug. The deviations are these:

  • An OSC closed by ESC \ is re-emitted with a BEL terminator.
  • A DCS prelude rebuilt through the parser fields is lossy. Its final byte is dropped and an intermediate byte comes back ahead of the parameters. A BEL-terminated DCS replays verbatim.
  • A sequence is capped at 32 parameters, and a parameter value accumulates only up to 65535, both inside the parser. A dispatched CSI still replays its bytes as sent.
  • A string payload stops at 64 KiB, so a longer OSC arrives cut at that length with its terminator attached.
  • Some C0 bytes are ignored inside an OSC payload and never reach the buffer.
  • An illegal parameter byte, or a CAN or SUB inside a control sequence, cancels the sequence in flight. The cancelled bytes appear only when a later byte observes them.
  • A truncated UTF-8 rune at end of stream is dropped. Invalid UTF-8 bytes in the middle of text are dropped with their position.
  • An 8-bit string introducer such as 0x9D (OSC) is re-emitted in its 7-bit spelling with a normalized terminator.
  • A CAN or SUB inside a string payload terminates it. The payload so far is reported as a truncated segment, and the cancel byte is consumed.

Upstream mapping

Upstream (Go, charmbracelet/sequin)candy-ansi-inspect (PHP)
The inspector's report and its per-sequence labelsInspector::report(), Inspector::describe*()
The byte position column, which sequin prints by default--show-offsets, opt-in
Running a child command for its output (-cmd)-- cmd [args…] exec mode

Divergences, by design. -- cmd replaces sequin's -cmd. The offset column is opt-in. There is no --raw inline-highlight mode, because the report's first column always shows the sent bytes tokenized, and there is nothing to switch off. There is no theming and no --list, since the cheat sheet is the README's decode section. There is no listen mode, because accepting network connections on a tool that renders untrusted byte streams is a security-review-sized feature the fleet has no precedent for.

Architecture

One parser, three front doors

Inspector::parse() and StreamingInspector both drive the same AnsiHandler, which implements the Handler interface of the sugar-ansi-parser state machine. The handler collects segments as the parser dispatches them. The file, pipe and exec doors all reach it through one of those two entry points, so they produce the same labels.

Sanitized labels

Labels are built from the decoded fields. The raw bytes are kept only in the segment's raw(), and the report displays them through SequenceSegment::printable(), which tokenizes control bytes. A payload therefore cannot forge a report line or replay a control at the terminal.

Changelog and versioning

The version a build reports comes from its packaging. A tagged phar reports its build stamp through --version. A downloaded archive reports the stamp it was built under. A source checkout reports dev-master, and the library never invents a semver for unreleased code. The phar build refuses a linked vendor tree or a dirty working tree, so release artifacts ship tested bytes.

  • sugar-pty: the pseudo-terminal layer that exec mode runs a child on.
  • sugar-ansi-parser: the escape-sequence state machine the handler implements.

Try the quickstart →

Demos.

A VHS-recorded GIF of the inspect demo, the one demo the library ships. Regenerated automatically on every push that touches the source.

Inspect

Inspect

A guided tour of SGR / OSC / CSI / SS3 / DCS / APC annotations from one saved stream.