config

package
v0.31.0 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package config loads Peen's deployment configuration from PEEN_ variables.

Index

Constants

View Source
const (
	// DefaultDockerSocketPath is the host socket a controller uses to create
	// worker containers. It is the controller's own grant, separate from the
	// socket a `docker: full` profile mounts into a worker.
	DefaultDockerSocketPath = "/var/run/docker.sock"
)

Variables

View Source
var (
	// ErrInvalidConfig reports invalid deployment configuration.
	ErrInvalidConfig = errors.New("invalid Peen configuration")
	// ErrInvalidUpstream reports malformed named LLM provider configuration.
	ErrInvalidUpstream = errors.New("invalid Peen upstream")
	// ErrControlSpaceRefused reports the control agent space offered beside a
	// reachable Docker socket. A control worker has the controller's own user
	// and groups, so it can use that socket to start a container that mounts
	// the host.
	ErrControlSpaceRefused = errors.New(
		"the control agent space is refused beside a Docker socket",
	)
)

Functions

func ControlWorkerEnvironment added in v0.19.1

func ControlWorkerEnvironment(environ, credentialKeys []string) []string

ControlWorkerEnvironment returns environ without the settings a control worker must not inherit from its controller.

It removes every controller-only key (the API token, the state directory, Docker settings, listen addresses, host identity, and log settings) and every PEEN_ key outside the worker allowlist. A key named in credentialKeys stays even when it starts with PEEN_, because it holds a provider credential the worker's model calls need, unless it is controller-only. Variables outside PEEN_ stay, so the agent's commands keep PATH, HOME, and the user's toolchain. PEEN_CONFIG_DIR is controller-only here too: the control launcher sets it from the launch document, as the Docker launcher does.

func ValidateStateDirectories added in v0.22.0

func ValidateStateDirectories(config, state string) error

ValidateStateDirectories applies the deployment's symlink-aware overlap check to callers that supply configuration directly instead of environment.

Types

type CompactionMode

type CompactionMode string

CompactionMode determines how Peen handles an over-budget transcript.

const (
	CompactionModeDropOldest CompactionMode = "drop-oldest"
	CompactionModeSummarize  CompactionMode = "summarize"
)

type Config

