session

package
v0.4.0 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: 12 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package session manages protocol-neutral shared stream sessions.

Index

Constants

View Source
const (
	// DefaultReceiveBufferSize is the retained stream-output capacity for a
	// newly created Session. The buffer overwrites its oldest bytes when full.
	DefaultReceiveBufferSize = 16 * 1024 * 1024
	// DefaultAIReadLimit is the initial recent-output limit for AI consumers.
	// Callers may request a larger bounded chunk when their task requires it.
	DefaultAIReadLimit = 64 * 1024
	// DefaultActivityBufferCapacity is the fixed number of recent operations a
	// Session retains for independent CLI and Agent activity consumers.
	DefaultActivityBufferCapacity = 1024
	// DefaultActivityBufferByteCapacity bounds the combined payload bytes retained
	// by recent Session activity independently from the event-count capacity.
	DefaultActivityBufferByteCapacity = 16 * 1024 * 1024
	// DefaultEventBufferCapacity is the fixed number of structured lifecycle and
	// operation events a Session retains for independent observers.
	DefaultEventBufferCapacity = 1024
)

Variables

View Source
var (
	// ErrInvalidActivityBufferCapacity is returned when an activity buffer has no capacity.
	ErrInvalidActivityBufferCapacity = errors.New("activity buffer capacity must be positive")
	// ErrInvalidActivityBufferByteCapacity is returned when an activity buffer has no byte capacity.
	ErrInvalidActivityBufferByteCapacity = errors.New("activity buffer byte capacity must be positive")
	// ErrInvalidActivityReadLimit is returned when an activity read does not request events.
	ErrInvalidActivityReadLimit = errors.New("activity read limit must be positive")
)
View Source
var (
	// ErrInvalidEventBufferCapacity is returned when an event buffer has no capacity.
	ErrInvalidEventBufferCapacity = errors.New("event buffer capacity must be positive")
	// ErrInvalidEventReadLimit is returned when an event read does not request events.
	ErrInvalidEventReadLimit = errors.New("event read limit must be positive")
)
View Source
var (
	// ErrInvalidBufferCapacity is returned when a receive buffer has no capacity.
	ErrInvalidBufferCapacity = errors.New("receive buffer capacity must be positive")
	// ErrInvalidReadLimit is returned when a chunk read does not request bytes.
	ErrInvalidReadLimit = errors.New("output read limit must be positive")
)
View Source
var (
	// ErrNotOpen is returned when stream I/O is requested before a session opens
	// or after it has closed.
	ErrNotOpen = errors.New("session is not open")
	// ErrInvalidID is returned when creating a session without an ID.
	ErrInvalidID = errors.New("session ID must not be empty")
	// ErrNilTransport is returned when creating a session without a transport.
	ErrNilTransport = errors.New("session transport must not be nil")
	// ErrNilChannel is returned when a Transport reports a successful connection
	// without transferring an established Channel.
	ErrNilChannel = errors.New("session transport returned a nil channel")
	// ErrInvalidActor is returned when a write request has no recognized source.
	ErrInvalidActor = errors.New("session write actor is invalid")
)
View Source
var ErrDuplicateSession = errors.New("session ID is already registered")

ErrDuplicateSession is returned when registering an ID that Manager owns.

View Source
var ErrManagerClosed = errors.New("session manager is closed")

ErrManagerClosed is returned when a caller tries to add a Session after Manager shutdown has started.

Functions

This section is empty.

Types

type ActivityChunk

type ActivityChunk struct {
	// Events contains no more events than the caller requested.
	Events []SessionEvent
	// Next is the cursor the caller supplies to its next ReadActivity call.
	Next ActivityCursor
	// Dropped reports that the requested cursor was older than retained activity.
	Dropped bool
}

ActivityChunk is a bounded activity-event snapshot for one consumer.

type ActivityCursor

type ActivityCursor uint64

ActivityCursor identifies the next activity event a consumer expects.

Cursors are monotonically increasing for one Session. They are independent from OutputCursor because activity metadata and stream output have separate retention, overflow, and consumer lifecycles.

