worker

package
v0.27.1 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package worker is the boundary between Peen's control plane and the session-bound processes that actually run work.

A worker is one live process for one session. It owns that session's model loop, tools, hooks, skills, child agents, and jobs. It never opens the controller's SQLite database: every durable read and write travels over the private, session-bound protocol in the protocol subpackage, and the controller writes each record before publishing it.

A control worker is a child `peen worker` process that runs where the controller runs. A Docker worker is a psyb0t/peen container running the same command. Nothing here accepts a launch detail from model output or a client request. A client names an agent space; the operator decides what that name means.

Index

Constants

View Source
const (
	// AgentSpaceControl is the built-in agent space whose worker runs where
	// the controller runs. It has no profile and no grants.
	AgentSpaceControl = "control"

	// DockerSpacePrefix starts the name of every Docker agent space. The rest
	// of the name is the Docker profile.
	DockerSpacePrefix = "docker:"

	// DockerProfileDefault is the built-in Docker profile: no Docker access,
	// bridge network, no sudo.
	DockerProfileDefault = "default"
)
View Source
const (

	// LabelManaged marks a container this Peen controller created.
	LabelManaged = "peen.managed"

	// LabelManagedValue is the only accepted value for LabelManaged.
	LabelManagedValue = "true"

	// LabelSession names the one session a worker container serves.
	LabelSession = "peen.session"
)

Docker worker identity. The controller only ever stops or removes a container whose stored ID still carries exactly these labels, so an unrelated container on the same host is never touched.

View Source
const (
	// ImageRepository is the repository a controller's own worker image comes
	// from. A deployment may name any other image it likes.
	ImageRepository = "psyb0t/peen"
)
View Source
const WorkerCommand = "worker"

WorkerCommand is the subcommand a worker process runs.

Control and Docker launches both run this exact subcommand of the same Peen binary, so a worker is the same program in both forms. It is not a general user command: without a controller-issued launch document on stdin it has no session, no endpoint, and nothing to do.

Variables

View Source
var ErrAgentSpaceNotAllowed = errors.New(
	"the agent space is not allowed by this deployment",
)

ErrAgentSpaceNotAllowed reports a requested agent space the deployment does not offer. A refusal wraps it together with commerr.ErrPermissionDenied, so a caller can tell it apart from a workspace the policy refused.

View Source
var ErrDockerAuthorityUnavailable = errors.New(
	"the controller has no Docker socket, so Docker agent spaces cannot launch",
)

ErrDockerAuthorityUnavailable reports a Docker agent space the controller cannot launch because it has no Docker socket of its own.

Peen never falls back to the control agent space when this happens. A Docker agent space is an operator's statement about isolation, and quietly running the session somewhere else would break that statement without telling anyone.

View Source
var ErrWorkerLaunchFailed = errors.New("worker launch failed")

ErrWorkerLaunchFailed reports a worker that never became ready.

Functions

func ContainerLabels

func ContainerLabels(sessionID uuid.UUID) map[string]string

ContainerLabels are the only labels a worker container carries.

func ContainerName

func ContainerName(sessionID uuid.UUID) string

ContainerName is the deterministic name of one session's worker container.

It is derived from the session alone, so a controller that restarts can find the container it left behind without storing a second identifier.

func DockerSpaceName added in v0.19.0

func DockerSpaceName(profile string) string

DockerSpaceName is the agent space name of a Docker profile.

func ImageDigestOf

func ImageDigestOf(reference string) string

ImageDigestOf returns the sha256 digest a reference pins, or an empty string when it pins none.

func ImageForBuildVersion

func ImageForBuildVersion(version string) string

ImageForBuildVersion returns the worker image a controller of this build runs.

The tag is the build's version verbatim. The worker and the controller are the same project, so a controller runs the image the same pipeline published beside it, and nothing here rewrites the version into some other tag.

This is why a worker image is named by tag rather than by digest. A digest exists only after the push that creates it, so no release could name its own image ahead of time.

A build that carries no release tag names an image its registry has no reason to hold. Set PEEN_WORKER_IMAGE to run a worker locally.

func ImageRepositoryOf

func ImageRepositoryOf(reference string) string

ImageRepositoryOf reduces a reference to its bare repository, dropping a Docker Hub host prefix, an optional tag, and any digest.

It is how a repository digest the daemon reports is compared against the repository the operator asked for, so a digest belonging to some other repository is never recorded as this worker's image.

func OwnedBy

func OwnedBy(labels map[string]string, sessionID uuid.UUID) bool

OwnedBy reports whether a container's labels mark it as this controller's worker for one session.

Cleanup and restart recovery both go through this. Combined with a stored container ID it is what keeps the controller from ever acting on a container it did not create.