type Config struct {
	// ConfigDirectory is the global configuration and harness directory. It is
	// the one directory every worker receives, read-only, so it holds only what
	// a worker is meant to read: AGENTS.md, .agents, SYSTEM.md,
	// APPEND_SYSTEM.md, and COMPACTION.md. Controller runtime state never lives
	// here, because mounting this directory into a worker hands that worker
	// everything inside it.
	ConfigDirectory string `env:"PEEN_CONFIG_DIR,required"`

	// StateDirectory is the controller's own durable runtime state: SQLite,
	// audit logs, worker socket roots, and controller-only credentials. No
	// worker ever receives it. Keeping it out of ConfigDirectory is what stops
	// a Docker worker from reading another session's transcript through its
	// configuration mount.
	//
	// The tag carries no `required` because Parse and ParseWorker need
	// different answers and gonfiguration decides that at parse time. A
	// controller requires it through Validate. A worker owns no durable state,
	// so ParseWorker leaves it empty and nothing reads it.
	StateDirectory string `env:"PEEN_STATE_DIR"`

	WorkingDirectory string

	// Agent is the root agent. A plain name picks a custom agent first and a
	// core agent second; a core: name picks only the core agent.
	Agent string `default:"core:general-purpose" env:"PEEN_AGENT"`

	// DisabledCoreSkills and DisabledCoreAgents list the embedded skills and
	// agents to remove, as comma-separated names without the core: prefix or
	// "all". They stay strings so a worker, which reads the same variables,
	// parses them with the same rules as the controller.
	DisabledCoreSkills string `env:"PEEN_DISABLED_CORE_SKILLS"`
	DisabledCoreAgents string `env:"PEEN_DISABLED_CORE_AGENTS"`

	UpstreamsJSON   string `env:"PEEN_UPSTREAMS,required"`
	DefaultModel    string `env:"PEEN_DEFAULT_MODEL,required"`
	CompactionModel string `env:"PEEN_COMPACTION_MODEL"`

	// WorkspaceRoot is the absolute directory a client may open session
	// workspaces under: the root itself or any directory below it. It bounds
	// which host directories the control surface will ever expose to a
	// session, so it is deployment configuration and never comes from a
	// client request. Empty uses the process working directory.
	WorkspaceRoot string `env:"PEEN_WORKSPACE_ROOT"`

	// DockerProfilesJSON defines the named Docker profiles a client may pick,
	// as a JSON array. Every worker capability lives here: image, mounts,
	// Docker access, network, and sudo. None of it ever comes from model
	// output or a client request, which only names an agent space.
	//
	// An empty value defines no profile beyond the built-in `default` one,
	// which has no Docker access, the bridge network, and no sudo.
	DockerProfilesJSON string `env:"PEEN_DOCKER_PROFILES"`

	// DefaultAgentSpace is where a session opened without naming one runs:
	// `control` or `docker:<profile>`. Empty takes `docker:default` when the
	// controller can reach a Docker socket and `control` when it cannot.
	DefaultAgentSpace string `env:"PEEN_DEFAULT_AGENT_SPACE"`

	// WorkerSocketDirectory is the root holding one private directory per
	// session worker. Empty puts it under the state directory, because a
	// socket root is controller runtime state and a worker receives only its
	// own session's directory, never the root.
	WorkerSocketDirectory string `env:"PEEN_WORKER_SOCKET_DIR"`

	// DockerSocket is the controller's own Docker socket, used to create
	// worker containers for a Docker profile. It is the first of three
	// candidates: this setting, a `unix://` DOCKER_HOST, and the platform
	// default. The first one that answers the Docker API launches workers, and
	// any one that answers, or a reachable `tcp://` DOCKER_HOST, counts as
	// Docker authority. Without authority a Docker agent space is refused
	// rather than run in the control agent space. With it, the control agent
	// space is refused, because a control worker could use the daemon to
	// become host root. Setting this to another path does not hide the others.
	DockerSocket string `env:"PEEN_DOCKER_SOCKET"`

	// HostUsername and HostHome describe the host account when a controller
	// itself runs in Docker as an arbitrary numeric UID and GID. In that case
	// the controller container has no passwd entry for the host account, but a
	// Docker worker still has to recreate the account before it can safely
	// write workspace files with host ownership. They are both empty for a
	// controller on the host, which resolves its account from the operating
	// system.
	HostUsername string `env:"PEEN_HOST_USERNAME"`
	HostHome     string `env:"PEEN_HOST_HOME"`

	// WorkerImage overrides the image for every Docker profile. Empty leaves
	// each profile's image in effect. Any reference the Docker daemon resolves,
	// including a local development image, is valid.
	WorkerImage string `env:"PEEN_WORKER_IMAGE"`

	MaxContextTokens       int            `default:"32768"       env:"PEEN_MAX_CONTEXT_TOKENS"`           //nolint:lll // Immutable env tag.
	OutputReserveTokens    int            `default:"4096"        env:"PEEN_OUTPUT_RESERVE_TOKENS"`        //nolint:lll // Immutable env tag.
	CompactionMode         CompactionMode `default:"drop-oldest" env:"PEEN_COMPACTION_MODE"`              //nolint:lll // Immutable env tag.
	CompactionOutputTokens int            `default:"2048"        env:"PEEN_COMPACTION_MAX_OUTPUT_TOKENS"` //nolint:lll // Immutable env tag.
	CompactionTimeout      time.Duration  `default:"2m"          env:"PEEN_COMPACTION_TIMEOUT"`           //nolint:lll // Immutable env tag.
	TurnTimeout            time.Duration  `default:"10m"         env:"PEEN_TURN_TIMEOUT"`                 //nolint:lll // Immutable env tag.

	// CrashRecovery applies to every workspace this controller serves. It is
	// controller-only: recovery runs before any worker starts.
	CrashRecovery CrashRecoveryMode `default:"pause" env:"PEEN_CRASH_RECOVERY"`

	// MaxConcurrentTurns bounds how many turns may run at once across every
	// session in this process, unlike MaxConcurrentAgentRunsPerSession, which
	// only bounds one session's child-agent runs.
	MaxConcurrentTurns int `default:"16" env:"PEEN_MAX_CONCURRENT_TURNS"` //nolint:lll // Immutable env tag.
	// MaxQueuedUserMessages bounds messages accepted while a session has a
	// running turn. They are delivered at an eligible provider round boundary.
	MaxQueuedUserMessages int `default:"16" env:"PEEN_MAX_QUEUED_USER_MESSAGES"` //nolint:lll // Immutable env tag.

	// MaxMessageBytes bounds the caller-supplied "message" field in a
	// message.send event. MaxSystemPromptBytes bounds its optional
	// "systemPrompt.content" field. MaxStoredMessageBytes bounds any single
	// message row, of any role, before it is written to the durable
	// transcript, since a stored assistant or tool message is not otherwise
	// bounded by a caller-facing setting.
	MaxMessageBytes       int `default:"262144"  env:"PEEN_MAX_MESSAGE_BYTES"`        //nolint:lll // Immutable env tag.
	MaxSystemPromptBytes  int `default:"65536"   env:"PEEN_MAX_SYSTEM_PROMPT_BYTES"`  //nolint:lll // Immutable env tag.
	MaxStoredMessageBytes int `default:"1048576" env:"PEEN_MAX_STORED_MESSAGE_BYTES"` //nolint:lll // Immutable env tag.

	MaxToolRounds        int           `default:"32"   env:"PEEN_MAX_TOOL_ROUNDS"`          //nolint:lll // Immutable env tag.
	MaxConcurrentTools   int           `default:"4"    env:"PEEN_MAX_CONCURRENT_TOOLS"`     //nolint:lll // Immutable env tag.
	ToolTimeout          time.Duration `default:"15m"  env:"PEEN_TOOL_TIMEOUT"`             //nolint:lll // Immutable env tag.
	MaxToolResultTokens  int           `default:"8192" env:"PEEN_MAX_TOOL_RESULT_TOKENS"`   //nolint:lll // Immutable env tag.
	HookCommandTimeout   time.Duration `default:"30s" env:"PEEN_HOOK_COMMAND_TIMEOUT"`      //nolint:lll // Immutable env tag.
	MaxHookCommandOutput int           `default:"65536" env:"PEEN_MAX_HOOK_COMMAND_OUTPUT"` //nolint:lll // Immutable env tag.

	ToolMaxListEntries        int           `default:"1000"    env:"PEEN_TOOL_MAX_LIST_ENTRIES"`         //nolint:lll // Immutable env tag.
	ToolMaxListDepth          int           `default:"16"      env:"PEEN_TOOL_MAX_LIST_DEPTH"`           //nolint:lll // Immutable env tag.
	ToolMaxSearchMatches      int           `default:"200"     env:"PEEN_TOOL_MAX_SEARCH_MATCHES"`       //nolint:lll // Immutable env tag.
	ToolMaxSearchFileBytes    int64         `default:"2097152" env:"PEEN_TOOL_MAX_SEARCH_FILE_BYTES"`    //nolint:lll // Immutable env tag.
	ToolMaxReadBytes          int           `default:"262144"  env:"PEEN_TOOL_MAX_READ_BYTES"`           //nolint:lll // Immutable env tag.
	ToolMaxReadLines          int           `default:"2000"    env:"PEEN_TOOL_MAX_READ_LINES"`           //nolint:lll // Immutable env tag.
	ToolMaxWriteBytes         int           `default:"4194304" env:"PEEN_TOOL_MAX_WRITE_BYTES"`          //nolint:lll // Immutable env tag.
	ToolMaxEdits              int           `default:"64"      env:"PEEN_TOOL_MAX_EDITS"`                //nolint:lll // Immutable env tag.
	ToolMaxDiffBytes          int           `default:"65536"   env:"PEEN_TOOL_MAX_DIFF_BYTES"`           //nolint:lll // Immutable env tag.
	ToolMaxRemoveEntries      int           `default:"20000"   env:"PEEN_TOOL_MAX_REMOVE_ENTRIES"`       //nolint:lll // Immutable env tag.
	ToolMaxCommandOutputBytes int           `default:"65536"   env:"PEEN_TOOL_MAX_COMMAND_OUTPUT_BYTES"` //nolint:lll // Immutable env tag.
	ToolCommandTimeout        time.Duration `default:"2m"      env:"PEEN_TOOL_COMMAND_TIMEOUT"`          //nolint:lll // Immutable env tag.
	ToolMaxCommandTimeout     time.Duration `default:"15m"     env:"PEEN_TOOL_MAX_COMMAND_TIMEOUT"`      //nolint:lll // Immutable env tag.

	MaxPendingEvents     int `default:"256"   env:"PEEN_MAX_PENDING_EVENTS"`       //nolint:lll // Immutable env tag.
	MaxEventSummaryBytes int `default:"4096"  env:"PEEN_MAX_EVENT_SUMMARY_BYTES"`  //nolint:lll // Immutable env tag.
	MaxEventDataBytes    int `default:"65536" env:"PEEN_MAX_EVENT_DATA_BYTES"`     //nolint:lll // Immutable env tag.
	MaxEventWakesPerHour int `default:"60"    env:"PEEN_MAX_EVENT_WAKES_PER_HOUR"` //nolint:lll // Immutable env tag.

	MaxChildAgentDepth               int `default:"5"     env:"PEEN_MAX_CHILD_AGENT_DEPTH"`             //nolint:lll // Immutable env tag.
	MaxChildAgentTurns               int `default:"16"    env:"PEEN_MAX_CHILD_AGENT_TURNS"`             //nolint:lll // Immutable env tag.
	MaxConcurrentAgentRunsPerSession int `default:"4"     env:"PEEN_MAX_CONCURRENT_AGENT_RUNS"`         //nolint:lll // Immutable env tag.
	MaxAgentRunEventCount            int `default:"2000"  env:"PEEN_MAX_AGENT_RUN_EVENT_COUNT"`         //nolint:lll // Immutable env tag.
	MaxAgentRunEventBytes            int `default:"65536" env:"PEEN_MAX_AGENT_RUN_EVENT_BYTES"`         //nolint:lll // Immutable env tag.
	MaxAdHocAgentInstructionBytes    int `default:"65536" env:"PEEN_MAX_ADHOC_AGENT_INSTRUCTION_BYTES"` //nolint:lll // Immutable env tag.

	AskTimeout time.Duration `default:"0" env:"PEEN_ASK_TIMEOUT"` //nolint:lll // Immutable env tag.

	HTTPListenAddress    string `default:":8080"           env:"PEEN_HTTP_LISTEN_ADDRESS"`   //nolint:lll // Immutable env tag.
	MetricsListenAddress string `default:"127.0.0.1:9090" env:"PEEN_METRICS_LISTEN_ADDRESS"` //nolint:lll // Immutable env tag.
	APIToken             string `env:"PEEN_API_TOKEN"`
	// contains filtered or unexported fields
}

