osc7501

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: MIT Imports: 12 Imported by: 0

README

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 owns and closes its reader.

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.

Documentation

Overview

Package osc7501 implements the Program Status Protocol (OSC 7501), revision 0.4. Programs use it to report activity, messages, progress, and requests for user input to a terminal.

Use NewEncoder with a terminal output stream and call Encoder.Encode to send a Report. Each report completely replaces the record with the same ID, so include its App, Title, and Message whenever they should remain visible. An empty ID addresses the root record; slash-separated IDs address subtasks.

Marshal and Unmarshal encode and parse complete escape sequences without I/O. NewDecoder reads reports and feature-detection replies from a supplied stream. Query and the capability functions support optional feature detection. The package never opens terminal input, changes terminal modes, checks environment variables, or starts background goroutines.

Reusing reports

A Report can be saved, updated, and encoded repeatedly. Copy a report to use its App, ID, and Title as a template. Copies share the Progress pointer; assign a new Percent value when independent progress values are needed. Reset Kind and Progress when changing to a state that does not accept them. Synchronize access if multiple goroutines update the same report.

Security

Reports are untrusted input. The codec rejects invalid UTF-8, control characters, and exceeded protocol limits before returning a parsed report or writing an encoded one. Decoding never writes a reply. Encoder.Reply should use locally configured capabilities, never values taken from a report.

Terminal integrations must display Message and Title as plain text, not markup. When displaying them outside the terminal grid, integrations should disarm text direction overrides and other invisible formatting characters, identify the source terminal, and rate-limit notifications and sounds. Parsed text retains these formatting characters; it is not sanitized for display. Integrations also enforce the terminal's record cap and eviction policy. This package does not store records or implement a terminal UI.

See https://www.superlogical.com/rex/docs/build/program-status.

Example
package main

import (
	"bytes"
	"fmt"
	"log"

	"github.com/SamiNassim/osc7501"
)

func main() {
	var output bytes.Buffer
	status := osc7501.NewEncoder(&output)
	if err := status.Encode(osc7501.Report{
		State:   osc7501.Blocked,
		ID:      "deploy/production",
		Kind:    osc7501.Permission,
		Title:   "Production",
		Message: "Approve deployment?",
	}); err != nil {
		log.Fatal(err)
	}

	report, err := osc7501.Unmarshal(output.Bytes())
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(report.State, report.Kind, report.Message)
}
Output:
blocked permission Approve deployment?

Index

Examples

Constants

View Source
const (

	// MaxSequenceBytes is the protocol limit for an entire sequence, including
	// its OSC prefix and terminator. Input is checked before parsing or decoding.
	MaxSequenceBytes = 4096
)
View Source
const Query = prefix + "?" + terminator

Query is the complete feature-detection request. A supporting terminal replies with the same marker, optionally followed by capability lists. Detection is optional; programs may send reports without querying first.

Variables

View Source
var (
	// ErrInvalidSequence identifies input that is not one complete OSC 7501
	// sequence. Unmarshal and ParseReply expect complete sequences; Decoder
	// scans a stream for them.
	ErrInvalidSequence = errors.New("osc7501: invalid sequence")
	// ErrInvalidReport identifies a report with an invalid required field or
	// unsafe text. Receiving applications should discard it in full.
	ErrInvalidReport = errors.New("osc7501: invalid report")
	// ErrInvalidReply identifies a malformed capability reply.
	ErrInvalidReply = errors.New("osc7501: invalid capability reply")
	// ErrLimitExceeded identifies a protocol size or depth limit violation.
	// Receiving applications should discard the entire sequence.
	ErrLimitExceeded = errors.New("osc7501: limit exceeded")
)

Functions

func Marshal

func Marshal(report Report) ([]byte, error)

Marshal encodes a report as a complete OSC 7501 sequence terminated by ESC \. It validates every field before returning any output. Invalid or inapplicable fields return an error rather than being silently dropped.

Example
package main

import (
	"fmt"
	"log"

	"github.com/SamiNassim/osc7501"
)