func SessionSocketDirectory

func SessionSocketDirectory(socketRoot string, sessionID uuid.UUID) string

SessionSocketDirectory is one session's own directory beneath the worker socket root.

A Docker worker receives this directory, never the root. The root holds every live session's socket, so mounting it would show one worker the path of every other session's controller surface. One directory per session is what keeps that list private.

func SocketPathFor

func SocketPathFor(socketRoot string, sessionID uuid.UUID) string

SocketPathFor names one session's private socket inside that session's own socket directory.

func ValidateSocketRoot

func ValidateSocketRoot(socketRoot string) error

ValidateSocketRoot refuses a socket root no session socket could fit under.

Every session socket is the root plus a fixed-length name, so the longest path this root will ever produce is known before any session exists. Checking it at startup turns a deep directory into one clear refusal naming the setting to change, instead of a bind failure on the first message a client sends.

Types

type AgentSpace added in v0.19.0

type AgentSpace struct {
	// Name is `control` or `docker:<profile>`.
	Name string
	Kind Kind

	// Revision increments when an operator changes this Docker profile. Every
	// generation stores the revision it started under, so a durable record
	// says which definition ran.
	Revision int64

	// Image is the container image of a Docker profile. Any reference the
	// Docker daemon can resolve is valid. An image that needs host-account
	// setup must provide Peen's worker entrypoint.
	Image string

	// Mounts are the extra paths beyond the workspace and the global Peen
	// configuration, which the launcher always adds.
	Mounts []Mount

	// Docker is how much of the host Docker daemon the worker reaches.
	Docker DockerAccess

	// Network is the network the worker gets.
	Network NetworkMode

	// Sudo permits passwordless sudo inside the worker.
	Sudo bool
}

AgentSpace is one place a session's agent can run.

The control agent space runs the agent where the controller runs. A Docker agent space runs it in its own container, shaped by a named Docker profile. Every field here comes from deployment configuration. None of it is ever taken from model output or a client request: a client names an agent space, and the operator decides what that name means.

func (AgentSpace) CapabilityWarnings added in v0.19.0

func (s AgentSpace) CapabilityWarnings() []string

CapabilityWarnings lists each risky grant this agent space makes, one sentence per grant. It is empty for a space that grants nothing risky.

func (AgentSpace) DockerProfile added in v0.19.0

func (s AgentSpace) DockerProfile() string

DockerProfile is the Docker profile behind a Docker agent space. It is empty for any other agent space.

func (AgentSpace) HostRootEquivalent added in v0.19.0

func (s AgentSpace) HostRootEquivalent() bool

HostRootEquivalent reports whether this agent space gives the worker access that is effectively host root. A Docker socket is the clearest case: any process that can reach it can start a privileged container that mounts the host. `docker: readonly` is not: its proxy refuses every request that could create, start, or change anything.

func (AgentSpace) RequiresDockerAuthority added in v0.19.0

func (s AgentSpace) RequiresDockerAuthority() bool

RequiresDockerAuthority reports whether launching this agent space needs the controller's own Docker socket. A deployment that cannot reach one refuses the space rather than running the work somewhere else.

func (AgentSpace) Resolved added in v0.19.0

func (s AgentSpace) Resolved() []Mount

Resolved returns the mounts with every empty target filled in from its source. Source equals target is the default, so a profile only writes a target when it deliberately relocates a path.

func (AgentSpace) Validate added in v0.19.0

func (s AgentSpace) Validate() error

Validate rejects an agent space a deployment cannot run.

type AgentSpaceSet added in v0.19.0

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

AgentSpaceSet is the deployment's allowed agent spaces.

func NewAgentSpaceSet added in v0.19.0

func NewAgentSpaceSet(
	spaces []AgentSpace,
	defaultSpace string,
) (*AgentSpaceSet, error)

NewAgentSpaceSet validates the operator's agent spaces and the default one.

func (*AgentSpaceSet) All added in v0.19.0

func (s *AgentSpaceSet) All() []AgentSpace

All returns every allowed agent space in a stable order.

func (*AgentSpaceSet) Default added in v0.19.0

func (s *AgentSpaceSet) Default() string

Default returns the deployment's default agent space name.

func (*AgentSpaceSet) Names added in v0.19.0

func (s *AgentSpaceSet) Names() []string

Names lists every allowed agent space name in a stable order.

func (*AgentSpaceSet) Select added in v0.19.0

func (s *AgentSpaceSet) Select(name string) (AgentSpace, error)

Select resolves a requested agent space name.

