terminal

package
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: MIT Imports: 35 Imported by: 0

Documentation

Overview

Package terminal owns resident terminal processes, their byte streams, and shared attachments.

Contracts live in contracts.go; registry and lifecycle in manager.go and session.go; output aggregation in coalescer.go; transport filtering in osc_filter.go; audit admission in audit_gate.go; screen state in vt/; and OS process handling in pty/.

Index

Constants

View Source
const (
	ModePTY  Mode = "pty"
	ModePipe Mode = "pipe"

	SignalINT  Signal = "INT"
	SignalTERM Signal = "TERM"
	SignalKILL Signal = "KILL"
	SignalHUP  Signal = "HUP"

	ActorKindHuman  ActorKind = "human"
	ActorKindAgent  ActorKind = "agent"
	ActorKindSystem ActorKind = "system"
)
View Source
const (
	DecimalUint64Pattern    = `` /* 419-byte string literal not displayed */
	DecimalUint64MaxLength  = uint64(20)
	DecimalUint64JSONSchema = `{"type":"string","pattern":"` + DecimalUint64Pattern + `","maxLength":20}`
)
View Source
const MaximumOutputTailBytes = 16 * 1024
View Source
const OperatorActorID = "operator"

OperatorActorID is the stable human identity used across transports.

Variables

View Source
var (
	ErrNotFound                = errors.New("terminal not found")
	ErrRequiresWorkspace       = errors.New("terminal requires workspace")
	ErrGenerationFenced        = errors.New("terminal generation fenced")
	ErrWriteAttachmentRequired = errors.New("terminal write attachment required")
	ErrNotInteractive          = errors.New("terminal not interactive")
	ErrApprovalRequired        = errors.New("terminal approval required")
	ErrPolicyDenied            = errors.New("terminal command denied by policy")
	ErrInputNotFound           = errors.New("terminal input request not found")
	ErrInputAnswered           = errors.New("terminal input request already answered")
	ErrInputSuperseded         = errors.New("terminal input request superseded")
	ErrInputResolved           = errors.New("terminal input request resolved without an answer")
	ErrInputResolving          = errors.New("terminal input request resolution in progress")
	ErrInputLimit              = errors.New("terminal input request limit reached")
	ErrInputRequiresHidden     = errors.New("terminal redacted input requires hidden input")
	ErrWaitTimeout             = errors.New("terminal wait timeout")
	ErrExited                  = errors.New("terminal exited")
	ErrExpired                 = errors.New("terminal expired")
	ErrLimitReached            = errors.New("terminal limit reached")
	ErrSubscriberLimit         = errors.New("terminal subscriber limit reached")
	ErrSlowConsumer            = errors.New("terminal subscriber is a slow consumer")
	ErrInvalidCwd              = errors.New("terminal invalid cwd")
	ErrInteractive             = errors.New("terminal interactive unavailable")
	ErrApprovalRejected        = errors.New("terminal approval rejected")
	ErrRecording               = errors.New("terminal recording unavailable")
	ErrJournalUnavailable      = errors.New("terminal journal unavailable")
	ErrShuttingDown            = errors.New("terminal manager shutting down")
	ErrUnsupported             = errors.New("terminal operation unsupported")
	ErrTicketInvalid           = errors.New("terminal attach ticket invalid")
	ErrTicketExpired           = errors.New("terminal attach ticket expired")
	ErrRunIdentityIncomplete   = errors.New("terminal agent run identity incomplete")
	ErrServiceUnavailable      = errors.New("terminal service unavailable")
)

Functions

func ErrorCodeValues

func ErrorCodeValues() []string

func IsErrorCode

func IsErrorCode(code ErrorCode) bool

func JournalWorkspaceID

func JournalWorkspaceID(workspaceID, profileID string) string

JournalWorkspaceID separates User journals without registering a project.

func RecordingAvailable

func RecordingAvailable(capabilities Capabilities) bool

RecordingAvailable derives recording support from interactive availability.

func RenderOutputSegment

func RenderOutputSegment(segment OutputSegment) string

func RenderOutputSegments

func RenderOutputSegments(segments []OutputSegment) string

func SanitizeTitle

func SanitizeTitle(input string) string

func ValidateExecYieldDuration

func ValidateExecYieldDuration(duration time.Duration) error

ValidateExecYieldDuration enforces the public terminal exec yield range.

Types

type Actor

type Actor struct {
	Kind       ActorKind `json:"kind"`
	ID         string    `json:"id"`
	ProfileID  string    `json:"profile_id"`
	SessionID  string    `json:"session_id,omitempty"`
	RunID      string    `json:"run_id,omitempty"`
	Generation int64     `json:"generation,omitzero"`
}

type ActorKind

type ActorKind string

type ArgvPattern

type ArgvPattern []string