Config is the deployment-owned configuration. Provider credentials stay in individually named environment variables, never inside PEEN_UPSTREAMS.

func Parse

func Parse() (Config, error)

Parse reads and validates the fixed PEEN_ environment bindings for a controller. It requires PEEN_STATE_DIR and enforces its separation from PEEN_CONFIG_DIR.

func ParseWorker added in v0.8.0

func ParseWorker() (Config, error)

ParseWorker reads the same bindings for a session worker.

A worker owns no durable state, so PEEN_STATE_DIR is neither required nor used. The controller keeps it out of a Docker worker's environment on purpose, and a control worker that inherits it still opens no database.

func (Config) AgentSpaces added in v0.19.0

func (c Config) AgentSpaces() (*worker.AgentSpaceSet, error)

AgentSpaces returns the deployment's allowed agent spaces.

Every Docker profile is a `docker:<name>` agent space, and the built-in `default` profile (no Docker access, bridge network, no sudo) exists unless PEEN_DOCKER_PROFILES defines a profile of the same name.

The control agent space is offered only when this controller cannot reach a Docker socket. With a reachable socket a control worker, which has the controller's own user and groups, could use that socket to start a container that mounts the host, so control is refused as the default and never offered. With a socket and no PEEN_DEFAULT_AGENT_SPACE the default is `docker:default`. Without a socket the default is `control`, and Docker agent spaces stay listed but refuse to launch.

func (Config) CommandEnvironment added in v0.19.0

func (c Config) CommandEnvironment(environ []string) ([]string, error)

CommandEnvironment returns environ without Peen's own secrets, for the commands a session's agent runs.

A worker holds the controller's API token and the provider credentials its model calls need. A command the agent runs, such as `env`, would print them into the stored transcript and the live feed, and the API token would let the agent drive every other session. So the token, every variable an upstream names with apiKeyEnv, and any other secret-carrying setting are removed. The worker process itself keeps its environment.

It fails when PEEN_UPSTREAMS cannot be read, because the credential variables cannot be named then, and a command environment that might hold a key is refused rather than returned.

func (Config) DisabledCoreAgentNames added in v0.18.0

func (c Config) DisabledCoreAgentNames() ([]string, error)

DisabledCoreAgentNames returns the core agents PEEN_DISABLED_CORE_AGENTS removes, without the core: prefix.

func (Config) DisabledCoreSkillNames added in v0.18.0

func (c Config) DisabledCoreSkillNames() ([]string, error)

DisabledCoreSkillNames returns the core skills PEEN_DISABLED_CORE_SKILLS removes, without the core: prefix.

func (Config) DockerAuthority added in v0.19.0

func (c Config) DockerAuthority() DockerAuthority

DockerAuthority probes every candidate daemon and reports what answers.

