osc7501

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 21, 2026 License: Apache-2.0 Imports: 8 Imported by: 0

README

osc7501

Go implementation of OSC 7501, the "program status" terminal protocol (spec rev 0.4). Programs use it to tell a terminal, CI runner or log viewer what they are doing: working (with progress), blocked on a prompt, done or failed. This package lets you emit those reports, detect them in a byte stream, and strip them from text output. It has no dependencies outside the standard library.

About this package

This package was written with the help of an AI coding assistant (Claude Code by Anthropic). It is reviewed, tested (unit and fuzz tests) and maintained by a human maintainer, Mark Wolfe.

Install

go get github.com/wolfeidau/osc7501

Emit status

r := osc7501.NewReporter(os.Stdout, "build")

_ = r.Working("compile", 40, "compiling") // progress 0-100; -1 = indeterminate
_ = r.Blocked("deploy", osc7501.KindPermission, "Approve deploy?")
_ = r.Done("deploy", "")
  • app is set once in NewReporter and tagged on every report.
  • Invalid state, id, app or kind returns an error wrapping ErrInvalidReport; nothing is written.
  • Title and msg are sanitised (control characters become spaces) and truncated to the limits below.
  • Progress is clamped to 100 and sent only for working and blocked. Kind is sent only for blocked.
  • Each report is one Write, terminated with ESC \.
  • Write osc7501.Query to detect whether the terminal supports OSC 7501; a supporting terminal replies on the program's stdin (so only when it runs on a terminal or PTY).

For full control, build a Report and call Reporter.Report, or Report.Encode for the raw bytes.

Consume status

Scanner is an io.Writer that forwards every byte unchanged to W and calls back when it sees a report or a query. Sequences may be split across writes at any byte.

s := &osc7501.Scanner{
	W: os.Stdout,
	OnReport: func(r osc7501.Report) {
		fmt.Fprintf(os.Stderr, "%s %s %d%%\n", r.State, r.ID, r.Progress)
	},
	OnQuery: func() {
		_, _ = io.WriteString(childStdin, osc7501.QueryReply) // PTY only
	},
}
_, _ = io.Copy(s, childOutput)

Callbacks run after the report bytes have been forwarded to W. QueryReply lists the default states and kinds; its body differs from the query, so an echoed reply does not trigger another query.

To decode a lone body (the bytes between 7501; and the terminator), use Parse:

r, err := osc7501.Parse([]byte("state=working:progress=50"))

A non-nil error means the whole report must be ignored. It wraps one of ErrNoState, ErrUnknownState, ErrLimit, ErrInvalidID or ErrInvalidText (test with errors.Is) and names the field that failed, for example osc7501: limit exceeded: app is 33 bytes, max 32.

Strip status

Use Stripper to remove reports and queries from logs or text output. It frames sequences exactly as Scanner does.

var s osc7501.Stripper
for chunk := range chunks {
	os.Stdout.Write(s.Strip(chunk))
}
os.Stdout.Write(s.Flush()) // bytes held for an unterminated sequence

Call Flush at the end of the stream. Other escape sequences pass through unchanged.

Limits

Item Limit
Sequence 4096 bytes (Parse rejects bodies over 4088)
Key 16 bytes
id 128 bytes, 8 levels (/-separated)
id segment and app [A-Za-z0-9_.+-]{1,32}
title 256 bytes encoded, 192 decoded
msg 2732 bytes encoded, 2048 decoded

A report that breaks a limit is discarded whole, including when a later duplicate key is valid.

Known limitations

Scanner and Stripper track only OSC framing. An ESC ] inside a DCS or APC string can be mis-framed.

Stability

Pre-1.0. The package tracks spec rev 0.4. Breaking changes bump the minor version and are documented in release notes.

Used by

console-stream streams process output and turns reports into ProgramStatus events.

License

Apache-2.0. See LICENSE.

Documentation

Overview

Package osc7501 implements the OSC 7501 "program status" terminal protocol (rev 0.4, https://www.superlogical.com/rex/docs/build/program-status).

Programs use it to tell the terminal or host what they are doing (working, blocked, done, error and so on) with a report of the form

ESC ] 7501 ; key=value:key=value ST

