bridgecontrol

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: MIT Imports: 20 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 bridgecontrol implements the optional, local-first bridgectl side of Bridge's control-plane WebSocket protocol (protocol v1, see the merged orchael/bridge PR #16 / docs/control-plane-v1.md). It publishes presence and session lifecycle metadata to Bridge; it never carries PTY output, environment variables, or credentials, and a failure anywhere in this package must never affect local Supervisor/session operations.

Index

Constants

View Source
const (
	StatusStarting = "starting"
	StatusRunning  = "running"
	StatusAttached = "attached"
	StatusStopping = "stopping"
	StatusStopped  = "stopped"
	StatusFailed   = "failed"
	StatusUnknown  = "unknown"
)

Session status values Bridge accepts, exactly matching control.validSessionStatuses.

View Source
const (
	InteractionUnknown            = "unknown"
	InteractionWorking            = "working"
	InteractionWaitingForInput    = "waiting_for_input"
	InteractionWaitingForApproval = "waiting_for_approval"
	InteractionIdle               = "idle"

	PendingRequestInput    = "input"
	PendingRequestApproval = "approval"
)

Interaction states and pending-request types Bridge accepts, exactly matching control.validInteractionStates / control.validPendingRequestTypes.

View Source
const (
	StatusFileName   = "bridge-control-status.json"
	RevisionFileName = "bridge-control-revisions.json"
)

StatusFileName and RevisionFileName are the state-dir-relative names under which the daemon persists the control client's status and lifecycle revision counters (the interaction counters live at InteractionRevisionPath(<RevisionFileName path>)). Read-only consumers such as `bridgectl session diagnose` use them to locate the same files.

View Source
const ProtocolVersion = 1

ProtocolVersion is the only control-plane protocol version this client speaks. Bridge rejects any other value on every message with a hard connection close (code "unsupported_protocol"); there is no negotiation or downgrade path.

View Source
const StatusStaleAfter = 2 * time.Minute

StatusStaleAfter is how old a "connected" Status entry can be before `doctor` stops trusting it at face value. The status file is written on every state *change*, not periodically, so a healthy long-lived connection can leave a "connected" entry untouched for hours — meaning a naive age check would misreport a perfectly healthy connection as disconnected. To make an age check meaningful without that false positive, Client refreshes the "connected" entry's timestamp on every successful heartbeat (see Client.sendHeartbeat); an entry older than this threshold can therefore only mean the daemon died without a chance to write a final status (killed, powered off) or the client has otherwise stopped heartbeating, both of which are correctly "disconnected". Set comfortably above the heartbeat interval Bridge documents today (30s) to tolerate normal scheduling jitter.

Variables

This section is empty.

Functions

func InteractionRevisionPath added in v1.4.4

func InteractionRevisionPath(base string) string

InteractionRevisionPath is the exported form of interactionRevisionPath for read-only consumers (see `bridgectl session diagnose`).

func ValidateEndpoint

func ValidateEndpoint(raw string) error

ValidateEndpoint enforces the same wss://-only shape at every point a control endpoint value is accepted: enrollment write time (cmd/bridgectl) and daemon read time (internal/localserver). A hand-edited or otherwise stale config could supply a plain ws:// URL; bridgectl must never send the bri_ bearer credential over an unencrypted connection, so both paths reject anything but a wss:// URL with a path and no credentials, query, or fragment, matching Bridge's own validation of BRIDGE_CONTROL_URL.

func WriteStatus

func WriteStatus(path string, st Status) error

WriteStatus atomically persists st to path. Errors are the caller's to handle (typically logged, never fatal): status reporting is best-effort observability, not part of the control protocol itself.

Types

type Client

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

Client is the optional outbound control-plane WebSocket client. All exported methods are non-blocking and safe to call from the Supervisor's hot path; the actual network I/O happens on a single background goroutine started by Start.

func New

func New(cfg Config) *Client

New constructs a Client. It does not connect until Start is called.

func (*Client) Close

func (c *Client) Close(ctx context.Context) error

Close stops the client and waits for its background goroutine to exit, or for ctx to expire. It is safe to call multiple times.

func (*Client) Notify

