worker

package
v0.2.0-rc3 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: Apache-2.0 Imports: 42 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package worker is the worker side of worker protocol v1 (docs/contracts/worker-protocol-v1.md): enrolment, the session loop, the host policy, offers, running jobs through internal/exec with worker-derived paths, the spool, blobs and controls. cmd/dd-worker is its command line. It imports no serve-side package (boundary_test.go).

Index

Constants

View Source
const (
	SandboxReadOnly  = "read-only"
	SandboxStrict    = "strict"
	SandboxWorkspace = "workspace"
)

Sandbox levels, strictest first (protocol v1 §6.5).

View Source
const (
	DefaultMaxTurns   = 80
	DefaultMaxWallSec = 2700
	DefaultMaxJobs    = 1
	MaxMaxJobs        = 16
	MaxMaxTurns       = 1000
	// MaxAllowedDomains bounds agent_allowed_domains; MaxMaxCostUSD bounds
	// max_cost_usd, the same ceiling the server puts on its own cap.
	MaxAllowedDomains = 16
	MaxMaxCostUSD     = 100
	// MaxDenySockets bounds agent_deny_sockets.
	MaxDenySockets = 32
	// DefaultAgentMaxCostUSD is the per-job cost cap when neither the server
	// nor this policy sets one (spec D5).
	DefaultAgentMaxCostUSD = 5
)

Policy defaults. A key absent from policy.toml takes these.

Variables

View Source
var (
	ErrRevoked     = errors.New("credential revoked: re-enrol this host (dd-worker init)")
	ErrReplaced    = errors.New("socket replaced 3 times in 10 minutes: another host uses this credential; re-enrol one of them")
	ErrProtocol    = errors.New("server does not speak worker protocol 1")
	ErrOrgMismatch = errors.New("policy.toml orgs does not list this worker's org")
	ErrNotEnrolled = errors.New("not enrolled: run dd-worker init")
)

Exit reasons of Run. cmd/dd-worker maps each to a non-zero exit.

View Source
var KnownAdapters = []string{"claude", "grok", "codex", "antigravity"}

KnownAdapters are the adapter names a policy may list (§5.1, Q4).

View Source
var Version = "0.1.0"

Version is the dd-worker version; cmd/dd-worker sets it from ldflags.

Functions

func CanonicalRepoURL

func CanonicalRepoURL(raw string) (string, error)

CanonicalRepoURL returns the canonical form the worker clones and hashes.

func CheckCredentialDir

func CheckCredentialDir(p Paths) error

CheckCredentialDir refuses a {state}/credential that is a symlink or not a directory: the credential is never written or read through a link. A missing dir is fine (it is created at mode 0700), and so is an empty one install.sh pre-created at 0700; one open to group or others is refused.

func EffectiveSandbox

func EffectiveSandbox(spec, floor string) string

EffectiveSandbox is the stricter of the spec's sandbox ("" is strict, as exec treats it) and the host's floor.

func Enroll

func Enroll(ctx context.Context, o EnrollOptions) (config.Config, error)

Enroll is §3: dial with the join token, send enroll, store the credential atomically at mode 0600. A refused token gets an error and writes nothing.

func Inside

func Inside(base, p string) bool

Inside reports whether p is base or below it, lexically.

func MigrateCredential

func MigrateCredential(p Paths, logf func(string, ...any)) error

MigrateCredential is the one-time move of a pre-W3 credential ({config}/env, env.prev) to {state}/credential/ (docs/worker-w3.md §3.2). It does nothing when there is no old env, or when the new env already exists. The move is a rename; when it fails (a root-owned /etc, or another filesystem) it logs the exact commands for the host owner and returns an error, so dd-worker run exits 1 instead of running from /etc.

func Under

func Under(base, rel string) (string, error)

Under joins base and a protocol relative path (§2) and checks the result stays under base. Every path the worker builds from a spec or frame goes through it.

func ValidEnvName

func ValidEnvName(s string) bool

ValidEnvName reports whether s is a usable environment variable name.

Types

type AdapterConfig

type AdapterConfig struct {
	ClaudeBin       string
	ClaudeConfigDir string // subscription mode: the logged-in config dir
	GrokBin         string
	GrokHome        string
	AgyBin          string
	AgyHome         string
}

AdapterConfig is how the host's coding-agent CLIs are found. Empty bins are looked up on PATH; empty homes take the CLI's default.

type EnrollOptions

type EnrollOptions struct {
	Paths       Paths
	Server      string // https origin
	JoinToken   string // dd_wjn_…, read from stdin
	InsecureDev bool
	// MachineIDFile is /etc/machine-id by default. When it is missing, a
	// random id is kept in {state}/machine-id instead.
	MachineIDFile string
	Hostname      string
}

EnrollOptions are dd-worker init's inputs.