where ST is ESC \ or BEL. The package covers four uses:

  • Emit reports with Reporter (or Report.Encode for the raw sequence).
  • Decode a report body with Parse.
  • Detect reports in a byte stream with Scanner, an io.Writer that forwards every byte unchanged and calls OnReport and OnQuery. Answer a feature query by writing QueryReply to the program's stdin.
  • Remove reports from a byte stream with Stripper.

Known limitation: Scanner and Stripper track only OSC framing, so an ESC ] that appears inside a DCS or APC string can be mis-framed.

Index

Examples

Constants

View Source
const (
	StateIdle    = "idle"
	StateWorking = "working"
	StateDone    = "done"
	StateBlocked = "blocked"
	StateError   = "error"
	StateClear   = "clear"
)

Report states.

View Source
const (
	KindPermission = "permission"
	KindQuestion   = "question"
	KindAuth       = "auth"
)

Blocked kinds.

View Source
const Query = "\x1b]7501;?\x1b\\"

Query is the feature query. A terminal that supports OSC 7501 replies on the program's stdin.

View Source
const QueryReply = "\x1b]7501;?:states=idle,working,done,blocked,error:kinds=permission,question,auth\x1b\\"

QueryReply is the feature-detection reply. It lists the rev 0.4 default states and kinds, so its body differs from the query: if the PTY echoes it back, Scanner does not mistake it for a new query (no reply loop).

Variables

View Source
var (
	ErrNoState      = errors.New("osc7501: missing state")
	ErrUnknownState = errors.New("osc7501: unknown state")
	ErrLimit        = errors.New("osc7501: limit exceeded")
	ErrInvalidID    = errors.New("osc7501: invalid id")
	ErrInvalidText  = errors.New("osc7501: invalid text")
)

Errors returned by Parse, wrapped with the key or value that failed. Test for them with errors.Is.

View Source
var ErrInvalidReport = errors.New("osc7501: invalid report")

ErrInvalidReport is wrapped by errors from Report.Validate and Reporter.

Functions

func ValidID

func ValidID(id string) bool

ValidID reports whether id is 1-128 bytes of at most 8 '/'-separated segments, each valid per ValidSegment.

func ValidSegment

func ValidSegment(s string) bool

ValidSegment reports whether s matches [A-Za-z0-9_.+-]{1,32}.

Types

type Report

type Report struct {
	State, ID, Kind, App, Title, Msg string // Title and Msg are decoded
	Progress                         int    // 0-100, or -1 if indeterminate
}

Report is a decoded program status report.

func Parse

func Parse(body []byte) (Report, error)

Parse decodes the body of a report (the bytes between "7501;" and ST). It returns an error if the whole report must be ignored. Every pair is checked against the protocol limits, so a report that breaks one is rejected even if a later duplicate key is valid. A body too long to fit in a 4096-byte sequence is rejected; Scanner enforces the exact limit with framing.

Example
package main

import (
	"errors"
	"fmt"
	"strings"

	"github.com/wolfeidau/osc7501"
)

func main() {
	r, err := osc7501.Parse([]byte("state=blocked:id=deploy:kind=permission:msg=QXBwcm92ZT8"))
	fmt.Println(err, r.State, r.ID, r.Kind, r.Msg, r.Progress)

	_, err = osc7501.Parse([]byte("state=done:app=" + strings.Repeat("a", 33)))
	fmt.Println(errors.Is(err, osc7501.ErrLimit), err)
}
Output:
<nil> blocked deploy permission Approve? -1
true osc7501: limit exceeded: app is 33 bytes, max 32

func (Report) Encode

func (r Report) Encode() []byte

Encode returns the full report sequence terminated by ESC \. Keys are emitted in canonical order (state, id, kind, progress, app, title, msg). Title and Msg are sanitised and truncated to the protocol limits. Empty values are omitted, progress is emitted only for working or blocked with a value of 0 or more (clamped to 100), and kind only for blocked.

func (Report) Validate

func (r Report) Validate() error

Validate reports whether r can be encoded as a valid report.

type Reporter

type Reporter struct {
	// contains filtered or unexported fields
}

Reporter writes OSC 7501 reports for one program.

Example
package main

import (
	"bytes"
	"fmt"

	"github.com/wolfeidau/osc7501"
)