Every candidate is checked, not just the first one that is set. An operator who points PEEN_DOCKER_SOCKET at a missing path, or DOCKER_HOST at a remote daemon, has not hidden the platform default socket from a control agent, and the agent space rules must see whatever the agent could reach.

Reachable means the daemon answers the Docker API, not that a file exists. A socket file the controller's user cannot open is unusable to the agent too, since it runs as the same user, so it does not count.

func (Config) DockerSocketPath added in v0.8.0

func (c Config) DockerSocketPath() string

DockerSocketPath is the local socket the controller launches workers through: the first candidate that answers the Docker API. Empty when none does.

func (Config) HasDockerAuthority added in v0.8.0

func (c Config) HasDockerAuthority() bool

HasDockerAuthority reports whether this controller can reach a Docker daemon.

The agent space rules depend on it at startup: with a daemon the control agent space is refused, and without one Docker agent spaces cannot run. A deployment without authority refuses Docker agent spaces outright and never falls back to a control worker.

func (Config) ResumesAfterCrash added in v0.30.0

func (c Config) ResumesAfterCrash() bool

ResumesAfterCrash reports whether work a crash interrupted continues on its own instead of waiting paused for a turn.

func (Config) Upstreams

func (c Config) Upstreams() ([]Upstream, error)

Upstreams parses and validates the configured named provider list.

func (Config) Validate

func (c Config) Validate() error

Validate checks values which need cross-field or filesystem-aware rules. It is the controller's contract and requires a state directory.

func (Config) ValidateWorker added in v0.8.0

func (c Config) ValidateWorker() error

ValidateWorker is Validate without the controller-only state directory rules.

func (Config) WithDockerEnvironment added in v0.19.0

func (c Config) WithDockerEnvironment(host, defaultSocket string) Config

WithDockerEnvironment returns a copy that finds the Docker daemon from the given DOCKER_HOST value and platform default socket instead of the process environment and /var/run/docker.sock.

A test that must not depend on the Docker daemon of the machine running it uses this. PEEN_DOCKER_SOCKET alone cannot do that, because it never hides the other candidates.

func (Config) WorkerEnvironment added in v0.8.0

func (c Config) WorkerEnvironment() (map[string]string, error)

WorkerEnvironment returns exactly the deployment settings a worker needs.

A Docker worker is a separate process with an intentionally small environment. It needs the same runtime limits, model selection, provider definitions, and named provider credentials as a control worker, but it must not inherit controller-only paths or authority. The allowlist makes that boundary visible and prevents a future PEEN_ control setting from quietly becoming a worker capability.

func (Config) WorkerSocketRoot added in v0.8.0

func (c Config) WorkerSocketRoot() string