func (c *Client) Notify(info SessionSnapshot)

Notify enqueues a session lifecycle change for publication to Bridge. It never blocks the caller (the Supervisor). Repeated calls for the same session_id coalesce into a single pending entry holding the latest state, so no update is ever silently lost to eviction just because the *same* session changed state again before it could be sent.

The bounded eventQueueSize instead limits how many *distinct* sessions may be pending at once — a much rarer condition in practice, since the Supervisor's own concurrency limits bound how many sessions can be simultaneously active. If that limit is ever hit, the oldest pending session is evicted to make room, but — unlike a plain drop — this also schedules a fresh authoritative snapshot (scheduleReconcile) rather than letting Bridge's view of the evicted session drift indefinitely until some future reconnect: the very next snapshot re-derives every session's true current state from the Supervisor directly, so nothing is lost for longer than it takes to send one more snapshot.

func (*Client) Start

func (c *Client) Start(ctx context.Context)

Start begins the background connect/reconnect loop. It returns immediately; ctx bounds the connection's lifetime in addition to Close.

type Command

type Command struct {
	ID               string    `json:"command_id"`
	OrganizationID   string    `json:"organization_id"`
	InstallationID   string    `json:"installation_id"`
	SessionID        string    `json:"session_id"`
	UserID           string    `json:"user_id"`
	Action           string    `json:"action"`
	PendingRequestID string    `json:"pending_request_id"`
	ExpiresAt        time.Time `json:"expires_at"`
	Text             string    `json:"text"`
	Decision         string    `json:"decision,omitempty"`
}

type CommandResult

type CommandResult struct {
	ID     string `json:"command_id"`
	Status string `json:"status"`
	Code   string `json:"code,omitempty"`
}

type Config

type Config struct {
	TerminalSupervisor func() *bridge.Supervisor
	CommandPath        string
	ObserveFunc        func(string, uint64, int, int) (bridge.ActivityWindow, error)
	InstructionFunc    func(context.Context, string, string, string) error
	// DiagnoseFunc returns the canonical schema-versioned diagnostic report
	// for a session as JSON (see DiagnosticRequest). nil disables the
	// diagnose_session capability.
	DiagnoseFunc func(sessionID string) ([]byte, error)
	RespondFunc  func(context.Context, string, string, string) error
	ApprovalFunc func(context.Context, string, string, string) error
	// Endpoint is the control-plane WebSocket URL, e.g.
	// "wss://control.bridge.orchael.dev/v1/control". Taken verbatim from
	// Bridge's enrollment response; never hard-coded here.
	Endpoint string
	// Credential is the bri_... control-only credential. Never the
	// telemetry-only brc_ credential.
	Credential string
	// BridgectlVersion is sent in hello.bridgectl_version.
	BridgectlVersion string
	// InstallationID is used only for status reporting/logging.
	InstallationID string

	// StatusPath, if set, receives a small JSON status snapshot on every
	// connection-state change, for `bridgectl doctor` to read. Optional.
	StatusPath string
	// RevisionPath, if set, persists per-session revision counters so they
	// survive a daemon restart. Optional but strongly recommended in
	// production wiring (see RevisionStore's doc comment).
	RevisionPath string

	// SnapshotFunc returns the current authoritative list of active
	// sessions. Called once per successful (re)connect, immediately after
	// hello_ack. A nil result is treated as zero active sessions.
	SnapshotFunc func() []SessionSnapshot

	// HTTPClient overrides the client used for the WebSocket upgrade
	// request. Nil (the default) uses coder/websocket's own default
	// client/transport, which performs normal TLS certificate verification.
	// This exists for tests to point at a local TLS test server (e.g.
	// httptest.NewTLSServer's own .Client(), which trusts that server's
	// certificate) — production wiring must never set this to a client with
	// relaxed certificate verification.
	HTTPClient *http.Client

	Logger *slog.Logger
}

Config configures a Client. Endpoint and Credential are required; a Client should simply not be constructed (or Started) when Bridge enrollment has no control endpoint/credential, per the "no Bridge configuration means no control connection is attempted" invariant.

type DiagnosticRequest added in v1.4.4