ArgvPattern is one administrator-approved command shape. A "*" argument matches one argv element; the executable is always matched by base name.

type AttachOptions

type AttachOptions struct {
	Mode     string
	Flow     string
	AfterSeq uint64
	Cols     uint16
	Rows     uint16
	Actor    Actor
}

type AttachTicket

type AttachTicket struct {
	Token     string
	Binding   AttachTicketBinding
	Actor     Actor
	ExpiresAt time.Time
}

AttachTicket is a short-lived, single-use grant minted by the terminal domain.

type AttachTicketBinding

type AttachTicketBinding struct {
	WorkspaceID string
	ProfileID   string
	TerminalID  ID
	Mode        string
}

AttachTicketBinding is the complete immutable scope of one attach grant.

type Capabilities

type Capabilities struct {
	Interactive bool `json:"interactive"`
}

type CommandClassification

type CommandClassification struct {
	Verdict CommandVerdict
	Reason  string
	Digest  string
}

CommandClassification is the deterministic result of classifying parsed argv.

func ClassifyArgv

func ClassifyArgv(argv []string, allowlist []ArgvPattern, denyLists ...[]ArgvPattern) CommandClassification

ClassifyArgv classifies parsed argv without performing an approval or reading state.

type CommandRow

type CommandRow struct {
	ID          string          `json:"command_id"`
	TerminalID  *ID             `json:"terminal_id"`
	ProfileID   string          `json:"profile_id"`
	ProfileName string          `json:"profile_name"`
	Actor       Actor           `json:"actor"`
	Command     string          `json:"command"`
	ArgvDigest  *string         `json:"argv_digest,omitzero"`
	Cwd         string          `json:"cwd"`
	StartedAt   time.Time       `json:"started_at"`
	DurationMs  *int64          `json:"duration_ms"`
	ExitCode    *int            `json:"exit_code"`
	ExitSignal  *string         `json:"signal"`
	ExitCause   string          `json:"exit_cause"`
	DetectedBy  string          `json:"detected_by"`
	Approval    string          `json:"approval"`
	OutputBytes int64           `json:"output_bytes"`
	Truncated   bool            `json:"truncated"`
	RecordingID *string         `json:"recording,omitzero"`
	OutputTail  []OutputSegment `json:"output_tail"`
}

type CommandVerdict

type CommandVerdict string

CommandVerdict describes whether parsed argv may bypass interactive approval.

const (
	CommandVerdictPrompt      CommandVerdict = "prompt"
	CommandVerdictAllowlisted CommandVerdict = "allowlisted"
	CommandVerdictDenied      CommandVerdict = "denied"
)

type EnvironmentProvider

type EnvironmentProvider func(context.Context, string, Actor) (LaunchEnvironment, error)

type Error

type Error struct {
	Code     ErrorCode
	Message  string
	Current  int
	Max      int
	Path     string
	Mode     Mode
	Platform string
	Action   string
	Err      error
}

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type ErrorCode

type ErrorCode string

ErrorCode is the closed public terminal failure vocabulary.

const (
	ErrorCodeNotFound                   ErrorCode = "terminal_not_found"
	ErrorCodeProfileSelectionConflict   ErrorCode = "profile_selection_conflict"
	ErrorCodeProfileSessionConflict     ErrorCode = "profile_session_conflict"
	ErrorCodeRequiresWorkspace          ErrorCode = "terminal_requires_workspace"
	ErrorCodeProfileArchived            ErrorCode = "profile_archived"
	ErrorCodeProfileUnavailable         ErrorCode = "profile_unavailable"
	ErrorCodeLimitReached               ErrorCode = "terminal_limit_reached"
	ErrorCodeSubscriberLimitReached     ErrorCode = "subscriber_limit_reached"
	ErrorCodeExited                     ErrorCode = "terminal_exited"
	ErrorCodeExpired                    ErrorCode = "terminal_expired"
	ErrorCodeInteractiveUnavailable     ErrorCode = "terminal_interactive_unavailable"
	ErrorCodeNotInteractive             ErrorCode = "terminal_not_interactive"
	ErrorCodeInvalidCwd                 ErrorCode = "invalid_cwd"
	ErrorCodeTimeoutOutOfRange          ErrorCode = "timeout_out_of_range"
	ErrorCodeGenerationFenced           ErrorCode = "generation_fenced"
	ErrorCodeApprovalRejected           ErrorCode = "approval_rejected"
	ErrorCodeTicketInvalid              ErrorCode = "ticket_invalid"
	ErrorCodeTicketExpired              ErrorCode = "ticket_expired"
	ErrorCodeInputRequestNotFound       ErrorCode = "input_request_not_found"
	ErrorCodeInputRequestAnswered       ErrorCode = "input_request_already_answered"
	ErrorCodeInputRequestSuperseded     ErrorCode = "input_request_superseded"
	ErrorCodeInputRequestLimitReached   ErrorCode = "input_request_limit_reached"
	ErrorCodeInputRequestRequiresHidden ErrorCode = "input_request_requires_hidden_input"
	ErrorCodeRecordingAlreadyStarted    ErrorCode = "recording_already_started"
	ErrorCodeRecordingNotActive         ErrorCode = "recording_not_active"
	ErrorCodeRecordingUnavailable       ErrorCode = "recording_unavailable"
	ErrorCodeSlowConsumer               ErrorCode = "slow_consumer"
	ErrorCodeJournalUnavailable         ErrorCode = "journal_unavailable"
)