WorkerSocketRoot is the directory holding one private directory per session worker.

It is controller runtime state, so it defaults under PEEN_STATE_DIR and never under PEEN_CONFIG_DIR. No worker receives this root: a Docker worker is given only its own session's directory beneath it, so it never learns another session's socket path.

func (Config) WorkspaceRoots added in v0.8.0

func (c Config) WorkspaceRoots() ([]string, error)

WorkspaceRoots returns the canonical directories a client may open a session under. Peen supports one workspace root, so the list holds exactly one entry: PEEN_WORKSPACE_ROOT, or the process working directory when it is unset. The list shape is what the workspace policy and the HTTP API carry.

The root is resolved through its symlinks, so a request naming an alias of it compares equal to it rather than being refused.

type CrashRecoveryMode added in v0.30.0

type CrashRecoveryMode string

CrashRecoveryMode decides what happens to work a crashed controller or worker left unfinished.

const (
	// CrashRecoveryPause keeps crashed work paused until a turn resumes it.
	CrashRecoveryPause CrashRecoveryMode = "pause"
	// CrashRecoveryResume lets the next worker continue crashed work by
	// itself, for deployments that run without anyone watching.
	CrashRecoveryResume CrashRecoveryMode = "resume"
)

type DockerAuthority added in v0.19.0

type DockerAuthority struct {
	// SocketPath is the first local socket that answers the Docker API. Empty
	// when no local socket does.
	SocketPath string

	// RemoteHost is a reachable `tcp://` DOCKER_HOST. Set only when no local
	// socket answers.
	RemoteHost string
}

DockerAuthority is the Docker daemon a controller can reach, resolved once so the agent space rules and the worker launcher agree on one answer.

func (DockerAuthority) Present added in v0.19.0

func (a DockerAuthority) Present() bool

Present reports whether any Docker daemon is reachable.

func (DockerAuthority) String added in v0.19.0

func (a DockerAuthority) String() string

String names the reachable daemon for an error message.

type DockerMount added in v0.19.0

type DockerMount struct {
	Source   string `json:"source"`
	Target   string `json:"target"`
	ReadOnly bool   `json:"readOnly"`
}

DockerMount is one extra path a Docker profile exposes. An empty target means the worker sees the source at its own absolute path.

type DockerProfile added in v0.19.0

type DockerProfile struct {
	Name     string `json:"name"`
	Revision int64  `json:"revision"`
	Image    string `json:"image"`

	Mounts []DockerMount `json:"mounts"`

	Docker  worker.DockerAccess `json:"docker"`
	Network worker.NetworkMode  `json:"network"`
	Sudo    bool                `json:"sudo"`
}

DockerProfile is one operator-defined Docker profile as it appears in PEEN_DOCKER_PROFILES. A Docker profile shapes the Docker agent space named `docker:<name>`.

This is the only place a Docker capability can be turned on. A client names an agent space; it never sends an image, a mount, a network setting, or a socket request. An omitted `docker` means none, and an omitted `network` means bridge.

type Upstream

type Upstream struct {
	Name      string       `json:"name"`
	Type      UpstreamType `json:"type"`
	BaseURL   string       `json:"baseUrl"`
	APIKeyEnv string       `json:"apiKeyEnv"`
}

Upstream configures one deployment-owned named provider. The name is Peen's stable prefix in qualified model references such as aigate/model-name, and the type is the wire protocol that provider speaks.

func (Upstream) APIKey

func (u Upstream) APIKey() string

APIKey resolves only the environment variable selected by the operator. Empty is legitimate for intentionally keyless endpoints.

type UpstreamType added in v0.10.0

type UpstreamType string

UpstreamType selects an Elelem driver implementation. It names the wire protocol an upstream speaks, not the vendor behind it. The vendor is the upstream's own Name.

const (
	UpstreamTypeOpenAI    UpstreamType = "openai"
	UpstreamTypeAnthropic UpstreamType = "anthropic"
	UpstreamTypeZAICoding UpstreamType = "zai-coding"
)

Directories

Path Synopsis
Package envtemplate renders Peen's commented .env file.
Package envtemplate renders Peen's commented .env file.

Jump to

Keyboard shortcuts

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