func main() {
	var buf bytes.Buffer
	r := osc7501.NewReporter(&buf, "build")

	_ = r.Working("compile", 40, "compiling")
	_ = r.Done("compile", "")

	fmt.Printf("%q\n", buf.String())
}
Output:
"\x1b]7501;state=working:id=compile:progress=40:app=build:msg=Y29tcGlsaW5n\x1b\\\x1b]7501;state=done:id=compile:app=build\x1b\\"

func NewReporter

func NewReporter(w io.Writer, app string) *Reporter

NewReporter returns a Reporter that writes to w and tags reports with app.

func (*Reporter) Blocked

func (r *Reporter) Blocked(id, kind, msg string) error

Blocked reports id as waiting for a person.

func (*Reporter) Clear

func (r *Reporter) Clear(id string) error

Clear removes the record for id; an empty id clears all records from this program.

func (*Reporter) Done

func (r *Reporter) Done(id, msg string) error

Done reports id as finished.

func (*Reporter) Failed

func (r *Reporter) Failed(id, msg string) error

Failed reports id as failed.

func (*Reporter) Idle

func (r *Reporter) Idle(id string) error

Idle reports id as idle.

func (*Reporter) Report

func (r *Reporter) Report(rep Report) error

Report validates rep and writes it in a single Write. App defaults to the Reporter's app. Nothing is written if rep is invalid.

func (*Reporter) Working

func (r *Reporter) Working(id string, progress int, msg string) error

Working reports id as working. A progress of -1 is indeterminate.

type Scanner

type Scanner struct {
	W        io.Writer // downstream; receives all bytes unchanged
	OnReport func(Report)
	OnQuery  func()
	// contains filtered or unexported fields
}

Scanner is an io.Writer that forwards every byte to W unchanged while recognising OSC 7501 reports and queries. Sequences may be split across Write calls at any byte. Callbacks run after all bytes up to and including the sequence terminator have been written to W.

Example
package main

import (
	"bytes"
	"fmt"

	"github.com/wolfeidau/osc7501"
)

func main() {
	var out bytes.Buffer
	s := &osc7501.Scanner{
		W: &out,
		OnReport: func(r osc7501.Report) {
			fmt.Println("report:", r.State, r.ID, r.Progress)
		},
	}

	// The report is split across two writes.
	_, _ = s.Write([]byte("start\n\x1b]7501;state=working:id=b"))
	_, _ = s.Write([]byte("uild:progress=50\x1b\\end\n"))

	fmt.Printf("downstream: %q\n", out.String())
}
Output:
report: working build 50
downstream: "start\n\x1b]7501;state=working:id=build:progress=50\x1b\\end\n"

func (*Scanner) Write

func (s *Scanner) Write(p []byte) (int, error)

Write implements io.Writer. On a downstream error it returns the number of bytes of p accepted by W and that error.

type Stripper

type Stripper struct {
	// contains filtered or unexported fields
}

Stripper removes complete OSC 7501 sequences (reports and queries) from a byte stream. It frames sequences exactly as Scanner does, so it removes precisely the sequences Scanner would report. State persists across Strip calls, so sequences may be split at any byte.

Bytes from an ESC that may begin a 7501 sequence are held back until the sequence resolves. If it aborts, is not 7501, or exceeds the size cap, the held bytes are emitted unchanged and in order. Everything else, including other OSC sequences, passes through unchanged.

Example
package main

import (
	"fmt"

	"github.com/wolfeidau/osc7501"
)

func main() {
	var s osc7501.Stripper

	fmt.Printf("%q\n", s.Strip([]byte("before \x1b]7501;state=done\x1b\\after\n")))
	fmt.Printf("%q\n", s.Strip([]byte("partial \x1b]7501;sta")))
	fmt.Printf("%q\n", s.Flush())
}
Output:
"before after\n"
"partial "
"\x1b]7501;sta"

func (*Stripper) Flush

func (s *Stripper) Flush() []byte

Flush returns any bytes still held (for example an unterminated sequence at the end of the stream) and resets the Stripper.

func (*Stripper) Strip

func (s *Stripper) Strip(p []byte) []byte

Strip returns p with complete OSC 7501 sequences removed. The result may alias p.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL