package rex import ( "bytes" "encoding/binary" "encoding/json" "errors" "fmt" "strconv" ) // A terminal's stream is a Ghostty snapshot, then everything the program // writes, with Rex's own messages placed where they are safe to apply. Each // message is an APC sequence, ESC _ rex1;; ESC \. // // The snapshot's own format is Ghostty's; libghostty decodes and validates // it. TerminalStream only finds where it ends: after a 10-byte envelope come // records, each a 10-byte header (a little-endian uint16 tag, a uint32 // payload length, and 4 more bytes) and its payload, ending with a FINISH // record. const ( snapshotEnvelope = "GHOSTSNP\x01\x00" snapshotHeaderBytes = 10 snapshotFinishTag = 6 maxSnapshotBytes = 256 << 20 maxMessageBytes = 1 << 20 ) // Message is one of Rex's own messages in a terminal's stream. type Message struct { // Type is resize, theme, or child_exited. Skip a type you don't know. Type string `json:"type"` // For resize: the terminal's size, and a cell's size in pixels, or 0 // when it's unknown. Owner is the block's owner when the size was set. Cols uint16 `json:"cols"` Rows uint16 `json:"rows"` CellWidthPx uint32 `json:"cell_width_px"` CellHeightPx uint32 `json:"cell_height_px"` Owner *string `json:"owner"` // For theme: the default colours, as RRGGBB or #RRGGBB, or "" for the // built-in one, and changes to the palette, each index=RRGGBB. Each // theme replaces the one before it. Foreground string `json:"foreground"` Background string `json:"background"` Cursor string `json:"cursor"` Palette []string `json:"palette"` Scheme string `json:"scheme"` // For child_exited: the program's exit code. ExitCode int `json:"exit_code"` } // TerminalStream splits a terminal's stream into its snapshot, the program's // output, and Rex's messages. type TerminalStream struct { prefix []byte // ESC _ rex1;; snapshot []byte scan int // offset of the next snapshot record header restored bool // the snapshot is complete held []byte inMessage bool } // NewTerminalStream returns a parser for a stream whose data connection's // welcome carried nonce. func NewTerminalStream(nonce uint64) *TerminalStream { return &TerminalStream{prefix: []byte("\x1b_rex1;" + strconv.FormatUint(nonce, 10) + ";")} } // StreamHandler receives the parts of a terminal's stream, in order. type StreamHandler interface { // Snapshot receives the complete snapshot. It is called once, before // anything else. Snapshot(data []byte) error // Output receives bytes the program wrote. data is only valid during // the call. Output(data []byte) error // Message receives one of Rex's messages. Message(m Message) error } // Feed parses the next part of the stream. func (s *TerminalStream) Feed(data []byte, h StreamHandler) error { if !s.restored { rest, done, err := s.feedSnapshot(data) if err != nil || !done { return err } snapshot := s.snapshot s.snapshot = nil if err := h.Snapshot(snapshot); err != nil { return err } data = rest } return s.feedOutput(data, h) } // feedSnapshot adds data to the snapshot. Once it is complete, it returns // done and the bytes that follow it. func (s *TerminalStream) feedSnapshot(data []byte) (rest []byte, done bool, err error) { if len(s.snapshot)+len(data) > maxSnapshotBytes { return nil, false, errors.New("rex: snapshot exceeds 256 MiB") } s.snapshot = append(s.snapshot, data...) if s.scan == 0 { if len(s.snapshot) < len(snapshotEnvelope) { return nil, false, nil } if string(s.snapshot[:len(snapshotEnvelope)]) != snapshotEnvelope { return nil, false, errors.New("rex: stream doesn't start with a Ghostty snapshot") } s.scan = len(snapshotEnvelope) } for len(s.snapshot) >= s.scan+snapshotHeaderBytes { header := s.snapshot[s.scan:] tag := binary.LittleEndian.Uint16(header) size := int(binary.LittleEndian.Uint32(header[2:])) if size > maxSnapshotBytes { return nil, false, errors.New("rex: snapshot record exceeds 256 MiB") } end := s.scan + snapshotHeaderBytes + size if end > len(s.snapshot) { return nil, false, nil } s.scan = end if tag == snapshotFinishTag { s.restored = true rest = bytes.Clone(s.snapshot[end:]) s.snapshot = s.snapshot[:end] return rest, true, nil } } return nil, false, nil } // feedOutput separates Rex's messages from the program's output. func (s *TerminalStream) feedOutput(data []byte, h StreamHandler) error { if len(s.held) > 0 { data = append(s.held, data...) s.held = nil } for len(data) > 0 { if s.inMessage { end := bytes.Index(data, []byte("\x1b\\")) if end < 0 { if len(data) > maxMessageBytes { return errors.New("rex: message exceeds 1 MiB") } s.held = bytes.Clone(data) return nil } var m Message if err := json.Unmarshal(data[len(s.prefix):end], &m); err != nil { return fmt.Errorf("rex: invalid message in stream: %w", err) } if err := h.Message(m); err != nil { return err } data = data[end+2:] s.inMessage = false continue } // Pass output through up to the next ESC that could start a // message. i := 0 for { esc := bytes.IndexByte(data[i:], 0x1b) if esc < 0 { i = len(data) break } i += esc n := min(len(data)-i, len(s.prefix)) if bytes.Equal(data[i:i+n], s.prefix[:n]) { break // a message, or the start of one } i++ } if i > 0 { if err := h.Output(data[:i]); err != nil { return err } data = data[i:] } if len(data) == 0 { return nil } if len(data) < len(s.prefix) { // Too short to tell yet. s.held = bytes.Clone(data) return nil } s.inMessage = true } return nil }