control

package
v0.44.0 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 28 Imported by: 0

Documentation

Overview

Package control owns the control surface's workspace policy and session registry. It decides which host directories a client may open as a session and resolves each request to the one canonical path that identifies it.

Index

Constants

View Source
const (
	// CoreServiceName opens configuration, SQLite, the provider registry, the
	// workspace policy, and the agent runtime.
	CoreServiceName = "control-core"

	// APIServiceName serves REST, the global WebSocket feed, and metrics over
	// what CoreServiceName opened.
	APIServiceName = "control-api"
)

Service names for the two control services. They live here rather than in either service because the dependency edge between them needs the other's name, and a service never imports a sibling service.

Variables

This section is empty.

Functions

func DialableAddress

func DialableAddress(listenAddress string) string

DialableAddress turns a configured listen address into one a client can connect to. A listener bound to every interface is written without a host, and that form cannot be dialed as written.

func LockStateDirectory added in v0.27.0

func LockStateDirectory(
	stateDirectory string,
) (func(context.Context), error)

LockStateDirectory takes the state directory for one controller and returns the function that gives it back.

SQLite alone does not stop a second controller from opening the same databases, and a second controller's startup recovery would mark the first one's running turns as interrupted. The lock is an advisory flock, so the kernel releases it when the process ends, crash included. It fails with commerr.ErrLockHeld while another controller holds the directory.

Types

type AdmissionWatcher added in v0.17.0

type AdmissionWatcher interface {
	WatchAdmission(
		sessionID uuid.UUID,
		requestID uuid.UUID,
		admitted func(),
	) func()
}

AdmissionWatcher reports when a session's worker admits a message.

It is an interface so the router depends on hearing about admission rather than on how worker events reach the controller.

type Core

type Core struct {
	Config    peenconfig.Config
	Upstreams []peenconfig.Upstream
	Runtime   *agent.Runtime
	Store     *session.Store
	Handle    *db.Handle
	Sessions  *Registry

	// AgentSpaces are the deployment's allowed agent spaces. The API reads
	// them so a client can see what it may name.
	AgentSpaces *worker.AgentSpaceSet

	// Workers supervises this controller's session workers. Shutdown stops
	// them through it, so no worker outlives the controller that launched it.
	Workers *supervisor.Supervisor

	// Turns routes an accepted client message to its session's worker. The
	// control plane routes work; it does not run the model loop.
	Turns *TurnRouter

	// Feed carries every committed feed row to the live feed, in sequence
	// order. control-core creates it and control-api registers the delivery
	// path, so a record is written before any client can see it.
	Feed *FeedPump

	Metrics *metrics.Metrics

	// MetricsStore writes observations to metrics.db. It is nil when that file
	// could not be opened, because telemetry never stops the controller.
	MetricsStore *metricsstore.Store
}

Core is the durable state and runtime that control-core opens and control-api serves. One controller owns exactly one Core.

type FeedPump added in v0.26.0

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

FeedPump carries every committed feed row from the durable store to the live feed, in sequence order, and reports when a session's worker admits a message.

It exists because the store signals that a session's feed gained rows, but it must not run the delivery read on the writer's own goroutine: a page read and a live broadcast both cost more than a SQLite write should wait for. One pump goroutine per session, single-flight, carries that work instead. control-core builds the pump over its store and service context, then control-api registers the sink once the WebSocket hub exists, the same handoff order the previous event relay used.

Reading and admission release do not depend on a sink. Before control-api registers one, the pump still reads every signalled page and releases the admissions it finds; it only has no live clients to hand the rows to.

func NewFeedPump added in v0.26.0

func NewFeedPump(ctx context.Context, store feedStore) *FeedPump

NewFeedPump builds a pump bound to ctx. Every pump goroutine stops when ctx ends, so callers pass their service context, never context.Background.

func (*FeedPump) SetSink added in v0.26.0

func (p *FeedPump) SetSink(sink FeedSink)

SetSink registers the live delivery path. Registering twice replaces it, which is what a restarted API service needs.

