consolestream

package module
v0.6.6 Latest Latest
Warning

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

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

README

Console Stream

A Go library for executing processes and streaming their output in real-time using Go iterators (Go 1.26+).

Features

  • Real-time streaming: Process output delivered at configurable intervals or buffer limits
  • Unified API: Single process type supports both pipe and PTY modes
  • Container execution: Run processes inside Docker/Podman containers with volume mounts
  • Event-driven: Process lifecycle events, output data, and heartbeat monitoring
  • Production ready: Context cancellation, process-group cleanup, error handling, and OpenTelemetry metrics
  • Asciicast: Record PTY sessions in asciicast v3 format
  • Program status: Typed ProgramStatus events from OSC 7501 reports, ordered against output (opt-in)

Quick Start

Run a command and print its output as it arrives:

package main

import (
    "context"
    "fmt"
    "os"
    "os/signal"
    "syscall"

    consolestream "github.com/wolfeidau/console-stream"
)

func main() {
    // Children do not receive Ctrl-C; cancel the context on SIGINT/SIGTERM.
    ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
    defer stop()

    process := consolestream.NewProcess("echo", []string{"Hello, World!"})

    for event, err := range process.ExecuteAndStream(ctx) {
        if err != nil {
            fmt.Printf("Error: %v\n", err)
            break
        }

        switch e := event.Event.(type) {
        case *consolestream.OutputData:
            fmt.Printf("Output: %s", e.Data)
        case *consolestream.ProcessError:
            fmt.Printf("Process error: %s\n", e.Message)
        case *consolestream.ProcessEnd:
            fmt.Printf("Process completed (Exit: %d)\n", e.ExitCode)
        }
    }
}

PTY Mode

Use a pseudo-terminal for interactive programs, colors and progress bars. ANSI escape sequences are preserved.

process := consolestream.NewProcess("npm", []string{"install"},
    consolestream.WithPTYMode(),
    consolestream.WithPTYSize(&pty.Winsize{Rows: 24, Cols: 80}), // github.com/creack/pty
    consolestream.WithEnvVar("NODE_ENV", "production"),
    consolestream.WithFlushInterval(500*time.Millisecond))
Process Options
Option Description
WithPipeMode() Use a pipe for stdout+stderr (default)
WithPTYMode() Use a pseudo-terminal
WithPTYSize(*pty.Winsize) Terminal dimensions for PTY
WithCancellor(c) Custom cancellation (default: NewLocalCancellor(5s))
WithEnv([]string) / WithEnvVar(k, v) / WithEnvMap(m) Environment variables
WithWorkingDir(dir) Working directory
WithFlushInterval(d) Output batch interval (default 1s): bounds live latency and event volume
WithHeartbeatInterval(d) Heartbeat interval (default 1s), independent of the batch interval
WithMaxBufferSize(n) Deliver a batch early when it reaches n bytes (default 10MB)
WithMeter(metric.Meter) OpenTelemetry metrics
WithProgramStatus() Parse OSC 7501 reports into ProgramStatus events (off by default)

Container Execution

Run a command inside a Docker or Podman container. Missing images are pulled automatically, with progress events every 2 seconds.

process := consolestream.NewContainerProcess("make", []string{"test"},
    consolestream.WithContainerImage("golang:1.25"),
    consolestream.WithContainerMount("/path/to/code", "/workspace", false),
    consolestream.WithContainerWorkingDir("/workspace"),
    consolestream.WithContainerEnvMap(map[string]string{"CI": "true"}))

for event, err := range process.ExecuteAndStream(ctx) {
    if err != nil {
        break
    }

    switch e := event.Event.(type) {
    case *consolestream.ImagePullStart:
        fmt.Printf("Pulling image: %s\n", e.Image)
    case *consolestream.ImagePullProgress:
        fmt.Printf("Pull progress: %d%% (%d/%d bytes)\n",
            e.PercentComplete, e.BytesDownloaded, e.BytesTotal)
    case *consolestream.ImagePullComplete:
        fmt.Printf("Pull complete: %s\n", e.Digest)
    case *consolestream.ContainerCreate:
        fmt.Printf("Container: %s\n", e.ContainerID)
    case *consolestream.OutputData:
        fmt.Print(string(e.Data))
    case *consolestream.ProcessEnd:
        fmt.Printf("Exit: %d\n", e.ExitCode)
    }
}

Event order: ContainerCreate → ProcessStart → OutputData/HeartbeatEvent → ProcessEnd | ProcessError → ContainerRemove, preceded by ImagePull* events when the image is missing.