type Event

type Event struct {
	Kind        EventKind
	WorkspaceID string
	ProfileID   string
	ProfileName string
	TerminalID  ID
	Actor       Actor
	Info        *Info
	Exit        *Exit
	Reason      string
	Detail      *EventDetail
	At          time.Time
}

func (Event) DetailValue

func (e Event) DetailValue() EventDetail

DetailValue returns the event detail or its zero value when absent.

type EventDetail

type EventDetail struct {
	Mode         Mode
	Title        string
	CommandID    string
	Command      string
	Cwd          string
	DetectedBy   string
	ExitCode     *int
	Signal       *string
	ExitCause    string
	DurationMS   int64
	Approval     string
	RequestID    InputRequestID
	Redacted     bool
	Length       int
	Outcome      string
	RecordingID  string
	Digest       string
	Bytes        int64
	Truncated    bool
	Flow         string
	Limit        string
	Current      int
	Max          int
	AuditBlocked bool
}

type EventKind

type EventKind string
const (
	EventKindDeleted           EventKind = "deleted"
	EventKindOpened            EventKind = "opened"
	EventKindClosed            EventKind = "closed"
	EventKindTitleChanged      EventKind = "title_changed"
	EventKindModeChanged       EventKind = "mode_changed"
	EventKindCommandStarted    EventKind = "command_started"
	EventKindCommandFinished   EventKind = "command_finished"
	EventKindInputRequested    EventKind = "input_requested"
	EventKindInputProvided     EventKind = "input_provided"
	EventKindRecordingStarted  EventKind = "recording_started"
	EventKindRecordingStopped  EventKind = "recording_stopped"
	EventKindSubscriberEvicted EventKind = "subscriber_evicted"
	EventKindLimitRejected     EventKind = "limit_rejected"
	EventKindAuditChanged      EventKind = "audit_changed"
)

type ExecAuthorizer

type ExecAuthorizer interface {
	AuthorizeTerminalExec(context.Context, ExecRequest, CommandClassification) (string, error)
}

ExecAuthorizer obtains a caller-owned approval decision for an agent command.

type ExecRequest

type ExecRequest struct {
	WS           string
	Command      string
	Args         []string
	Cwd          string
	Env          map[string]string
	YieldMs      int
	Visible      bool
	Output       OutputShape
	Approval     string
	Actor        Actor
	Capabilities Capabilities
}

type ExecResult

type ExecResult struct {
	ExitCode     *int      `json:"exit_code"`
	Signal       *string   `json:"signal"`
	Output       string    `json:"output"`
	Truncated    bool      `json:"truncated"`
	Untrusted    bool      `json:"untrusted"`
	Spill        *SpillRef `json:"spill,omitzero"`
	DurationMs   int64     `json:"duration_ms"`
	CommandID    string    `json:"command_id"`
	StillRunning bool      `json:"still_running,omitzero"`
	TerminalID   *ID       `json:"terminal_id"`
}

type ExecutionRootResolver

type ExecutionRootResolver func(context.Context, string, Actor) (string, error)

ExecutionRootResolver returns a trusted bound-session root, or an empty root for workspace-bound sessions. Errors deny launch before process creation.

type Exit

type Exit struct {
	Cause  string    `json:"cause"`
	Code   *int      `json:"code,omitzero"`
	Signal *string   `json:"signal,omitzero"`
	At     time.Time `json:"at"`
}

type FilterResult

type FilterResult struct {
	DisplayBytes []byte
	MarkerFacts  []MarkerFacts
}

type Frame

type Frame = terminalwire.Frame

type Handle

type Handle interface {
	Info() Info
	MarkerNonce() string
	Attach(ctx context.Context, options AttachOptions) (Subscription, error)
	Write(ctx context.Context, actor Actor, input []byte) error
	Screen(ctx context.Context, options ReadOptions) (*ReadResult, error)
	Wait(ctx context.Context, condition WaitCondition) (*WaitResult, error)
	RequestInput(ctx context.Context, actor Actor, request InputRequest) (*InputOutcome, error)
	AnswerInput(ctx context.Context, actor Actor, id InputRequestID, answer InputAnswer) (*InputOutcome, error)
	RejectInput(ctx context.Context, actor Actor, id InputRequestID, reason string) error
	PendingInput(id InputRequestID) (*PendingInputRequest, error)
	Signal(ctx context.Context, actor Actor, signal Signal) error
	StartRecording(ctx context.Context, actor Actor) (RecordingRef, error)
	StopRecording(ctx context.Context, actor Actor) (RecordingRef, error)
}