type Options

type Options struct {
	Paths    Paths
	Adapters AdapterConfig
	Timing   Timing
	// SpoolMax is the worker-wide spool cap (§6.1, 200 MiB).
	SpoolMax int64
	// Log receives the worker's log lines, already redacted. Nil is stderr.
	Log io.Writer
	// OwnerUID overrides the owner check of policy.toml and secrets.env
	// (tests: a temp file cannot be chowned to root).
	OwnerUID func(os.FileInfo) (uint32, bool)
}

Options configure a Worker.

type Paths

type Paths struct {
	ConfigDir string
	StateDir  string
}

Paths is the worker's on-disk layout (docs/worker-w3.md §3.2). ConfigDir holds the host owner's files (policy.toml, secrets.env); it is root-owned and the worker never writes it. StateDir holds what the worker writes: the rotating credential (credential/env, env.prev), repos, jobs, controls.

func (Paths) AgentState

func (p Paths) AgentState(id string) string

AgentState is exec's per-job adapter state dir under DataRoot (the state dir): exec.Host.StateDir.

func (Paths) Blobs

func (p Paths) Blobs(id string) string

func (Paths) ControlsDir

func (p Paths) ControlsDir() string

func (Paths) CredentialDir

func (p Paths) CredentialDir() string

CredentialDir is {state}/credential (mode 0700): env and env.prev.

func (Paths) Env

func (p Paths) Env() string

func (Paths) EnvPrev

func (p Paths) EnvPrev() string

func (Paths) Evidence

func (p Paths) Evidence(id string) string

func (Paths) Handoff

func (p Paths) Handoff(id string) string

func (Paths) JobControls

func (p Paths) JobControls(id string) string

JobControls holds a job's stored control results, outside the job dir so a discard (which removes the job dir) can still answer a redelivery.

func (Paths) JobDir

func (p Paths) JobDir(id string) string

JobDir is {state}/jobs/<job_id>. id must already be a valid protocol id; JobDir panics otherwise, because a path built from an unchecked id is a traversal bug, not an input error.

func (Paths) JobMeta

func (p Paths) JobMeta(id string) string

func (Paths) JobsDir

func (p Paths) JobsDir() string

func (Paths) LegacyEnv

func (p Paths) LegacyEnv() string

LegacyEnv and LegacyEnvPrev are where a worker before W3 kept the credential; MigrateCredential moves them once.

func (Paths) LegacyEnvPrev

func (p Paths) LegacyEnvPrev() string

func (Paths) Policy

func (p Paths) Policy() string

func (Paths) ReadinessDir

func (p Paths) ReadinessDir() string

func (Paths) RepoClone

func (p Paths) RepoClone(canonicalURL string) string

RepoClone is {state}/repos/<sha256 of the canonical URL> (D1).

func (Paths) ReposDir

func (p Paths) ReposDir() string

ReposDir is {state}/repos; JobsDir is {state}/jobs (protocol v1 §8.2).

func (Paths) Secrets

func (p Paths) Secrets() string

func (Paths) SpoolRoot

func (p Paths) SpoolRoot(id string) string

SpoolRoot is the dir the spool package puts its "spool" dir in.

func (Paths) StatusFile

func (p Paths) StatusFile() string