func (*FeedPump) Signal added in v0.26.0

func (p *FeedPump) Signal(sessionID uuid.UUID, first int64)

Signal notifies the pump that sessionID's feed gained rows starting at first. It is the function session.Store.SetFeedSignal calls, once per commit, strictly after the writing transaction returned nil.

The first signal a session receives sets its cursor to first-1, so a controller that starts with history already stored reads only new rows. Admission release must never wait on a client being able to watch, so Signal reads whether or not a sink is registered.

func (*FeedPump) WatchAdmission added in v0.26.0

func (p *FeedPump) WatchAdmission(
	sessionID uuid.UUID,
	requestID uuid.UUID,
	admitted func(),
) func()

WatchAdmission calls admitted once the session's worker admits the message sent under requestID.

A worker records userMessage.created for a message exactly when it admits it, whether the message starts a turn or joins the running turn's queue, and the record passes through this pump's delivery loop. admitted runs at most once, on the pump's session goroutine, so it must not block. The returned stop ends the watch and is safe to call after admitted has run.

type FeedSink added in v0.26.0

type FeedSink func(
	ctx context.Context,
	sessionID uuid.UUID,
	items []session.FeedItem,
)

FeedSink delivers one session's feed rows to live clients, in sequence order. The pump calls it once per page it reads, never out of order and never with a row skipped.

type Handoff

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

Handoff passes one Core from the service that opens it to the service that serves it.

Servicepack builds each service from a no-argument factory, so two services in one process cannot receive a shared dependency through a constructor. The dependency graph orders them, control-api after control-core, and the readiness gate makes the Core present before control-api runs. Await still blocks rather than trusting that order, so a misconfigured graph surfaces as a timeout instead of a nil dereference.

func NewHandoff

func NewHandoff() *Handoff

NewHandoff builds an empty handoff. Tests use one of these instead of the process-wide handoff so scenarios stay independent.

func SharedHandoff

func SharedHandoff() *Handoff

SharedHandoff returns the process-wide handoff between the control services.

func (*Handoff) Await

func (h *Handoff) Await(ctx context.Context) (*Core, error)

Await returns the published Core, blocking until control-core publishes one or the context ends.

func (*Handoff) Clear

func (h *Handoff) Clear()

Clear drops the published Core so the next controller in this process starts from nothing. control-core clears it as it shuts down, and tests clear it between scenarios.

func (*Handoff) Publish

func (h *Handoff) Publish(core *Core) error

Publish records the Core and releases every waiter. Publishing twice is a wiring bug, because one process runs one controller.

type InProcessEndpoint added in v0.27.0

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

InProcessEndpoint carries the listener a controller serves its API on when it must not be reachable from the network.

Servicepack builds control-api from a no-argument factory, so the one-shot command, which runs the controller inside its own process, sets the listener here before the services start. An empty endpoint means control-api binds PEEN_HTTP_LISTEN_ADDRESS and PEEN_METRICS_LISTEN_ADDRESS as usual.

func SharedInProcessEndpoint added in v0.27.0

func SharedInProcessEndpoint() *InProcessEndpoint

SharedInProcessEndpoint returns the process-wide in-process endpoint.

func (*InProcessEndpoint) Clear added in v0.27.0

func (e *InProcessEndpoint) Clear()

Clear returns the endpoint to the configured network listeners.

func (*InProcessEndpoint) Listener added in v0.27.0

func (e *InProcessEndpoint) Listener() net.Listener

Listener returns the in-process listener, or nil when none is set.

func (*InProcessEndpoint) Set added in v0.27.0

func (e *InProcessEndpoint) Set(listener net.Listener)

Set makes control-api serve on listener instead of the configured address. It must be called before the controller starts.

type OpenResult

type OpenResult struct {
	Session *models.Session
	Created bool
}

OpenResult reports the session a workspace resolved to and whether this call is what created it.

type ProtectedDirectories added in v0.20.0

