worker

package
v0.15.2 Latest Latest
Warning

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

Go to latest
Published: Oct 9, 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 native worker is a child `peen worker` process. 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 a profile; the operator decides what that name means.

Index

Constants

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 (
	ProfileNative         = "native"
	ProfileDockerSandbox  = "docker.sandbox"
	ProfileDockerHostLike = "docker.host-like"
)

Named profiles the plan defines. An operator may define more, but these three are the ones the documentation and defaults refer to by name.

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.

Native 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 ErrDockerAuthorityUnavailable = errors.New(
	"the controller has no Docker socket, so Docker profiles cannot launch",
)

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

Peen never falls back to host or in-container native work when this happens. A Docker profile 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 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 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 native 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 Generation

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

	Kind            Kind
	Profile         string
	ProfileRevision 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 native 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 (
	// KindNative runs the worker as a child process of the controller.
	KindNative Kind = "native"
	// KindDocker runs the worker as a psyb0t/peen sibling container.
	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"`

	// Profile names the operator-defined profile this generation runs under.
	// The worker reports it back; it cannot choose another.
	Profile string `json:"profile"`
}

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
	Profile  Profile
}

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

Native 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 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 Profile

type Profile struct {
	Name string
	Kind Kind

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

	// Image is the container image for a Docker profile, ignored for native.
	// 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

	// AllowDockerSocket mounts the host Docker socket into the worker. That is
	// host-root-equivalent access for the worker, so it is off unless the
	// named profile says otherwise, and it is reported as a capability
	// warning. It is a different grant from the controller's own Docker
	// socket, which is what permits creating worker containers at all.
	AllowDockerSocket bool

	// AllowNetwork leaves the worker's network in place. False asks the
	// launcher for an isolated network.
	AllowNetwork bool

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

Profile is one operator-defined worker environment.

Every field here comes from deployment configuration. None of it is ever taken from model output or a client request: a client names a profile, and the operator decides what that name means.

func (Profile) CapabilityWarning

func (p Profile) CapabilityWarning() string

CapabilityWarning is the operator-facing warning for a profile that grants host-root-equivalent access. It is empty for a profile that does not.

func (Profile) HostRootEquivalent

func (p Profile) HostRootEquivalent() bool

HostRootEquivalent reports whether this profile grants the worker access that is effectively host root. A writable Docker socket is the clearest case: any process that can reach it can start a privileged container.

func (Profile) RequiresDockerAuthority

func (p Profile) RequiresDockerAuthority() bool

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

func (Profile) Resolved

func (p Profile) 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 (Profile) Validate

func (p Profile) Validate() error

Validate rejects a profile a deployment cannot run.

type ProfileSet

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

ProfileSet is the deployment's allowed worker profiles.

func NewProfileSet

func NewProfileSet(
	profiles []Profile,
	defaultProfile string,
) (*ProfileSet, error)

NewProfileSet validates the operator's profiles and the default one.

func (*ProfileSet) All

func (s *ProfileSet) All() []Profile

All returns every allowed profile in a stable order.

func (*ProfileSet) Default

func (s *ProfileSet) Default() string

Default returns the deployment's default profile name.

func (*ProfileSet) Names

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

Names lists every allowed profile name in a stable order.

func (*ProfileSet) Select

func (s *ProfileSet) Select(name string) (Profile, error)

Select resolves a requested profile name.

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

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 docker launches a session worker as a psyb0t/peen sibling container.
Package docker launches a session worker as a psyb0t/peen sibling container.
Package native launches a session worker as a child process of the controller.
Package native launches a session worker as a child process of the controller.
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