runtimegateway

package
v0.0.13 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2026 License: MIT Imports: 19 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 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 → Session for routing.

The package deliberately does NOT depend on the connector implementation — the connector imports it, not the other way around.

Index

Constants

This section is empty.

Variables

View Source
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
	// function result or cancellation 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.

View Source
var ErrAuthBadCredential = errors.New("agentdaemon auth: bad credential")

ErrAuthBadCredential folds "no credential on row" together with "wrong credential" so probes can't distinguish them.

View Source
var ErrAuthIncompatibleVersion = errors.New("agentdaemon auth: incompatible protocol version")
View Source
var ErrAuthMissingParams = errors.New("agentdaemon auth: missing device_id / token / version")
View Source
var ErrAuthUnknownDevice = errors.New("agentdaemon auth: unknown device")
View Source
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.

View Source
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.

View Source
var ErrSessionClosed = errors.New("agentdaemon gateway: session closed")

ErrSessionClosed is returned by Send / Subscribe when the session has shut down.

View Source
var ErrSubscriberOverflow = errors.New("execution subscriber buffer overflow")
View Source
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

func RegisterRoutes(r chi.Router, h *Handler)

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

Both accept the daemon credential described in contracts/agents-api/machine-api.md.

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
	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 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 with its credential. 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) WS

func (h *Handler) WS(w http.ResponseWriter, r *http.Request)

WS is the websocket upgrade entry point. Errors before the upgrade return JSON 4xx; errors during the WS read loop fall to Session.Close which closes subscriptions with a transport error, without execution events.

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 marks the runtime 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

	// 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 and mark the runtime 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. Two O(1) indexes are maintained: byDevice (primary) and byRun (per Subscribe).

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) Announced added in v0.0.13

func (r *Registry) Announced() <-chan struct{}

Announced signals after a session first reports its agent kinds. Polling recovers a coalesced signal.

func (*Registry) AttachRun

func (r *Registry) AttachRun(runID string, sess *Session)

AttachRun adds the runID -> session mapping. Idempotent.

func (*Registry) Deregister

func (r *Registry) Deregister(sess *Session)

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) DetachRun

func (r *Registry) DetachRun(runID string)

DetachRun removes a runID -> session mapping.

func (*Registry) Devices

func (r *Registry) Devices() []string

Devices returns a snapshot of registered device ids in arbitrary order.

func (*Registry) LookupDevice

func (r *Registry) LookupDevice(deviceID string) (*Session, error)

LookupDevice returns the registered session for a device, or ErrDeviceNotRegistered when the device has never dialled in / has dropped.

func (*Registry) LookupRun

func (r *Registry) LookupRun(runID string) *Session

LookupRun returns the session currently handling a runID, or nil when the run has not been subscribed yet / has completed.

func (*Registry) PendingWaiters

func (r *Registry) PendingWaiters(deviceID string) []chan *Session

PendingWaiters returns the pending WaitForDevice waiter channels for a given deviceID. Diagnostics only.

func (*Registry) Register

func (r *Registry) Register(sess *Session) (previous *Session)

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 index entries are evicted (the caller closes the displaced *Session).

func (*Registry) UnwatchDevice added in v0.0.10

func (r *Registry) UnwatchDevice(deviceID string, ch chan *Session)

UnwatchDevice purges a waiter channel from the pending list. Safe to call after Register has already drained the slice. Idempotent.

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".

func (*Registry) WatchDevice added in v0.0.10

func (r *Registry) WatchDevice(deviceID string, ch chan *Session)

WatchDevice arms a one-shot registration notification without waiting. The caller owns a buffered channel and must not close it while watched. Multiple devices may share a channel to coalesce notifications; consumers then recheck every watched device. Re-arming the same device/channel pair is idempotent.

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
	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, 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 (*Session) AgentKindStatus

func (s *Session) AgentKindStatus(kind string) (info proto.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

func (s *Session) AuthenticatedWith(digest string) bool

AuthenticatedWith compares the credential digest captured by the HTTP upgrade. The digest is never accepted from a daemon frame.

func (*Session) Close

func (s *Session) Close(reason string)

Close closes the transport and subscriptions with ErrSessionClosed, then releases connection ownership. It establishes no execution outcome. Idempotent.

func (*Session) CloseWithCode

func (s *Session) CloseWithCode(code int, reason string)

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

func (s *Session) DrainArchivedCancellation(ctx context.Context) (bool, error)

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) IsClosed

func (s *Session) IsClosed() bool

IsClosed reports whether Close has been called.

func (*Session) LastSeen

func (s *Session) LastSeen() time.Time

LastSeen returns the timestamp of the most recent inbound frame.

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

ReadWorkspaceFile observes one private operation; cancellation never retries or cancels native work.

func (*Session) Send

func (s *Session) Send(ctx context.Context, env proto.Envelope) error

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 durable delivery 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

SuspendControl correlates one lifecycle operation on this authenticated socket. A closed socket is not an acknowledgement; callers retain their durable intent.

func (*Session) TrackExecutionDelivery

func (s *Session) TrackExecutionDelivery(runID string) (func(), error)

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 (s *Session) Unsubscribe(runID string)

func (*Session) UnsubscribePreparation

func (s *Session) UnsubscribePreparation(requestID string)

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

type SessionLogger func(format string, args ...any)

SessionLogger is the minimal logging surface a session needs. Pass nil to silence logs.

type Subscription

type Subscription struct {
	Events <-chan proto.Envelope
	// contains filtered or unexported fields
}

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.

Jump to

Keyboard shortcuts

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