type DiagnosticRequest struct {
	ID             string `json:"request_id"`
	OrganizationID string `json:"organization_id"`
	InstallationID string `json:"installation_id"`
	SessionID      string `json:"session_id"`
}

DiagnosticRequest asks bridgectl for the schema-versioned diagnostic report of one session ("diagnose_session"). It carries identity only: Bridge cannot pass options, paths or commands, and bridgectl answers from its own Supervisor state and local control files, never from Bridge.

type DiagnosticResult added in v1.4.4

type DiagnosticResult struct {
	ID     string          `json:"request_id"`
	Report json.RawMessage `json:"report,omitempty"`
	Code   string          `json:"code,omitempty"`
}

DiagnosticResult is the "session_diagnostic" reply. Report is the canonical diagnostic document (internal/diagnose.Report) as opaque JSON so this package, which diagnose imports, does not depend on it. Code is a fixed vocabulary: "" on success, otherwise invalid_request, unsupported, not_found or unavailable.

type ObservationRequest

type ObservationRequest struct {
	ID             string `json:"request_id"`
	OrganizationID string `json:"organization_id"`
	InstallationID string `json:"installation_id"`
	SessionID      string `json:"session_id"`
	AfterSequence  uint64 `json:"after_sequence"`
	MaxEvents      int    `json:"max_events"`
	MaxBytes       int    `json:"max_bytes"`
}

type ObservationResult

type ObservationResult struct {
	ID     string                `json:"request_id"`
	Window bridge.ActivityWindow `json:"window"`
	Code   string                `json:"code,omitempty"`
}

type RevisionStore

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

RevisionStore persists the monotonic per-session lifecycle revision counters bridgectl has assigned when publishing to Bridge. Bridge requires a strictly increasing revision per session_id (session_started must start at 1; each later event must be exactly current+1) and uses it to detect duplicates, stale events, and gaps.

Revisions are scoped to (session_id) only, matching Bridge's contract, and are assigned lazily at send time (see Client.sendEvent), not at the moment a local state change occurs — so a notification dropped from the bounded in-memory queue never creates a numeric gap on the wire, only a delay in Bridge learning about an intermediate state.

Persisting to disk (rather than keeping this purely in memory) matters when the bridgectl daemon itself restarts while a session is recovered (SessionInfo.Recovered): without it, a fresh in-memory counter would reissue revision 1 for an already-known session, and Bridge would ignore that snapshot row as stale (a lower revision than what it already has), silently failing to reconcile the session's true current status.

func NewRevisionStore

func NewRevisionStore(path string) *RevisionStore

NewRevisionStore loads persisted revisions from path if present. A missing or unreadable file is treated as an empty store (fresh installation, or first run after this feature was added) rather than an error: revision bookkeeping is best-effort recovery metadata, not something whose absence should block the control client from starting.

func (*RevisionStore) Current

func (rs *RevisionStore) Current(sessionID string) int64

Current returns the last revision assigned to sessionID, or 0 if none has been assigned yet.

func (*RevisionStore) Forget

func (rs *RevisionStore) Forget(sessionID string)

Forget drops bookkeeping for a session that has reached a terminal state and been successfully reported to Bridge, keeping this store bounded to currently-relevant sessions rather than growing for the lifetime of the daemon process.

func (*RevisionStore) Next

func (rs *RevisionStore) Next(sessionID string) int64

Next allocates and persists the next monotonic revision for sessionID, starting at 1 for a session never seen before.

type SessionSnapshot

type SessionSnapshot struct {
	SessionID   string
	Provider    string
	ProjectID   string
	Status      string
	CreatedAt   time.Time
	Interaction bridge.Interaction
}

SessionSnapshot is the safe, minimal session metadata bridgecontrol publishes to Bridge: no PTY output, environment variables, provider credentials, OAuth tokens, or filesystem contents.

Interaction carries the session's current authoritative interaction state as bridgectl knows it right now (bridge.InteractionUnknown with a zero-value capability for a provider that reports nothing). It is always populated here; Client decides on the wire whether it actually needs resending (see Client.toInteractionPayload) so an unsupported/unchanged provider does not spam Bridge with no-op traffic.