type ProtectedDirectories struct {
	// State directories hold controller-only data: SQLite with every
	// transcript, audit logs, and worker sockets. A workspace may not equal,
	// contain, or sit inside one.
	State []string

	// Configuration directories reach every worker read-only already. A
	// workspace may not equal or contain one, because a workspace mount is
	// writable and would let one session rewrite the harness of every other.
	Configuration []string
}

ProtectedDirectories are the controller's own directories, which no workspace may expose.

A workspace is bind-mounted into a Docker worker. If a root such as $HOME holds the controller's directories, opening that root or a directory between it and them would hand one session every other session's data.

type Registry

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

Registry is the control surface's session registry. It is the only place a client-requested workspace becomes a durable session, so the workspace policy cannot be bypassed by reaching the store directly.

func NewRegistry

func NewRegistry(options RegistryOptions) (*Registry, error)

NewRegistry validates the registry's dependencies.

func (*Registry) AgentSpaces added in v0.19.0

func (r *Registry) AgentSpaces() api.AgentSpaceList

AgentSpaces reports the agent spaces a client may name, with the grants of each Docker space and the capability warnings for any risky grant.

func (*Registry) DeleteLearnedFile added in v0.37.0

func (r *Registry) DeleteLearnedFile(
	ctx context.Context,
	sessionID uuid.UUID,
	reference harness.LearnedFileReference,
) error

DeleteLearnedFile removes one learned rule or skill. The next harness resolution no longer loads it.

func (*Registry) ListAgentSpaceDecisions added in v0.19.0

func (r *Registry) ListAgentSpaceDecisions(
	ctx context.Context,
	sessionID uuid.UUID,
	params api.ListSessionAgentSpaceDecisionsParams,
) (api.SessionAgentSpaceDecisionPage, error)

ListAgentSpaceDecisions returns one page of a session's agent space decision history, newest first.

func (*Registry) ListLearnedFiles added in v0.37.0

func (r *Registry) ListLearnedFiles(
	ctx context.Context,
	sessionID uuid.UUID,
) (api.LearnedFileList, error)

ListLearnedFiles lists the learned rules and skills the session's workspace and the global learned directory hold.

func (*Registry) ListSessions

func (r *Registry) ListSessions(
	ctx context.Context,
	params api.ListSessionsParams,
) (api.SessionPage, error)

ListSessions returns one bounded page of the sessions this control surface holds, newest-updated first.

func (*Registry) ListWorkerGenerations

func (r *Registry) ListWorkerGenerations(
	ctx context.Context,
	sessionID uuid.UUID,
	params api.ListSessionWorkersParams,
) (api.WorkerGenerationPage, error)

ListWorkerGenerations returns one page of a session's worker generations, newest first.

func (*Registry) MCPStatus added in v0.38.0

func (r *Registry) MCPStatus(
	ctx context.Context,
	sessionID uuid.UUID,
) (api.MCPStatusReport, error)

MCPStatus returns the MCP servers the session's worker reported at the start of its most recent turn. Before any report the server list is empty and ReportedAt is nil.

func (*Registry) Open

func (r *Registry) Open(
	ctx context.Context,
	requested string,
	agentSpaceName string,
) (OpenResult, error)

Open resolves a requested workspace and returns the one durable session for it, creating that session the first time the directory is opened.

The policy check runs before the store is touched, so a path outside every configured root is refused without creating a row. Opening the same directory again, by any of its names, resumes the existing session rather than making a second one.

func (*Registry) OpenWorkspaceSession

func (r *Registry) OpenWorkspaceSession(
	ctx context.Context,
	workspace string,
	agentSpaceName string,
) (api.OpenedSession, error)

OpenWorkspaceSession resolves a requested workspace to its durable session and reports whether this call created it.

It returns commerr.ErrPermissionDenied when the path falls outside every configured workspace root or names an agent space the deployment does not offer, and commerr.ErrValidationFailed when the path is not a usable directory. None of those cases creates a session.

func (*Registry) ReadLearnedFile added in v0.37.0