Option Description
WithContainerImage(img) Container image (required)
WithContainerRuntime(r) "docker" (default) or "podman"
WithContainerMount(src, dst, ro) Volume mount
WithContainerWorkingDir(d) Working directory in container
WithContainerEnv([]string) / WithContainerEnvMap(m) Environment variables
WithContainerFlushInterval(d) Output batch interval (default 1s)
WithContainerHeartbeatInterval(d) Heartbeat interval (default 1s)
WithContainerMaxBufferSize(n) Maximum batch size (default 10MB)
WithContainerMeter(metric.Meter) OpenTelemetry metrics
WithContainerProgramStatus() Parse OSC 7501 reports into ProgramStatus events (off by default)

Program status (OSC 7501)

Programs can report what they are doing (working, blocked, done) with OSC 7501 escape sequences (spec; local copy in spec/osc7501-program-status.md). Enable parsing with WithProgramStatus() (pipe and PTY) or WithContainerProgramStatus(). It is off by default.

  • Each report yields a ProgramStatus event (State, ID, Kind, App, Title, Msg, Progress; Progress is -1 when indeterminate; Title and Msg are decoded).
  • The report bytes still pass through unchanged in OutputData.
  • Ordering: ProgramStatus is yielded after the OutputData holding all preceding bytes and before any following bytes. It is delivered promptly, not at the next batch tick.
  • Event.Timestamp is the time the report was read.
  • Lifetime: after ProcessEnd or ProcessError, working and blocked no longer apply. The library emits no synthetic events and keeps no record store; track state in the consumer.
  • Feature query: in PTY mode the library answers OSC 7501;? by writing a reply listing the default states and kinds to the child's stdin. Pipe and container modes have no stdin back-channel and cannot reply, so programs there should report without querying. CSI c (DA1) is not answered.
  • Only OSC framing is tracked; an ESC ] inside a DCS or APC string can be mis-framed.
  • Asciicast: a marker (status: <state>[/<kind>][ <id>][ <progress>%][: <msg>]) is written when (id, state, kind) changes for an ID. Progress-only and message-only changes write nothing, and the recording continues.
  • Time in state: StatusTimer (feed it events with Observe, read Totals) measures wall-clock time per state. At each instant the run counts once under its most urgent live state (blocked > working > idle) across IDs; done/error end an ID's record, clear removes it and its descendants, and ProcessEnd/ProcessError stop the clock. With WithMeter the counter process.program_status.duration{state} (seconds) is recorded, and GetStats().StatusTime returns the totals. The runner logs them as status_time.
process := consolestream.NewProcess("agent", nil,
    consolestream.WithPTYMode(),
    consolestream.WithProgramStatus())

ctx, cancel := context.WithCancel(ctx)
defer cancel()

for event, err := range process.ExecuteAndStream(ctx) {
    if err != nil {
        break
    }
    if s, ok := event.Event.(*consolestream.ProgramStatus); ok && s.State == "blocked" {
        fmt.Printf("blocked (%s): %s\n", s.Kind, s.Msg)
        cancel()
    }
}

To emit status from a Go program, use github.com/wolfeidau/osc7501 (osc7501.NewReporter(os.Stdout, app).Working(...)); parsing and stripping also live there. Programs already using charm can use github.com/charmbracelet/x/ansi (v0.11.9+) instead: ansi.SetProgramStatus(ansi.ProgramStatus{...}) returns a sanitised report to write to stdout. example/programstatus/ runs a child that reports with osc7501.Reporter and a parent that stops the child when it blocks:

go run ./example/programstatus

Asciicast Recording

Record a PTY session in asciicast v3 format:

process := consolestream.NewProcess("bash", []string{"-c", "ls --color"},
    consolestream.WithPTYMode())

metadata := consolestream.AscicastV3Metadata{
    Term:    consolestream.TermInfo{Cols: 80, Rows: 24},
    Command: "ls --color",
}

file, err := os.Create("session.cast")
if err != nil {
    log.Fatal(err)
}
defer file.Close()

err = consolestream.WriteAscicastV3(process.ExecuteAndStream(ctx), metadata, func(b []byte) error {
    _, err := file.Write(b)
    return err
})

ToAscicastV3 returns the lines as an iterator if you need to process them yourself. A ProcessError ends the recording with an "m" marker (error: <message>) instead of an "x" exit event.

ToAscicastV3 maps each event type to a line: output to "o", TerminalResizeEvent to "r", and process end to "x". The library does not emit resize events itself (PTY size is fixed by WithPTYSize); callers wrapping the event stream may inject them.

Recordings use per-read timestamps from OutputData.Segments, so the batch interval (WithFlushInterval) does not affect playback timing; there is no need to lower it for recordings. Always record with WithPTYMode().

timestamp defaults to the recording start time (Unix seconds) when unset. TermInfo accepts optional Type, Version and Theme (*TermTheme); event intervals are rounded to microseconds.

