Documentation
¶
Overview ¶
Package gateway is the server-side hub of the agent_daemon connector. It owns the HTTP / WebSocket entry points the daemon dials in to, per-device long-lived WebSocket sessions, and a process-local registry of deviceID/runID/permID → Session for routing.
The package deliberately does NOT depend on the connector implementation — the connector imports it, not the other way around.
Index ¶
- Variables
- func RegisterRoutes(r chi.Router, h *Handler)
- type ArchivedCancellationStore
- type AuthenticatedRuntime
- type Authenticator
- type DeviceOwnerStore
- type Handler
- type HandlerConfig
- type HeartbeatTouch
- type Registry
- func (r *Registry) AttachPermission(permID string, sess *Session)
- func (r *Registry) AttachPromptForUserChoice(askID string, sess *Session)
- func (r *Registry) AttachRun(runID string, sess *Session)
- func (r *Registry) Deregister(sess *Session)
- func (r *Registry) DetachPermission(permID string)
- func (r *Registry) DetachPromptForUserChoice(askID string)
- func (r *Registry) DetachRun(runID string)
- func (r *Registry) Devices() []string
- func (r *Registry) LookupDevice(deviceID string) (*Session, error)
- func (r *Registry) LookupPermission(permID string) (*Session, error)
- func (r *Registry) LookupPromptForUserChoice(askID string) (*Session, error)
- func (r *Registry) LookupRun(runID string) *Session
- func (r *Registry) PendingWaiters(deviceID string) []chan *Session
- func (r *Registry) Register(sess *Session) (previous *Session)
- func (r *Registry) WaitForDevice(ctx context.Context, deviceID string, timeout time.Duration) (*Session, error)
- type RuntimeStore
- type Session
- func (s *Session) AgentKindStatus(kind string) (info runtimedevice.SupportedAgentKind, found bool, snapshotKnown bool)
- func (s *Session) AuthenticatedWith(digest string) bool
- func (s *Session) Close(reason string)
- func (s *Session) CloseWithCode(code int, reason string)
- func (s *Session) Closed() <-chan struct{}
- func (s *Session) DrainArchivedCancellation(ctx context.Context) (bool, error)
- func (s *Session) ExportWorkspaceOutputs(ctx context.Context, request proto.WorkspaceExportPayload, ...) error
- func (s *Session) IsClosed() bool
- func (s *Session) LastSeen() time.Time
- func (s *Session) ListWorkspaceDirectory(ctx context.Context, request proto.WorkspaceReadPayload) (proto.WorkspaceReadResultPayload, error)
- func (s *Session) PrepareRuntime(ctx context.Context, id string, request proto.RuntimePreparePayload, ...) (proto.RuntimePrepareResultPayload, error)
- func (s *Session) ReadWorkspaceFile(ctx context.Context, request proto.WorkspaceReadPayload) (proto.WorkspaceReadResultPayload, error)
- func (s *Session) Send(ctx context.Context, env proto.Envelope) error
- func (s *Session) SendAndWaitInteractionAck(ctx context.Context, env proto.Envelope, deliveryID string) (proto.InteractionDecisionAckPayload, error)
- func (s *Session) Start()
- func (s *Session) SubscribeDurable(runID string) (*Subscription, error)
- func (s *Session) SubscribePreparation(requestID string) (*Subscription, error)
- func (s *Session) SuspendControl(ctx context.Context, kind string, request proto.EnvironmentSuspendPayload) (proto.EnvironmentSuspendResultPayload, error)
- func (s *Session) TrackExecutionDelivery(runID string) (func(), error)
- func (s *Session) Unsubscribe(runID string)
- func (s *Session) UnsubscribePreparation(requestID string)
- func (s *Session) WriteWorkspaceFile(ctx context.Context, id string, request proto.WorkspaceWritePayload, ...) (proto.WorkspaceWriteResultPayload, error)
- type SessionLogger
- type Subscription
- type WSConn
Constants ¶
This section is empty.
Variables ¶
var ( // DefaultHeartbeatInterval is the cadence the daemon is told to // send heartbeats at via the bootstrap response. The server uses // HeartbeatTimeout (not this cadence) to decide a session is dead. DefaultHeartbeatInterval = 15 * time.Second // HeartbeatTimeout is how long the server tolerates no inbound // frame (heartbeat OR data) before declaring the session unhealthy. HeartbeatTimeout = 60 * time.Second // WriteTimeout caps how long a single outbound frame may block. // Past this we treat the peer as wedged and close the session. WriteTimeout = 10 * time.Second // InteractionAckTimeout bounds the application-level round trip for a // permission or user-input decision after it is written to the daemon. InteractionAckTimeout = 15 * time.Second // ReadLimit caps a single inbound frame at 4 MiB. tool_call // results can be large but anything past this is almost certainly // a misbehaving daemon (or hostile input). ReadLimit int64 = 4 * 1024 * 1024 // CloseRuntimeDeleted is a custom WS close code (4001) sent when // a heartbeat discovers the runtime has been deleted. The daemon // treats this as a permanent error and exits rather than reconnecting. CloseRuntimeDeleted = 4001 )
Tunables. Package-level so tests can override via small helpers without exposing struct fields on every Session.
var ErrAuthBadCredential = errors.New("agentdaemon auth: bad credential")
ErrAuthBadCredential folds "no credential on row" together with "wrong credential" so probes can't distinguish them.
var ErrAuthIncompatibleVersion = errors.New("agentdaemon auth: incompatible protocol version")
var ErrAuthMissingParams = errors.New("agentdaemon auth: missing device_id / token / version")
var ErrAuthUnknownDevice = errors.New("agentdaemon auth: unknown device")
var ErrAuthWrongRuntimeType = errors.New("agentdaemon auth: runtime_type mismatch")
ErrAuthWrongRuntimeType is returned when the runtimes row exists but is registered as a different runtime_type.
var ErrDeviceNotRegistered = errors.New("agentdaemon gateway: device not registered (offline / never connected)")
ErrDeviceNotRegistered is returned by Registry lookups when a caller asks for a device the gateway has no live session for.
var ErrPermissionNotRegistered = errors.New("agentdaemon gateway: permission id not registered (expired / unknown)")
ErrPermissionNotRegistered is returned when SubmitPermission arrives for a perm id we don't have a pending mapping for.
var ErrPromptForUserChoiceNotRegistered = errors.New("agentdaemon gateway: prompt_for_user_choice id not registered (expired / unknown)")
ErrPromptForUserChoiceNotRegistered is returned when SubmitPromptForUserChoice arrives for an ask id we don't have a pending mapping for. Same race semantics as the permission variant (cancelled / expired / never seen).
var ErrSessionClosed = errors.New("agentdaemon gateway: session closed")
ErrSessionClosed is returned by Send / Subscribe when the session has shut down.
var ErrSubscriberOverflow = errors.New("execution subscriber buffer overflow")
var ErrWaitForDeviceTimeout = errors.New("agentdaemon gateway: timed out waiting for device to register")
ErrWaitForDeviceTimeout is returned by WaitForDevice when the deadline expires before a daemon dials in.
Functions ¶
func RegisterRoutes ¶
RegisterRoutes mounts the agent_daemon HTTP / WebSocket endpoints onto a chi router.
GET /agent-daemon/ws — daemon dial-in (WS upgrade) POST /agent-daemon/bootstrap — daemon first-call to fetch wsUrl + heartbeat cadence GET /agent-daemon/device-status — daemon self-check
All three accept the runtime credential issued via the runtimes/pairings flow with type='agent_daemon'.
Types ¶
type ArchivedCancellationStore ¶
type ArchivedCancellationStore interface {
ArchivedCancellationReceipt(context.Context, string, string, []string) (runtimedevice.ArchivedCancellationReceipt, error)
}
ArchivedCancellationStore is deliberately separate from RuntimeStore: a receipt opportunity cannot authenticate a new connection or authorize work.
type AuthenticatedRuntime ¶
type AuthenticatedRuntime struct {
DeviceID string
WorkspaceID string
Name string
RuntimeNodeID string
RuntimeAllocationID string
}
AuthenticatedRuntime is the result of a successful credential check.
type Authenticator ¶
type Authenticator struct {
// contains filtered or unexported fields
}
Authenticator validates the (device_id, token, version) trio that the daemon presents on /agent-daemon/ws upgrade and on /agent-daemon/bootstrap.
func NewAuthenticator ¶
func NewAuthenticator(store RuntimeStore) *Authenticator
func (*Authenticator) AuthenticateBearer ¶
func (a *Authenticator) AuthenticateBearer(ctx context.Context, deviceID, bearer string) (AuthenticatedRuntime, error)
AuthenticateBearer runs the runtime credential check. Returns a populated AuthenticatedRuntime on success or one of the typed Err* sentinels on failure so the caller can map them to the appropriate WS close code / HTTP status.
type DeviceOwnerStore ¶
type DeviceOwnerStore interface {
ClaimAgentDaemonDeviceOwner(ctx context.Context, input runtimedevice.ClaimOwner) (runtimedevice.Owner, error)
RenewAgentDaemonDeviceOwner(ctx context.Context, input runtimedevice.RenewOwner) (runtimedevice.Owner, bool, error)
ReleaseAgentDaemonDeviceOwner(ctx context.Context, input runtimedevice.ReleaseOwner) (bool, error)
GetAgentDaemonDeviceOwner(ctx context.Context, deviceID string) (runtimedevice.Owner, bool, error)
}
DeviceOwnerStore is the DB-backed owner lease surface used by the gateway.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler exposes the agent_daemon HTTP endpoints.
func NewHandler ¶
func NewHandler(cfg HandlerConfig) *Handler
NewHandler panics on missing Authenticator / Registry — a misconfigured gateway is a bug we'd rather catch at boot than at the first dial-in.
func (*Handler) Bootstrap ¶
func (h *Handler) Bootstrap(w http.ResponseWriter, r *http.Request)
Bootstrap is the daemon's first HTTP call after pairing. Validating the bearer in a separate HTTP step (rather than folded into the WS upgrade) lets the daemon fail fast on credential problems with a real HTTP status rather than the opaque WS close code.
func (*Handler) DeviceStatus ¶
func (h *Handler) DeviceStatus(w http.ResponseWriter, r *http.Request)
DeviceStatus is a lightweight liveness probe the daemon hits before the WS dial.
type HandlerConfig ¶
type HandlerConfig struct {
// Authenticator validates the bearer credential on /agent-daemon/ws
// upgrade and on /agent-daemon/bootstrap.
Authenticator *Authenticator
Registry *Registry
// Heartbeat flips pending_pairing -> online and keeps
// last_heartbeat_at fresh. nil tracks liveness in-process only.
Heartbeat HeartbeatTouch
// ArchivedCancellations reads the receipt that an archived Session's
// cancellation still owes a connection's delivery. nil drains nothing.
ArchivedCancellations ArchivedCancellationStore
// PublicWSURL is the wss://... URL returned in the bootstrap
// response so deployments behind a TLS terminator can advertise
// the externally-reachable URL.
PublicWSURL string
// OwnerStore enables multi-pod WebSocket ownership. When set, every
// successful daemon WS dial-in claims device_id -> owner_pod_id in
// Postgres and receives a generation fencing token. nil preserves
// the legacy single-pod in-memory Registry behavior.
OwnerStore DeviceOwnerStore
OwnerPodID string
OwnerURL string
// OwnerLeaseTTL controls how long the owner row stays valid without
// a renewing inbound daemon frame. Zero uses the package default.
OwnerLeaseTTL time.Duration
// HeartbeatInterval overrides DefaultHeartbeatInterval. Zero -> default.
HeartbeatInterval time.Duration
// Log is the gateway's leveled-ish log sink. nil silences logs.
Log SessionLogger
}
HandlerConfig wires the gateway's HTTP/WS handlers. nil values panic on use; the gateway only ever runs in a fully-configured production server, so loud failure beats silent fall-through.
type HeartbeatTouch ¶
type HeartbeatTouch interface {
TouchRuntimeHeartbeat(ctx context.Context, runtimeID string) (runtimedevice.HeartbeatStatus, error)
TouchAgentDaemonHeartbeat(ctx context.Context, input runtimedevice.Heartbeat) (runtimedevice.HeartbeatStatus, error)
}
HeartbeatTouch is the persistence interface the gateway uses to bump last_heartbeat_at / promote pending_pairing -> online when a daemon connects.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry is the process-wide map of live daemon sessions. It is concurrency-safe; readers and writers live in different goroutines. Four O(1) indexes are maintained: byDevice (primary), byRun (per Subscribe), byPerm (per permission_request), byAsk (per prompt_for_user_choice).
func NewRegistry ¶
func NewRegistry() *Registry
NewRegistry returns an empty registry. The zero value would also work but the constructor avoids accidental nil-map panics.
func (*Registry) AttachPermission ¶
AttachPermission records a permID -> session mapping so a later SubmitPermission can route the decision frame to the right device.
func (*Registry) AttachPromptForUserChoice ¶
AttachPromptForUserChoice records askID → session so a later SubmitPromptForUserChoice can route the decision back to the right daemon. Mirrors AttachPermission.
func (*Registry) Deregister ¶
Deregister removes a device's session if it matches the one currently registered. Caller passes the *Session pointer so a stale goroutine that wakes up after a reconnect can't evict the new session.
func (*Registry) DetachPermission ¶
DetachPermission clears the permID -> session mapping. Idempotent.
func (*Registry) DetachPromptForUserChoice ¶
DetachPromptForUserChoice clears the askID → session mapping. Idempotent.
func (*Registry) LookupDevice ¶
LookupDevice returns the registered session for a device, or ErrDeviceNotRegistered when the device has never dialled in / has dropped.
func (*Registry) LookupPermission ¶
LookupPermission returns the session that owns a pending permID, or ErrPermissionNotRegistered when the permission has expired / been cancelled.
func (*Registry) LookupPromptForUserChoice ¶
LookupPromptForUserChoice returns the session that owns a pending askID, or ErrPromptForUserChoiceNotRegistered when the ask has expired or been cancelled.
func (*Registry) LookupRun ¶
LookupRun returns the session currently handling a runID, or nil when the run has not been subscribed yet / has completed.
func (*Registry) PendingWaiters ¶
PendingWaiters returns the pending WaitForDevice waiter channels for a given deviceID. Diagnostics only.
func (*Registry) Register ¶
Register adds a freshly-upgraded session under its deviceID. The latest dial-in wins: if a session was already registered for that device, the old one's run/perm indexes are evicted (the caller closes the displaced *Session).
func (*Registry) WaitForDevice ¶
func (r *Registry) WaitForDevice(ctx context.Context, deviceID string, timeout time.Duration) (*Session, error)
WaitForDevice blocks until a session for deviceID is registered, or until (timeout, ctx) bound expires. Returns the *Session on success.
Fast path returns immediately if already registered. Slow path registers a buffered(1) channel under r.waiters[deviceID] which Register drains the moment a matching session arrives. timeout of 0 means "use the context deadline only".
type RuntimeStore ¶
type RuntimeStore interface {
GetDeviceCredential(ctx context.Context, runtimeID string) (runtimedevice.Credential, bool, error)
}
RuntimeStore supplies device credentials without exposing product runtime records.
type Session ¶
type Session struct {
DeviceID string
WorkspaceID string
DaemonVersion string
ConnectedAt time.Time
// contains filtered or unexported fields
}
Session owns one goroutine for the read loop and serialises writes via a single send goroutine so callers can Send concurrently without violating gorilla's "single writer" requirement.
func NewSession ¶
func NewSession(conn WSConn, deviceID, workspaceID, daemonVersion string, reg *Registry, log SessionLogger) *Session
NewSession wires a freshly-upgraded WS connection into a Session. The session does NOT start its goroutines automatically — Start runs once the handler is ready so the session can't race with response writes.
func NewSessionWithOwner ¶
func NewSessionWithOwner(conn WSConn, deviceID, workspaceID, daemonVersion string, reg *Registry, log SessionLogger, owner *ownerLease) *Session
NewSessionWithOwner wires a session with an optional DB-backed owner lease. Multi-pod deployments pass the lease returned by ClaimAgentDaemonDeviceOwner so heartbeats can fence stale connections.
func (*Session) AgentKindStatus ¶
func (s *Session) AgentKindStatus(kind string) (info runtimedevice.SupportedAgentKind, found bool, snapshotKnown bool)
AgentKindStatus returns the latest advertised descriptor for kind. found=false means the daemon has not advertised that kind; snapshotKnown distinguishes "no heartbeat yet" from "heartbeat arrived and omitted it".
func (*Session) AuthenticatedWith ¶
AuthenticatedWith compares the credential digest captured by the HTTP upgrade. The digest is never accepted from a daemon frame.
func (*Session) Close ¶
Close closes the transport and subscriptions with ErrSessionClosed, then releases connection ownership. It establishes no execution outcome. Idempotent.
func (*Session) CloseWithCode ¶
CloseWithCode sends a WS close frame with a custom status code so permanent conditions (e.g. runtime deleted) can be distinguished from transient disconnects.
func (*Session) Closed ¶
func (s *Session) Closed() <-chan struct{}
Closed returns a channel that's closed once the session has shut down.
func (*Session) DrainArchivedCancellation ¶
DrainArchivedCancellation checks both durable archive identity and this exact connection's unfinished delivery. It performs no liveness or credential write.
func (*Session) ExportWorkspaceOutputs ¶
func (s *Session) ExportWorkspaceOutputs(ctx context.Context, request proto.WorkspaceExportPayload, consume func(io.Reader) error) error
ExportWorkspaceOutputs consumes bounded chunks and requires the exporter completion receipt.
func (*Session) ListWorkspaceDirectory ¶
func (s *Session) ListWorkspaceDirectory(ctx context.Context, request proto.WorkspaceReadPayload) (proto.WorkspaceReadResultPayload, error)
func (*Session) PrepareRuntime ¶
func (s *Session) PrepareRuntime(ctx context.Context, id string, request proto.RuntimePreparePayload, data []byte) (proto.RuntimePrepareResultPayload, error)
PrepareRuntime sends one typed preparation operation once. An interrupted or unconfirmed transfer reports unknown; callers must not replay it.
func (*Session) ReadWorkspaceFile ¶
func (s *Session) ReadWorkspaceFile(ctx context.Context, request proto.WorkspaceReadPayload) (proto.WorkspaceReadResultPayload, error)
ReadWorkspaceFile observes one private operation; cancellation never retries or cancels native work.
func (*Session) Send ¶
Send queues an envelope for the WS write loop. Returns ErrSessionClosed if the session has shut down, or context.DeadlineExceeded if the send queue is full for longer than ctx's timeout.
Side effect: stamps env.Trace from ctx if absent, so every server → daemon frame inherits the caller's trace_id. Callers that explicitly set env.Trace win.
func (*Session) SendAndWaitInteractionAck ¶
func (s *Session) SendAndWaitInteractionAck(ctx context.Context, env proto.Envelope, deliveryID string) (proto.InteractionDecisionAckPayload, error)
SendAndWaitInteractionAck sends a decision and waits until the daemon confirms that its agent session applied it. Queueing or writing the WebSocket frame alone is not success: without this receipt the canonical database interaction must remain retryable.
func (*Session) Start ¶
func (s *Session) Start()
Start kicks off the read + write loops. The caller MUST eventually call Close (or wait for the read loop to fail) before *Session is GC-eligible.
func (*Session) SubscribeDurable ¶
func (s *Session) SubscribeDurable(runID string) (*Subscription, error)
SubscribeDurable reports transport loss and overflow separately from native execution events. Callers must inspect Err after Events closes.
func (*Session) SubscribePreparation ¶
func (s *Session) SubscribePreparation(requestID string) (*Subscription, error)
SubscribePreparation correlates private control responses without registering a Run. Unsubscribe on abandonment; a terminal resource status closes the stream. This subscription belongs to this physical daemon connection only.
func (*Session) SuspendControl ¶
func (s *Session) SuspendControl(ctx context.Context, kind string, request proto.EnvironmentSuspendPayload) (proto.EnvironmentSuspendResultPayload, error)
SuspendControl correlates one lifecycle operation on this authenticated socket. A closed socket is not an acknowledgement; callers retain their durable intent.
func (*Session) TrackExecutionDelivery ¶
TrackExecutionDelivery retains the exact existing Core delivery through its terminal database commit. Durable subscriptions may already have seen Done or been removed while cancellation ACK/commit is still pending.
func (*Session) Unsubscribe ¶
func (*Session) UnsubscribePreparation ¶
func (*Session) WriteWorkspaceFile ¶
func (s *Session) WriteWorkspaceFile(ctx context.Context, id string, request proto.WorkspaceWritePayload, data []byte) (proto.WorkspaceWriteResultPayload, error)
WriteWorkspaceFile sends an already durably owned mutation once. A transport error is not a rejection and must retain the caller's unknown-outcome gate.
type SessionLogger ¶
SessionLogger is the minimal logging surface a session needs. Pass nil to silence logs.
type Subscription ¶
func (*Subscription) Err ¶
func (s *Subscription) Err() error
type WSConn ¶
type WSConn interface {
ReadMessage() (int, []byte, error)
WriteMessage(messageType int, data []byte) error
WriteControl(messageType int, data []byte, deadline time.Time) error
SetReadLimit(limit int64)
SetReadDeadline(t time.Time) error
SetWriteDeadline(t time.Time) error
Close() error
}
WSConn is the slice of *websocket.Conn the session uses, exported so cross-package tests can substitute a fake without a real WS upgrader.