Documentation
¶
Overview ¶
Package gateway provides an embeddable Human Agent model gateway.
Open assembles the supported SQLite store, model-compatible HTTP handlers, and worker WebSocket transport without owning a TCP listener. Applications can use Server directly as an http.Handler, or mount ModelHandler and WorkerHandler in their own router and authentication perimeter.
Index ¶
- Constants
- Variables
- type Authenticator
- type AuthenticatorFunc
- type CapabilityTier
- type Config
- type IssuedToken
- type PreparedToken
- type Principal
- type PrincipalType
- type RateLimitConfig
- type Server
- func (server *Server) ActivateToken(ctx context.Context, prepared PreparedToken) error
- func (server *Server) Close() error
- func (server *Server) Issue(ctx context.Context, principalType PrincipalType, subjectID string) (IssuedToken, error)
- func (server *Server) ModelHandler() http.Handler
- func (server *Server) PrepareToken(principalType PrincipalType, subjectID string) (PreparedToken, error)
- func (server *Server) Revoke(ctx context.Context, keyID string) error
- func (server *Server) RevokeToken(ctx context.Context, secret, expectedKeyID string) error
- func (server *Server) ServeHTTP(response http.ResponseWriter, request *http.Request)
- func (server *Server) ValidateToken(ctx context.Context, secret string) (Principal, error)
- func (server *Server) WorkerHandler() http.Handler
- type WorkerRouteRequest
- type WorkerRouter
- type WorkerRouterFunc
- type WorkerTransportConfig
Constants ¶
const WorkerPath = "/internal/v1/worker/ws"
WorkerPath is the worker WebSocket route mounted by Server.ServeHTTP.
Variables ¶
var ( // application principal is present on the request. ErrUnauthorized = errors.New("unauthorized") // ErrBuiltInAuthDisabled reports that token administration was requested // from a Server configured to use an application's custom authenticator. ErrBuiltInAuthDisabled = errors.New("built-in token authentication is disabled") // ErrCredentialMismatch reports that a token does not own the key ID an // application expected. Conditional revocation returns this error without // revoking either the supplied token or the unrelated key ID. ErrCredentialMismatch = errors.New("credential does not match expected key ID") // ErrWorkerRouteDenied is returned by a WorkerRouter when an authenticated // caller is not permitted to create a task on any worker. It produces a // finite 403 and is distinct from an offline selected worker or router // infrastructure failure. ErrWorkerRouteDenied = errors.New("worker route denied") // ErrDatabaseInUse prevents two gateway runtimes from recovering and serving // the same single-instance SQLite state through independent in-memory hubs. ErrDatabaseInUse = errors.New("gateway database is already held by another running instance") )
Functions ¶
This section is empty.
Types ¶
type Authenticator ¶
Authenticator lets an application use its existing cookie, JWT, mTLS, or upstream identity system. It receives the complete HTTP request, including its context. Returning an error rejects the request.
type AuthenticatorFunc ¶
AuthenticatorFunc adapts a function to Authenticator.
func (AuthenticatorFunc) AuthenticateRequest ¶
func (function AuthenticatorFunc) AuthenticateRequest(request *http.Request) (Principal, error)
AuthenticateRequest implements Authenticator.
type CapabilityTier ¶
type CapabilityTier string
CapabilityTier is the caller-side capability contract presented to worker routing policy.
const ( CapabilityChat CapabilityTier = "chat" CapabilityRemoteTools CapabilityTier = "remote_tools" CapabilityWorkspace CapabilityTier = "workspace" )
type Config ¶
type Config struct {
DatabasePath string
Models []string
QueueCapacity int
MaxBodyBytes int64
MaxWorkerMessageBytes int64
HeartbeatInterval time.Duration
// StreamWriteTimeout bounds one SSE write plus flush. It is reset after
// every successful emission and never acts as a whole-stream timeout.
StreamWriteTimeout time.Duration
MaxPending time.Duration
RateLimit RateLimitConfig
Worker WorkerTransportConfig
AuditPayload bool
AuditPayloadTTL time.Duration
ReplayPayloadGrace time.Duration
RetentionSweepInterval time.Duration
DisableCodexAutoIdempotency bool
// Authenticator replaces built-in bearer/X-Api-Key authentication. When
// set, Issue and Revoke return ErrBuiltInAuthDisabled.
Authenticator Authenticator
// WorkerRouter binds each new task to an exact worker subject using the
// embedding application's tenant and authorization policy. The chosen
// subject is durable task affinity across continuations and recovery.
WorkerRouter WorkerRouter
Logger *slog.Logger
}
Config controls an embedded gateway. SQLite is deliberately the only store implementation exposed in this release; internal persistence contracts are not presented as a stable public driver API.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns protocol and runtime defaults for one gateway. DatabasePath is deliberately empty: an embedder must choose its persistence identity explicitly instead of accidentally sharing a process-global user database with an unrelated embedded gateway. The standalone and local CLI compositions supply their own private OS user-data paths.
type IssuedToken ¶
IssuedToken is returned once when the built-in token service creates a credential. Only its hash is retained in SQLite.
type PreparedToken ¶
type PreparedToken struct {
KeyID string
Secret string
Type PrincipalType
SubjectID string
}
PreparedToken is a built-in credential that has been generated but is not yet accepted by the gateway. Persist it in a private durable journal before calling ActivateToken to make credential rotation recoverable across a process crash. Secret must be treated like any other plaintext API token.
type Principal ¶
type Principal struct {
Type PrincipalType
SubjectID string
KeyID string
}
Principal is the authenticated identity supplied by an embedding application. SubjectID and a non-empty KeyID must match the durable-key grammar [A-Za-z0-9][A-Za-z0-9._:-]{0,127}. KeyID is an optional stable credential/session identifier used for admission limiting and audit metadata; when empty, the gateway derives one from the type and subject.
type PrincipalType ¶
type PrincipalType string
PrincipalType identifies which side of the Human Agent protocol a principal may use. Callers access model endpoints; workers access the private worker WebSocket endpoint.
const ( PrincipalCaller PrincipalType = "caller" PrincipalWorker PrincipalType = "worker" )
type RateLimitConfig ¶
RateLimitConfig controls per-credential admission. Zero fields select the documented defaults.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server owns the embedded SQLite store and protocol components. It does not own a listener; the embedding application controls routing and shutdown of its HTTP server.
func Open ¶
Open initializes, purges, and recovers an embedded gateway. The returned Server is ready to serve HTTP. Canceling ctx stops background work and active completion sessions; call Close after the application's HTTP server has stopped accepting requests.
func (*Server) ActivateToken ¶
func (server *Server) ActivateToken(ctx context.Context, prepared PreparedToken) error
ActivateToken makes an exact prepared token authenticatable. Replaying the same prepared value succeeds, while a conflicting key, secret, type, or subject fails closed.
func (*Server) Close ¶
Close terminates and drains worker WebSockets, stops completion and retention work, waits for durable cleanup, and closes SQLite. The embedding application should still stop its HTTP server before calling Close so no new model handler can race store shutdown. Close is idempotent.
func (*Server) Issue ¶
func (server *Server) Issue( ctx context.Context, principalType PrincipalType, subjectID string, ) (IssuedToken, error)
Issue creates a built-in caller or worker token. It is unavailable when a custom Authenticator owns identity.
func (*Server) ModelHandler ¶
ModelHandler returns the model API handler for mounting in an application router. It serves /livez, /readyz, the readiness-compatible /healthz alias, /v1/models, /v1/chat/completions, /v1/messages, and /v1/responses.
func (*Server) PrepareToken ¶
func (server *Server) PrepareToken( principalType PrincipalType, subjectID string, ) (PreparedToken, error)
PrepareToken generates a built-in credential without inserting it into the authentication store. The returned secret cannot authenticate until the exact value is passed to ActivateToken.
func (*Server) Revoke ¶
Revoke revokes a built-in token by key ID. It is unavailable when a custom Authenticator owns identity.
func (*Server) RevokeToken ¶
RevokeToken conditionally revokes a built-in token only when the supplied secret currently authenticates as expectedKeyID. This prevents a stale or tampered credential file from revoking an unrelated key by ID alone.
func (*Server) ServeHTTP ¶
func (server *Server) ServeHTTP(response http.ResponseWriter, request *http.Request)
ServeHTTP serves the built-in worker route and all model routes.
func (*Server) ValidateToken ¶
ValidateToken authenticates a built-in token and returns its bound principal. It is useful to bind persisted local credentials to an expected type, subject, and key ID before using them. Invalid and revoked secrets return ErrUnauthorized. It is unavailable when a custom Authenticator owns identity.
func (*Server) WorkerHandler ¶
WorkerHandler returns the private worker WebSocket handler. Applications may mount it at a custom path; ServeHTTP mounts it at /internal/v1/worker/ws.
type WorkerRouteRequest ¶
type WorkerRouteRequest struct {
Request *http.Request
Caller Principal
Model string
CapabilityTier CapabilityTier
WorkspaceKey string
TaskID string
IdempotencyKey string
HarnessID string
HarnessVersion string
HarnessSessionID string
WorkspaceRoot string
ExecAllowed bool
}
WorkerRouteRequest is the complete policy input for the first completion in a task. Request is a clone of the authenticated HTTP request with a fresh, readable body. Caller is the authenticated principal; the remaining fields are decoded or validated protocol identity, never unauthenticated guesses. Continuations and recovery do not invoke the router: they retain the original durable worker owner.
type WorkerRouter ¶
type WorkerRouter interface {
RouteWorker(context.Context, WorkerRouteRequest) (string, error)
}
WorkerRouter chooses the exact worker SubjectID for a new task. Returning "" explicitly requests the gateway's deterministic default worker. Return ErrWorkerRouteDenied for a policy denial; other errors are treated as router failures and never fall back to another worker.
type WorkerRouterFunc ¶
type WorkerRouterFunc func(context.Context, WorkerRouteRequest) (string, error)
WorkerRouterFunc adapts a function to WorkerRouter.
func (WorkerRouterFunc) RouteWorker ¶
func (function WorkerRouterFunc) RouteWorker( ctx context.Context, request WorkerRouteRequest, ) (string, error)
RouteWorker implements WorkerRouter.