An empty name takes the deployment's default. A name the operator did not define is refused with commerr.ErrPermissionDenied, because naming an agent space is the only worker choice a client gets: it never supplies an image, mount, socket, network setting, capability, or credential.

type Credential

type Credential string

Credential is a worker's one-time proof that its controller launched it.

The raw value exists only in memory and in the launch document. SQLite stores the hash, so a controller that reads its own database back cannot recover a credential, and a restarted controller can still accept the worker it recorded when that worker reconnects.

func NewCredential

func NewCredential() (Credential, error)

NewCredential mints one generation's credential.

func (Credential) Hash

func (c Credential) Hash() string

Hash is the verification digest stored with the generation.

func (Credential) Matches

func (c Credential) Matches(storedHash string) bool

Matches reports whether this credential verifies against a stored hash.

The comparison is constant time, so a worker cannot learn a hash one byte at a time by timing its own rejections.

type Descriptor

type Descriptor struct {
	// ProcessID is set for a control worker.
	ProcessID int

	// ContainerID and ImageDigest are set for a Docker worker. The digest is
	// immutable image identity, never a moving tag.
	ContainerID string
	ImageDigest string
}

Descriptor is a launched worker's recorded identity.

type DockerAccess added in v0.19.0

type DockerAccess string

DockerAccess is how much of the host Docker daemon a Docker agent space reaches.

const (
	// DockerAccessNone gives the worker no Docker socket.
	DockerAccessNone DockerAccess = "none"
	// DockerAccessReadonly gives the worker a controller-run proxy that
	// answers only read endpoints of the host Docker daemon. The worker never
	// receives the socket itself.
	DockerAccessReadonly DockerAccess = "readonly"
	// DockerAccessFull mounts the host Docker socket into the worker, which
	// is host root.
	DockerAccessFull DockerAccess = "full"
)

func (DockerAccess) Valid added in v0.19.0

func (a DockerAccess) Valid() bool

Valid reports whether the access is one this build understands.

type Generation

type Generation struct {
	ID        uuid.UUID
	SessionID uuid.UUID

	Kind               Kind
	AgentSpace         string
	AgentSpaceRevision int64
	State              State

	// Workspace is the literal path the worker runs in. It reads the same on
	// the host, in a Docker controller, and inside a Docker worker.
	Workspace string

	// SocketPath is the private session-bound Unix socket this generation
	// talks to its controller over.
	SocketPath string

	// ProcessID is the operating system PID of a control worker. It is zero for
	// a Docker worker, whose identity is its container.
	ProcessID int

	// ContainerID identifies a Docker worker. ImageDigest records immutable
	// repository identity when Docker reports one. It is empty for a local
	// image without a repository digest.
	ContainerID string
	ImageDigest string

	// FailureDetail says why a generation failed or was replaced. It never
	// carries a credential.
	FailureDetail string

	// ExitCode is the worker's process or container exit status once it ended.
	ExitCode int

	StartedAt *time.Time
	EndedAt   *time.Time
}

Generation is the durable record of one worker process.

It exists before the process launches, so a controller that dies mid-launch still leaves a row an operator can reconcile.

type Kind

type Kind string

Kind is the form a worker process takes.

const (
	// KindControl runs the worker as a child process of the controller, in
	// the control agent space.
	KindControl Kind = "control"
	// KindDocker runs the worker as a psyb0t/peen sibling container, in a
	// Docker agent space.
	KindDocker Kind = "docker"
)

func (Kind) Valid

func (k Kind) Valid() bool

Valid reports whether the kind is one this build understands.

type LaunchDocument

type LaunchDocument struct {
	SessionID    uuid.UUID  `json:"sessionId"`
	GenerationID uuid.UUID  `json:"generationId"`
	Credential   Credential `json:"credential"`

	// SocketPath is the worker's private, session-bound Unix socket. It lives
	// in this session's own directory beneath the socket root, so a Docker
	// worker receives that one directory and never the root. It is the only
	// controller surface the worker has, and it carries no generic control API
	// credential.
	SocketPath string `json:"socketPath"`

	// Workspace is the literal directory the worker runs in.
	Workspace string `json:"workspace"`

	// ConfigDirectory is the global Peen configuration, read-only in a Docker
	// worker. Controller runtime state lives under PEEN_STATE_DIR instead, and
	// the controller refuses to start if that directory sits inside this one,
	// so the database is never reachable through this mount.
	ConfigDirectory string `json:"configDirectory"`

	// AgentSpace names the agent space this generation runs under. The worker
	// reports it back; it cannot choose another.
	AgentSpace string `json:"agentSpace"`
}

LaunchDocument is everything the controller tells one worker at launch.

It is the entire worker contract. A worker that starts without one fails, because `peen worker` is not a general user command: it cannot choose its session, its endpoint, or its workspace.