type Actor

type Actor string

Actor identifies the ChannelTerm component that initiated a Channel write.

Actor is internal metadata only. Core never forwards it to Channel, so the connected endpoint receives exactly the bytes supplied in WriteRequest.Data.

const (
	// ActorUser identifies input initiated by a human using a ChannelTerm client.
	ActorUser Actor = "user"
	// ActorAgent identifies input initiated through an Agent-facing integration.
	ActorAgent Actor = "agent"
	// ActorSystem identifies input initiated by ChannelTerm itself.
	ActorSystem Actor = "system"
)

func (Actor) Valid

func (actor Actor) Valid() bool

Valid reports whether actor is one of ChannelTerm's defined write sources.

type Core

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

Core is the default Session implementation.

Core serializes lifecycle transitions with mu. Its dedicated reader goroutine appends output to receive, allowing slow clients to wait without blocking Channel.Read.

func New

func New(id string, source transport.Transport, options ...Option) (*Core, error)

New creates a Core in StateNew with a fixed-capacity receive buffer.

id becomes the stable Session identifier and Manager registration key. source is used once by Connect to establish the Channel that Core owns until Close. options may change the default receive-output, activity-event count, activity payload byte, or structured event capacity.

func (*Core) Close

func (s *Core) Close() error

Close releases the underlying Channel, output reader, and receive buffer.

Close first wakes output consumers, then closes Channel to unblock its reader, waits for that goroutine to exit, and finally releases the retained buffer memory. Sequential calls after StateClosed return the original close result so cleanup errors remain observable.

func (*Core) Connect

func (s *Core) Connect(ctx context.Context) error

Connect asks the Transport to establish a Channel and starts its output reader.

ctx controls the connection attempt. Core checks ctx before calling Transport.Connect and passes it to Transport so cancellation and deadlines can interrupt protocol-specific connection work. A pre-cancelled ctx does not call Transport and moves Core directly to StateFailed.

Connect may run only once, while Core is in StateNew. It records StateFailed when ctx is cancelled or Transport returns an error, and otherwise moves to StateOpen before starting the dedicated reader goroutine. Connect must not run concurrently with Close because the caller owns the connection lifecycle.

func (*Core) HasPendingInput added in v0.3.0

func (s *Core) HasPendingInput() bool

HasPendingInput reports conservatively tracked non-system input since the last submit/cancel/clear byte. Unlike activity history, this summary cannot be overwritten. It does not prove that the remote program is an idle shell. System protocol writes deliberately leave the summary unchanged.

func (*Core) ID

func (s *Core) ID() string

ID returns the stable identifier supplied to New.

func (*Core) PublishEvent

func (s *Core) PublishEvent(event Event)

PublishEvent records structured Session metadata independently from raw terminal output and activity. It never waits for an observer.

func (*Core) ReadActivity

func (s *Core) ReadActivity(ctx context.Context, next ActivityCursor, maxEvents int) (ActivityChunk, error)

ReadActivity waits for activity events at next and returns at most maxEvents.

The Activity Event Buffer is separate from stream output, so reading it cannot consume Channel bytes or affect any OutputCursor consumer.

func (*Core) ReadEvents

func (s *Core) ReadEvents(ctx context.Context, next EventCursor, maxEvents int) (EventChunk, error)

ReadEvents waits for structured Session events without reading terminal output or affecting any other observer's event cursor.

func (*Core) ReadOutput

func (s *Core) ReadOutput(ctx context.Context, next OutputCursor, maxBytes int) (OutputChunk, error)

ReadOutput waits for stream output at next and returns at most maxBytes.

next is the cursor returned by the preceding OutputChunk. ctx stops the wait if no output is available. A slow consumer receives Dropped=true and resumes from the oldest retained byte after the Ring Buffer overwrites its requested cursor. ReadOutput does not copy more than maxBytes into the returned chunk.

func (*Core) ReadRecent

func (s *Core) ReadRecent(maxBytes int) (OutputChunk, error)

ReadRecent returns at most maxBytes from the newest retained stream output.