type ID

type ID string

type Info

type Info struct {
	ID           ID           `json:"id"`
	WS           string       `json:"workspace_id"`
	ProfileID    string       `json:"profile_id"`
	Title        string       `json:"title"`
	Shell        string       `json:"shell"`
	Cwd          string       `json:"cwd"`
	Mode         Mode         `json:"mode"`
	State        string       `json:"state"`
	Viewers      int          `json:"viewers"`
	BoundRun     *RunRef      `json:"bound_run,omitzero"`
	Capabilities Capabilities `json:"capabilities"`
	CreatedAt    time.Time    `json:"created_at"`
	Exit         *Exit        `json:"exit,omitzero"`
}

type InputActorProjection

type InputActorProjection struct {
	Kind ActorKind `json:"kind"`
	ID   string    `json:"id"`
}

InputActorProjection identifies an input requester or resolver without exposing run authority.

type InputAnswer

type InputAnswer struct {
	Input []byte
}

type InputOutcome

type InputOutcome struct {
	Outcome        InputResolutionOutcome `json:"outcome"`
	Redacted       bool                   `json:"redacted"`
	Length         int                    `json:"length"`
	DeliveredBytes int                    `json:"-"`
}

type InputRequest

type InputRequest struct {
	Reason        string
	PromptExcerpt string
	Redact        bool
}

type InputRequestID

type InputRequestID string

type InputResolutionOutcome

type InputResolutionOutcome string

InputResolutionOutcome is the closed outcome vocabulary for resolved input requests.

const (
	InputResolutionOutcomeAnswered   InputResolutionOutcome = "answered"
	InputResolutionOutcomeRejected   InputResolutionOutcome = "rejected"
	InputResolutionOutcomeSuperseded InputResolutionOutcome = "superseded"
	InputResolutionOutcomeExpired    InputResolutionOutcome = "expired"
)

func ParseInputResolutionOutcome

func ParseInputResolutionOutcome(value string) (InputResolutionOutcome, error)

func (*InputResolutionOutcome) UnmarshalJSON

func (o *InputResolutionOutcome) UnmarshalJSON(data []byte) error

type Journal

type Journal interface {
	MarkerConsumer
	ReserveCommandID(ctx context.Context, workspaceID string) (string, error)
	ReleaseCommandID(workspaceID, commandID string)
	ReserveRecordingID(ctx context.Context, workspaceID string) (string, error)
	ReleaseRecordingID(workspaceID, recordingID string)
	Record(ctx context.Context, workspaceID string, row CommandRow) error
	RecordQueued(ctx context.Context, terminal Info, row CommandRow) error
	Query(ctx context.Context, workspaceID string, scope store.ReadScope, query Query) (*Page, error)
	LinkRecording(ctx context.Context, workspaceID string, terminalID ID, recording RecordingRef) error
	PersistRecording(
		ctx context.Context,
		workspaceID string,
		terminalID ID,
		recording RecordingRef,
		contents []byte,
	) (RecordingRef, error)
	WriteArtifact(
		ctx context.Context,
		workspaceID string,
		profileID string,
		commandID string,
		terminalID *ID,
		contents []byte,
		expiresAt time.Time,
	) (SpillRef, error)
	Recording(
		ctx context.Context,
		workspaceID string,
		scope store.ReadScope,
		id string,
	) (*RecordingRef, io.ReadCloser, error)
	Artifact(ctx context.Context, workspaceID string, scope store.ReadScope, id string) (io.ReadCloser, error)
	RegisterTerminal(terminal Info, setBlocked func(bool), emit func(Event))
	CloseTerminal(ctx context.Context, terminal Info) error
	ReserveInput(terminal Info, input JournalInput) (JournalInputReservation, bool)
	ObserveOutput(terminal Info, output []byte)
	PrepareWorkspaceRemoval(
		ctx context.Context,
		workspaceID string,
	) (workspacepkg.UnregisterPreparation, error)
	PrepareWorkspaceRemovalAt(
		ctx context.Context,
		workspaceID string,
		rootDir string,
	) (workspacepkg.UnregisterPreparation, error)
	RemoveWorkspace(ctx context.Context, workspaceID string) error
	Shutdown(ctx context.Context) error
}

type JournalInput

type JournalInput struct {
	Content    []byte
	Redacted   bool
	Characters int
}

