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 ¶
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 )
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 ¶
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 ¶
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.
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 ¶
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 ¶
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 ¶
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 ¶
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)
}
}
Output:
func (*Encoder) Query ¶
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 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 ¶
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. )