func DecodeLaunchDocument

func DecodeLaunchDocument(raw []byte) (LaunchDocument, error)

DecodeLaunchDocument reads one launch document and validates it.

func (LaunchDocument) Encode

func (d LaunchDocument) Encode() ([]byte, error)

Encode serializes the launch document for stdin or a launch file.

func (LaunchDocument) Redacted

func (d LaunchDocument) Redacted() LaunchDocument

Redacted returns the document with its credential removed, for logging and for any record that outlives the launch.

func (LaunchDocument) Validate

func (d LaunchDocument) Validate() error

Validate rejects a launch document a worker cannot act on.

type LaunchRequest

type LaunchRequest struct {
	Document   LaunchDocument
	AgentSpace AgentSpace
}

LaunchRequest is one fully resolved worker launch.

Every field comes from the controller. Nothing here is taken from model output or a client request.

type Launcher

type Launcher interface {
	// Kind is the agent space kind this launcher serves.
	Kind() Kind

	// Launch starts the worker and returns once the process or container
	// exists. It does not wait for the worker to register: the supervisor
	// waits for that on the protocol socket, which is the only proof the
	// worker is actually usable.
	Launch(ctx context.Context, request LaunchRequest) (Process, error)
}

Launcher starts one worker process for one session.

Control and Docker launching differ only here. Everything above this point, the generation record, the credential, the socket, and the protocol, is the same for both, so a new launch form does not change the supervisor.

type Mount

type Mount struct {
	Source   string
	Target   string
	ReadOnly bool
}

Mount is one path a Docker worker sees.

Source and Target are literal host paths. Peen does not translate paths: a workspace at /srv/work/project is /srv/work/project inside the worker too, so paths in prompts, hooks, logs, and tool calls stay truthful. A relocated target is a deliberate operator field and is recorded with both paths.

type NetworkMode added in v0.19.0

type NetworkMode string

NetworkMode is the network a Docker agent space gives its worker.

const (
	// NetworkModeNone gives the worker no network.
	NetworkModeNone NetworkMode = "none"
	// NetworkModeBridge puts the worker on Docker's default bridge network.
	NetworkModeBridge NetworkMode = "bridge"
	// NetworkModeHost shares the host's network stack with the worker.
	NetworkModeHost NetworkMode = "host"
)

func (NetworkMode) Valid added in v0.19.0

func (m NetworkMode) Valid() bool

Valid reports whether the mode is one this build understands.

type Process

type Process interface {
	// Describe reports the worker's operating system or container identity.
	Describe() Descriptor

	// Stop asks the worker to end and waits for it within the context.
	Stop(ctx context.Context) error

	// Wait blocks until the worker ends and returns its exit code.
	Wait() (int, error)
}

Process is a launched worker as its launcher holds it.

type State

type State string

State is one point in a worker generation's durable lifecycle.

const (
	// StateRequested means the generation is recorded but nothing has launched.
	StateRequested State = "requested"
	// StateStarting means the process or container is coming up.
	StateStarting State = "starting"
	// StateReady means the worker registered over the protocol and may run
	// work for its session.
	StateReady State = "ready"
	// StateStopping means the worker was asked to finish and exit.
	StateStopping State = "stopping"
	// StateStopped means the worker ended as asked.
	StateStopped State = "stopped"
	// StateFailed means the worker ended without being asked to, or never
	// became ready.
	StateFailed State = "failed"
)

func (State) Terminal

func (s State) Terminal() bool

Terminal reports whether a generation in this state can no longer run work.

func (State) Valid

func (s State) Valid() bool

Valid reports whether the state is one this build understands.

Directories

Path Synopsis
Package controlspace launches a session worker in the control agent space, as a child process of the controller.
Package controlspace launches a session worker in the control agent space, as a child process of the controller.
Package docker launches a session worker as a psyb0t/peen sibling container.
Package docker launches a session worker as a psyb0t/peen sibling container.
Package dockerproxy is the read-only Docker Engine API proxy behind `docker: readonly`.
Package dockerproxy is the read-only Docker Engine API proxy behind `docker: readonly`.
Package protocol carries Peen's private, session-bound worker protocol.
Package protocol carries Peen's private, session-bound worker protocol.
Package run is the body of the internal `peen worker` command.
Package run is the body of the internal `peen worker` command.
Package supervisor owns the lifecycle of one controller's session workers.
Package supervisor owns the lifecycle of one controller's session workers.
Package workerlog carries a worker process's log records into the controller's own logging stack.
Package workerlog carries a worker process's log records into the controller's own logging stack.

Jump to

Keyboard shortcuts

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