Events

Event Description
ProcessStart Process started (PID, command, args)
OutputData Output bytes (stdout and stderr are combined); Segments carries per-read timing
HeartbeatEvent Process alive, no output since the previous heartbeat tick
ProcessEnd Exit code, duration, success. A non-zero exit is a ProcessEnd, not an error. A signal-terminated process reports 128 + signal (137 for SIGKILL), matching shells and container mode
ProcessError Failure that is not a non-zero exit
TerminalResizeEvent Terminal size change (PTY)
ContainerCreate / ContainerRemove Container created / cleaned up
ImagePullStart / ImagePullProgress / ImagePullComplete Image pull (container)
ProgramStatus OSC 7501 report (state, id, kind, app, title, msg, progress); requires WithProgramStatus()

Streaming Behaviour

  • Output is delivered in batches: one OutputData event per batch interval (WithFlushInterval, default 1s), earlier if the buffer reaches the max size (default 10MB), and a final batch on exit.
  • The batch interval trades live latency for event volume. It does not affect timing accuracy: OutputData.Segments records when each chunk was read.
  • Heartbeats run on their own interval (WithHeartbeatInterval, default 1s): on each tick a HeartbeatEvent fires if no output was delivered or buffered since the previous tick. A short batch interval does not add heartbeats.
  • Pipe mode is not line-buffered: events can split mid-line. Reassemble lines in the consumer if needed.
  • Stdout and stderr share one pipe, so their relative order is preserved but they cannot be distinguished.

Cancellation and Signals

Breaking out of the range loop or cancelling the context stops the child through the Cancellor (SIGTERM to the process group, SIGKILL after the timeout) and waits for all goroutines before the iterator returns. Containers are stopped and then removed.

Children run in their own process group (pipe: Setpgid, PTY: Setsid), so they do not receive Ctrl-C from your terminal. Use signal.NotifyContext for SIGINT/SIGTERM and cancel the context, as in the Quick Start.

Known limits:

  • PTY children that create job-control subgroups (e.g. interactive shells) have descendants the group kill does not reach.
  • Grandchildren that daemonize are not killed when the child exits normally.

Error Handling

  • A process that cannot start yields a ProcessStartError as the iterator error.
  • Failures after start arrive as ProcessError events; non-zero exits arrive as ProcessEnd with Success == false.
var startErr consolestream.ProcessStartError
if errors.As(err, &startErr) {
    fmt.Printf("could not start %s: %v\n", startErr.Cmd, startErr.Err)
}

Command Line Tool

Build and use the runner tool:

# Build
go build -o runner ./cmd/runner

# Execute with YAML config
./runner exec --config task.yaml --format json --output results.json

Example config:

command: "docker"
args: ["build", "-t", "myapp", "."]
process_type: "pty"
timeout: "10m"
env:
  DOCKER_BUILDKIT: "1"
Program status in the runner

Set program_status: true to parse OSC 7501 reports (see Program status (OSC 7501)). Set fail_on_blocked: true (requires program_status) to stop the child and exit non-zero on the first blocked status.

  • Text format prints [STATUS] 15:04:05 working/kind build 50%: msg lines, starting a new line first if output was mid-line.
  • JSON format emits PROGRAM_STATUS events.
  • Asciicast format records "m" markers. With fail_on_blocked, the recording ends at the blocked marker with no exit line.
  • The completion log includes a program_status summary of the last state per ID (id=state, root shown as -) and status_time, the time spent working, blocked and idle (for example working=12.3s blocked=4.1s idle=200ms; zero entries omitted).
  • When the runner's stderr is a terminal, each report is re-emitted there as OSC 7501, grouped under the run id: status_id (default <command>-xxxx) prefixes ids (build becomes <id>/build, the root becomes <id>).
  • The runner also relays its own run record under the run id: working at start, then done or error (with the exit code) at end, which persists in the terminal after exit.
  • Text output strips OSC 7501 sequences from [OUTPUT] lines when program_status is on; JSON and asciicast keep the raw bytes.

See config/program-status-runner-config.yaml.

Installation

go get github.com/wolfeidau/console-stream

Requirements: Go 1.26+, Unix-like system

License

Apache License, Version 2.0 - Copyright Mark Wolfe

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsContainerCreateEvent added in v0.4.0

func IsContainerCreateEvent(event StreamEvent) bool

func IsContainerRemoveEvent added in v0.4.0

func IsContainerRemoveEvent(event StreamEvent) bool

func IsHeartbeatEvent

func IsHeartbeatEvent(event StreamEvent) bool

func IsOutputEvent added in v0.3.0