func main() {
	sequence, err := osc7501.Marshal(osc7501.Report{
		State: osc7501.Clear,
		ID:    "build/test",
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%q\n", sequence)
}
Output:
"\x1b]7501;state=clear:id=build/test\x1b\\"

func MarshalReply

func MarshalReply(capabilities Capabilities) ([]byte, error)

MarshalReply encodes a feature-detection reply terminated by ESC \. Nil lists are omitted. Values may include future extensions, but must each be a nonempty protocol value without commas. Clear is not a list member. A reply exceeding MaxSequenceBytes returns ErrLimitExceeded.

func Percent

func Percent(value int) *int

Percent returns a pointer to a percentage for Report.Progress. Marshal checks that the value is between 0 and 100.

Types

type Capabilities

type Capabilities struct {
	States []State // Clear is implicit and must not be advertised.
	Kinds  []Kind
}

Capabilities describes a terminal's supported states and blocked kinds. Nil lists mean the protocol's fixed defaults. A non-nil empty list means none. Unknown values are preserved so future protocol extensions can be inspected. The zero value advertises all revision 0.4 states and kinds.

func ParseReply

func ParseReply(sequence []byte) (Capabilities, error)

ParseReply parses a complete feature-detection reply. The bare Query sequence is also a valid reply: requests and default replies have identical bytes, and the caller distinguishes them by context. Both terminators are accepted. Missing lists retain their fixed defaults; unknown keys are ignored. No terminal input is read, and no timeout is imposed.

Example
package main

import (
	"fmt"
	"log"

	"github.com/SamiNassim/osc7501"
)

func main() {
	capabilities, err := osc7501.ParseReply([]byte("\x1b]7501;?:states=idle,working,done:kinds=auth\x1b\\"))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(capabilities.SupportsState(osc7501.Working))
	fmt.Println(capabilities.SupportsKind(osc7501.Permission))
}
Output:
true
false

func (Capabilities) SupportsKind

func (c Capabilities) SupportsKind(kind Kind) bool

SupportsKind reports whether the terminal advertises kind.

func (Capabilities) SupportsState

func (c Capabilities) SupportsState(state State) bool

SupportsState reports whether the terminal advertises state. Clear is always supported and does not appear in the advertised state list.

type Decoder

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

Decoder reads OSC 7501 sequences from an io.Reader. It discards ordinary output and other ESC-based control strings, including unrelated OSCs. Decode reads reports; DecodeReply reads feature-detection replies. Both methods consume the next OSC 7501 sequence, even if its type is wrong.

A decoder may read ahead. Give it exclusive access to its input stream; use Unmarshal or ParseReply with an existing terminal parser when other input must be preserved. A Decoder is not safe for concurrent use and must not be copied after first use. Its zero value returns io.ErrClosedPipe.

func NewDecoder

func NewDecoder(r io.Reader) *Decoder

NewDecoder returns a decoder that reads from r. The caller owns r and controls blocking, cancellation, and deadlines through that reader. The decoder never reads stdin implicitly or changes terminal modes.

func (*Decoder) Decode

func (d *Decoder) Decode() (Report, error)

Decode reads the next OSC 7501 sequence and parses it with Unmarshal. It accepts ESC \ and BEL terminators. A feature-detection sequence returns ErrInvalidReport; use DecodeReply when a reply is expected.

Invalid complete sequences are consumed, so Decode can be called again to continue. Oversized sequences return ErrLimitExceeded as soon as the limit is exceeded; subsequent calls discard their remainder through the terminator before looking for another sequence. Sequence storage never exceeds MaxSequenceBytes, even while discarding oversized or unrelated strings.

Decode returns io.EOF when no sequence remains, and io.ErrUnexpectedEOF when EOF interrupts a matching prefix or a report. Other reader errors are returned unchanged, preserving incomplete input for a retry. Every error returns a zero Report.

Example
package main

import (
	"fmt"
	"io"
	"log"
	"strings"

	"github.com/SamiNassim/osc7501"
)

func main() {
	input := strings.NewReader("build output\n" +
		"\x1b]7501;state=working:msg=QnVpbGRpbmc=\x1b\\" +
		"\x1b]7501;state=done:msg=QnVpbGQgY29tcGxldGU=\a")
	decoder := osc7501.NewDecoder(input)
	for {
		report, err := decoder.Decode()
		if err == io.EOF {
			break
		}
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(report.State, report.Message)
	}
}
Output:
working Building
done Build complete

func (*Decoder) DecodeReply

func (d *Decoder) DecodeReply() (Capabilities, error)

DecodeReply reads the next OSC 7501 sequence and parses it with ParseReply. A report returns ErrInvalidReply. The bare Query is accepted because a request and a default reply have identical bytes. Framing, limits, recovery, and reader errors behave as described for Decode. Every error returns zero Capabilities. Reading a query does not send a reply.

Example
package main

import (
	"fmt"
	"log"
	"strings"

	"github.com/SamiNassim/osc7501"
)

func main() {
	decoder := osc7501.NewDecoder(strings.NewReader(osc7501.Query))
	capabilities, err := decoder.DecodeReply()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(capabilities.SupportsState(osc7501.Working))
	fmt.Println(capabilities.SupportsKind(osc7501.Auth))
}
Output:
true
true

type Encoder

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

Encoder sends OSC 7501 sequences to an io.Writer. Its methods are safe for concurrent use and serialize complete sequences through this encoder. Other writes to the same writer must be synchronized by the caller. An Encoder must not be copied after first use. The zero value returns io.ErrClosedPipe on writes.

func NewEncoder

func NewEncoder(w io.Writer) *Encoder

NewEncoder returns an encoder that writes to w, usually os.Stderr or os.Stdout connected to a terminal. The caller owns and closes w.

func (*Encoder) Encode

func (e *Encoder) Encode(report Report) error

Encode validates and sends a report. Validation errors write nothing. Each sequence is passed to the underlying writer in a single Write call. A writer error may leave a partially written sequence and is returned as-is.

Example
package main

import (
	"log"
	"os"

	"github.com/SamiNassim/osc7501"
)

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

func (*Encoder) Query

func (e *Encoder) Query() error

Query sends the optional feature-detection request. It does not read a reply.

func (*Encoder) Reply

func (e *Encoder) Reply(capabilities Capabilities) error

Reply sends the terminal's feature-detection reply. It does not echo any report text or identifiers. The caller supplies the supported capabilities.

type Kind

type Kind string

Kind describes the input needed by a blocked task.

const (
	Permission Kind = "permission" // Approval to perform an action.
	Question   Kind = "question"   // An answer to a question.
	Auth       Kind = "auth"       // A login, token, or credential.
)

type Report

type Report struct {
	State    State
	ID       string // Empty for the root; otherwise a slash-separated task path.
	Kind     Kind
	Progress *int   // Optional percentage from 0 through 100, inclusive.
	App      string // Stable program identifier, at most 32 ASCII bytes.
	Title    string // Single-line label, at most 192 UTF-8 bytes.
	Message  string // Single-line message, at most 2048 UTF-8 bytes.
}

Report replaces one terminal status record. The zero value is invalid: State must be set. Optional strings are omitted when empty.

A nil Progress means indeterminate activity; Percent(0) reports zero percent. Kind is only valid with Blocked. Progress is only valid with Working or Blocked. Message and Title are plain UTF-8 text, not base64.

Reports can be saved and encoded repeatedly. Copies share the Progress pointer; assign Percent(value) to give a copy independent progress. Callers must not mutate reports or their Progress values concurrently with use.

Example
package main

import (
	"bytes"
	"fmt"
	"log"

	"github.com/SamiNassim/osc7501"
)

func main() {
	var output bytes.Buffer
	encoder := osc7501.NewEncoder(&output)
	report := osc7501.Report{
		State:   osc7501.Working,
		App:     "myapp",
		ID:      "build",
		Title:   "Build",
		Message: "Compiling packages",
	}
	if err := encoder.Encode(report); err != nil {
		log.Fatal(err)
	}

	// Keep the task's identity and update only what changed.
	report.State = osc7501.Done
	report.Message = "Build complete"
	output.Reset()
	if err := encoder.Encode(report); err != nil {
		log.Fatal(err)
	}

	decoded, err := osc7501.Unmarshal(output.Bytes())
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(decoded.App, decoded.ID, decoded.Title, decoded.State, decoded.Message)
}
Output:
myapp build Build done Build complete

func Unmarshal

func Unmarshal(sequence []byte) (Report, error)

Unmarshal parses one complete OSC 7501 report, accepting ESC \ or BEL as its terminator and padded or unpadded standard base64 text. Unknown keys and malformed pairs are ignored, and the last value for a key wins. Invalid kind, progress, and app values are treated as absent. Invalid ID values are rejected instead of being treated as absent.

A missing or unknown state, invalid ID, invalid text, or exceeded limit rejects the whole report. The returned report is zero on error. Limits and text safety are checked even in pairs superseded by a later duplicate. Decoded text remains untrusted; see the package's security guidance before displaying it outside a terminal grid.

Example
package main

import (
	"fmt"
	"log"

	"github.com/SamiNassim/osc7501"
)

func main() {
	report, err := osc7501.Unmarshal([]byte("\x1b]7501;state=done:msg=VGVzdHMgcGFzc2Vk\a"))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(report.State, report.Message)
}
Output:
done Tests passed

type State

type State string

State describes the current activity of a program or task.

const (
	Idle    State = "idle"    // Waiting for the user's next instruction.
	Working State = "working" // Running; progress may be reported.
	Blocked State = "blocked" // Waiting for user input; kind may explain why.
	Done    State = "done"    // Finished successfully; the result is ready.
	Error   State = "error"   // Failed and stopped.
	Clear   State = "clear"   // Remove this record and all its descendants.
)

Jump to

Keyboard shortcuts

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