func (r *Registry) ReadLearnedFile(
	ctx context.Context,
	sessionID uuid.UUID,
	reference harness.LearnedFileReference,
) (api.LearnedFileContent, error)

ReadLearnedFile returns one learned rule or skill and its content.

func (*Registry) ReconfigureSession

func (r *Registry) ReconfigureSession(
	ctx context.Context,
	sessionID uuid.UUID,
	request api.ReconfigureSessionRequest,
) (api.SessionAgentSpaceDecision, error)

ReconfigureSession moves an idle session to a different agent space.

The agent space must be one the deployment offers, the session must have no turn in flight, and the change is recorded with the caller's reason. The session's current worker is stopped, so the next turn starts a new generation in the new agent space rather than continuing in the old environment.

func (*Registry) Roots

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

Roots reports the directories this registry will open sessions under.

func (*Registry) WorkspaceRoots added in v0.13.0

func (r *Registry) WorkspaceRoots() api.WorkspaceRootList

WorkspaceRoots reports the directories this authenticated controller lets a client select when opening its first workspace session.

type RegistryOptions

type RegistryOptions struct {
	Store        *session.Store
	Policy       *WorkspacePolicy
	RootAgent    string
	DefaultModel string

	// AgentSpaces are the deployment's allowed agent spaces. A client names
	// one when it opens a workspace, and an undefined name is refused.
	AgentSpaces *worker.AgentSpaceSet

	// Workers supervises each session's worker process. Reconfiguring a
	// session stops its worker so the next turn starts a new generation in
	// the new agent space. A nil supervisor records the decision without
	// replacing anything.
	Workers *supervisor.Supervisor

	// LearnedDirectory is the global learned directory sessions load, which
	// the learned file endpoints list, read, and delete from. Empty leaves the
	// global scope out.
	LearnedDirectory string
}

RegistryOptions supplies the durable store and the policy a registry opens workspaces under.

type TurnRouter

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

TurnRouter sends one accepted client message to its session's worker.

This is the join between the public control surface and the private worker protocol. The controller resolves which session the message is for and which agent space that session runs in, makes sure a worker for that agent space is live, then hands the turn over. The controller never runs the model loop itself.

Messages for one session reach its worker one at a time, in the order they were received. Each waits only until the worker has admitted the one before it, by starting a turn for it or queueing it, never for a whole turn.

func NewTurnRouter

func NewTurnRouter(
	registry *Registry,
	workers WorkerSupervisor,
	admissionEvents AdmissionWatcher,
) (*TurnRouter, error)

NewTurnRouter binds the session registry to the worker supervisor. admissionEvents must observe the events the supervisor's workers publish, or each message would hold its session until its whole turn ended.

func (*TurnRouter) CancelSessionAgentRun added in v0.21.0

func (r *TurnRouter) CancelSessionAgentRun(
	ctx context.Context,
	sessionID uuid.UUID,
	agentRunID uuid.UUID,
) (bool, error)

CancelSessionAgentRun asks the session's live worker to stop one running child agent. A session with no live worker runs no children here, so the answer is that nothing was stopped rather than an error.

func (*TurnRouter) CancelSessionTurn

func (r *TurnRouter) CancelSessionTurn(
	ctx context.Context,
	sessionID uuid.UUID,
) (bool, error)

CancelSessionTurn asks the session's live worker to cancel its active turn.

A session with no live worker has nothing running in this controller, so the answer is that nothing was cancelled rather than an error.

func (*TurnRouter) ReserveSessionMessage added in v0.17.0

func (r *TurnRouter) ReserveSessionMessage(
	sessionID uuid.UUID,
) *session.AdmissionTicket

ReserveSessionMessage takes a message's place in its session's admission line without waiting. A caller that runs the message on another goroutine reserves first, so messages are admitted in the order it received them rather than the order its goroutines run in. The reservation must reach RunReservedSessionMessage or be released.

func (*TurnRouter) RunReservedSessionMessage added in v0.17.0

