server

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

Documentation

Overview

Package server serves a session.Runtime over host-defined wire protocols.

Protocol is the extension point. Implement it to own HTTP routes and WebSocket, stream framing, and HITL resume. The ACP built-in is package server/acp. More protocols can be mounted on the same Server:

srv := server.NewServer(rt, agent, acp.New(nil), myProtocol{})
_ = srv.ServeHTTP(ctx, addr)

The program on the other end of a connection is the caller's. This module does not ship that program. A protocol asks it through Conn.Ask.

RunTurn pumps Runtime.Prompt/Resume/Subscribe through Protocol.OnStreamEvent and OnStreamClosed. A protocol parses its own credential payload and stores the bindings on session.CredentialBag. Runtime, harness, VFS, and Temporal do not import this package.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrAuthenticationRequired means no authenticated principal is available.
	ErrAuthenticationRequired = errors.New("authentication required")
	// ErrAuthenticationFailed means supplied credentials were rejected.
	ErrAuthenticationFailed = errors.New("authentication failed")
	// ErrAuthorizationDenied means the principal cannot perform an operation.
	ErrAuthorizationDenied = errors.New("authorization denied")
)
View Source
var (
	ErrInvalidRequest  = errors.New("invalid request")
	ErrMethodNotFound  = errors.New("method not found")
	ErrInternal        = errors.New("internal server error")
	ErrSessionNotFound = session.ErrSessionNotFound
)

Wire-facing sentinels. Session errors are the owning package's sentinels (same pointer) so errors.Is is one check. Authentication sentinels live in auth.go.

View Source
var ErrNetworkSecurityPolicyRequired = errors.New("server: configure security or explicitly allow anonymous network access")

ErrNetworkSecurityPolicyRequired prevents accidental anonymous listeners.

Functions

func ErrorCause added in v0.4.0

func ErrorCause(sentinel, cause error, format string, args ...any) error

ErrorCause is Errorf with an underlying cause for errors.Is.

func Errorf added in v0.4.0

func Errorf(sentinel error, format string, args ...any) error

Errorf is a caller-facing error that unwraps to sentinel.

func IsClientError

func IsClientError(err error) bool

func PublicError

func PublicError(err error) error

PublicError returns a wire-safe error: client errors pass through unchanged; all other errors become ErrInternal so internal details are not leaked.

func RunTurn added in v0.2.0

func RunTurn(
	ctx context.Context,
	env ProtocolEnv,
	proto Protocol,
	threadID string,
	reqID json.RawMessage,
	prompt PromptOrResume,
) error

RunTurn pumps Runtime.Prompt or Resume, then Subscribe, through proto's stream policy.

Types

type Ask added in v0.4.0

type Ask interface {
	Ready(ctx context.Context) error
	NoteHello(params json.RawMessage)
	FormSupported() bool
	Permission(ctx context.Context, sessionID, messageID string, perm tacklr.ToolPermissionInterrupt) (resolution []byte, cancelled bool, err error)
	Elicit(ctx context.Context, sessionID, messageID, question string, opts []tacklr.UserChoice) (action string, resolution []byte, err error)
}

Ask is how the active protocol reaches the program on the other end of the connection during a turn. That program belongs to the caller. This package does not implement it. A nil Ask cannot answer mid-turn.

type Attempt added in v0.4.0

type Attempt struct {
	Scheme     string
	Credential Secret
	Binding    ChannelBinding
}

Attempt is the canonical input to a host Authenticator.

type Authenticator added in v0.4.0

type Authenticator interface {
	Authenticate(context.Context, Attempt) (Principal, error)
}

Authenticator verifies an authentication attempt supplied by a protocol or transport adapter.

type Authorizer added in v0.4.0

type Authorizer interface {
	Authorize(context.Context, Principal, Operation) error
}

Authorizer decides whether a principal can perform an operation.

type ChannelBinding added in v0.4.0

type ChannelBinding struct {
	Kind string
	ID   string
}

ChannelBinding identifies the logical channel on which authentication occurred. Values are transport-neutral and contain no credential material.

type Conn

type Conn struct {
	Writer      MessageWriter
	Ask         Ask
	Security    *Context
	SetSecurity func(Context)
}

Conn is one connection for the turn that is running now.

func (*Conn) EstablishSecurity added in v0.4.0

func (c *Conn) EstablishSecurity(securityContext Context)

EstablishSecurity stores the authenticated context and notifies SetSecurity.

type Connection

type Connection struct {
	ID     string
	Writer MessageWriter
	// contains filtered or unexported fields
}

Connection is one WebSocket. Harness sessions live on session.Runtime.

func (*Connection) Context

func (c *Connection) Context() context.Context

Context is cancelled when the connection is removed.

func (*Connection) SecurityContext added in v0.4.0

func (c *Connection) SecurityContext() Context

func (*Connection) SetSecurityContext added in v0.4.0

func (c *Connection) SetSecurityContext(securityContext Context)