type JournalInputReservation

type JournalInputReservation interface {
	Commit(actor Actor, input JournalInput)
	Release()
}

JournalInputReservation pins one terminal journal lane across PTY delivery.

type LaunchEnvironment

type LaunchEnvironment struct {
	Values  map[string]string
	Unset   []string
	Release func()
}

LaunchEnvironment contains resolved declarations and their redaction lifetime. Release is retained until terminal removal so retained output remains protected.

type Manager

type Manager interface {
	Open(ctx context.Context, request OpenRequest) (Handle, error)
	Exec(ctx context.Context, request ExecRequest) (*ExecResult, error)
	Handle(ctx context.Context, workspaceID, profileID string, id ID) (Handle, error)
	Get(ctx context.Context, workspaceID, profileID string, id ID) (*Info, error)
	List(ctx context.Context, workspaceID string, scope store.ReadScope) ([]Info, error)
	ActiveRecordings(ctx context.Context, workspaceID string, scope store.ReadScope) ([]RecordingRef, error)
	Close(ctx context.Context, workspaceID string, id ID, actor Actor, signal Signal) (*Exit, error)
	Capabilities(ctx context.Context, workspaceID string) (Capabilities, error)
	MintAttachTicket(ctx context.Context, binding AttachTicketBinding, actor Actor) (AttachTicket, error)
	AttachWithTicket(
		ctx context.Context,
		token string,
		workspaceID string,
		terminalID ID,
		mode string,
		options AttachOptions,
	) (Handle, Subscription, AttachTicket, error)
	RunEnded(ctx context.Context, workspaceID string, actor Actor) int
	SessionRunEnded(ctx context.Context, workspaceID, profileID, sessionID, runID string, generation int64) int
	RuntimeRecovered(ctx context.Context, workspaceID string, previous, current Actor) int
	InputRequests(
		ctx context.Context,
		workspaceID string,
		scope store.ReadScope,
		terminalID ID,
	) ([]PendingInputRequest, error)
	ResolvedInputRequests(
		ctx context.Context,
		workspaceID string,
		scope store.ReadScope,
		terminalID ID,
	) ([]ResolvedInputRequest, error)
	Journal() Journal
	Shutdown(ctx context.Context) error
	Observe(fn func(context.Context, Event))
	ArchiveProfile(ctx context.Context, profileID string) error
	ArchiveWorkspace(ctx context.Context, workspaceID string) error
	PrepareWorkspaceRemoval(
		ctx context.Context,
		workspaceID string,
	) (workspacepkg.UnregisterPreparation, error)
}

type MarkerConsumer

type MarkerConsumer interface {
	ConsumeMarkerFacts(ctx context.Context, terminal Info, facts []MarkerFacts) error
}

type MarkerFacts

type MarkerFacts struct {
	Kind    string
	Command string
	Cwd     string
	Exit    *int
}

type Mode

type Mode string

type Notifier

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

func NewNotifier

func NewNotifier(logger *slog.Logger) *Notifier

func (*Notifier) Notify

func (n *Notifier) Notify(ctx context.Context, event Event)

Notify synchronously fans a typed terminal event out to the frozen observer set.

func (*Notifier) Observe

func (n *Notifier) Observe(fn func(context.Context, Event))

Observe registers an observer until the first Notify freezes the observer set. Registrations attempted after that point are ignored and logged.

type OpenRequest

type OpenRequest struct {
	WS           string
	Cwd          string
	Shell        string
	Title        string
	Cols         uint16
	Rows         uint16
	Actor        Actor
	Capabilities Capabilities
}

type Option

type Option func(*Service) error

Option configures one terminal Service dependency.

func WithAgentNiceness

func WithAgentNiceness(niceness int) Option

WithAgentNiceness lowers the scheduling priority of agent-owned terminal groups. Human and system terminals retain the daemon's inherited priority.

func WithClock

func WithClock(now func() time.Time) Option

WithClock sets the clock used for terminal lifecycle timestamps.

func WithEntropy

func WithEntropy(entropy io.Reader) Option

WithEntropy sets the cryptographic entropy reader used for identifiers.

func WithEnvironmentProvider

func WithEnvironmentProvider(provider EnvironmentProvider) Option

func WithExecAuthorizer

func WithExecAuthorizer(authorizer ExecAuthorizer) Option

WithExecAuthorizer sets the command approval authority.

func WithExecutionRootResolver

func WithExecutionRootResolver(resolver ExecutionRootResolver) Option

WithExecutionRootResolver applies session worktree bindings to agent launches. System-owned pipe consumers retain their independently resolved execution roots.

func WithJournal

func WithJournal(journal Journal) Option

WithJournal sets the terminal audit journal.

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger sets the structured logger.

func WithNotifier