func IsOutputEvent(event StreamEvent) bool

func IsProcessEndEvent

func IsProcessEndEvent(event StreamEvent) bool

func IsProcessErrorEvent

func IsProcessErrorEvent(event StreamEvent) bool

func IsProcessLifecycleEvent

func IsProcessLifecycleEvent(event StreamEvent) bool

func IsProcessStartEvent

func IsProcessStartEvent(event StreamEvent) bool

func IsProgramStatusEvent added in v0.6.0

func IsProgramStatusEvent(event StreamEvent) bool

func IsTerminalResizeEvent

func IsTerminalResizeEvent(event StreamEvent) bool

func ToAscicastV3

func ToAscicastV3(events iter.Seq2[Event, error], metadata AscicastV3Metadata) iter.Seq2[AscicastV3Line, error]

ToAscicastV3 transforms a stream of console-stream events into asciicast v3 format

func WriteAscicastV3

func WriteAscicastV3(events iter.Seq2[Event, error], metadata AscicastV3Metadata, writeFunc func([]byte) error) error

WriteAscicastV3 is a convenience function to write asciicast v3 to any writer

Types

type AscicastV3Event

type AscicastV3Event [3]any

AscicastV3Event represents an event line in asciicast v3 format: [interval, code, data]

func NewExitEvent

func NewExitEvent(interval float64, exitCode int) AscicastV3Event

NewExitEvent creates an asciicast exit event

func NewMarkerEvent added in v0.5.0

func NewMarkerEvent(interval float64, label string) AscicastV3Event

NewMarkerEvent creates an asciicast marker event

func NewOutputEvent

func NewOutputEvent(interval float64, data string) AscicastV3Event

NewOutputEvent creates an asciicast output event

func NewResizeEvent

func NewResizeEvent(interval float64, cols, rows uint16) AscicastV3Event

NewResizeEvent creates an asciicast resize event

func (AscicastV3Event) MarshalJSON

func (e AscicastV3Event) MarshalJSON() ([]byte, error)

MarshalJSON implements AscicastV3Line interface for events

type AscicastV3Header

type AscicastV3Header struct {
	Version int `json:"version"`
	AscicastV3Metadata
}

AscicastV3Header represents the first line of an asciicast v3 file

func (AscicastV3Header) MarshalJSON

func (h AscicastV3Header) MarshalJSON() ([]byte, error)

MarshalJSON implements AscicastV3Line interface for headers

type AscicastV3Line

type AscicastV3Line interface {
	MarshalJSON() ([]byte, error)
}

AscicastV3Line represents either a header or event line in asciicast v3 format

type AscicastV3Metadata

type AscicastV3Metadata struct {
	Term      TermInfo          `json:"term"`
	Timestamp *int64            `json:"timestamp,omitempty"`
	Command   string            `json:"command,omitempty"`
	Title     string            `json:"title,omitempty"`
	Env       map[string]string `json:"env,omitempty"`
	Tags      []string          `json:"tags,omitempty"`
}

AscicastV3Metadata contains the metadata for the asciicast header

type BufferWriter added in v0.2.0

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

BufferWriter wraps buffer operations and implements io.WriteCloser This can be used by both PipeProcess and PTYProcess for consistent buffer management

func NewBufferWriter added in v0.2.0

func NewBufferWriter(flushChan chan<- struct{}, maxBufferSize int) *BufferWriter

func (*BufferWriter) Close added in v0.2.0

func (w *BufferWriter) Close() error

func (*BufferWriter) FlushAndClear added in v0.2.0

func (w *BufferWriter) FlushAndClear() []byte

FlushAndClear returns the current buffer contents and clears it (including segments)

func (*BufferWriter) FlushSegments added in v0.5.0

func (w *BufferWriter) FlushSegments() ([]byte, []OutputSegment)

FlushSegments returns copies of the buffer contents and their read segments, clearing both (and any pending statuses). It returns nil, nil when the buffer is empty.

func (*BufferWriter) Len added in v0.2.0

func (w *BufferWriter) Len() int

Len returns the current buffer length (thread-safe)

func (*BufferWriter) Write added in v0.2.0

func (w *BufferWriter) Write(data []byte) (int, error)

type Cancellor

type Cancellor interface {
	Cancel(ctx context.Context, pid int) error
}

Cancellor defines the interface for cancelling processes

type ContainerCreate added in v0.4.0

type ContainerCreate struct {
	ContainerID string
	Image       string
}

ContainerCreate represents container creation

func (*ContainerCreate) String added in v0.4.0

func (c *ContainerCreate) String() string

func (*ContainerCreate) Type added in v0.4.0

func (c *ContainerCreate) Type() EventType

type ContainerMount added in v0.4.0