StatusFile is {state}/status.json (dd-worker status); ReadinessDir is {state}/readiness (the adapters' readiness checks). Both are the worker's own files that an agent must not write (spec §4.1.11).

func (Paths) Worktree

func (p Paths) Worktree(id, repo string) (string, error)

Worktree is {state}/jobs/<job_id>/worktrees/<repo>.

func (Paths) WorktreeRoot

func (p Paths) WorktreeRoot(id string) string

type Policy

type Policy struct {
	Exists              bool
	Valid               bool
	Reason              string
	Hash                string
	Enabled             bool
	Orgs                []string
	Adapters            []string
	Repos               []string
	MinSandbox          string
	MaxTurns            int
	MaxWallSec          int
	MaxJobs             int
	AllowVerifyCommands bool
	AllowShip           bool
	// AllowedDomains are the exact hosts an agent's sandbox may reach
	// (empty: no network). MaxCostUSD lowers the server's per-job cost cap
	// (0: unset). Whole dollars: the policy file has no decimals.
	AllowedDomains []string
	MaxCostUSD     int
	// AgentBrowser is the host's headless browser ("": no browser jobs).
	// Setting it also gives a browser job's sandbox unix sockets, with every
	// host socket the worker could reach masked (B1, B2). DenySockets are
	// extra paths that sandbox hides.
	AgentBrowser string
	DenySockets  []string
	// contains filtered or unexported fields
}

Policy is /etc/dd-worker/policy.toml as the worker enforces it. When Valid is false every offer is declined policy_denied and Reason says why.

func LoadPolicy

func LoadPolicy(path string, skipOwner bool, uid func(os.FileInfo) (uint32, bool)) Policy

LoadPolicy reads path with bot-agent's file checks (root owner, not group- or world-writable, size) unless skipOwner, then applies DD's keys and defaults. uid overrides the owner for tests.

func (Policy) AdapterAllowed

func (p Policy) AdapterAllowed(name string) bool

AdapterAllowed reports whether name is in policy.adapters.

func (Policy) HasOrg

func (p Policy) HasOrg(org string) bool

HasOrg reports whether org is listed.

func (Policy) RepoAllowed

func (p Policy) RepoAllowed(raw string) bool

RepoAllowed canonicalises raw and matches it against policy.repos: the host exactly, the path segment by segment, "*" matching one segment.

func (Policy) Usable

func (p Policy) Usable() bool

Usable reports whether the policy lets the worker take any job.

func (Policy) Wire

func (p Policy) Wire() workerproto.Policy

Wire is the policy as hello and status report it (§4.1). masked_sockets is empty here; the worker adds its last scan (Worker.wirePolicy).

type Secrets

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

Secrets is /etc/dd-worker/secrets.env (D5): test-account passwords and adapter API keys the host owner keeps on this host. Values never leave the worker except to the one child that needs them.

func LoadSecrets

func LoadSecrets(path string, uid func(os.FileInfo) (uint32, bool)) (Secrets, error)

LoadSecrets reads path. A missing file is an empty set. The file must be a regular file (not a symlink) with no group or world bits, owned by root or by the worker's own user (the unit runs unprivileged and must read it). uid overrides the owner for tests.

func (Secrets) DenySet

func (s Secrets) DenySet(adapterKeep []string, specStrip []string) []string

DenySet is the env names stripped from every child of a job (§6.6, with Main Dev's 2026-11-15 clarification): every name in secrets.env except the chosen adapter's own key, plus the spec's StripEnv. The job's own SecretEnv is stripped too: exec reads that one value in-process and the child gets it only as DD_TEST_ACCOUNT_PASSWORD. Invalid names are ignored.

func (Secrets) Get

func (s Secrets) Get(name string) (string, bool)

Get returns the value of name.

func (Secrets) Names

func (s Secrets) Names() []string

Names are the variable names, sorted.

func (Secrets) Redactor

func (s Secrets) Redactor(extra ...string) redact.Exact

Redactor is the exact-value redaction set over every value, plus extra values (the worker credential, job tokens).

type Snapshot

type Snapshot struct {
	Connected bool                        `json:"connected"`
	Since     string                      `json:"since"`
	Server    string                      `json:"server"`
	WorkerID  string                      `json:"workerId"`
	OrgID     string                      `json:"orgId"`
	Version   string                      `json:"version"`
	Adapters  []workerproto.AdapterStatus `json:"adapters"`
	Policy    workerproto.Policy          `json:"policy"`
	PolicyWhy string                      `json:"policyReason,omitempty"`
	MaxJobs   int                         `json:"maxJobs"`
	Busy      []string                    `json:"busyJobIds"`
	// Tools is the last tools readiness (git, and browser with
	// agent_browser), as hello and status send it.
	Tools []workerproto.ToolStatus `json:"tools,omitempty"`
}

Snapshot is {state}/status.json, written by run for dd-worker status. It holds no credential, token or secret value.

func ReadSnapshot

func ReadSnapshot(p Paths) (Snapshot, error)

ReadSnapshot reads the last snapshot run wrote.

type Timing

type Timing struct {
	AcceptGrace     time.Duration // §5.2: 5 s with no lease_lost before starting
	CancelGrace     time.Duration // §4.4, §6.3: SIGINT then SIGKILL after 3 s
	BatchInterval   time.Duration // §6.1: 1 s
	Readiness       time.Duration // §4.2: 5 min
	ReplacedBackoff time.Duration // §4.5: at least 60 s plus jitter
	ReplacedWindow  time.Duration // §4.5: 10 min
	LeaseWait       time.Duration // replay a busy job with no lease frame after this
	HelloTimeout    time.Duration
	BackoffMax      time.Duration // reconnect backoff cap (conn.Backoff caps at 30 s)
}

Timing are the protocol's waits, overridable so tests run in seconds. Zero fields take the protocol values.

type Worker

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

Worker is one dd-worker process.

func New

func New(opts Options) (*Worker, error)

New loads the credential, policy and secrets and recovers jobs left by a previous run (§6.4).

func (*Worker) Run

func (w *Worker) Run(ctx context.Context) error

Run is the session loop: dial, hello, serve frames, reconnect with backoff, until ctx ends (nil) or the server ends this worker for good.

Jump to

Keyboard shortcuts

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