func WithNotifier(notifier *Notifier) Option

WithNotifier sets the terminal lifecycle notifier.

func WithPTY

func WithPTY(starter pty.PTY) Option

WithPTY replaces the platform process starter.

func WithProcessRegistry

func WithProcessRegistry(registry *toolruntime.Registry) Option

WithProcessRegistry registers spawned terminal processes with toolruntime.

func WithProfileGuard

func WithProfileGuard(guard ProfileGuard) Option

WithProfileGuard sets the profile availability guard.

func WithProfileNameResolver

func WithProfileNameResolver(resolver ProfileNameResolver) Option

WithProfileNameResolver sets the profile-name projection used in events.

func WithSettingsProvider

func WithSettingsProvider(provider SettingsProvider) Option

WithSettingsProvider sets the effective terminal policy provider.

func WithWorkspaceResolver

func WithWorkspaceResolver(resolver WorkspaceResolver) Option

WithWorkspaceResolver sets the workspace boundary resolver.

type OutputSegment

type OutputSegment struct {
	Kind       OutputSegmentKind `json:"kind"`
	Text       string            `json:"text,omitempty"`
	Characters int               `json:"characters,omitzero"`
}

func BoundedOutputTail

func BoundedOutputTail(segments []OutputSegment) []OutputSegment

func OutputTailFromBytes

func OutputTailFromBytes(output []byte) []OutputSegment

func RedactedInputMarker

func RedactedInputMarker(characters int) OutputSegment

type OutputSegmentKind

type OutputSegmentKind string
const (
	OutputSegmentBytes         OutputSegmentKind = "output"
	OutputSegmentRedactedInput OutputSegmentKind = "redacted_input"
)

type OutputShape

type OutputShape struct {
	MaxBytes int    `json:"max_bytes,omitzero"`
	Strategy string `json:"strategy,omitempty"`
	Grep     string `json:"grep,omitempty"`
}

type PTY

type PTY = terminalpty.PTY

type Page

type Page struct {
	Entries []CommandRow `json:"entries"`
	Next    string       `json:"next,omitempty"`
}

type PartialWriteError

type PartialWriteError struct {
	Delivered int
	Err       error
}

func (*PartialWriteError) Error

func (e *PartialWriteError) Error() string

func (*PartialWriteError) Unwrap

func (e *PartialWriteError) Unwrap() error

type PendingInputRequest

type PendingInputRequest struct {
	ID            InputRequestID       `json:"id"`
	TerminalID    ID                   `json:"terminal_id"`
	WorkspaceID   string               `json:"workspace_id,omitempty"`
	ProfileID     string               `json:"profile_id"`
	ProfileName   string               `json:"profile_name"`
	Reason        string               `json:"reason"`
	PromptExcerpt string               `json:"prompt_excerpt"`
	Redacted      bool                 `json:"redacted"`
	RequestedAt   time.Time            `json:"requested_at"`
	Requester     InputActorProjection `json:"requester"`
}

PendingInputRequest is the profile-scoped public projection of one unresolved prompt.

type PipeRequest

type PipeRequest struct {
	WS           string
	Argv         []string
	Cwd          string
	Env          map[string]string
	Title        string
	AllowedRoots []string
	Actor        Actor
	Capabilities Capabilities
}

PipeRequest describes a captured, non-interactive command owned by a consumer.

type Proc

type Proc = terminalpty.Proc

type ProcSpec

type ProcSpec = terminalpty.ProcSpec

type ProfileGuard

type ProfileGuard interface {
	EnsureAvailableID(ctx context.Context, profileID string) error
}

type ProfileNameResolver

type ProfileNameResolver interface {
	ProfileName(ctx context.Context, profileID string) (string, error)
}

ProfileNameResolver projects a stable profile ID to its display name.

type ProfileWorkspaceResolver

type ProfileWorkspaceResolver interface {
	ResolveForProfile(ctx context.Context, idOrPath string, profileName string) (workspacepkg.ResolvedWorkspace, error)
}

ProfileWorkspaceResolver resolves a workspace using profile-owned aliases.

type Query

type Query struct {
	Actor    string
	Since    string
	Terminal string
	Failed   bool
	Limit    int
	Cursor   string
}

type ReadOptions

type ReadOptions struct {
	View     string
	MaxBytes int
	SinceSeq uint64
	FromLine int
	ToLine   int
	Grep     string
}

type ReadResult

type ReadResult struct {
	Content   string          `json:"content"`
	Segments  []OutputSegment `json:"segments,omitempty"`
	Seq       uint64          `json:"seq"`
	Truncated bool            `json:"truncated"`
	Busy      bool            `json:"busy"`
	Untrusted bool            `json:"untrusted"`
	Spill     *SpillRef       `json:"spill,omitzero"`
}

type RecordingRef