maxBytes bounds allocation and prevents consumers from accidentally copying the complete receive buffer. AI callers should use DefaultAIReadLimit unless their requested diagnostic task needs more context.

func (*Core) ReadRecentActivity

func (s *Core) ReadRecentActivity(maxEvents int) (ActivityChunk, error)

ReadRecentActivity returns a bounded snapshot of recent Session operations.

The returned event payloads are copies and therefore remain valid after this call returns even while future writes overwrite the bounded event buffer.

func (*Core) ReadRecentEvents

func (s *Core) ReadRecentEvents(maxEvents int) (EventChunk, error)

ReadRecentEvents returns a bounded snapshot of the newest Session events.

func (*Core) Resize

func (s *Core) Resize(cols, rows uint16) error

Resize forwards a terminal dimension change when the Channel supports it.

cols is the terminal width in character columns and rows is the terminal height in character rows. Resize returns ErrNotOpen before Connect or after Close so an unavailable Channel never receives a stale terminal-size request.

func (*Core) State

func (s *Core) State() SessionState

State returns a synchronized snapshot of the current Core lifecycle stage.

func (*Core) Write

func (s *Core) Write(request WriteRequest) (int, error)

Write sends request data as one contiguous Channel write sequence when Core is open.

request.Data is caller-owned input and is never retained by Core. request.Actor is validated and recorded in the independent Activity Event Buffer, but Core deliberately passes only request.Data to Channel. Write serializes the complete short-write retry loop so concurrent callers cannot interleave their payload bytes. Close does not acquire writeMu: closing the Channel instead releases an in-flight write, avoiding a lifecycle lock cycle. Write returns ErrNotOpen rather than invoking Channel before Connect or after Close.

type Event

type Event struct {
	ID        uint64         `json:"id"`
	Timestamp time.Time      `json:"timestamp"`
	SessionID string         `json:"session_id"`
	Type      EventType      `json:"type"`
	Actor     string         `json:"actor"`
	Metadata  map[string]any `json:"metadata,omitempty"`
}

Event is structured Session state that is deliberately separate from raw terminal bytes and write activity.

ID is assigned by the owning Session and is monotonic within that Session. SessionID is also assigned by the owning Session. Metadata contains only JSON-compatible presentation data; lease owner capabilities and terminal payload bytes must never be published there.

type EventChunk

type EventChunk struct {
	// Events contains no more events than the caller requested.
	Events []Event
	// Next is the cursor the caller supplies to its next ReadEvents call.
	Next EventCursor
	// Dropped reports that the requested cursor was older than retained events.
	Dropped bool
}

EventChunk is a bounded event snapshot for one observer.

type EventCursor

type EventCursor uint64

EventCursor identifies the next Session event a consumer expects.

Cursors are monotonically increasing for one Session and are independent from output and activity cursors. Consumers keep their own cursor, so one slow observer never delays or consumes events for another observer.

type EventType

type EventType string

EventType identifies a lifecycle or operation transition on a Session.

The defined values are intentionally transport-neutral. Additional values may be added without changing the event stream contract.

