Documentation
¶
Index ¶
- Constants
- Variables
- func ValidateResponse(text string) error
- type Activity
- type ActivityBuffer
- type ActivityProvider
- type ActivityWindow
- type AttachRole
- type AttachState
- type BoltSessionStore
- func (s *BoltSessionStore) Close() error
- func (s *BoltSessionStore) LoadAll() ([]SessionInfo, error)
- func (s *BoltSessionStore) LoadChunkPage(sessionID string, after uint64, maxBytes int) ([]OutputChunk, error)
- func (s *BoltSessionStore) LoadChunks(sessionID string) ([]OutputChunk, error)
- func (s *BoltSessionStore) Save(info SessionInfo) error
- func (s *BoltSessionStore) SaveChunk(sessionID string, chunk OutputChunk) error
- type ByteBuffer
- func (b *ByteBuffer) After(afterSeq uint64) []OutputChunk
- func (b *ByteBuffer) Append(payload []byte) OutputChunk
- func (b *ByteBuffer) AppendChunk(chunk OutputChunk) OutputChunk
- func (b *ByteBuffer) AppendSized(payload []byte, ctype ChunkType, cols, rows uint32) OutputChunk
- func (b *ByteBuffer) AppendTyped(payload []byte, ctype ChunkType) OutputChunk
- func (b *ByteBuffer) LastSeq() uint64
- func (b *ByteBuffer) OldestSeq() uint64
- type ChunkPageStore
- type ChunkType
- type ClaimWriterResult
- type ControlObserver
- type EnvHealthProvider
- type InstructionProvider
- type Interaction
- type InteractionCapabilities
- type InteractionCapableProvider
- type InteractionEvidence
- type InteractionStateValue
- type InteractionWatcher
- type OutputChunk
- type PendingApprovalResponder
- type PendingInputResponder
- type PendingRequest
- type PendingRequestKind
- type PendingRequestType
- type Policy
- type Provider
- type Registry
- type RepoSetupRunner
- type SessionConfig
- type SessionInfo
- type SessionState
- type SessionStore
- type StreamJSONProvider
- type StripANSIProvider
- type Supervisor
- func (s *Supervisor) Attach(sessionID, clientID string, afterSeq uint64, role AttachRole) (*AttachState, error)
- func (s *Supervisor) ClaimWriter(sessionID, clientID string, force bool) (*ClaimWriterResult, error)
- func (s *Supervisor) Close()
- func (s *Supervisor) DecideApproval(ctx context.Context, sessionID, pendingID, decision string) error
- func (s *Supervisor) Detach(sessionID, clientID string) (wasWriter bool, err error)
- func (s *Supervisor) Get(sessionID string) (*SessionInfo, error)
- func (s *Supervisor) List(projectID string) []SessionInfo
- func (s *Supervisor) LoadHistory() error
- func (s *Supervisor) NotifyWriterClaimed(sessionID, claimantClientID string)
- func (s *Supervisor) NotifyWriterReleased(sessionID, releasingClientID string)
- func (s *Supervisor) ObserveActivity(sessionID string, after uint64, events, bytes int) (ActivityWindow, error)
- func (s *Supervisor) ReleaseWriter(sessionID, clientID string) error
- func (s *Supervisor) Resize(sessionID, clientID string, cols, rows uint32) error
- func (s *Supervisor) RespondToInput(ctx context.Context, sessionID, pendingID, text string) error
- func (s *Supervisor) SendInstruction(ctx context.Context, sessionID, text string) error
- func (s *Supervisor) Shutdown(ctx context.Context) error
- func (s *Supervisor) Start(ctx context.Context, cfg SessionConfig) (*SessionInfo, error)
- func (s *Supervisor) Stop(sessionID string, force bool) error
- func (s *Supervisor) StoredReplayPage(session string, after uint64) ([]OutputChunk, error)
- func (s *Supervisor) TerminalWindow(sessionID, clientID string, after uint64) (TerminalWindow, error)
- func (s *Supervisor) UpdateInteraction(sessionID string, next Interaction) error
- func (s *Supervisor) WaitTerminalWindow(ctx context.Context, session, client string, after uint64) (TerminalWindow, error)
- func (s *Supervisor) WriteInput(sessionID, clientID string, data []byte) (int, error)
- type SupervisorOption
- type TelemetryObserver
- type TerminalWindow
Constants ¶
const MaxResponseBytes = 16384
Variables ¶
var ( ErrInvalidArgument = errors.New("invalid argument") ErrSessionNotFound = errors.New("session not found") ErrSessionAlreadyExists = errors.New("session already exists") ErrSessionNotRunning = errors.New("session not running") ErrSessionAlreadyAttached = errors.New("session already has an attached client") ErrClientNotAttached = errors.New("client is not attached") ErrClientMismatch = errors.New("client does not own attached session") ErrRepoSetupFailed = errors.New("repo setup failed") ErrSupervisorShuttingDown = errors.New("supervisor shutting down") ErrSessionLimitReached = errors.New("session limit reached") ErrInputTooLarge = errors.New("input too large") // ErrWriterConflict is returned by ClaimWriter when another client already // holds the active-writer slot and force was not requested. ErrWriterConflict = errors.New("session already has an active writer") )
var ( ErrPendingRequestMismatch = errors.New("pending input request is no longer current") ErrRemoteResponseUnsupported = errors.New("provider does not support remote response") ErrInvalidResponse = errors.New("response must be valid nonempty UTF-8 text of at most 16384 bytes without control characters") )
Functions ¶
func ValidateResponse ¶
Types ¶
type Activity ¶
type Activity struct {
Sequence uint64 `json:"sequence"`
At time.Time `json:"at"`
Kind string `json:"kind"`
Summary string `json:"summary"`
}
Activity is an allowlisted provider event, never a terminal output chunk.
type ActivityBuffer ¶
type ActivityBuffer struct {
// contains filtered or unexported fields
}
ActivityBuffer is local to a provider session, independent of control-plane connectivity and telemetry. It retains at most 128 events, 32 KiB, 15 minutes. Sequence numbers never reset during this session's lifetime.
func (*ActivityBuffer) Append ¶
func (b *ActivityBuffer) Append(kind, summary string, now time.Time)
func (*ActivityBuffer) Window ¶
func (b *ActivityBuffer) Window(after uint64, maxEvents, maxBytes int, now time.Time) ActivityWindow
type ActivityProvider ¶
type ActivityWindow ¶
type AttachRole ¶
type AttachRole int
AttachRole controls whether the attaching client can send input (Writer) or is read-only (Observer).
const ( // AttachRoleWriter requests the active-writer slot. Fails with // ErrWriterConflict when another client already holds the slot. AttachRoleWriter AttachRole = iota // AttachRoleObserver attaches read-only; WriteInput / Resize are rejected. AttachRoleObserver )
type AttachState ¶
type AttachState struct {
ClientID string
Role AttachRole
Replay []OutputChunk
Live <-chan OutputChunk
ReplayGap bool
OldestSeq uint64
LastSeq uint64
// Checkpoint redraws the current screen as of LastSeq (see
// liveScreen.checkpoint). Nil when the screen is unavailable. Transports
// use it instead of a retained suffix when they cannot replay from the
// start of the session.
Checkpoint []byte
ExitRecorded bool
ExitCode int
Cols uint32
Rows uint32
}
AttachState is returned by Supervisor.Attach and holds the replay buffer, live output channel, and session metadata for the attaching client.
type BoltSessionStore ¶
type BoltSessionStore struct {
// contains filtered or unexported fields
}
BoltSessionStore implements SessionStore using bbolt (an embedded key/value store). Each session is stored as a JSON-encoded SessionInfo keyed by its session ID inside the "sessions" bucket.
func NewBoltSessionStore ¶
func NewBoltSessionStore(path string) (*BoltSessionStore, error)
NewBoltSessionStore opens (or creates) a bbolt database at path and ensures the sessions and chunks buckets exist.
func (*BoltSessionStore) Close ¶
func (s *BoltSessionStore) Close() error
Close closes the underlying database.
func (*BoltSessionStore) LoadAll ¶
func (s *BoltSessionStore) LoadAll() ([]SessionInfo, error)
LoadAll returns every session record currently in the store.
func (*BoltSessionStore) LoadChunkPage ¶ added in v1.4.6
func (s *BoltSessionStore) LoadChunkPage(sessionID string, after uint64, maxBytes int) ([]OutputChunk, error)
func (*BoltSessionStore) LoadChunks ¶
func (s *BoltSessionStore) LoadChunks(sessionID string) ([]OutputChunk, error)
LoadChunks returns all persisted chunks for sessionID in ascending seq order.
func (*BoltSessionStore) Save ¶
func (s *BoltSessionStore) Save(info SessionInfo) error
Save writes (or overwrites) the session info for info.SessionID.
func (*BoltSessionStore) SaveChunk ¶
func (s *BoltSessionStore) SaveChunk(sessionID string, chunk OutputChunk) error
SaveChunk persists a single PTY output chunk for the given session.
type ByteBuffer ¶
type ByteBuffer struct {
// contains filtered or unexported fields
}
ByteBuffer is a bounded ring-like buffer of PTY output chunks with byte-based retention.
func NewByteBuffer ¶
func NewByteBuffer(capacity int) *ByteBuffer
func (*ByteBuffer) After ¶
func (b *ByteBuffer) After(afterSeq uint64) []OutputChunk
func (*ByteBuffer) Append ¶
func (b *ByteBuffer) Append(payload []byte) OutputChunk
func (*ByteBuffer) AppendChunk ¶
func (b *ByteBuffer) AppendChunk(chunk OutputChunk) OutputChunk
AppendChunk appends a pre-existing chunk while preserving its sequence number and timestamp. This is used when rebuilding buffer state from durable storage after a daemon restart.
func (*ByteBuffer) AppendSized ¶ added in v1.4.6
func (b *ByteBuffer) AppendSized(payload []byte, ctype ChunkType, cols, rows uint32) OutputChunk
func (*ByteBuffer) AppendTyped ¶
func (b *ByteBuffer) AppendTyped(payload []byte, ctype ChunkType) OutputChunk
AppendTyped adds a payload with an explicit ChunkType to the buffer.
func (*ByteBuffer) LastSeq ¶
func (b *ByteBuffer) LastSeq() uint64
func (*ByteBuffer) OldestSeq ¶
func (b *ByteBuffer) OldestSeq() uint64
type ChunkPageStore ¶ added in v1.4.6
type ChunkPageStore interface {
LoadChunkPage(sessionID string, after uint64, maxBytes int) ([]OutputChunk, error)
}
ChunkPageStore supports bounded replay without loading a session into RAM. Optional so other SessionStore implementations remain source compatible.
type ChunkType ¶
type ChunkType uint8
ChunkType classifies an OutputChunk's content.
const ( // ChunkTypeOutput is raw terminal/text output (default, zero value). ChunkTypeOutput ChunkType = 0 // ChunkTypeThinking carries a thinking block from a stream-JSON provider. ChunkTypeThinking ChunkType = 1 // ChunkTypeWriterClaimed is a control event broadcast when a client claims // the writer role. It is never appended to the replay buffer. ChunkTypeWriterClaimed ChunkType = 2 // ChunkTypeWriterReleased is a control event broadcast when the writer // releases its role. It is never appended to the replay buffer. ChunkTypeWriterReleased ChunkType = 3 )
type ClaimWriterResult ¶
type ClaimWriterResult struct {
// PreviousWriterClientID is set when force evicted an existing writer.
PreviousWriterClientID string
}
ClaimWriterResult is returned by ClaimWriter.
type ControlObserver ¶
type ControlObserver interface {
// SessionChanged is called whenever a session's lifecycle state is set or
// changes (on start, on attach/detach, on stop, and on process exit) and
// also whenever its interaction state changes (see
// Supervisor.UpdateInteraction). info.Interaction always reflects the
// session's full current interaction state, not just what changed;
// implementations that only care about one axis can compare against
// their own last-seen copy of info to tell the two apart.
SessionChanged(SessionInfo)
// Close flushes/shuts down the observer. It must return promptly; any
// network I/O it performs must itself be bounded by ctx.
Close(context.Context) error
}
ControlObserver receives safe, minimal session lifecycle metadata for an optional external presence/coordination system (e.g. a Bridge control-plane client). Implementations must never block: notifications are expected to be enqueued asynchronously, never delivered synchronously over a network connection from inside SessionChanged.
Unlike TelemetryObserver, ControlObserver never sees PTY/stdin byte content — only the same safe fields exposed by SessionInfo (session id, provider, project id, lifecycle state, interaction state, timestamps).
type EnvHealthProvider ¶
EnvHealthProvider is implemented by providers that can evaluate runtime availability against a prepared session environment.
type InstructionProvider ¶
type Interaction ¶
type Interaction struct {
State InteractionStateValue
// Revision is a local, monotonically increasing sequence number bumped
// only when State or Pending's identity actually changes (never on a
// repeated report of the same value, and never reset except by a new
// session). Transports that forward Interaction downstream (e.g.
// bridgecontrol) allocate their own wire-level, restart-durable revision
// from this signal; see internal/bridgecontrol/observer.go.
Revision uint64
// UpdatedAt is when State (or Pending's identity) last actually changed.
UpdatedAt time.Time
// LastActivityAt is when bridgectl last received any authoritative
// interaction report for this session, even one that repeats the
// current State. It is refreshed on every UpdateInteraction call and is
// what lets a consumer tell "still confirmed current" apart from "we
// simply haven't heard anything new" (the latter is a connectivity/
// staleness concern, not an interaction-state one).
LastActivityAt time.Time
// Pending is non-nil only while State is WaitingForInput or
// WaitingForApproval and the provider has supplied a stable request
// identity for it.
Pending *PendingRequest
Evidence InteractionEvidence
}
Interaction is the current authoritative interaction state of a session. The zero value (State == "") is treated identically to InteractionUnknown by State's accessor below.
func (Interaction) EffectiveState ¶
func (i Interaction) EffectiveState() InteractionStateValue
EffectiveState returns State, normalizing the zero value to InteractionUnknown so callers never have to special-case an empty string.
type InteractionCapabilities ¶
type InteractionCapabilities struct {
RemoteResponseSupported bool
StructuredApprovalSupported bool
// InteractionStateSupported means the provider can authoritatively
// distinguish at least Working from Idle/Unknown for its sessions.
InteractionStateSupported bool
// ApprovalStateSupported means the provider can authoritatively raise
// InteractionWaitingForApproval with a PendingRequest (not merely
// WaitingForInput used loosely for both cases).
ApprovalStateSupported bool
// PendingSummarySupported means the provider can supply a privacy-safe
// PendingRequest.Summary rather than leaving it empty.
PendingSummarySupported bool
}
InteractionCapabilities declares what a provider can authoritatively report about interaction state. Every field defaults to false: a provider that does not implement InteractionCapableProvider is treated exactly as if every field here were false, which is what makes InteractionUnknown its only honest report.
type InteractionCapableProvider ¶
type InteractionCapableProvider interface {
InteractionCapabilities() InteractionCapabilities
}
InteractionCapableProvider is implemented by providers that can report authoritative interaction state for the sessions they run. A provider that does not implement this interface is treated as fully unsupported: Supervisor never guesses on its behalf, and every session it runs reports InteractionUnknown with a zero-value InteractionCapabilities.
type InteractionEvidence ¶
type InteractionEvidence struct {
// Source identifies the concrete signal that produced this report, e.g.
// "claude-stream-json", "opencode-sse". Empty Source is only valid for
// the zero-value/Unknown Interaction that a session starts with.
Source string
// Capability is the reporting provider's declared capability at the time
// of this report.
Capability InteractionCapabilities
}
InteractionEvidence records where an interaction-state value came from, so nothing downstream has to guess whether a given report is authoritative.
type InteractionStateValue ¶
type InteractionStateValue string
InteractionStateValue is the provider-neutral, authoritative-only interaction state of a session: what the agent is doing right now from the user's point of view. It is a distinct axis from SessionState (process lifecycle) and from control-plane connectivity, and must never be inferred from either: a running process is not necessarily "working", and an online control connection says nothing about whether the agent is actively doing anything.
This set is intentionally small and extensible; adding a new value here does not require changing SessionState or any transport that already forwards InteractionStateValue as an opaque string.
const ( // InteractionUnknown is the only state a provider without interaction // capability may report. It is also the zero value: a session that has // never received an authoritative interaction update reports Unknown, // never a guess. InteractionUnknown InteractionStateValue = "unknown" // InteractionWorking means the agent is actively processing (generating, // running a tool, editing) and is not blocked on the user. InteractionWorking InteractionStateValue = "working" // InteractionWaitingForInput means the provider has authoritatively // reported that it is blocked on a free-form answer from the user. InteractionWaitingForInput InteractionStateValue = "waiting_for_input" // InteractionWaitingForApproval means the provider has authoritatively // reported that it is blocked on the user approving or denying a // specific action (e.g. running a command, applying a patch). InteractionWaitingForApproval InteractionStateValue = "waiting_for_approval" // InteractionIdle means the agent finished its current turn and is not // blocked on any specific pending request; it is simply not doing // anything right now (e.g. between turns in a chat-style session). InteractionIdle InteractionStateValue = "idle" )
type InteractionWatcher ¶
type InteractionWatcher interface {
WatchInteraction(ctx context.Context, sessionID string, cfg SessionConfig) (<-chan Interaction, error)
}
InteractionWatcher is implemented by a provider that can supply a live stream of authoritative interaction-state updates for a session out of band from however its PTY/stdout is otherwise structured — for example a companion protocol connection alongside an ordinary interactive PTY process (see internal/provider's Codex app-server observer). A provider that also implements InteractionCapableProvider should keep the two consistent: the capability it declares should describe exactly what this watch stream can report.
Supervisor starts watching immediately after the session's process is successfully started and stops when the session's context is cancelled (on Stop, on process exit, or on daemon shutdown). WatchInteraction must return promptly; any setup it needs (dialing a companion process, etc.) happens after return, inside the goroutine that drains the returned channel, so a slow or failing watch connection never delays session startup or blocks WriteInput/Attach.
type OutputChunk ¶
type OutputChunk struct {
Cols uint32 `json:",omitempty"`
Rows uint32 `json:",omitempty"`
Seq uint64
Timestamp time.Time
Payload []byte
Type ChunkType // defaults to ChunkTypeOutput
}
OutputChunk is one retained output chunk from an agent session.
type PendingApprovalResponder ¶
type PendingApprovalResponder interface {
DecideApproval(context.Context, string, string, string) error
}
RespondToInput borrows the unowned writer slot for one bounded structured operation. Holding the session lock excludes Attach/ClaimWriter/Stop and local writes during dispatch. It never evicts a local writer, even one controlled by the same user. DecideApproval does not need the writer slot: it answers the provider's own approval request, and the provider accepts only the first answer. Provider state remains authoritative afterward.
type PendingInputResponder ¶
type PendingInputResponder interface {
RespondToInput(context.Context, string, string, string) error
}
PendingInputResponder must revalidate the provider's live request identity. Implementations must use a request-bound input operation, never fall back to unstructured terminal input, and respect the context deadline.
type PendingRequest ¶
type PendingRequest struct {
ID string
Type PendingRequestType
// Summary is an optional, short, privacy-safe description of the pending
// request, supplied verbatim by the provider (e.g. a tool-call name or a
// structured prompt title). It must never be derived from raw terminal
// output, chain-of-thought, or free-form transcript text: if the
// provider does not supply a safe structured summary, this stays empty
// and consumers fall back to a generic label such as "Waiting for your
// answer".
Summary string
// Kind classifies the request from structured provider data (never from
// terminal text). Empty means unclassified.
Kind PendingRequestKind
}
PendingRequest is a stable-identity request for user attention.
ID must be stable for the lifetime of the request: the same logical question or approval must keep the same ID across repeated authoritative reports, so a consumer (bridgectl's control client, Bridge) can tell "this is still the same pending request" apart from "the provider resolved one request and immediately raised a new one". It is cleared only by UpdateInteraction being called again with authoritative evidence that the request was resolved or superseded — never as a side effect of writing bytes to a PTY. See Supervisor.WriteInput and Supervisor.UpdateInteraction.
type PendingRequestKind ¶ added in v1.4.4
type PendingRequestKind string
PendingRequestKind is a provider-assigned, fixed-vocabulary category of a pending request. It exists so diagnostics and UIs can say *what sort of thing* the agent is blocked on without any free text (a Summary can embed working directories, full commands and credentials). The zero value means the provider did not classify the request.
const ( PendingKindCommand PendingRequestKind = "command" PendingKindFileChange PendingRequestKind = "file_change" PendingKindTool PendingRequestKind = "tool" PendingKindQuestion PendingRequestKind = "question" PendingKindOther PendingRequestKind = "other" )
type PendingRequestType ¶
type PendingRequestType string
PendingRequestType identifies why a session is blocked on the user.
const ( PendingRequestInput PendingRequestType = "input" PendingRequestApproval PendingRequestType = "approval" )
type Policy ¶
type Policy struct {
MaxPerProject int
MaxGlobal int
MaxInputBytes int
AllowedPaths []string // glob patterns for allowed repo_path values
}
Policy defines runtime limits and guards for the bridge.
func (*Policy) CheckSessionLimits ¶
CheckSessionLimits verifies that creating a new session would not exceed limits.
func (*Policy) ValidateInput ¶
ValidateInput checks that input text does not exceed the maximum size.
func (*Policy) ValidateInputBytes ¶
ValidateInputBytes checks that PTY input bytes do not exceed the maximum size.
func (*Policy) ValidateRepoPath ¶
ValidateRepoPath checks that the given path is under one of the allowed path patterns. If no patterns are configured, all paths are allowed.
type Provider ¶
type Provider interface {
ID() string
Binary() string
PromptPattern() *regexp.Regexp
StartupTimeout() time.Duration
StopGrace() time.Duration
BuildCommand(ctx context.Context, cfg SessionConfig) (*exec.Cmd, error)
ValidateStartup(ctx context.Context) error
Health(ctx context.Context) error
Version(ctx context.Context) (string, error)
}
Provider describes an interactive PTY-backed CLI provider.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry holds registered provider adapters keyed by provider ID.
type RepoSetupRunner ¶
type RepoSetupRunner interface {
Prepare(ctx context.Context, repoPath string, baseEnv []string) ([]string, error)
}
RepoSetupRunner prepares a repository-specific environment before provider selection and launch.
type SessionConfig ¶
type SessionConfig struct {
ProjectID string
SessionID string
RepoPath string
Options map[string]string
Env []string
// Fallbacks is an ordered list of provider IDs to try if the primary
// provider (Options["provider"]) is unavailable. At most 2 entries are
// meaningful; extras are silently ignored.
Fallbacks []string
InitialCols uint32
InitialRows uint32
}
SessionConfig holds configuration for starting a new provider session.
type SessionInfo ¶
type SessionInfo struct {
SessionID string
ProjectID string
Provider string
RepoPath string
State SessionState
ProcessID int
CreatedAt time.Time
StoppedAt time.Time
Error string
Attached bool
AttachedClientID string
Recovered bool
ExitRecorded bool
ExitCode int
OldestSeq uint64
LastSeq uint64
Cols uint32
Rows uint32
// ActiveWriterClientID is the client currently holding the writer slot.
// Empty when no writer is attached.
ActiveWriterClientID string
// ObserverCount is the number of read-only observer clients currently attached.
ObserverCount int
// Interaction is the session's current authoritative interaction state.
// It is a distinct axis from State (runtime lifecycle) and is never
// inferred from it; see interaction.go.
Interaction Interaction
// InteractionCapabilities is the reporting provider's declared
// capability for Interaction, duplicated onto SessionInfo so consumers
// (doctor, the control client, Bridge) don't need a separate provider
// lookup to know how much to trust Interaction.
InteractionCapabilities InteractionCapabilities
}
SessionInfo holds metadata about a running session.
type SessionState ¶
type SessionState int
SessionState represents the lifecycle state of a session.
const ( SessionStateStarting SessionState = iota + 1 SessionStateRunning SessionStateAttached SessionStateStopping SessionStateStopped SessionStateFailed )
type SessionStore ¶
type SessionStore interface {
Save(info SessionInfo) error
LoadAll() ([]SessionInfo, error)
SaveChunk(sessionID string, chunk OutputChunk) error
LoadChunks(sessionID string) ([]OutputChunk, error)
Close() error
}
SessionStore persists session metadata and PTY output chunks so they survive daemon restarts.
type StreamJSONProvider ¶
type StreamJSONProvider interface {
IsStreamJSON() bool
}
StreamJSONProvider is implemented by providers that emit structured JSONL (e.g. claude --output-format stream-json) instead of raw PTY bytes. These providers run without a PTY and have their stdout parsed for typed events (text, thinking).
type StripANSIProvider ¶
type StripANSIProvider interface {
IsStripANSI() bool
}
StripANSIProvider is implemented by providers that should have ANSI escape codes stripped from their PTY output before forwarding to clients.
type Supervisor ¶
type Supervisor struct {
// contains filtered or unexported fields
}
Supervisor manages the lifecycle of PTY-backed provider sessions.
func NewSupervisor ¶
func NewSupervisor(registry *Registry, policy Policy, outputBufSize int, idleTimeout time.Duration, opts ...SupervisorOption) *Supervisor
func (*Supervisor) Attach ¶
func (s *Supervisor) Attach(sessionID, clientID string, afterSeq uint64, role AttachRole) (*AttachState, error)
Attach connects clientID to the session. role controls whether the client attaches as a writer (can send input) or observer (read-only).
Writers: only one writer is allowed at a time. Returns ErrWriterConflict if another client already holds the writer slot.
Observers: unlimited. Observers always succeed unless the session is not found.
func (*Supervisor) ClaimWriter ¶
func (s *Supervisor) ClaimWriter(sessionID, clientID string, force bool) (*ClaimWriterResult, error)
ClaimWriter promotes clientID to the active-writer slot. If force is true and another client holds the slot, that client is evicted (its channel is not closed here; the server must send them a WRITER_RELEASED event). Returns ErrWriterConflict when force is false and the slot is taken.
func (*Supervisor) Close ¶
func (s *Supervisor) Close()
func (*Supervisor) DecideApproval ¶
func (s *Supervisor) DecideApproval(ctx context.Context, sessionID, pendingID, decision string) error
func (*Supervisor) Detach ¶
func (s *Supervisor) Detach(sessionID, clientID string) (wasWriter bool, err error)
Detach removes clientID from the session's observer set. It returns true if the detaching client held the active-writer slot (so the server can broadcast a WRITER_RELEASED event), and any error.
func (*Supervisor) Get ¶
func (s *Supervisor) Get(sessionID string) (*SessionInfo, error)
func (*Supervisor) List ¶
func (s *Supervisor) List(projectID string) []SessionInfo
func (*Supervisor) LoadHistory ¶
func (s *Supervisor) LoadHistory() error
LoadHistory reads all persisted sessions from the store and places them in the in-memory history map so they are visible via Get and List. Sessions that were not in a terminal state (i.e. the daemon crashed mid-flight) are marked as SessionStateFailed with an "orphaned by daemon restart" message and their updated state is written back to the store.
Call LoadHistory once, before serving requests.
func (*Supervisor) NotifyWriterClaimed ¶
func (s *Supervisor) NotifyWriterClaimed(sessionID, claimantClientID string)
NotifyWriterClaimed broadcasts a ChunkTypeWriterClaimed control event to all observers of sessionID so they learn immediately which client now owns the writer role. The payload is the claimant clientID.
func (*Supervisor) NotifyWriterReleased ¶
func (s *Supervisor) NotifyWriterReleased(sessionID, releasingClientID string)
NotifyWriterReleased broadcasts a ChunkTypeWriterReleased control event to all observers of sessionID. The payload is the releasing clientID.
func (*Supervisor) ObserveActivity ¶
func (s *Supervisor) ObserveActivity(sessionID string, after uint64, events, bytes int) (ActivityWindow, error)
func (*Supervisor) ReleaseWriter ¶
func (s *Supervisor) ReleaseWriter(sessionID, clientID string) error
ReleaseWriter demotes clientID from the active-writer slot to observer. Returns ErrClientMismatch if clientID does not currently hold the slot.
func (*Supervisor) Resize ¶
func (s *Supervisor) Resize(sessionID, clientID string, cols, rows uint32) error
func (*Supervisor) RespondToInput ¶
func (s *Supervisor) RespondToInput(ctx context.Context, sessionID, pendingID, text string) error
func (*Supervisor) SendInstruction ¶
func (s *Supervisor) SendInstruction(ctx context.Context, sessionID, text string) error
func (*Supervisor) Shutdown ¶
func (s *Supervisor) Shutdown(ctx context.Context) error
Shutdown gracefully stops all active sessions and waits until they reach a terminal state. If ctx expires, any remaining sessions are force-stopped and ctx.Err() is returned.
func (*Supervisor) Start ¶
func (s *Supervisor) Start(ctx context.Context, cfg SessionConfig) (*SessionInfo, error)
func (*Supervisor) StoredReplayPage ¶ added in v1.4.6
func (s *Supervisor) StoredReplayPage(session string, after uint64) ([]OutputChunk, error)
StoredReplayPage exposes a bounded page to authenticated attach transports. A nil page means this store has no paged replay capability.
func (*Supervisor) TerminalWindow ¶
func (s *Supervisor) TerminalWindow(sessionID, clientID string, after uint64) (TerminalWindow, error)
TerminalWindow reads without attaching, claiming a writer, or resizing a PTY.
func (*Supervisor) UpdateInteraction ¶
func (s *Supervisor) UpdateInteraction(sessionID string, next Interaction) error
UpdateInteraction records a new authoritative interaction-state report for sessionID. Callers must only invoke this from a real provider/runtime signal (see InteractionEvidence.Source) — never in response to bridgectl merely writing bytes to a session's stdin/PTY (WriteInput does not, and must not, call this). next.Evidence.Source identifies that signal; an empty Source is rejected.
The stored revision and UpdatedAt only advance when next actually differs from the current state (a different State, or a different Pending request identity/summary — see Interaction.changed); a repeated report of the same value still refreshes LastActivityAt and is still forwarded to the optional ControlObserver so Bridge's staleness reasoning has a fresh timestamp to work with, but never fabricates a new state transition.
func (*Supervisor) WaitTerminalWindow ¶ added in v1.4.6
func (s *Supervisor) WaitTerminalWindow(ctx context.Context, session, client string, after uint64) (TerminalWindow, error)
WaitTerminalWindow wakes on new output. A one-second heartbeat also carries end/resize/writer changes, without polling through the network gateways.
func (*Supervisor) WriteInput ¶
func (s *Supervisor) WriteInput(sessionID, clientID string, data []byte) (int, error)
type SupervisorOption ¶
type SupervisorOption func(*Supervisor)
SupervisorOption configures optional Supervisor behaviour.
func WithControlObserver ¶
func WithControlObserver(observer ControlObserver) SupervisorOption
WithControlObserver attaches an optional ControlObserver to the Supervisor. It is independent of WithTelemetry: either, both, or neither may be configured.
func WithRepoSetupRunner ¶
func WithRepoSetupRunner(runner RepoSetupRunner) SupervisorOption
func WithStore ¶
func WithStore(store SessionStore) SupervisorOption
WithStore attaches a SessionStore so that session metadata is persisted on every terminal state transition and reloaded at startup via LoadHistory.
func WithTelemetry ¶
func WithTelemetry(observer TelemetryObserver) SupervisorOption
type TelemetryObserver ¶
type TerminalWindow ¶
type TerminalWindow struct {
More bool `json:"more"`
Data []byte `json:"data"`
FirstSequence uint64 `json:"first_sequence,omitempty"`
NextSequence uint64 `json:"next_sequence"`
Gap bool `json:"gap"`
Ended bool `json:"ended"`
Writer bool `json:"writer"`
Cols uint32 `json:"cols"`
Rows uint32 `json:"rows"`
}
TerminalWindow is a bounded, transient view of retained PTY output. Data is encoded as base64 by JSON so split UTF-8 and escape sequences stay intact.