type RecordingRef struct {
	ID         string     `json:"id"`
	State      string     `json:"state,omitempty"`
	TerminalID ID         `json:"terminal_id"`
	ProfileID  string     `json:"profile_id"`
	Digest     string     `json:"digest"`
	Path       string     `json:"-"`
	StartedAt  time.Time  `json:"started_at"`
	StoppedAt  *time.Time `json:"stopped_at,omitempty"`
	Bytes      int64      `json:"bytes"`
	ExpiresAt  time.Time  `json:"expires_at"`
}

type Replay

type Replay struct {
	Preamble  []byte
	Segments  []SequencedOutputSegment
	Seq       uint64
	Truncated bool
}

func (Replay) Bytes

func (r Replay) Bytes() []byte

type ResolvedInputRequest

type ResolvedInputRequest struct {
	ID          InputRequestID         `json:"id"`
	TerminalID  ID                     `json:"terminal_id"`
	WorkspaceID string                 `json:"workspace_id,omitempty"`
	ProfileID   string                 `json:"profile_id"`
	ProfileName string                 `json:"profile_name"`
	Requester   InputActorProjection   `json:"requester"`
	Outcome     InputResolutionOutcome `json:"outcome"`
	ResolvedBy  InputActorProjection   `json:"resolved_by"`
	Reason      string                 `json:"reason,omitempty"`
	Redacted    bool                   `json:"redacted"`
	Length      int                    `json:"length"`
	RequestedAt time.Time              `json:"requested_at"`
	ResolvedAt  time.Time              `json:"resolved_at"`
}

ResolvedInputRequest is the bounded, secret-free outcome projection of an input request.

type Ring

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

func NewRing

func NewRing(capacity int) *Ring

func (*Ring) Append

func (r *Ring) Append(input []byte) (start uint64, end uint64)

func (*Ring) AppendRedactedInput

func (r *Ring) AppendRedactedInput(characters int) (start uint64, end uint64)

func (*Ring) Bounds

func (r *Ring) Bounds() (oldest uint64, next uint64)

func (*Ring) ReplayFrom

func (r *Ring) ReplayFrom(seq uint64) Replay

func (*Ring) SetModePreamble

func (r *Ring) SetModePreamble(preamble []byte)

func (*Ring) Snapshot

func (r *Ring) Snapshot() ([]byte, uint64)

func (*Ring) SnapshotSegments

func (r *Ring) SnapshotSegments() ([]OutputSegment, uint64)

type RunRef

type RunRef struct {
	SessionID  string `json:"session_id"`
	RunID      string `json:"run_id"`
	Generation int64  `json:"generation"`
}

type SequencedOutputSegment

type SequencedOutputSegment struct {
	Seq     uint64
	End     uint64
	Segment OutputSegment
}

type Service

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

Service is the daemon-owned terminal domain authority.

func NewManager

func NewManager(options ...Option) (*Service, error)

func (*Service) ActiveRecordings

func (m *Service) ActiveRecordings(
	ctx context.Context,
	workspaceID string,
	scope store.ReadScope,
) ([]RecordingRef, error)

func (*Service) ArchiveProfile

func (m *Service) ArchiveProfile(ctx context.Context, profileID string) error

func (*Service) ArchiveWorkspace

func (m *Service) ArchiveWorkspace(ctx context.Context, workspaceID string) error

func (*Service) AttachWithTicket

func (m *Service) AttachWithTicket(
	ctx context.Context,
	token string,
	workspaceID string,
	terminalID ID,
	mode string,
	options AttachOptions,
) (Handle, Subscription, AttachTicket, error)

func (*Service) Capabilities

func (m *Service) Capabilities(ctx context.Context, workspaceID string) (Capabilities, error)

Capabilities resolves the authoritative runtime capability for one workspace.

func (*Service) Close

func (m *Service) Close(
	ctx context.Context,
	workspaceID string,
	id ID,
	actor Actor,
	signal Signal,
) (*Exit, error)

func (*Service) Exec

func (m *Service) Exec(ctx context.Context, request ExecRequest) (*ExecResult, error)

func (*Service) Get

func (m *Service) Get(ctx context.Context, workspaceID, profileID string, id ID) (*Info, error)

func (*Service) Handle

func (m *Service) Handle(ctx context.Context, workspaceID, profileID string, id ID) (Handle, error)

func (*Service) InputRequests

func (m *Service) InputRequests(
	ctx context.Context,
	workspaceID string,
	scope store.ReadScope,
	terminalID ID,
) ([]PendingInputRequest, error)

func (*Service) InputRequestsAggregate

func (m *Service) InputRequestsAggregate(ctx context.Context, scope store.ReadScope) ([]PendingInputRequest, error)

InputRequestsAggregate reads pending input across workspaces without per-project fan-out.