const (
	// EventOperationState reports application operation readiness and completion.
	// Metadata contains operation IDs and states, never payloads or capabilities.
	EventOperationState EventType = "OPERATION_STATE"
	// EventDebugState records a debug lifecycle transition without owner secrets.
	EventDebugState EventType = "DEBUG_STATE"
	// EventDebugClientReport carries explicitly reported external-debugger text.
	// It is caller-supplied observation, not raw terminal data or verified execution.
	EventDebugClientReport EventType = "DEBUG_CLIENT_REPORT"
	// EventSessionCreated records successful Manager registration of a Session.
	EventSessionCreated EventType = "SESSION_CREATED"
	// EventSessionAttached records one client attachment to a Session.
	EventSessionAttached EventType = "SESSION_ATTACHED"
	// EventSessionDetached records one client detachment from a Session.
	EventSessionDetached EventType = "SESSION_DETACHED"
	// EventLeaseAcquired records an exclusive writer lease becoming active.
	EventLeaseAcquired EventType = "LEASE_ACQUIRED"
	// EventLeaseReleased records an exclusive writer lease ending.
	EventLeaseReleased EventType = "LEASE_RELEASED"
	// EventFileTransferStarted records the beginning of a file transfer.
	EventFileTransferStarted EventType = "FILE_TRANSFER_STARTED"
	// EventFileTransferProgress records confirmed file-transfer progress.
	EventFileTransferProgress EventType = "FILE_TRANSFER_PROGRESS"
	// EventFileTransferCompleted records a verified successful file transfer.
	EventFileTransferCompleted EventType = "FILE_TRANSFER_COMPLETED"
	// EventFileTransferCancelled records a user-confirmed file transfer cancellation.
	EventFileTransferCancelled EventType = "FILE_TRANSFER_CANCELLED"
	// EventFileTransferFailed records a failed file transfer.
	EventFileTransferFailed EventType = "FILE_TRANSFER_FAILED"
	// EventTerminalCommandStarted records an Agent shell command entering its
	// isolated execution scope. Metadata includes the original display command
	// and the raw-output cursor from which bootstrap presentation is hidden.
	EventTerminalCommandStarted EventType = "TERMINAL_COMMAND_STARTED"
	// EventTerminalCommandOutputStarted records the first raw-output cursor that
	// belongs to the command rather than its hidden shell bootstrap.
	EventTerminalCommandOutputStarted EventType = "TERMINAL_COMMAND_OUTPUT_STARTED"
	// EventTerminalCommandCompleted records an isolated shell command exit code.
	EventTerminalCommandCompleted EventType = "TERMINAL_COMMAND_COMPLETED"
	// EventTerminalCommandFailed records setup, cancellation, or recovery failure
	// before a normal isolated shell command completion.
	EventTerminalCommandFailed EventType = "TERMINAL_COMMAND_FAILED"
)

type Manager

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

Manager owns the set of active sessions.

Manager protects registration and lookup with a read-write lock. It does not hold that lock while closing sessions, because Close can block on Transport resource cleanup.

func NewManager

func NewManager() *Manager

NewManager creates an empty Manager ready to register Sessions.

func (*Manager) Close

func (m *Manager) Close() error

Close closes every registered Session and removes it from Manager.

Close prevents new registrations, waits for in-progress connection attempts, then snapshots the final registrations before cleanup. It does not hold the Manager lock while a Session blocks during resource release. Concurrent and repeated calls are safe; only the first caller can take owned Sessions.

func (*Manager) Get

func (m *Manager) Get(identifier string) (Session, bool)

Get returns the Session registered under identifier and whether it exists.

identifier can be the opaque ID supplied when the Session was created or the Manager-assigned short Reference. The returned Session remains owned by Manager and must not be closed by a lookup caller.

func (*Manager) GetOrCreate

func (m *Manager) GetOrCreate(ctx context.Context, metadata SessionMetadata, create func() (Session, error)) (SessionInfo, bool, error)

GetOrCreate returns the active Session for metadata's transport and endpoint or creates exactly one new Session through create.

create runs without Manager's lock because opening a Transport can block. Its caller retains ownership of a failed candidate, while Manager takes ownership only after successful registration. Concurrent callers for the same endpoint wait for the first attempt and receive the same successful Session or error. Failed and closed Sessions do not prevent a later retry.

func (*Manager) List

func (m *Manager) List() []Session

List returns a snapshot of every currently registered Session.

The returned slice is independent from Manager's internal map, but each Session remains owned by Manager. Callers must not close a listed Session; use Remove when ownership needs to transfer for explicit cleanup.

func (*Manager) ListInfo

func (m *Manager) ListInfo() []SessionInfo

ListInfo returns a snapshot of every currently registered Session and its fixed metadata.

The returned slice and metadata values are independent from Manager's map. Session State is read after the registration snapshot is copied so Manager never holds its lock while calling into a Session implementation.

func (*Manager) Reference

func (m *Manager) Reference(identifier string) (string, bool)