type ContainerMount struct {
	Source   string
	Target   string
	ReadOnly bool
}

ContainerMount represents a volume mount for container processes

type ContainerProcess added in v0.4.0

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

ContainerProcess represents a process running inside a container

func NewContainerProcess added in v0.4.0

func NewContainerProcess(cmd string, args []string, opts ...ContainerProcessOption) *ContainerProcess

NewContainerProcess creates a new container process with functional options

func (*ContainerProcess) ExecuteAndStream added in v0.4.0

func (cp *ContainerProcess) ExecuteAndStream(ctx context.Context) iter.Seq2[Event, error]

ExecuteAndStream starts a container and returns an iterator over Event objects

type ContainerProcessOption added in v0.4.0

type ContainerProcessOption func(*containerProcessConfig)

ContainerProcessOption represents a functional option for configuring container processes

func WithContainerEnv added in v0.4.0

func WithContainerEnv(env []string) ContainerProcessOption

WithContainerEnv sets environment variables as a slice of "KEY=value" strings

func WithContainerEnvMap added in v0.4.0

func WithContainerEnvMap(envMap map[string]string) ContainerProcessOption

WithContainerEnvMap sets environment variables from a map for convenience

func WithContainerFlushInterval added in v0.4.0

func WithContainerFlushInterval(interval time.Duration) ContainerProcessOption

WithContainerFlushInterval sets the output batch interval (default 1s): how often buffered output is delivered as an OutputData event. It bounds live delivery latency and event volume. It does not affect timing accuracy: each event's Segments record when output was read.

func WithContainerHeartbeatInterval added in v0.5.1

func WithContainerHeartbeatInterval(interval time.Duration) ContainerProcessOption

WithContainerHeartbeatInterval sets the heartbeat interval (default 1s). On each interval tick, a HeartbeatEvent is emitted if no output was delivered or buffered since the previous tick, so the first heartbeat follows one to two intervals of silence and repeats every interval. Independent of the batch interval.

func WithContainerImage added in v0.4.0

func WithContainerImage(image string) ContainerProcessOption

WithContainerImage sets the container image to use (REQUIRED for container processes)

func WithContainerMaxBufferSize added in v0.4.0

func WithContainerMaxBufferSize(size int) ContainerProcessOption

WithContainerMaxBufferSize sets the maximum batch size (default 10MB): output is delivered as soon as the buffer reaches it, without waiting for the interval.

func WithContainerMeter added in v0.4.0

func WithContainerMeter(meter metric.Meter) ContainerProcessOption

WithContainerMeter sets an OpenTelemetry meter for metrics collection for container processes

func WithContainerMount added in v0.4.0

func WithContainerMount(source, target string, readOnly bool) ContainerProcessOption

WithContainerMount adds a volume mount to the container

func WithContainerProgramStatus added in v0.6.0

func WithContainerProgramStatus() ContainerProcessOption

WithContainerProgramStatus enables parsing of OSC 7501 program status reports in the container output. Each report yields a ProgramStatus event, ordered exactly against OutputData. The report bytes still pass through unchanged in OutputData.

func WithContainerRuntime added in v0.4.0

func WithContainerRuntime(runtime string) ContainerProcessOption

WithContainerRuntime sets the container runtime ("docker" or "podman")

func WithContainerWorkingDir added in v0.4.0

func WithContainerWorkingDir(dir string) ContainerProcessOption

WithContainerWorkingDir sets the working directory for the container process

type ContainerRemove added in v0.4.0

type ContainerRemove struct {
	ContainerID string
}

ContainerRemove represents container cleanup

func (*ContainerRemove) String added in v0.4.0

func (c *ContainerRemove) String() string

func (*ContainerRemove) Type added in v0.4.0

func (c *ContainerRemove) Type() EventType

type Event

type Event struct {
	Timestamp time.Time
	Event     StreamEvent
}

func (Event) EventType

func (e Event) EventType() EventType

EventType returns the type of the event contained in this Event

func (Event) String

func (e Event) String() string

String returns a human-readable representation of the Event

type EventType

type EventType int

EventType defines the different kinds of events

const (
	ProcessStartEvent EventType = iota
	ProcessEndEvent
	ProcessErrorEvent
	HeartbeatEventType
	OutputEvent
	TerminalResizeEventType
	ContainerCreateEvent
	ContainerRemoveEvent
	ImagePullStartEvent
	ImagePullProgressEvent
	ImagePullCompleteEvent
	ProgramStatusEventType
)

func (EventType) String

func (e EventType) String() string

type HeartbeatEvent

type HeartbeatEvent struct {
	ProcessAlive bool
	ElapsedTime  time.Duration
}

HeartbeatEvent represents a keep-alive signal when no output is generated