func (*Service) Journal

func (m *Service) Journal() Journal

func (*Service) List

func (m *Service) List(ctx context.Context, workspaceID string, scope store.ReadScope) ([]Info, error)

func (*Service) ListAggregate

func (m *Service) ListAggregate(ctx context.Context, scope store.ReadScope) ([]Info, error)

ListAggregate snapshots live terminals across workspaces within the requested profile scope.

func (*Service) MintAttachTicket

func (m *Service) MintAttachTicket(
	ctx context.Context,
	binding AttachTicketBinding,
	actor Actor,
) (AttachTicket, error)

func (*Service) Observe

func (m *Service) Observe(fn func(context.Context, Event))

func (*Service) Open

func (m *Service) Open(ctx context.Context, request OpenRequest) (Handle, error)

func (*Service) OpenPipe

func (m *Service) OpenPipe(ctx context.Context, request PipeRequest) (Handle, error)

OpenPipe starts a non-interactive command for protocol adapters such as ACP.

func (*Service) PrepareWorkspaceDeletion

func (m *Service) PrepareWorkspaceDeletion(
	ctx context.Context,
	workspace workspacepkg.Workspace,
) (workspacepkg.UnregisterPreparation, error)

PrepareWorkspaceDeletion rebuilds removal ownership from the durable deletion snapshot.

func (*Service) PrepareWorkspaceRemoval

func (m *Service) PrepareWorkspaceRemoval(
	ctx context.Context,
	workspaceID string,
) (workspacepkg.UnregisterPreparation, error)

PrepareWorkspaceRemoval captures journal identity while the workspace registration still exists. It does not close a terminal or delete data.

func (*Service) Release

func (m *Service) Release(ctx context.Context, workspaceID, profileID string, id ID, actor Actor) error

Release closes and immediately forgets a consumer-owned terminal.

func (*Service) ResolvedInputRequests

func (m *Service) ResolvedInputRequests(
	ctx context.Context,
	workspaceID string,
	scope store.ReadScope,
	terminalID ID,
) ([]ResolvedInputRequest, error)

func (*Service) RunEnded

func (m *Service) RunEnded(_ context.Context, workspaceID string, actor Actor) int

RunEnded resolves pending input requests created by a completed run.

func (*Service) RuntimeRecovered

func (m *Service) RuntimeRecovered(_ context.Context, workspaceID string, previous, current Actor) int

RuntimeRecovered advances provenance to the replacement runtime generation.

func (*Service) SessionRunEnded

func (m *Service) SessionRunEnded(
	_ context.Context,
	workspaceID, profileID, sessionID, runID string,
	generation int64,
) int

SessionRunEnded resolves pending input requests for one completed session generation.

func (*Service) Shutdown

func (m *Service) Shutdown(ctx context.Context) error

func (*Service) Start

func (m *Service) Start(ctx context.Context) error

type Settings

type Settings struct {
	DefaultShell           string
	ShellIntegration       bool
	ScrollbackBytes        int
	DetachedTTL            time.Duration
	ExitRetention          time.Duration
	Recording              bool
	RecordingRetentionDays int
	MaxPerWorkspace        int
	MaxPerDaemon           int
	MaxSubscribers         int
}

func DefaultSettings

func DefaultSettings() Settings

type SettingsProvider

type SettingsProvider func(context.Context, string, string) (Settings, error)

SettingsProvider returns the effective terminal policy for a workspace and profile.

type Signal

type Signal string

type SpillRef

type SpillRef struct {
	ArtifactID string `json:"artifact_id"`
	Path       string `json:"-"`
	ProfileID  string `json:"-"`
	Bytes      int64  `json:"bytes"`
}

type Subscription

type Subscription interface {
	Frames() <-chan Frame
	Err() error
	Ack(bytes int)
	Resize(cols, rows uint16) error
	Close() error
}

type WaitCondition

type WaitCondition struct {
	Until     string
	Pattern   string
	TimeoutMs int
}

type WaitResult

type WaitResult struct {
	Reason    string `json:"reason"`
	ExitCode  *int   `json:"exit_code,omitzero"`
	Screen    string `json:"screen"`
	Untrusted bool   `json:"untrusted"`
}

type WorkspaceResolver

type WorkspaceResolver interface {
	Resolve(ctx context.Context, idOrPath string) (workspacepkg.ResolvedWorkspace, error)
}

WorkspaceResolver resolves an operator-supplied workspace ID or path.

Directories

Path Synopsis
Package idgen creates permanent terminal identifiers from cryptographic entropy.
Package idgen creates permanent terminal identifiers from cryptographic entropy.
Package journal owns terminal command persistence and retained byte artifacts.
Package journal owns terminal command persistence and retained byte artifacts.

Jump to

Keyboard shortcuts

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