Reference returns the short reference assigned to identifier.

identifier can be either a Session ID or a short Reference. The returned reference is process-local and is not a persistent device identity.

func (*Manager) Register

func (m *Manager) Register(s Session) error

Register adds s under its ID.

s remains owned by Manager until Remove or Close returns. Register returns ErrDuplicateSession when another Session already has the same ID.

Register rejects duplicate IDs so callers cannot silently replace a live Session and lose responsibility for its resources.

func (*Manager) RegisterWithMetadata

func (m *Manager) RegisterWithMetadata(s Session, metadata SessionMetadata) error

RegisterWithMetadata adds s and its fixed display metadata under its ID.

Metadata remains owned by Manager until Remove or Close returns. Manager assigns its Reference from Metadata.Transport, so callers must not rely on a caller-supplied Reference value. Duplicate labels and endpoints are permitted, while duplicate Session IDs return ErrDuplicateSession.

func (*Manager) Remove

func (m *Manager) Remove(identifier string) (Session, bool)

Remove unregisters and returns the Session under identifier without closing it.

identifier can be either the opaque Session ID or its short Reference. The caller becomes responsible for closing a successfully removed Session.

type Operation

type Operation string

Operation identifies the action represented by a SessionEvent.

const (
	// OperationWrite records bytes successfully passed to a Session Channel.
	OperationWrite Operation = "write"
)

type Option

type Option func(*config) error

Option configures a Core created by New.

func WithActivityBufferByteCapacity

func WithActivityBufferByteCapacity(bytes int) Option

WithActivityBufferByteCapacity sets the total number of write payload bytes retained by a Session's activity buffer.

bytes must be positive. The buffer evicts the oldest complete events before exceeding the limit; an individual larger event is not retained.

func WithActivityBufferCapacity

func WithActivityBufferCapacity(events int) Option

WithActivityBufferCapacity sets the fixed number of events retained by a Session.

events must be positive. The Activity Event Buffer overwrites the oldest event when full, so activity consumers never impose backpressure on Session.Write.

func WithEventBufferCapacity

func WithEventBufferCapacity(events int) Option

WithEventBufferCapacity sets the fixed number of structured events retained by a Session. When full, the oldest events are overwritten rather than blocking the Session reader, writer, or event publisher.

func WithReceiveBufferCapacity

func WithReceiveBufferCapacity(bytes int) Option

WithReceiveBufferCapacity sets the fixed number of output bytes retained by a Session.

bytes must be positive. When the buffer becomes full, incoming output overwrites the oldest bytes rather than blocking the Channel reader.

type OutputChunk

type OutputChunk struct {
	// Data contains no more bytes than the read limit requested by the caller.
	Data []byte
	// Next is the cursor the caller supplies to its next ReadOutput call.
	Next OutputCursor
	// Dropped reports that the requested cursor was older than retained output.
	Dropped bool
}

OutputChunk is a bounded copy of stream output retained by a Session.

type OutputCursor

type OutputCursor uint64

OutputCursor identifies the next byte a consumer expects from a Session.

Cursors are monotonically increasing for one Session. They are not offsets into the current Ring Buffer because old bytes can be overwritten.

type Session