func (*HeartbeatEvent) String

func (h *HeartbeatEvent) String() string

func (*HeartbeatEvent) Type

func (h *HeartbeatEvent) Type() EventType

type ImagePullComplete added in v0.4.0

type ImagePullComplete struct {
	Image  string
	Digest string
}

ImagePullComplete represents successful completion of an image pull

func (*ImagePullComplete) String added in v0.4.0

func (i *ImagePullComplete) String() string

func (*ImagePullComplete) Type added in v0.4.0

func (i *ImagePullComplete) Type() EventType

type ImagePullProgress added in v0.4.0

type ImagePullProgress struct {
	Image           string
	Status          string
	PercentComplete int
	BytesDownloaded int64
	BytesTotal      int64
}

ImagePullProgress represents progress during an image pull

func (*ImagePullProgress) String added in v0.4.0

func (i *ImagePullProgress) String() string

func (*ImagePullProgress) Type added in v0.4.0

func (i *ImagePullProgress) Type() EventType

type ImagePullStart added in v0.4.0

type ImagePullStart struct {
	Image string
}

ImagePullStart represents the beginning of an image pull operation

func (*ImagePullStart) String added in v0.4.0

func (i *ImagePullStart) String() string

func (*ImagePullStart) Type added in v0.4.0

func (i *ImagePullStart) Type() EventType

type LocalCancellor

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

LocalCancellor implements process cancellation for local processes.

Cancel signals the whole process group led by pid (kill(-pid)), so grandchildren spawned by the process are terminated with it. Processes started by this library are group leaders (Setpgid for pipes, Setsid for PTYs). If pid is not a group leader, Cancel falls back to signalling pid alone.

Limitation: PTY children that create their own job-control process groups (for example interactive shells) have descendants outside the group, which the group kill does not reach.

func NewLocalCancellor

func NewLocalCancellor(terminateTimeout time.Duration) *LocalCancellor

func (*LocalCancellor) Cancel

func (lc *LocalCancellor) Cancel(ctx context.Context, pid int) error

Cancel sends SIGTERM to the process group led by pid (or to pid alone if it is not a group leader), then SIGKILL if it has not exited by the terminate timeout or ctx is done.

type OutputData added in v0.3.0

type OutputData struct {
	Data []byte
	// Segments carries per-read timing for Data; may be nil for events not
	// produced by this library.
	Segments []OutputSegment
}

OutputData represents output data from the process (combined stdout/stderr)

func (*OutputData) String added in v0.3.0

func (o *OutputData) String() string

func (*OutputData) Type added in v0.3.0

func (o *OutputData) Type() EventType

type OutputSegment added in v0.5.0

type OutputSegment struct {
	Offset int
	Time   time.Time
}

OutputSegment marks where a write into the output buffer began and when it was read. Segment i covers Data[Offset_i:Offset_{i+1}] (the last runs to len(Data)).

type Process added in v0.3.0

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

Process represents a unified process that can run in either PTY or pipe mode

func NewProcess added in v0.3.0

func NewProcess(cmd string, args []string, opts ...ProcessOption) *Process

NewProcess creates a new unified process with functional options. Children run in their own process group (pipe: Setpgid, PTY: Setsid) and so do not receive terminal-generated signals; cancel the ExecuteAndStream context on SIGINT/SIGTERM (e.g. signal.NotifyContext) to stop them.

func (*Process) ExecuteAndStream added in v0.3.0

func (p *Process) ExecuteAndStream(ctx context.Context) iter.Seq2[Event, error]

ExecuteAndStream starts a process and returns an iterator over Event objects.

The child runs in its own process group (pipe mode: Setpgid; PTY mode: Setsid), so it does not receive terminal-generated signals such as Ctrl-C. Callers should cancel ctx on SIGINT/SIGTERM (e.g. signal.NotifyContext) so the Cancellor can stop the child and its descendants.

Breaking out of the loop or cancelling ctx stops the child via the Cancellor and waits for all goroutines to finish before the iterator returns.

func (*Process) GetStats added in v0.3.0

func (p *Process) GetStats() ProcessStatsSnapshot

GetStats returns a copy of the current process statistics

type ProcessEnd

type ProcessEnd struct {
	ExitCode int
	Duration time.Duration
	Success  bool
}

ProcessEnd represents the completion of process execution

func (*ProcessEnd) String

func (p *ProcessEnd) String() string

func (*ProcessEnd) Type

func (p *ProcessEnd) Type() EventType

type ProcessError

type ProcessError struct {
	Error   error
	Message string
}

ProcessError represents an error during process execution

func (*ProcessError) String

func (p *ProcessError) String() string

func (*ProcessError) Type