func ActiveSnapshots

func ActiveSnapshots(infos []bridge.SessionInfo) []SessionSnapshot

ActiveSnapshots filters Supervisor.List's result to non-terminal sessions and converts them to the safe metadata sent in an authoritative session_snapshot. Terminal sessions (stopped/failed) are excluded: Bridge treats any previously-known session absent from a fresh snapshot as implicitly stopped, so there is no need to (and no safe way to) keep asserting a revision for a session bridgectl no longer tracks.

type State

type State string

State summarizes the control client's current connection state for display in `bridgectl doctor`. It is persisted to a small local file rather than queried live, because `doctor` runs as a short-lived CLI process while the control connection is held by the long-lived daemon; a live check would either require RPC plumbing or, if it opened its own WebSocket with the shared installation credential, would trigger Bridge's generation-fencing and evict the daemon's real connection.

const (
	// StateNotProvisioned means the current enrollment has no control
	// endpoint/credential (pre-Bridge-#16 enrollment, or logged out).
	StateNotProvisioned State = "not_provisioned"
	StateConnecting     State = "connecting"
	StateConnected      State = "connected"
	StateDisconnected   State = "disconnected"
	StateAuthRejected   State = "auth_rejected"
	StateUnavailable    State = "unavailable"
)

type Status

type Status struct {
	State          State     `json:"state"`
	InstallationID string    `json:"installation_id,omitempty"`
	LastError      string    `json:"last_error,omitempty"`
	UpdatedAt      time.Time `json:"updated_at"`
	// LastConnectedAt is the last time the client was observed connected
	// (connect or heartbeat). It survives later non-connected states and
	// daemon restarts, so it answers "when did this last work" while
	// UpdatedAt only answers "when did the state last change". Absent in
	// status files written by older versions.
	LastConnectedAt time.Time `json:"last_connected_at,omitempty"`
}

Status is the JSON shape persisted to disk and read back by `doctor`.

func ReadStatus

func ReadStatus(path string) (*Status, error)

ReadStatus reads back a previously persisted Status. Returns os.ErrNotExist (wrapped) when the daemon has never started a control client, which the caller should treat the same as "not provisioned" or "not yet connected" depending on context.

type SupervisorObserver

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

SupervisorObserver adapts bridge.Supervisor lifecycle notifications into bridgecontrol.Client calls. It implements bridge.ControlObserver.

It never talks to Bridge itself and never blocks: SessionChanged only enqueues into Client's bounded, non-blocking notification channel.

func NewSupervisorObserver

func NewSupervisorObserver(client *Client) *SupervisorObserver

NewSupervisorObserver wraps client as a bridge.ControlObserver.

func (*SupervisorObserver) Close

func (o *SupervisorObserver) Close(ctx context.Context) error

Close implements bridge.ControlObserver.

func (*SupervisorObserver) SessionChanged

func (o *SupervisorObserver) SessionChanged(info bridge.SessionInfo)

SessionChanged implements bridge.ControlObserver.

type TerminalRequest

type TerminalRequest struct {
	Stream         bool      `json:"stream,omitempty"`
	ID             string    `json:"request_id"`
	OrganizationID string    `json:"organization_id"`
	InstallationID string    `json:"installation_id"`
	SessionID      string    `json:"session_id"`
	ClientID       string    `json:"client_id"`
	Action         string    `json:"action"`
	KeepWriter     bool      `json:"keep_writer,omitempty"`
	AfterSequence  uint64    `json:"after_sequence"`
	Data           []byte    `json:"data,omitempty"`
	Cols           uint32    `json:"cols,omitempty"`
	Rows           uint32    `json:"rows,omitempty"`
	ExpiresAt      time.Time `json:"expires_at"`
}

TerminalRequest is an ephemeral control request. ClientID must be scoped by the authenticated gateway to the user and browser tab, never a local CLI ID.

type TerminalResult

type TerminalResult struct {
	ID     string                `json:"request_id"`
	Window bridge.TerminalWindow `json:"window"`
	Code   string                `json:"code,omitempty"`
}

Jump to

Keyboard shortcuts

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