type Session interface {
	// ID returns the stable caller-provided identifier for this Session.
	ID() string
	// State returns a snapshot of the current lifecycle stage.
	State() SessionState
	// ReadOutput waits for output at next and returns at most maxBytes.
	//
	// next is the cursor returned by the preceding OutputChunk. ctx cancels the
	// wait for new output. Dropped is true when next has been overwritten.
	ReadOutput(ctx context.Context, next OutputCursor, maxBytes int) (OutputChunk, error)
	// ReadRecent returns at most maxBytes from the newest retained output.
	//
	// AI consumers should begin with DefaultAIReadLimit instead of the complete
	// receive buffer. maxBytes can grow for a specific task but remains bounded.
	ReadRecent(maxBytes int) (OutputChunk, error)
	// ReadActivity waits for activity events at next and returns at most maxEvents.
	//
	// ctx cancels the wait for future events. Dropped is true when next has been
	// overwritten by the bounded Activity Event Buffer.
	ReadActivity(ctx context.Context, next ActivityCursor, maxEvents int) (ActivityChunk, error)
	// ReadRecentActivity returns at most maxEvents from the newest retained activity.
	//
	// Its Next cursor always represents the current activity tail, so consumers
	// can use it to begin waiting without replaying older events.
	ReadRecentActivity(maxEvents int) (ActivityChunk, error)
	// ReadEvents waits for structured Session events at next and returns at most
	// maxEvents. Event cursors are independent from output and activity cursors.
	ReadEvents(ctx context.Context, next EventCursor, maxEvents int) (EventChunk, error)
	// ReadRecentEvents returns at most maxEvents from the newest retained events.
	// Its Next cursor always represents the current event tail.
	ReadRecentEvents(maxEvents int) (EventChunk, error)
	// PublishEvent appends structured metadata without changing terminal output
	// or waiting for observers. Session assigns ID, SessionID, and a timestamp
	// when the caller leaves Timestamp empty.
	PublishEvent(Event)
	// Write sends request.Data when State is StateOpen.
	//
	// request.Actor must be a recognized Actor. It is internal metadata only and
	// is never encoded into the Channel byte stream.
	Write(request WriteRequest) (int, error)
	// Resize requests a terminal size change when State is StateOpen.
	//
	// cols is the terminal width in character columns and rows is its height in
	// character rows.
	Resize(cols, rows uint16) error
	// Close releases Session resources and is safe to call repeatedly.
	Close() error
}

Session represents shared access to a protocol-neutral stream Channel.

Session owns the continuous Channel reader and keeps only the newest output in a fixed-capacity Ring Buffer. UI and AI consumers use cursor-based chunk reads; they never access Channel.Read or the buffer implementation directly.

type SessionEvent

type SessionEvent struct {
	Timestamp time.Time
	Actor     Actor
	Operation Operation
	Data      []byte
}

SessionEvent records a completed stream operation and its internal source.

Timestamp is the local time at which Core began executing the operation. Data is a copied snapshot of the bytes actually written; it may be a prefix of the original request when a Channel reports a partial write followed by an error.

type SessionInfo

type SessionInfo struct {
	ID       string
	Metadata SessionMetadata
	State    SessionState
}

SessionInfo is a point-in-time view of one Manager-owned Session.

Metadata is fixed at registration. State is read when ListInfo creates the snapshot, so it can change immediately afterwards as the Session lifecycle proceeds.

type SessionMetadata

type SessionMetadata struct {
	Transport string
	Endpoint  string
	Label     string
	Reference string
}

SessionMetadata describes fixed, display-oriented information for a Session.

Manager records Metadata when the Session is registered. Reference is a short, transport-prefixed identifier assigned by Manager and accepted as an alternative to the opaque Session ID. It remains valid only while Manager owns the Session and is never reused during the Manager lifetime.

type SessionState

type SessionState uint8

SessionState describes the lifecycle stage of a Session.

const (
	// StateNew indicates that the Session has a Transport but no Channel yet.
	StateNew SessionState = iota
	// StateConnecting indicates that Connect is establishing a Channel.
	StateConnecting
	// StateOpen indicates that stream I/O can be forwarded to Channel.
	StateOpen
	// StateClosing indicates that Close has started and I/O is no longer allowed.
	StateClosing
	// StateClosed indicates that Close has finished and cannot run again.
	StateClosed
	// StateFailed indicates that Connect or the Channel reader has failed.
	StateFailed
)

func (SessionState) String

func (s SessionState) String() string

String returns the stable lowercase form of a SessionState for diagnostics.

type WriteRequest

type WriteRequest struct {
	Actor Actor
	Data  []byte
}

WriteRequest contains one stream payload together with its operation source.

Data remains owned by the caller and is not retained after Write returns. Actor describes the operation source recorded by Session activity; it does not alter the bytes passed to the underlying Channel.

Jump to

Keyboard shortcuts

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