func (p *ProcessError) Type() EventType

type ProcessInfo added in v0.2.1

type ProcessInfo struct {
	Command string
	Args    []string
	PID     int
}

ProcessInfo contains process information for metrics attributes

type ProcessMode added in v0.3.0

type ProcessMode int

processConfig holds configuration options for processes ProcessMode defines whether to use PTY or pipe mode for process execution

const (
	PipeMode ProcessMode = iota
	PTYMode
)

func (ProcessMode) String added in v0.3.0

func (m ProcessMode) String() string

type ProcessOption

type ProcessOption func(*processConfig)

ProcessOption represents a functional option for configuring processes

func WithCancellor

func WithCancellor(cancellor Cancellor) ProcessOption

WithCancellor sets a custom cancellor for the process

func WithEnv

func WithEnv(env []string) ProcessOption

WithEnv sets environment variables as a slice of "KEY=value" strings

func WithEnvMap

func WithEnvMap(envMap map[string]string) ProcessOption

WithEnvMap sets environment variables from a map for convenience

func WithEnvVar

func WithEnvVar(key, value string) ProcessOption

WithEnvVar sets a single environment variable

func WithFlushInterval

func WithFlushInterval(interval time.Duration) ProcessOption

WithFlushInterval sets the output batch interval (default 1s): how often buffered output is delivered as an OutputData event. It bounds live delivery latency and event volume. It does not affect timing accuracy: each event's Segments record when output was read.

func WithHeartbeatInterval added in v0.5.1

func WithHeartbeatInterval(interval time.Duration) ProcessOption

WithHeartbeatInterval sets the heartbeat interval (default 1s). On each interval tick, a HeartbeatEvent is emitted if no output was delivered or buffered since the previous tick, so the first heartbeat follows one to two intervals of silence and repeats every interval. Independent of the batch interval.

func WithMaxBufferSize

func WithMaxBufferSize(size int) ProcessOption

WithMaxBufferSize sets the maximum batch size (default 10MB): output is delivered as soon as the buffer reaches it, without waiting for the interval.

func WithMeter added in v0.2.1

func WithMeter(meter metric.Meter) ProcessOption

WithMeter sets an OpenTelemetry meter for metrics collection

func WithPTYMode added in v0.3.0

func WithPTYMode() ProcessOption

WithPTYMode sets the process to use a pseudo-terminal

func WithPTYSize

func WithPTYSize(size *pty.Winsize) ProcessOption

WithPTYSize sets a custom terminal size for PTY processes

func WithPipeMode added in v0.3.0

func WithPipeMode() ProcessOption

WithPipeMode sets the process to use standard pipes (stdout/stderr)

func WithProgramStatus added in v0.6.0

func WithProgramStatus() ProcessOption

WithProgramStatus enables parsing of OSC 7501 program status reports in the child output. Each report yields a ProgramStatus event, ordered exactly against OutputData. The report bytes still pass through unchanged in OutputData.

func WithWorkingDir added in v0.3.2

func WithWorkingDir(dir string) ProcessOption

WithWorkingDir sets the working directory for the process

type ProcessStart

type ProcessStart struct {
	PID     int
	Command string
	Args    []string
}

ProcessStart represents the beginning of process execution

func (*ProcessStart) String

func (p *ProcessStart) String() string

func (*ProcessStart) Type

func (p *ProcessStart) Type() EventType

type ProcessStartError

type ProcessStartError struct {
	Cmd string
	Err error
}

Error types for different process failure scenarios

func (ProcessStartError) Error

func (e ProcessStartError) Error() string

type ProcessStats added in v0.3.0

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

ProcessStats manages comprehensive metrics during process execution

func NewProcessStats added in v0.3.0

func NewProcessStats(meter metric.Meter, processInfo ProcessInfo) (*ProcessStats, error)

NewProcessStats creates a new ProcessStats instance with OpenTelemetry metrics

func (*ProcessStats) CloseStatus added in v0.6.5

func (s *ProcessStats) CloseStatus(ctx context.Context, at time.Time)

CloseStatus stops the program status timer at the given time; idempotent.

func (*ProcessStats) GetSnapshot added in v0.3.0

func (s *ProcessStats) GetSnapshot() ProcessStatsSnapshot

GetSnapshot returns a thread-safe snapshot of the current statistics

func (*ProcessStats) ObserveStatus added in v0.6.5

func (s *ProcessStats) ObserveStatus(ctx context.Context, ev Event)

ObserveStatus feeds an event to the program status timer.

func (*ProcessStats) RecordError added in v0.3.0

func (s *ProcessStats) RecordError(ctx context.Context, eventType string)

RecordError increments the error count

func (*ProcessStats) RecordEvent added in v0.3.0