type ConnectionRegistry

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

ConnectionRegistry tracks live ACP WebSockets by Acp-Connection-Id.

func NewConnectionRegistry

func NewConnectionRegistry() *ConnectionRegistry

NewConnectionRegistry returns an empty registry.

func (*ConnectionRegistry) Create

func (r *ConnectionRegistry) Create(writer MessageWriter) *Connection

Create registers a new connection. Writer may be filled in after Accept.

func (*ConnectionRegistry) Get

func (r *ConnectionRegistry) Get(id string) *Connection

Get returns the connection for id, or nil.

func (*ConnectionRegistry) Remove

func (r *ConnectionRegistry) Remove(id string)

Remove deletes the connection and cancels its context.

type Context added in v0.4.0

type Context struct {
	Principal Principal
	Binding   ChannelBinding
}

Context is the authenticated state propagated through server connections.

func (Context) Authenticated added in v0.4.0

func (c Context) Authenticated() bool

Authenticated reports whether this context contains a valid principal.

type HTTPAttemptExtractor added in v0.2.0

type HTTPAttemptExtractor func(*http.Request) (Attempt, bool)

HTTPAttemptExtractor translates transport credential evidence into the protocol-neutral security model. It is an edge adapter, not part of the core.

type HTTPRoute

type HTTPRoute struct {
	Method               string // e.g. "POST"
	Pattern              string // e.g. "/acp"
	AllowUnauthenticated bool
	Handler              func(env ProtocolEnv, w http.ResponseWriter, r *http.Request)
}

HTTPRoute is one HTTP endpoint owned by a Protocol.

type MemoryWireStore

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

MemoryWireStore is an in-process ProtocolWireStore.

func NewMemoryWireStore

func NewMemoryWireStore() *MemoryWireStore

NewMemoryWireStore returns an empty in-memory wire store.

func (*MemoryWireStore) Delete

func (s *MemoryWireStore) Delete(_ context.Context, sessionID string) error

func (*MemoryWireStore) Get

func (s *MemoryWireStore) Get(_ context.Context, sessionID string) ([]byte, error)

func (*MemoryWireStore) Put

func (s *MemoryWireStore) Put(_ context.Context, sessionID string, payload []byte) error

type MessageWriter

type MessageWriter interface {
	WriteResult(id json.RawMessage, result any) error
	// WriteError writes a failure. Implementations must not leak internal details.
	WriteError(id json.RawMessage, err error) error
	WriteFrame(data []byte) error
}

MessageWriter is the sink a Protocol uses for results and streamed frames. Each protocol supplies an implementation for its own wire.

type Operation added in v0.4.0

type Operation struct {
	Action   string
	Resource string
}

Operation is a protocol-neutral authorization request.

type PostgresWireStore

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

PostgresWireStore implements ProtocolWireStore against Postgres. Call Setup once per database. Shares a *pgx.Conn with a brain store when desired; the table is separate from harness session checkpoints.

func NewPostgresWireStore

func NewPostgresWireStore(conn *pgx.Conn, protocolKey string) *PostgresWireStore

NewPostgresWireStore wraps an existing pgx connection. protocolKey labels rows (e.g. "acp"); empty defaults to "acp".

func (*PostgresWireStore) Delete

func (s *PostgresWireStore) Delete(ctx context.Context, sessionID string) error

func (*PostgresWireStore) Get

func (s *PostgresWireStore) Get(ctx context.Context, sessionID string) ([]byte, error)

func (*PostgresWireStore) Put

func (s *PostgresWireStore) Put(ctx context.Context, sessionID string, payload []byte) error

func (*PostgresWireStore) Setup added in v0.2.0

func (s *PostgresWireStore) Setup(ctx context.Context) error

Setup creates public.protocol_wire_session (idempotent).

type Principal added in v0.4.0

type Principal struct {
	Subject string
}

Principal is the stable, opaque identity returned by a host Authenticator. Subject must be stable across reconnects when durable sessions can be loaded.

func NewPrincipal added in v0.4.0

func NewPrincipal(subject string) (Principal, error)

NewPrincipal constructs a Principal and rejects an empty subject.

func (Principal) Valid added in v0.4.0

func (p Principal) Valid() bool

Valid reports whether the principal has a stable subject.

type PromptOrResume added in v0.2.0

type PromptOrResume struct {
	Prompt session.Prompt
	Resume *session.Resume
	After  session.Seq
}

PromptOrResume is one protocol turn against Runtime.

type Protocol

type Protocol interface {
	// HandleInbound decodes one connection-oriented body (WebSocket).
	// HTTP-route-only protocols may return nil.
	HandleInbound(ctx context.Context, env ProtocolEnv, body []byte) error
	HTTPRoutes() []HTTPRoute

	OnStreamEvent(ctx context.Context, env ProtocolEnv, threadID string, ev tacklr.StreamEvent, reqID json.RawMessage) StreamControl
	OnStreamClosed(ctx context.Context, env ProtocolEnv, threadID string, reqID json.RawMessage, cancelled bool) error
}