func (r *TurnRouter) RunReservedSessionMessage(
	ctx context.Context,
	reservation *session.AdmissionTicket,
	request agent.MessageRequest,
	requestID uuid.UUID,
) (*agent.MessageRunResult, error)

RunReservedSessionMessage runs one message in its session's worker once its reservation is admitted, and releases the reservation.

The session is loaded first, so a message naming a session that does not exist fails before any worker is started. The agent space comes from the stored session rather than the request: the agent space is a decision recorded at open or reconfigure time, never something a message carries.

The reservation is held while the worker is ensured, so concurrent messages cannot launch two workers for one session, and until the worker admits the message. The worker reports admission through the message's userMessage.created event; a call that ends first, by failing or by answering, releases it too.

func (*TurnRouter) RunSessionMessage

func (r *TurnRouter) RunSessionMessage(
	ctx context.Context,
	sessionID uuid.UUID,
	request agent.MessageRequest,
	requestID uuid.UUID,
) (*agent.MessageRunResult, error)

RunSessionMessage runs one message in the session's worker, reserving its place in the session's admission line on entry.

func (*TurnRouter) SignalSessionJob

func (r *TurnRouter) SignalSessionJob(
	ctx context.Context,
	sessionID uuid.UUID,
	jobID uuid.UUID,
	signal string,
) (*api.JobSignalResponse, error)

SignalSessionJob asks the session's live worker to signal one of its jobs.

A job's process group is a child of the worker, so the controller cannot reach it. A nil response means no live worker holds the job, which tells the caller to record the request against the durable row instead of treating it as an error.

type WorkerSupervisor

type WorkerSupervisor interface {
	EnsureSessionWorker(
		ctx context.Context,
		sessionID uuid.UUID,
		workspace string,
		agentSpaceName string,
	) (*protocol.Worker, error)
	Current(sessionID uuid.UUID) (*protocol.Worker, bool)
}

WorkerSupervisor is the worker lifecycle the router needs.

It is an interface so the router depends on ensuring and cancelling a session's worker rather than on how one is launched.

type WorkspacePolicy

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

WorkspacePolicy admits only directories beneath an operator-configured root. It is the single place a client-supplied path becomes a host path, so the control surface never opens a directory the deployment did not allow.

func NewWorkspacePolicy

func NewWorkspacePolicy(
	roots []string,
	options ...WorkspacePolicyOption,
) (*WorkspacePolicy, error)

NewWorkspacePolicy validates the operator's roots once at startup. Every root must already be absolute and canonical, which config.WorkspaceRoots guarantees, so a later request compares against a stable path.

func (*WorkspacePolicy) Resolve

func (p *WorkspacePolicy) Resolve(requested string) (string, error)

Resolve turns a requested workspace into the canonical path that identifies its session. It returns commerr.ErrNotFound when an admitted path does not exist, commerr.ErrValidationFailed for a path that is not a usable directory, and commerr.ErrPermissionDenied for one outside every configured root.

The path is resolved through its symlinks before the root check, so an alias of an allowed directory is admitted and resolves to the same session as the real path. Resolving first is also what stops a symlink inside an allowed root from reaching a directory outside it.

func (*WorkspacePolicy) Roots

func (p *WorkspacePolicy) Roots() []string

Roots returns the configured roots for reporting. The copy keeps a caller from rewriting the policy it is only meant to read.

type WorkspacePolicyOption added in v0.20.0

type WorkspacePolicyOption func(*ProtectedDirectories)

WorkspacePolicyOption changes how NewWorkspacePolicy builds a policy.

func WithProtectedDirectories added in v0.20.0

func WithProtectedDirectories(
	directories ProtectedDirectories,
) WorkspacePolicyOption

WithProtectedDirectories refuses workspaces that would expose directories. Empty paths are ignored, so a caller can pass optional settings as they are. Every other path must be absolute. It is resolved through its symlinks when the policy is built, and a part that does not exist yet is kept literally.

Directories

Path Synopsis
Package client is the local control client behind Peen's CLI commands.
Package client is the local control client behind Peen's CLI commands.

Jump to

Keyboard shortcuts

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