func (s *ProcessStats) RecordEvent(ctx context.Context, eventType string)

RecordEvent records a general event

func (*ProcessStats) RecordOutput added in v0.3.0

func (s *ProcessStats) RecordOutput(ctx context.Context, dataSize int64)

RecordOutput records output data and metrics

func (*ProcessStats) SetExitCode added in v0.3.0

func (s *ProcessStats) SetExitCode(code int)

SetExitCode sets the process exit code

func (*ProcessStats) Start added in v0.3.0

func (s *ProcessStats) Start(ctx context.Context)

Start initializes the stats and records process start

func (*ProcessStats) Stop added in v0.3.0

func (s *ProcessStats) Stop(ctx context.Context)

Stop finalizes the stats and records process stop

type ProcessStatsSnapshot added in v0.3.0

type ProcessStatsSnapshot struct {
	// Basic execution stats
	StartTime  time.Time
	EventCount int
	ErrorCount int
	ExitCode   *int
	Duration   time.Duration

	// StatusTime is wall-clock time per program status state.
	StatusTime StatusDurations
}

ProcessStatsSnapshot represents a point-in-time view of process statistics

type ProgramStatus added in v0.6.0

type ProgramStatus struct {
	State    string // e.g. working, blocked, done
	ID       string
	Kind     string
	App      string
	Title    string // decoded
	Msg      string // decoded
	Progress int    // 0-100, or -1 if indeterminate
}

ProgramStatus is a typed OSC 7501 program status report found in the child output. It is yielded after the OutputData holding all preceding bytes and before any following bytes. Timestamp is when the report was read.

func (*ProgramStatus) String added in v0.6.0

func (p *ProgramStatus) String() string

func (*ProgramStatus) Type added in v0.6.0

func (p *ProgramStatus) Type() EventType

type StatusDurations added in v0.6.5

type StatusDurations struct{ Working, Blocked, Idle time.Duration }

StatusDurations is wall-clock time per program status state.

type StatusTimer added in v0.6.5

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

StatusTimer accumulates StatusDurations from an event stream: at each instant the run counts once under its most urgent live state (blocked > working > idle). The zero value is ready to use; it is not safe for concurrent use.

func (*StatusTimer) Close added in v0.6.5

func (t *StatusTimer) Close(at time.Time)

Close stops all records counting at the given time; later reports are ignored. It is idempotent.

func (*StatusTimer) Observe added in v0.6.5

func (t *StatusTimer) Observe(ev Event)

Observe applies a ProgramStatus at its event timestamp. ProcessEnd and ProcessError close the timer; other events are ignored.

func (*StatusTimer) Totals added in v0.6.5

func (t *StatusTimer) Totals() StatusDurations

Totals returns the time accrued so far.

type StreamEvent

type StreamEvent interface {
	Type() EventType
	String() string
}

StreamEvent represents different types of events that can occur during process execution

type TermInfo

type TermInfo struct {
	Cols    int        `json:"cols"`
	Rows    int        `json:"rows"`
	Type    string     `json:"type,omitempty"`
	Version string     `json:"version,omitempty"`
	Theme   *TermTheme `json:"theme,omitempty"`
}

TermInfo represents terminal dimensions for asciicast header

type TermTheme added in v0.5.0

type TermTheme struct {
	Fg      string `json:"fg"`
	Bg      string `json:"bg"`
	Palette string `json:"palette"`
}

TermTheme describes terminal colours. Palette is a colon-separated list of hex colours, as asciinema writes it.

type TerminalResizeEvent

type TerminalResizeEvent struct {
	Rows uint16
	Cols uint16
	X    uint16 // Width in pixels
	Y    uint16 // Height in pixels
}

TerminalResizeEvent represents a terminal window size change

func (*TerminalResizeEvent) String

func (t *TerminalResizeEvent) String() string

func (*TerminalResizeEvent) Type

func (t *TerminalResizeEvent) Type() EventType

Directories

Path Synopsis
cmd
runner command
Package main provides a pretty slog handler for human-readable colored terminal output.
Package main provides a pretty slog handler for human-readable colored terminal output.
tester command
example
asciicast command
buffering command
burst command
container command
logging command
programstatus command
Command programstatus shows both sides of OSC 7501 program status: a child that reports its status with github.com/wolfeidau/osc7501, and a parent that receives the reports as ProgramStatus events and stops the child when it blocks on a prompt.
Command programstatus shows both sides of OSC 7501 program status: a child that reports its status with github.com/wolfeidau/osc7501, and a parent that receives the reports as ProgramStatus events and stops the child when it blocks on a prompt.
pty command
simple command
stream command

Jump to

Keyboard shortcuts

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