Protocol is the host extension point for streaming and delivery over session.Runtime.

The ACP built-in is package server/acp. Hosts implement Protocol to define their own wire: HTTP/WebSocket routes, frame encoding, and HITL resume. The kernel does not import protocol types. Parse wire credentials into vfs.Binding values and store them on a session.CredentialBag. Put bag.Take() on Prompt or Resume. Call RunTurn to pump Runtime.Subscribe through OnStreamEvent.

type ProtocolEnv

type ProtocolEnv struct {
	Runtime session.Runtime
	Agent   tacklr.AgentOptions
	Conn    *Conn
	// Security is protocol-neutral. Implementations map wire credentials into
	// this service and store the resulting Context on Conn.
	Security *Service
	// Connections is optional connection tracking (ACP WebSocket uses it).
	// Custom protocols may leave it unused.
	Connections *ConnectionRegistry
}

ProtocolEnv is the domain + connection context passed into protocol handlers.

type ProtocolWireStore

type ProtocolWireStore interface {
	Put(ctx context.Context, sessionID string, payload []byte) error
	Get(ctx context.Context, sessionID string) ([]byte, error)
	Delete(ctx context.Context, sessionID string) error
}

ProtocolWireStore persists protocol-owned session envelopes (not harness checkpoints). Payload is opaque JSON defined by each protocol. May share a database connection with other Tacklr stores without sharing schema.

type Secret added in v0.4.0

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

Secret is ephemeral credential material. Its String and GoString methods are deliberately redacted so ordinary structured logging cannot reveal it.

func NewSecret added in v0.4.0

func NewSecret(value []byte) Secret

NewSecret copies credential material into a redaction-safe value.

func (Secret) Bytes added in v0.4.0

func (s Secret) Bytes() []byte

Bytes returns a copy for a host Authenticator.

func (Secret) Empty added in v0.4.0

func (s Secret) Empty() bool

Empty reports whether no credential material is present.

func (Secret) GoString added in v0.4.0

func (Secret) GoString() string

func (Secret) String added in v0.4.0

func (Secret) String() string

type Server

type Server struct {
	Runtime   session.Runtime
	Agent     tacklr.AgentOptions
	Protocols []Protocol
	// Connections tracks ACP WebSocket connections.
	// Custom protocols may ignore it.
	Connections *ConnectionRegistry
	// Security is protocol-neutral authentication and authorization supplied by the host.
	Security *Service
	// HTTPAttempt translates request credentials at the HTTP transport edge.
	HTTPAttempt HTTPAttemptExtractor
	// contains filtered or unexported fields
}

Server serves a session.Runtime over HTTP, with WebSocket when the request upgrades. Protocols is the ordered list of wire implementations (ACP and/or host protocols).

func NewServer

func NewServer(rt session.Runtime, agent tacklr.AgentOptions, protocols ...Protocol) *Server

NewServer wraps a Runtime and one or more Protocols. The ACP built-in is acp.New. Pass more Protocols to mount them on the same mux.

func (*Server) AllowAnonymousNetwork added in v0.2.0

func (s *Server) AllowAnonymousNetwork() *Server

AllowAnonymousNetwork explicitly enables unauthenticated network serving. It is intended for local development and trusted private environments.

func (*Server) HTTPMux

func (s *Server) HTTPMux() *http.ServeMux

HTTPMux mounts every Protocol's HTTP routes. Used by ServeHTTP and tests.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(ctx context.Context, addr string) error

ServeHTTP starts an HTTP server mounting all protocol routes.

func (*Server) WithSecurity added in v0.2.0

func (s *Server) WithSecurity(service *Service, extract HTTPAttemptExtractor) *Server

WithSecurity installs host authentication and optional HTTP credential extraction. Protocol-native flows such as ACP authenticate can use service without an extractor.

type Service added in v0.4.0

type Service struct {
	Authenticator Authenticator
	Authorizer    Authorizer
}

Service coordinates host-provided authentication and authorization without knowing how any protocol represents credentials or errors.

func (*Service) Authenticate added in v0.4.0

func (s *Service) Authenticate(ctx context.Context, attempt Attempt) (Context, error)

Authenticate delegates to the host and validates its returned invariant.

func (*Service) Authorize added in v0.4.0

func (s *Service) Authorize(ctx context.Context, securityContext Context, operation Operation) error

Authorize requires an authenticated principal and delegates to the optional host policy. No Authorizer means every authenticated principal is allowed.

type StreamControl

type StreamControl struct {
	Frames   [][]byte
	Resume   map[string][]byte
	Finished bool
	Err      error
}

StreamControl is the protocol's decision after observing one harness event.

Directories

Path Synopsis
Package acp is the Agent Client Protocol built into the server.
Package acp is the Agent Client Protocol built into the server.

Jump to

Keyboard shortcuts

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