Skip to content
SamiNassimPublic

About

A dependency-free Go library for OSC 7501 terminal status, messages, and progress.

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Repository files navigation

osc7501

Report activity, messages, progress, and requests for user input to a terminal from Go. Implements the Program Status Protocol (OSC 7501), revision 0.4. Requires Go 1.22 or newer. Standard library only.

Go reference

Install

go get github.com/SamiNassim/osc7501

Use

Create an encoder for your terminal output and send reports:

package main

import (
	"log"
	"os"

	"github.com/SamiNassim/osc7501"
)

func main() {
	status := osc7501.NewEncoder(os.Stderr)
	report := osc7501.Report{
		State:    osc7501.Working,
		App:      "myapp",
		Message:  "Building packages",
		Progress: osc7501.Percent(40),
	}
	if err := status.Encode(report); err != nil {
		log.Fatal(err)
	}

	// Do work here.

	report.State = osc7501.Done
	report.Message = "Build complete"
	report.Progress = nil
	if err := status.Encode(report); err != nil {
		log.Fatal(err)
	}
}

Message and Title are ordinary UTF-8 strings. Encoding and decoding base64 is automatic. Choose a writer connected to a terminal; your application controls whether status output is enabled.

Save and reuse Report values as shown above, or copy a report to use as a template. Each call sends its current fields, including the saved App, ID, and Title. When changing state, clear any Kind or Progress that no longer applies. Copies share the progress pointer; assigning a new Percent(value) gives a copy independent progress.

State Use
Idle Waiting for the next instruction; also use after cancellation.
Working Running.
Blocked Waiting for user input.
Done Finished successfully.
Error Failed and stopped.
Clear Remove this record and its descendants.

Progress is optional: leave it nil for indeterminate activity, or use Percent(0) through Percent(100). Only Working and Blocked accept progress. Report Done or Error before exiting; terminals keep these results after the process ends. No heartbeat is needed.

User input and subtasks

Use Blocked with Permission, Question, or Auth to explain the input needed:

if err := status.Encode(osc7501.Report{
	State:   osc7501.Blocked,
	ID:      "deploy/production",
	Kind:    osc7501.Permission,
	App:     "myapp",
	Title:   "Production",
	Message: "Approve deployment?",
}); err != nil {
	log.Fatal(err)
}

An empty ID addresses the root record. IDs such as build/test let you report independent tasks. Each report replaces the whole record, so repeat fields you want to keep. A task without App inherits it from its nearest ancestor that has one.

Send Report{State: osc7501.Clear, ID: "build"} to clear a task and its descendants. Omit ID to clear every record in the terminal. Returning to Working after a blocked state clears the previous request when you omit Kind.

Encode, parse, and detect support

API Purpose
Marshal(report) Return a complete escape sequence without writing it.
Unmarshal(sequence) Parse one complete report, including its OSC prefix and terminator.
NewDecoder(reader) Create a decoder for a stream.
decoder.Decode() Read the next report.
decoder.DecodeReply() Read the next feature-detection reply from the same stream.
status.Query() Write the optional feature-detection request.
ParseReply(sequence) Parse a terminal's reply into Capabilities.
caps.SupportsState(state) / caps.SupportsKind(kind) Check advertised support.
status.Reply(caps) / MarshalReply(caps) Generate a terminal's feature-detection reply.

Feature detection is optional; you can send reports directly. If you query, your application handles reading the reply and choosing a timeout. Query also provides the request as a string. The package never reads stdin implicitly or changes terminal modes. Requests and default replies have identical bytes, so distinguish them by context.

Capabilities{} means the protocol's default states and kinds. A non-nil empty list means none. Unknown advertised values are preserved for future extensions; Clear is always supported.

Output uses ESC \ termination. Parsing also accepts BEL and unpadded standard base64. Unmarshal and ParseReply expect exactly one complete sequence. Terminal applications manage the resulting records and their lifetimes.

Read a stream

Use a decoder for reports embedded in an io.Reader:

func readReports(r io.Reader) error {
	decoder := osc7501.NewDecoder(r)
	for {
		report, err := decoder.Decode()
		if err == io.EOF {
			return nil
		}
		if err != nil {
			return err
		}
		fmt.Println(report.State, report.Message)
	}
}

The decoder discards ordinary output and unrelated ESC-based control strings. It may read ahead, so give it exclusive access to its reader. Use Unmarshal or ParseReply with your own terminal parser when other input must be preserved. Your reader controls blocking, cancellation, and deadlines.

Both decoding methods consume the next OSC 7501 sequence. Call DecodeReply when a capability reply is expected; using the wrong method returns a validation error. Decoding never automatically replies to a query.

Frame storage is capped at 4096 bytes. Invalid frames return an error and can be followed by another decode call. Oversized frames return ErrLimitExceeded immediately; the next call discards the rest of that frame before looking for another. Truncated frames return io.ErrUnexpectedEOF; a stream with no remaining frames returns io.EOF.

Validation and concurrency

Sending validates the entire report before writing. Invalid fields return an error; text is never silently truncated. Messages are limited to 2048 UTF-8 bytes and titles to 192 bytes. Both must be valid UTF-8 without C0, DEL, or C1 control characters, including tabs and newlines.

App, when set, and each ID segment must contain 1–32 characters from [A-Za-z0-9_.+-]. IDs allow up to 8 slash-separated segments and 128 total bytes. Complete sequences are limited to 4096 bytes.

Parsing ignores unknown keys and malformed pairs as the protocol requires. Invalid IDs reject the report instead of falling back to the root record. Unsafe text, invalid required fields, and limit violations also reject the whole report. Use errors.Is with ErrInvalidSequence, ErrInvalidReport, ErrInvalidReply, or ErrLimitExceeded to classify errors. A parsing error always returns a zero result.

An encoder is safe to share between goroutines. It writes each sequence in a single Write call and returns writer errors, including short writes. Synchronize other writes to the same writer yourself. Keep report progress pointers and capability slices unchanged while they are being used. The caller owns the writer and handles any flushing or closing.

A Decoder is not safe for concurrent use. The caller retains ownership of the underlying reader and is responsible for closing it, if applicable.

Terminal integration security

Treat parsed text as untrusted plain text. A terminal integration must not interpret messages or titles as markup. When displaying them outside the terminal grid, disarm text direction overrides and other invisible formatting characters, identify the source terminal, and rate-limit notifications and sounds. The parser preserves formatting characters; validation does not sanitize text for a particular UI.

Generate capability replies from local configuration, never received report content. The byte-slice parsers perform no I/O, and the streaming decoder never writes replies. Integrations also enforce the terminal's record limit (up to 256, supporting at least 64) and evict the record updated least recently when the limit is reached. The package does not store records.

Test

go test -race -cover ./...
go vet ./...
go test -run='^$' -fuzz='^FuzzUnmarshal$' -fuzztime=30s
go test -run='^$' -fuzz='^FuzzParseReply$' -fuzztime=30s
go test -run='^$' -fuzz='^FuzzDecoder$' -fuzztime=30s

With Go 1.26 or newer, check for behavior-preserving modernizations:

go fix -diff ./...

CI runs this check on latest stable Go and separately tests Go 1.22 compatibility.

License

MIT.

About

A dependency-free Go library for OSC 7501 terminal status, messages, and progress.

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages