Documentation
¶
Overview ¶
Package agents dispatches one bounded coding task to one configured agent harness running inside an isolated WB worktree, and reports the execution facts of that run to whoever asks later.
It is deliberately the deterministic execution layer only: it resolves an agent profile, creates or resolves a worktree through WB's existing worktree service, launches the harness as a detached child, and records what happened. It never judges whether the work is correct. A PASS/FAIL/ESCALATE verdict on a diff is a semantic decision that belongs to the supervisor above WB, not to WB.
Index ¶
- Constants
- Variables
- func AllHarnesses() []string
- func BoundResult(message string) string
- func CodexArgv(options HarnessOptions) ([]string, error)
- func DetectVersion(ctx context.Context, harness string, deps PreflightDeps) string
- func HarnessCapabilityFor(harness string) string
- func IsRequestError(err error) bool
- func IsUnknownAgent(err error) bool
- func IsUnknownExperiment(err error) bool
- func LoadRemoteTargets(configPath string) (map[string]RemoteTarget, error)
- func NewExperimentID() string
- func NewID() (string, error)
- func NewRequestError(message string) error
- func NormalizeState(result *Result)
- func OwnerCLI(arguments []string, deps OwnerDeps) int
- func Preflight(ctx context.Context, resolved Resolved, deps PreflightDeps) error
- func ReadCredentialFile(path string) (string, error)
- func RecentActions(reader io.Reader, limit int) []string
- func RedactText(text, secret string) (string, int)
- func RenderDiff(ctx context.Context, record Record, patch bool, deps TargetDeps) (string, error)
- func RunOwner(ctx context.Context, store Store, agentID string, deps OwnerDeps) error
- func SpawnOwner(runDir string, executable func() (string, error), extraFiles []*os.File) (int, error)
- func SplitAgentRef(reference string) (machine, agentID string, err error)
- func SummaryLine(task string) string
- func TaskIdentity(task string) (digest string, size int)
- func ValidationBudget(steps []ValidationStepResult) time.Duration
- func WorkerEnvironment(credential Credential) []string
- type Attempt
- type ChangeSummary
- type Config
- type CostRecord
- type Credential
- type Defaults
- type DispatchDeps
- type DispatchRequest
- type ExecutionStatus
- type Experiment
- type ExperimentReport
- type Harness
- type HarnessCapabilities
- type HarnessLaunch
- type HarnessOptions
- type HarnessSummary
- type Launch
- type Lease
- type LeaseHeldError
- type LeaseInfo
- type OwnerDeps
- type Plan
- type Planner
- type PreflightDeps
- type PreparedRun
- type Profile
- type ProfileSummary
- type Provider
- type Record
- type RemoteDeps
- type RemoteRequest
- type RemoteResponse
- type RemoteTarget
- type RequestError
- type Resolved
- type Result
- type ReviewEntry
- type ReviewRecord
- type RunRequest
- type State
- type Store
- func (store Store) AcquireLease(worktreeDir, agentID, experimentID, repository string, now time.Time) (*Lease, error)
- func (store Store) AppendReview(agentID string, entry ReviewEntry) (ReviewRecord, error)
- func (store Store) BuildReport(experiment Experiment) ExperimentReport
- func (store Store) Create(record Record) error
- func (store Store) CreateExperiment(experiment Experiment) error
- func (store Store) Dir(agentID string) string
- func (store Store) ExperimentDir(experimentID string) string
- func (store Store) ExperimentPath(experimentID string) string
- func (store Store) HarnessHomePath(agentID string) string
- func (store Store) LastMessagePath(agentID string) string
- func (store Store) LeaseLive(worktreeDir string) (bool, error)
- func (store Store) LeasePath(worktreeDir string) (string, error)
- func (store Store) List() ([]Record, error)
- func (store Store) Load(agentID string) (Record, error)
- func (store Store) LoadExperiment(experimentID string) (Experiment, error)
- func (store Store) LoadReview(agentID string) (ReviewRecord, error)
- func (store Store) LogPath(agentID string) string
- func (store Store) RecordPath(agentID string) string
- func (store Store) Render(record Record) Result
- func (store Store) ReviewPath(agentID string) string
- func (store Store) Save(record Record) error
- func (store Store) WriteDiff(ctx context.Context, agentID, worktreeDir, baseSHA string, deps TargetDeps) (string, error)
- type Target
- type TargetDeps
- type TaskType
- type Telemetry
- type Tokens
- type UnknownAgentError
- type UnknownExperimentError
- type Usage
- type ValidationOptions
- type ValidationRecord
- type ValidationStep
- type ValidationStepResult
Constants ¶
const ( ModeNew = "new" ModeExisting = "existing" )
Worktree modes. Exactly one is required: creating a new isolated workspace and modifying an existing one have materially different intent, so they stay two explicit options rather than one ambiguous --worktree.
const ( AttemptPlanned = "planned" AttemptDispatched = "dispatched" AttemptBaseMismatch = "base_mismatch" AttemptFailed = "failed" )
Attempt states inside one experiment. An attempt that fails before it starts is still recorded: an experiment that silently drops a planned comparison would misreport itself.
const ( EffortConfig = "config" EffortVariant = "variant" EffortUnsupported = "unsupported" TaskDeliveryStdin = "stdin" TaskDeliveryArgv = "argv" UsageFromEvents = "events" CostHarnessEstimated = "harness-estimated" CredentialWBInjected = "wb-injected" CredentialHarnessStore = "harness-store" IsolationPrivateHome = "private-home" IsolationUserHome = "user-home" )
Harness capability vocabulary. A capability is declared by the adapter, not guessed from the configuration, so an unsupported setting is refused or recorded instead of being silently dropped.
const ( SourceExplicit = "explicit" SourceTaskType = "task_type" SourceTaskTypeComplexity = "task_type_complexity" SourceProfile = "profile" SourceDefault = "default" SourceSynthesized = "synthesized" SourceOverridden = "overridden" SourceFallback = "fallback" SourceNone = "none" )
Value sources recorded in a plan. They are the audit trail that answers "why did this run use this model", which a resolved snapshot alone cannot.
const ( HarnessCodex = "codex" HarnessOpenCode = "opencode" HarnessDSH = "dsh" )
Harness names a coding-agent environment and tool loop. Each name is an adapter in this package; the field exists so provider and model are not collapsed into the harness name.
const ( WireAPIResponses = "responses" WireAPIChat = "chat" )
Wire protocols the Codex harness can speak. The set is closed because it is the harness's own contract, not a user extension point.
const ( FallbackPreflight = "preflight" FallbackRuntime = "runtime" )
Fallback triggers. Preflight is a capability WB can prove before a worktree exists; runtime is a failure the harness reported after it started.
const ( RemoteDispatch = "dispatch" RemoteStatus = "status" RemoteAwait = "await" RemoteList = "list" RemoteLogs = "logs" RemoteStop = "stop" )
Remote operations, one per local command that can address another machine.
const ( DefaultRemoteTimeout = 10 * time.Minute // MaxRemoteLogBytes bounds a remote transcript fetch. `wb agent logs --raw` // over a link is the one operation that could pull an entire run into a // caller's context, so it is refused past this rather than truncated. MaxRemoteLogBytes = 2 << 20 )
Remote bounds and limits. A remote reply is a small protocol document, so the caps are generous for it and deliberately not generous for a transcript.
const ( FailureUsage = "usage" FailureConfig = "config" FailureCredential = "credential" FailureProvider = "provider" FailureHarnessMiss = "harness_missing" FailureHarness = "harness_failed" FailureValidation = "validation_failed" FailureTimeout = "timeout" FailureCancelled = "cancelled" FailureBaseMismatch = "base_mismatch" FailureWorktree = "worktree" FailureInternal = "internal" )
Failure categories are a closed vocabulary: an orchestration decision can branch on the category without parsing a message.
const ( ValidationPending = "pending" ValidationRunning = "running" ValidationPassed = "passed" ValidationFailed = "failed" ValidationSkipped = "skipped" )
Validation statuses. Validation is its own axis: a process can exit zero and still fail the objective checks.
const ( ReviewPending = "pending" ReviewAccepted = "accepted" ReviewRejected = "rejected" ReviewNeedsChange = "needs_changes" )
Review statuses. Review is the third axis and is written only by an explicit review command.
const ( ModeAuto = "auto" ModeCurrent = "current" ModePath = "path" )
Worktree modes for `run`/`compare`. ModeNew and ModeExisting predate them and stay supported by `dispatch`.
const ( AcceptanceRequired = "required" AcceptanceOptional = "optional" )
Acceptance policies a task type can declare.
const DefaultTimeout = 30 * time.Minute
DefaultTimeout bounds a dispatched run when the caller names no bound.
const DirName = "agents"
DirName is the directory under WB's home that holds dispatched agent runs.
const IDPrefix = "agt-"
IDPrefix begins every agent run ID. The shape follows WB's existing random session-ID convention rather than a timestamp, so an ID never encodes — and therefore never leaks — when or where the work happened.
const OwnerArgument = "--wb-internal-agent-run"
OwnerArgument selects the private, detached run-owner command. It is handled before normal command dispatch, following WB's existing self-exec convention for internal child processes: the dispatching process re-invokes its own executable with this argument rather than depending on a daemon.
const ProviderCredentialEnv = "WB_AGENT_PROVIDER_CREDENTIAL"
ProviderCredentialEnv is the environment variable WB synthesises when a provider supplies its credential as a file. The harness is told this name — never a value — so the same per-process mechanism serves both sources.
const ProviderDshDefault = "deepseek-official"
ProviderDshDefault is the only inference provider the `dsh` compose tree names, so it is the only one this build can prove for that harness.
const RemoteArgument = "--wb-internal-agent-remote"
RemoteArgument selects the private remote entry point. It is handled before normal command dispatch on the target machine, so the request can only be a validated protocol value read from stdin — never text the remote shell parsed.
Variables ¶
var ErrLeaseUnsupported = errors.New("exclusive worktree leases are not supported on this platform")
ErrLeaseUnsupported reports that this platform cannot express an exclusive file lock, so shared-checkout execution must be refused rather than raced.
Functions ¶
func AllHarnesses ¶
func AllHarnesses() []string
AllHarnesses is the ordered list of harness names this build can launch.
func BoundResult ¶
BoundResult trims the worker's final message so the one free-text artefact of a run cannot become the transcript it exists to replace.
func CodexArgv ¶
func CodexArgv(options HarnessOptions) ([]string, error)
CodexArgv builds the exact non-interactive Codex invocation.
The task is deliberately absent: it is delivered on stdin (a trailing "-"), so task text never appears in the process table. Values are JSON-encoded because the harness parses each override value as TOML, where a bare word and a quoted string are different things.
func DetectVersion ¶
func DetectVersion(ctx context.Context, harness string, deps PreflightDeps) string
DetectVersion reads the installed harness version, best effort. An unknown version is recorded as absent rather than guessed.
func HarnessCapabilityFor ¶
HarnessCapabilityFor answers the effort question without instantiating an adapter, so configuration validation and planning share one answer.
func IsRequestError ¶
IsRequestError reports whether an error refused the invocation.
func IsUnknownAgent ¶
IsUnknownAgent reports whether an error is a lookup miss rather than a corrupt record. A miss is a finding — the invocation was admitted and the named run does not exist — so the CLI can use the findings exit code instead of pretending the caller mistyped.
func IsUnknownExperiment ¶
IsUnknownExperiment reports whether an error is a lookup miss.
func LoadRemoteTargets ¶
func LoadRemoteTargets(configPath string) (map[string]RemoteTarget, error)
LoadRemoteTargets reads the configured machines WB may dispatch to.
It reuses WB's session_move target map on purpose. A machine and its courier address are one fact about the fleet; a second list would be a second place to be wrong, and the operator would have to keep them in step by hand.
func NewRequestError ¶
NewRequestError marks an error as a refused invocation (exit 2) rather than a finding, for callers outside this package.
func NormalizeState ¶
func NormalizeState(result *Result)
NormalizeState makes this process's closed state vocabulary authoritative for a result that arrived from somewhere else. A remote answer carries a state; whether that state is terminal is WB's rule, so it is derived here rather than trusted from the wire, where a version skew could disagree.
func OwnerCLI ¶
OwnerCLI runs the private owner command line:
wb --wb-internal-agent-run --run-dir <absolute run directory>
It is called from main before cobra parses anything, so the owner can never be affected by, or accidentally honour, a user-facing flag contract.
func Preflight ¶
func Preflight(ctx context.Context, resolved Resolved, deps PreflightDeps) error
Preflight proves an execution can start before anything is created: the harness binary exists, a Codex run has a resolvable credential, and a `dsh` run can prove the model its overlay asks for.
func ReadCredentialFile ¶
ReadCredentialFile reads a credential file, refusing anything that is not a private regular file WB itself would have written.
The permission check is deliberate: a credential readable by another account on the machine is not a credential, and discovering that at dispatch time is far better than discovering it in a log.
func RecentActions ¶
RecentActions condenses the harness event stream into the last few things the worker actually did. It exists so `wb agent logs` can show a human something useful without printing an entire run into a caller's context.
func RedactText ¶
RedactText applies the same rule to a whole value, such as the harness's own final-message file, which it writes itself and which the stream writer never sees.
func RenderDiff ¶
RenderDiff builds the `wb agent diff` document for one finished run. The short form reports the stat and the untracked paths; the patch form prints the bounded patch itself.
func RunOwner ¶
RunOwner executes one dispatched run to completion and records its terminal state. It is the process that outlives the dispatching CLI, so everything a later `status` or `await` can learn about the run is written here.
func SpawnOwner ¶
func SpawnOwner(runDir string, executable func() (string, error), extraFiles []*os.File) (int, error)
SpawnOwner starts the detached run owner for a persisted run and returns without waiting for it. The owner is this same WB executable re-invoked with the private owner argument, so a dispatched run needs no daemon and survives the dispatching CLI exiting.
func SplitAgentRef ¶
SplitAgentRef accepts either a bare agent run ID or the machine-qualified form a remote dispatch prints, so a supervisor can pass back exactly what it was given. An agent ID contains only the prefix and hexadecimal, so the colon is unambiguous.
func SummaryLine ¶
SummaryLine is the one-line non-sensitive description stored beside the private task so listings and cross-machine checks can name the work without republishing it.
func TaskIdentity ¶
TaskIdentity returns the identity of the exact task bytes without keeping a second copy of them.
func ValidationBudget ¶
func ValidationBudget(steps []ValidationStepResult) time.Duration
ValidationBudget is the worst-case time the snapshotted steps can take, so a caller waiting for a run can bound validation as well as the harness.
func WorkerEnvironment ¶
func WorkerEnvironment(credential Credential) []string
WorkerEnvironment builds the child harness environment.
It is an allowlist, following WB's existing detached-worker convention: a delegated worker gets the variables it genuinely needs and nothing else. That is a stronger guarantee than any deny-list, because a secret this machine happens to export tomorrow is excluded by default rather than by pattern.
Neither a whole-environment copy nor an ambient-agent-variable inheritance is acceptable here: the first hands a model-driven process every credential on the machine, and the second would make a dispatched worker look like the parent session it must not disturb.
Types ¶
type Attempt ¶
type Attempt struct {
Profile string `json:"profile"`
RepeatIndex int `json:"repeat_index"`
AgentID string `json:"agent_id"`
Operation string `json:"operation"`
BaseSHA string `json:"base_sha,omitempty"`
Status string `json:"status"`
Failure string `json:"failure,omitempty"`
}
Attempt is one planned execution inside an experiment.
type ChangeSummary ¶
type ChangeSummary struct {
FilesChanged int `json:"files_changed"`
Files []string `json:"files,omitempty"`
Insertions int `json:"insertions,omitempty"`
Deletions int `json:"deletions,omitempty"`
Commits int `json:"commits,omitempty"`
Truncated bool `json:"files_truncated,omitempty"`
// Untracked lists paths Git does not include in a diff, so a reader knows
// the patch is incomplete rather than assuming a small change.
Untracked []string `json:"untracked,omitempty"`
}
ChangeSummary is a cheap, deterministic description of what the worker left behind in its worktree.
func SummarizeChangesWith ¶
func SummarizeChangesWith(ctx context.Context, worktreeDir, baseSHA string, preexisting []string) *ChangeSummary
SummarizeChanges derives a cheap, deterministic description of what a worker left behind in its worktree. It reads Git state only; it never reads file contents, so it cannot grow into a transcript and cannot be mistaken for a review of the change.
A failure to read Git state yields no summary rather than a failed run: the worktree is the artefact and a missing diff stat must not hide it. SummarizeChangesWith describes what a worker left behind. The preexisting paths are the ones that were already dirty before it started: when a base commit is known the changed files come from the diff, which includes the worker's commits and excludes pre-existing uncommitted work; otherwise Git status is the only evidence available.
type Config ¶
type Config struct {
Providers map[string]Provider
Profiles map[string]Profile
TaskTypes map[string]TaskType
// ConfiguredTaskTypes records which task types came from the operator, so
// discovery can tell an override from a built-in.
ConfiguredTaskTypes map[string]bool
Validations map[string][]ValidationStep
Defaults Defaults
Fallback []string
}
Config is the resolved user agent configuration: providers, profiles, task types, named validation suites, defaults and the ordered fallback list.
func LoadConfigFile ¶
LoadConfigFile reads the agent configuration from a wb.yaml document. A missing file is not an error: it yields the built-in provider registry and no profiles, so "no such profile" stays the actionable message rather than "no such file".
func (Config) ProfileNames ¶
ProfileNames returns every configured profile in name order.
func (Config) ProviderNames ¶
ProviderNames returns every provider (built-in or overridden) in name order.
func (Config) Resolve ¶
Resolve turns a requested profile name into an executable configuration, failing closed on anything it cannot execute.
func (Config) TaskTypesInOrder ¶
TaskTypes returns every task type, built-in or configured, in name order.
type CostRecord ¶
type CostRecord struct {
USD *float64 `json:"usd,omitempty"`
Kind string `json:"kind"`
Source string `json:"source"`
PricingVersion string `json:"pricing_version,omitempty"`
EstimatedAt *time.Time `json:"estimated_at,omitempty"`
Note string `json:"note,omitempty"`
}
CostRecord is an API-equivalent estimate, never a billed amount. A nil USD means no per-run price was observed.
type Credential ¶
Credential is a resolved provider credential: the environment variable name the harness must read it from, and the value WB injects under that name. The value never leaves the child's environment.
func ResolveCredential ¶
func ResolveCredential(provider Provider) (Credential, error)
ResolveCredential reads the credential a provider names, from whichever source that provider configured. It fails closed with a message naming the exact source, because a missing credential is the single most likely reason a dispatch cannot start.
type Defaults ¶
type Defaults struct {
TaskType string `yaml:"task_type,omitempty" json:"task_type,omitempty"`
Profile string `yaml:"profile,omitempty" json:"profile,omitempty"`
}
Defaults are the values a request inherits when it names neither a task type nor a profile. They exist so an operator can make one command the default without editing every task type.
type DispatchDeps ¶
type DispatchDeps struct {
ConfigPath string
LoadConfig func() (Config, error)
ProjectsRoot string
Home string
// BeforeCreate refreshes managed hooks in the canonical clones, exactly as
// `wb worktree create` does before it creates anything.
BeforeCreate func(repositories []string) error
// AfterCreate writes the checkout marker exactly as `wb worktree create`
// does after creation. It MUST be best-effort: a marker WB could not write
// does not make a checkout unusable.
AfterCreate func(repositories []string, results []worktrees.CreateResult)
// CreateWorktree, ListWorktrees, and OriginSlug default to WB's own
// worktree service. They are injectable only so the orchestration above them
// can be exercised without a live fleet; production never replaces them.
CreateWorktree func(context.Context, []string, worktrees.CreateOptions) ([]worktrees.CreateResult, error)
ListWorktrees func(context.Context, worktrees.ListOptions) ([]worktrees.ListResult, error)
OriginSlug func(context.Context, string) (string, error)
// SpawnOwner starts the detached run owner for a persisted run and returns
// its process ID. extraFiles carry the inherited writer lease, so the claim
// lives exactly as long as the owner or anything it starts.
SpawnOwner func(agentID string, extraFiles []*os.File) (int, error)
// Preflight proves the resolved profile can start before a worktree exists.
Preflight func(context.Context, Resolved) error
// DetectVersion reads the installed harness version, best effort.
DetectVersion func(context.Context, string) string
Now func() time.Time
}
DispatchDeps are the seams dispatch needs from the command layer. Only the things internal/agents cannot know about — WB's CLI-layer worktree side effects, and how a detached owner is started — are injected; everything else is reused directly.
type DispatchRequest ¶
type DispatchRequest struct {
Mode string
Worktree string
// Plan is the resolved execution plan. When it is nil the request is the
// legacy `dispatch` shape and Profile is resolved on its own.
Plan *Plan
Profile string
Task string
// Repository is owner/repository. Empty means "derive it from the invoking
// checkout's origin", exactly as `wb worktree create` does.
Repository string
// Branch and Base are optional pass-throughs to WB's existing worktree
// naming policy; empty leaves that policy in charge.
Branch string
Base string
Timeout time.Duration
AllowCanonical bool
AllowDirty bool
// AgentID lets a caller pre-allocate the identity, which an experiment must
// do before it records its plan. Empty mints a fresh one.
AgentID string
// ExperimentID and RepeatIndex place this execution in a comparison.
ExperimentID string
RepeatIndex int
// RetryOf, FallbackFrom and FallbackReason describe an infrastructure
// failover: this execution replaces another one after its provider failed.
RetryOf string
FallbackFrom string
FallbackReason string
}
DispatchRequest is one requested offload.
type ExecutionStatus ¶
type ExecutionStatus string
ExecutionStatus is the richer, additive status of one execution. It never replaces State: an older build must still be able to list and await a record this build wrote.
const ( StatusQueued ExecutionStatus = "queued" StatusRunning ExecutionStatus = "running" StatusCompleted ExecutionStatus = "completed" StatusFailed ExecutionStatus = "failed" StatusCancelled ExecutionStatus = "cancelled" StatusTimedOut ExecutionStatus = "timed_out" // StatusAbandoned is derived at read time when the owner process vanished // without recording a terminal status. It is never stored. StatusAbandoned ExecutionStatus = "abandoned" )
func (ExecutionStatus) String ¶
func (status ExecutionStatus) String() string
String is the string form of an execution status.
func (ExecutionStatus) Terminal ¶
func (status ExecutionStatus) Terminal() bool
Terminal reports whether an execution status is final.
type Experiment ¶
type Experiment struct {
SchemaVersion int `json:"schema_version"`
ExperimentID string `json:"experiment_id"`
TaskSHA256 string `json:"task_sha256"`
TaskBytes int `json:"task_bytes"`
TaskType string `json:"task_type"`
Complexity string `json:"complexity,omitempty"`
Base string `json:"base,omitempty"`
BaseSHA string `json:"base_sha,omitempty"`
Profiles []string `json:"profiles"`
Repeat int `json:"repeat"`
Concurrency int `json:"concurrency"`
Attempts []Attempt `json:"attempts"`
CreatedAt time.Time `json:"created_at"`
// UncontrolledDifferences states what WB could not hold equal across
// attempts, so a reader never mistakes a comparison for a controlled trial.
UncontrolledDifferences []string `json:"uncontrolled_differences,omitempty"`
}
Experiment is the immutable description of one comparison: one task, one base, several profiles and repeats. It is written once, before any execution starts, and never rewritten; member results live in their own run records.
type ExperimentReport ¶
type ExperimentReport struct {
Experiment
Runs []Result `json:"runs"`
Summaries []ProfileSummary `json:"summaries"`
}
ExperimentReport is the persisted experiment plus its member results and the per-profile rollup.
type Harness ¶
type Harness interface {
Name() string
Capabilities() HarnessCapabilities
Prepare(Launch) (HarnessLaunch, error)
Summarize(io.Reader) HarnessSummary
Actions(io.Reader, int) []string
}
Harness is one coding-agent adapter. Three implementations exist; adding a fourth is a new file in this package plus a name in supportedHarnesses.
func HarnessFor ¶
HarnessFor returns the adapter for a harness name.
type HarnessCapabilities ¶
type HarnessCapabilities struct {
Harness string `json:"harness"`
JSONEvents bool `json:"json_events"`
TaskDelivery string `json:"task_delivery"`
TokenUsage string `json:"token_usage"`
Cost string `json:"cost"`
Effort string `json:"effort"`
Credential string `json:"credential_source"`
Isolation string `json:"isolation"`
// Version is filled from the installed binary at dispatch time; it is
// empty in a dry run, which starts no process.
Version string `json:"version,omitempty"`
}
HarnessCapabilities is what WB can prove about one adapter. It is recorded on every run so a comparison can state which differences were not controlled.
type HarnessLaunch ¶
type HarnessLaunch struct {
Argv []string
Env []string
Stdin string
// PrivateFiles are paths the adapter wrote for this launch, recorded so a
// reader can find them; they live under the private run directory.
PrivateFiles []string
// SplitStderr keeps stderr out of the captured result stream. An adapter
// whose stdout *is* the final message needs it: merged diagnostics would
// become part of the answer.
SplitStderr bool
}
HarnessLaunch is the exact process an adapter wants WB to start. Nothing about a harness's flag spelling lives above this boundary.
type HarnessOptions ¶
type HarnessOptions struct {
WorktreeDir string
Model string
Reasoning string
// ProviderName keys the provider registry entry, and Provider carries the
// routing. The credential itself is never here — only the environment
// variable name the harness must read it from.
ProviderName string
Provider Provider
// LastMessagePath asks the harness to write its final message there, which
// is the one bounded, non-transcript result channel.
LastMessagePath string
}
HarnessOptions is everything the Codex harness needs that is not in the process environment. It exists so every harness-specific flag and configuration-key spelling lives in exactly one file: a harness version change is a one-file change.
type HarnessSummary ¶
type HarnessSummary struct {
TurnCompleted bool
TurnFailed bool
// Tokens is nil when the harness reported no usage at all; a harness that
// reports zeros fills the pointers with zeros.
Tokens *Tokens
// CostUSD is a per-run cost the harness itself estimated. It is nil when the
// harness reports none, and zero values are rejected by CostRecord.
CostUSD *float64
// CostNote explains a reported-but-unusable cost, such as a zero cost on a
// subscription plan.
CostNote string
ToolCalls int
// Diagnostics are non-fatal harness messages worth keeping in the record.
Diagnostics []string
// MalformedLines counts lines that look like harness events but could not
// be decoded. Ordinary non-JSON output is a harness's own stderr sharing the
// file and is expected; a malformed *event* is not.
MalformedLines int
// FinalMessage is set by adapters whose only output is the final message,
// such as `dsh`.
FinalMessage string
}
HarnessSummary is what the run owner extracts from one harness stream. It is execution metadata only: nothing here judges whether the work is correct.
func SummarizeEvents ¶
func SummarizeEvents(reader io.Reader) HarnessSummary
SummarizeEvents parses the Codex JSONL event stream.
type Launch ¶
type Launch struct {
RunDir string
WorktreeDir string
Model string
Variant string
Effort string
ProviderName string
Provider Provider
LastMessagePath string
// Task is used only by adapters that deliver the task on the command line.
Task string
}
Launch is everything an adapter needs to build one non-interactive run.
type Lease ¶
type Lease struct {
// contains filtered or unexported fields
}
Lease is an exclusive writer claim on one worktree. The open descriptor is what holds the claim, so the claim survives as long as any process inheriting it lives.
func (*Lease) File ¶
File is the descriptor a dispatcher passes to the detached owner. Inheriting it is what keeps the claim held until the last worker process exits.
type LeaseHeldError ¶
LeaseHeldError reports that another live execution owns a worktree. It names the owner so the caller can await or stop that run instead of guessing.
func (*LeaseHeldError) Error ¶
func (err *LeaseHeldError) Error() string
type LeaseInfo ¶
type LeaseInfo struct {
SchemaVersion int `json:"schema_version"`
AgentID string `json:"agent_id"`
ExperimentID string `json:"experiment_id,omitempty"`
Repository string `json:"repository,omitempty"`
WorktreeDir string `json:"worktree_dir"`
OwnerPID int `json:"owner_pid,omitempty"`
ClaimedAt time.Time `json:"claimed_at"`
}
LeaseInfo is the diagnostic body of a lease file. It is never the authority: the authority is the kernel's lock on the retained inode.
type OwnerDeps ¶
type OwnerDeps struct {
// LookPath resolves the harness executable. Resolving it by name through
// PATH is what lets a test substitute a fake harness without a production
// override flag.
LookPath func(string) (string, error)
// Now is the clock, injected for deterministic tests.
Now func() time.Time
// Sleep is StopRun's grace-period poll seam, injected for deterministic
// tests. A test exercising a worker that ignores termination shrinks
// StopGrace/StopPollInterval instead of leaving Sleep real, because that
// path genuinely waits on a real OS process; every other test replaces
// Sleep with a recorder.
Sleep func(time.Duration)
// StopGrace and StopPollInterval configure StopRun's escalation wait.
// Both are struct fields, not package-level mutable vars, so a test
// cannot leave shared package state mutated for another test running in
// parallel. StopRun does not default a zero OwnerDeps -- every caller
// (production and test) builds on DefaultOwnerDeps, which already
// populates every field, so StopRun trusts deps as given.
StopGrace time.Duration
StopPollInterval time.Duration
// Lease is the inherited worktree claim. Production reads the descriptor the
// dispatcher passed; a test supplies a file it already holds a lock on.
Lease *os.File
// Validation runs the snapshotted objective checks. It is a seam so a test
// can assert the environment and the inherited lease without spawning a
// process tree.
Validation func(context.Context, ValidationOptions) ValidationRecord
}
OwnerDeps are the seams the run owner needs. They are injected so the whole owner can be exercised deterministically against a fake harness.
func DefaultOwnerDeps ¶
func DefaultOwnerDeps() OwnerDeps
DefaultOwnerDeps returns the production seams. Lease is deliberately not set here: only OwnerCLI, the detached entry point, may adopt an inherited descriptor, because a test process's fd 3 is not a lease.
type Plan ¶
type Plan struct {
TaskType string `json:"task_type"`
TaskTypeSource string `json:"task_type_source"`
Profile Resolved `json:"profile"`
ProfileSource string `json:"profile_source"`
Complexity string `json:"complexity,omitempty"`
ComplexitySource string `json:"complexity_source,omitempty"`
ComplexityOverridden bool `json:"complexity_overridden,omitempty"`
EffortRequested string `json:"effort_requested,omitempty"`
EffortSource string `json:"effort_source,omitempty"`
EffortEffective string `json:"effort_effective,omitempty"`
EffortApplied bool `json:"effort_applied"`
EffortVariant string `json:"effort_variant,omitempty"`
EffortNote string `json:"effort_note,omitempty"`
WorktreeMode string `json:"worktree_mode"`
WorktreeSource string `json:"worktree_source"`
TimeoutMS int64 `json:"timeout_ms"`
TimeoutSource string `json:"timeout_source"`
Validation []string `json:"validation,omitempty"`
ValidationSource string `json:"validation_source"`
ValidationSteps []ValidationStep `json:"validation_steps,omitempty"`
AcceptanceRequired bool `json:"acceptance_required"`
// FallbackFrom names the profile the plan would have used when preflight
// substituted a configured fallback. Empty means no substitution happened.
FallbackFrom string `json:"fallback_from,omitempty"`
// FallbackReason explains a preflight substitution: why the chosen profile
// was unusable.
FallbackReason string `json:"fallback_reason,omitempty"`
// FallbackChain is the remaining ordered profiles a runtime failover may
// use, after the chosen one. Empty when the task type declares none.
FallbackChain []string `json:"fallback_chain,omitempty"`
// FallbackOn records which triggers are enabled for this plan.
FallbackOn []string `json:"fallback_on,omitempty"`
// contains filtered or unexported fields
}
Plan is one fully resolved execution. It is the `--dry-run` document and the provenance snapshot a run record keeps for each resolved value.
func (Plan) AllowsFallback ¶
AllowsFallback reports whether a plan permits the given trigger.
type Planner ¶
Planner resolves requests against one configuration. Probe is the preflight a caller can supply — harness present, credential resolvable — and is the only reason a plan can fall back to another configured profile.
type PreflightDeps ¶
type PreflightDeps struct {
LookPath func(string) (string, error)
ResolveCredential func(Provider) (Credential, error)
Run func(ctx context.Context, name string, args ...string) ([]byte, error)
TempDir func() (string, error)
}
PreflightDeps are the seams preflight needs.
func DefaultPreflightDeps ¶
func DefaultPreflightDeps() PreflightDeps
DefaultPreflightDeps returns the production seams.
type PreparedRun ¶
type PreparedRun struct {
Record Record
Lease *Lease
// Store is the run store the record lives in, so an aborted preparation can
// still be recorded as a terminal failure.
Store Store
}
PreparedRun is an admitted execution: resolved, recorded, leased and waiting for its owner. Splitting preparation from start is what lets a comparison create every worktree — and therefore pin every base — before any worker runs.
func PrepareRun ¶
func PrepareRun(ctx context.Context, request DispatchRequest, deps DispatchDeps) (*PreparedRun, error)
PrepareRun resolves the plan, proves it can start, resolves or creates the worktree, takes the writer lease, and persists the run record. It starts no process, so a caller can prepare several attempts and start them later.
type Profile ¶
type Profile struct {
Harness string `yaml:"harness" json:"harness"`
Provider string `yaml:"provider,omitempty" json:"provider,omitempty"`
Model string `yaml:"model" json:"model"`
// Variant is an OpenCode model variant, appended as "#variant" when the
// argv is built. It is a separate field because "#" is not a legal
// execution identifier and because a variant name is model-specific.
Variant string `yaml:"variant,omitempty" json:"variant,omitempty"`
// EffortVariants maps a WB effort level to the harness's own variant name.
// An effort with no mapping is not applied to OpenCode.
EffortVariants map[string]string `yaml:"effort_variants,omitempty" json:"effort_variants,omitempty"`
// Effort is the profile's default reasoning effort. Reasoning is the
// legacy spelling of the same thing; naming both is an error.
Effort string `yaml:"effort,omitempty" json:"effort,omitempty"`
Reasoning string `yaml:"reasoning,omitempty" json:"reasoning,omitempty"`
// Timeout is a Go duration string bounding one run with this profile.
Timeout string `yaml:"timeout,omitempty" json:"timeout,omitempty"`
}
Profile is a named agent execution configuration. It is intentionally this small: harness + provider + model + optional effort and timeout, and nothing else. Nothing here names a model WB ships: the operator's configuration is the only place a model identifier exists.
type ProfileSummary ¶
type ProfileSummary struct {
Profile string `json:"profile"`
Attempts int `json:"attempts"`
Completed int `json:"completed"`
Failed int `json:"failed"`
Validated int `json:"validated"`
Accepted int `json:"accepted"`
// MeanDurationMS is the mean wall time of terminal attempts, or nil when
// none finished.
MeanDurationMS *int64 `json:"mean_duration_ms,omitempty"`
// TotalTokens is nil unless every completed attempt reported usage.
TotalTokens *int `json:"total_tokens,omitempty"`
}
ProfileSummary aggregates the attempts of one profile.
type Provider ¶
type Provider struct {
BaseURL string `yaml:"base_url" json:"base_url"`
// CredentialEnv is the *name* of the environment variable holding the
// credential. The value is read from the process environment at launch and
// never persisted.
CredentialEnv string `yaml:"credential_env,omitempty" json:"credential_env,omitempty"`
// CredentialFile is an absolute path to a private file holding the
// credential, following WB's existing credential-file convention (a path in
// configuration, the secret in a 0600 file under
// ~/.config/wb/credentials). It exists because a dispatched worker needs its
// credential in the harness's environment, and a remote machine reachable
// only over non-interactive SSH has no reliable place to export one.
CredentialFile string `yaml:"credential_file,omitempty" json:"credential_file,omitempty"`
WireAPI string `yaml:"wire_api" json:"wire_api"`
}
Provider is one entry in the provider registry: where inference lives, which environment variable carries its credential, and which wire protocol the harness must use. It never carries the credential itself.
type Record ¶
type Record struct {
SchemaVersion int `json:"schema_version"`
AgentID string `json:"agent_id"`
State State `json:"state"`
// ExecutionStatus is the additive status; empty on a record written before
// this field existed, in which case it is derived from State.
ExecutionStatus ExecutionStatus `json:"execution_status,omitempty"`
FailureCategory string `json:"failure_category,omitempty"`
// RequestedProfile is what the caller asked for. Resolved is what actually
// ran; keeping both is what makes a later profile edit harmless.
RequestedProfile string `json:"requested_profile"`
Resolved Resolved `json:"resolved"`
// Routing provenance: every resolved value says where it came from.
TaskType string `json:"task_type,omitempty"`
TaskTypeSource string `json:"task_type_source,omitempty"`
ProfileSource string `json:"profile_source,omitempty"`
RoutingReason string `json:"routing_reason,omitempty"`
Complexity string `json:"complexity,omitempty"`
ComplexitySource string `json:"complexity_source,omitempty"`
ComplexityOverridden bool `json:"complexity_overridden,omitempty"`
EffortRequested string `json:"effort_requested,omitempty"`
EffortSource string `json:"effort_source,omitempty"`
EffortEffective string `json:"effort_effective,omitempty"`
EffortApplied bool `json:"effort_applied,omitempty"`
EffortNote string `json:"effort_note,omitempty"`
WorktreeSource string `json:"worktree_source,omitempty"`
TimeoutSource string `json:"timeout_source,omitempty"`
HarnessVersion string `json:"harness_version,omitempty"`
HarnessCapabilities HarnessCapabilities `json:"harness_capabilities"`
// Task is the exact originating request. It is private: it is never
// rendered by status or await, only persisted here.
Task string `json:"task"`
// TaskSummary is a bounded, single-line form of Task for a human reading
// the record. It is derived from the task, so it is private for exactly the
// same reason Task is, and is likewise never rendered.
TaskSummary string `json:"task_summary,omitempty"`
// TaskSHA256 is the identity of the exact task bytes, so two executions can
// be proven comparable without republishing the task.
TaskSHA256 string `json:"task_sha256,omitempty"`
TaskBytes int `json:"task_bytes,omitempty"`
Repository string `json:"repository"`
WorktreeMode string `json:"worktree_mode"`
Worktree string `json:"worktree"`
WorktreeDir string `json:"worktree_dir,omitempty"`
Branch string `json:"branch,omitempty"`
Base string `json:"base,omitempty"`
BaseSHA string `json:"base_sha,omitempty"`
// SourceSHA is the commit the writable checkout was at when the run
// started, and SnapshotSHA the stash commit a dirty checkout produced, so a
// later diff separates the worker's change from what was already there.
SourceSHA string `json:"source_sha,omitempty"`
SnapshotSHA string `json:"snapshot_sha,omitempty"`
SourceDirty bool `json:"source_dirty,omitempty"`
DirtyFiles []string `json:"source_dirty_files,omitempty"`
// WorkLogClaimPath links this run to the immutable Work Log claim the
// worktree service already publishes, so one dispatch never produces two
// unreferenced records of the same piece of work.
WorkLogClaimPath string `json:"work_log_claim_path,omitempty"`
WorkLogRunID string `json:"work_log_run_id,omitempty"`
// LeasePath is the retained writer-lease file this run holds, if any.
LeasePath string `json:"lease_path,omitempty"`
// ExperimentID and RepeatIndex place this execution in a comparison. Both
// are empty for a standalone run.
ExperimentID string `json:"experiment_id,omitempty"`
RepeatIndex int `json:"repeat_index,omitempty"`
// RetryOf is the execution this one replaces after an infrastructure
// failover, and FallbackFrom/FallbackReason say which profile failed and why.
// A retry is a new execution with its own worktree, never a resumed one.
RetryOf string `json:"retry_of,omitempty"`
FallbackFrom string `json:"fallback_from,omitempty"`
FallbackReason string `json:"fallback_reason,omitempty"`
// TimeoutMS bounds the run. It is persisted because the owner, not the
// dispatcher, enforces it.
TimeoutMS int64 `json:"timeout_ms,omitempty"`
// StartedAt is when the run was admitted. ExecutionStartedAt is when the
// harness itself started, so queue time never inflates wall time.
StartedAt time.Time `json:"started_at"`
ExecutionStartedAt time.Time `json:"execution_started_at,omitempty"`
FinishedAt time.Time `json:"finished_at,omitempty"`
DurationMS int64 `json:"duration_ms,omitempty"`
// QueueDurationMS is how long an execution waited behind a concurrency
// bound before its harness started.
QueueDurationMS int64 `json:"queue_duration_ms,omitempty"`
// TimeToFirstOutputMS is how long the harness ran before its first byte.
TimeToFirstOutputMS int64 `json:"time_to_first_output_ms,omitempty"`
// QueueOwnerPID is the dispatching process while a run is queued behind a
// concurrency bound. It is the only liveness evidence a queued run has.
QueueOwnerPID int `json:"queue_owner_pid,omitempty"`
OwnerPID int `json:"owner_pid,omitempty"`
WorkerPID int `json:"worker_pid,omitempty"`
ExitCode *int `json:"exit_code,omitempty"`
Failure string `json:"failure,omitempty"`
Result string `json:"result,omitempty"`
ToolCalls int `json:"tool_calls,omitempty"`
Usage *Usage `json:"usage,omitempty"`
Changes *ChangeSummary `json:"changes,omitempty"`
HarnessEvents []string `json:"harness_diagnostics,omitempty"`
// Telemetry and Cost carry the provenance the legacy Usage cannot express.
Telemetry Telemetry `json:"telemetry"`
Cost CostRecord `json:"cost"`
Validation ValidationRecord `json:"validation"`
// DiffPath is the private patch artefact for this run, when one was written.
DiffPath string `json:"diff_path,omitempty"`
// AcceptanceRequired records the task type's policy at dispatch time, so a
// later configuration change cannot make an unreviewed run look complete.
AcceptanceRequired bool `json:"acceptance_required,omitempty"`
// Retries counts automatic retries attempted. This build performs none.
Retries int `json:"retries"`
// TaskVisibility states how the task reached the harness. `stdin` keeps it
// off the process table; `argv` does not.
TaskVisibility string `json:"task_visibility,omitempty"`
TaskNormalized bool `json:"task_normalized,omitempty"`
LogPath string `json:"log_path,omitempty"`
}
Record is the durable description of one dispatched run. It is private: it holds the original task, which never travels back out through status or await.
func Dispatch ¶
func Dispatch(ctx context.Context, request DispatchRequest, deps DispatchDeps) (Record, error)
Dispatch admits one run, creates or resolves its worktree, persists the run, and starts the detached owner. It returns as soon as the owner is started: the caller is never attached to the worker's stdout and never waits for it.
func StartRun ¶
func StartRun(prepared *PreparedRun, deps DispatchDeps) (Record, error)
StartRun starts the detached owner for a prepared run and returns without waiting. The run is already durable, so a launch failure is diagnosable.
type RemoteDeps ¶
type RemoteDeps struct {
// LookPath resolves the local ssh executable.
LookPath func(string) (string, error)
// Runner executes it. Replacement is for tests only.
Runner remotessh.Runner
// Timeout bounds one remote call when the operation has no bound of its own.
Timeout time.Duration
}
RemoteDeps are the seams the local side needs to reach another machine.
func DefaultRemoteDeps ¶
func DefaultRemoteDeps() RemoteDeps
DefaultRemoteDeps returns the production seams.
type RemoteRequest ¶
type RemoteRequest struct {
SchemaVersion int `json:"schema_version"`
Operation string `json:"operation"`
// dispatch
Mode string `json:"mode,omitempty"`
Worktree string `json:"worktree,omitempty"`
Profile string `json:"profile,omitempty"`
Task string `json:"task,omitempty"`
Repository string `json:"repository,omitempty"`
Branch string `json:"branch,omitempty"`
Base string `json:"base,omitempty"`
TimeoutMS int64 `json:"timeout_ms,omitempty"`
// status, await, logs, stop
AgentID string `json:"agent_id,omitempty"`
WaitTimeoutMS int64 `json:"wait_timeout_ms,omitempty"`
Raw bool `json:"raw,omitempty"`
Tail int `json:"tail,omitempty"`
}
RemoteRequest is the exact request a local WB sends to a remote WB. The remote validates it with the same code that validates local flags, so a request can never reach a state a local invocation could not.
func (RemoteRequest) Validate ¶
func (request RemoteRequest) Validate() error
Validate refuses a request that is not a well-formed WB agent protocol value. It is deliberately independent of the local flag parser: a hand-written request must satisfy exactly the same constraints.
type RemoteResponse ¶
type RemoteResponse struct {
SchemaVersion int `json:"schema_version"`
Operation string `json:"operation"`
Result *Result `json:"result,omitempty"`
// Results deliberately has no omitempty: an empty inventory must travel as
// an empty list, not disappear into a null the caller has to special-case.
Results []Result `json:"results"`
Logs string `json:"logs,omitempty"`
Failure string `json:"failure,omitempty"`
}
RemoteResponse is the exact reply a remote WB sends back. A refusal on the remote side travels as Failure rather than as a transport error, so the caller can tell "the remote refused" apart from "the remote was unreachable".
func CallRemote ¶
func CallRemote(ctx context.Context, target RemoteTarget, request RemoteRequest, deps RemoteDeps) (RemoteResponse, error)
CallRemote performs one remote WB agent operation over SSH and returns the decoded reply. A non-empty reply Failure is returned as an error: the remote ran and refused, which is a finding rather than a transport failure.
type RemoteTarget ¶
RemoteTarget is one configured machine WB can dispatch to. It is derived from WB's existing session_move target map, so there is one host list rather than a second one that can drift from it.
func ResolveRemoteTarget ¶
func ResolveRemoteTarget(configPath, machine string) (RemoteTarget, error)
ResolveRemoteTarget looks up one configured machine, naming the alternatives when it is unknown so a typo is one command away from being fixed.
func (RemoteTarget) Validate ¶
func (target RemoteTarget) Validate() error
Validate refuses a target whose configured address could be reinterpreted by OpenSSH. The values come from WB configuration, but the remote command line is the one place a configuration typo could become a remote shell command.
type RequestError ¶
type RequestError struct {
// contains filtered or unexported fields
}
RequestError marks a refusal of the invocation itself: the caller asked for something WB cannot even attempt, such as an unconfigured profile. It is deliberately distinguishable from a run that started and then failed, because the two need different exit codes and different caller responses.
func (*RequestError) Error ¶
func (err *RequestError) Error() string
type Resolved ¶
type Resolved struct {
Profile string `json:"profile"`
Harness string `json:"harness"`
Provider string `json:"provider,omitempty"`
Model string `json:"model"`
// Variant is the OpenCode model variant exactly as configured; it is never
// folded into Model, so Model stays a valid execution identifier.
Variant string `json:"variant,omitempty"`
// Effort is the profile's own default. The effort a run actually requested
// and whether it was applied are recorded separately from this snapshot.
Effort string `json:"effort,omitempty"`
// EffortVariants snapshots the profile's effort→variant map, so a plan can
// still resolve an effort after the configuration file changes.
EffortVariants map[string]string `json:"effort_variants,omitempty"`
// Routing is the provider registry entry a Codex run will be configured
// with. It carries no credential, only the name of the variable holding it,
// and is absent for harnesses that use their own auth store.
Routing Provider `json:"routing,omitempty"`
// TimeoutMS is the profile's own bound, when configured.
TimeoutMS int64 `json:"timeout_ms,omitempty"`
}
Resolved is one profile after resolution: the requested name plus what will actually execute, snapshotted so a later edit to the profile cannot rewrite what a finished run did.
type Result ¶
type Result struct {
AgentID string `json:"agent_id"`
// Machine names the machine that holds this run's record and worktree. It
// is empty for a run dispatched by this machine and is stamped by the caller
// that asked another machine, so a result always says where its artefact
// lives.
Machine string `json:"machine,omitempty"`
State State `json:"state"`
Status ExecutionStatus `json:"execution_status"`
Terminal bool `json:"terminal"`
FailureCategory string `json:"failure_category,omitempty"`
RequestedProfile string `json:"profile"`
Resolved Resolved `json:"resolved"`
TaskType string `json:"task_type,omitempty"`
TaskTypeSource string `json:"task_type_source,omitempty"`
ProfileSource string `json:"profile_source,omitempty"`
Complexity string `json:"complexity,omitempty"`
ComplexitySource string `json:"complexity_source,omitempty"`
EffortRequested string `json:"effort_requested,omitempty"`
EffortEffective string `json:"effort_effective,omitempty"`
EffortApplied bool `json:"effort_applied"`
EffortNote string `json:"effort_note,omitempty"`
WorktreeSource string `json:"worktree_source,omitempty"`
TimeoutSource string `json:"timeout_source,omitempty"`
HarnessVersion string `json:"harness_version,omitempty"`
HarnessCapabilities HarnessCapabilities `json:"harness_capabilities"`
Repository string `json:"repository"`
WorktreeMode string `json:"worktree_mode"`
Worktree string `json:"worktree"`
WorktreeDir string `json:"worktree_dir,omitempty"`
Branch string `json:"branch,omitempty"`
Base string `json:"base,omitempty"`
BaseSHA string `json:"base_sha,omitempty"`
SourceSHA string `json:"source_sha,omitempty"`
SnapshotSHA string `json:"snapshot_sha,omitempty"`
SourceDirty bool `json:"source_dirty,omitempty"`
ExperimentID string `json:"experiment_id,omitempty"`
RepeatIndex int `json:"repeat_index,omitempty"`
RetryOf string `json:"retry_of,omitempty"`
FallbackFrom string `json:"fallback_from,omitempty"`
FallbackReason string `json:"fallback_reason,omitempty"`
StartedAt time.Time `json:"started_at"`
ExecutionStartedAt *time.Time `json:"execution_started_at,omitempty"`
FinishedAt *time.Time `json:"finished_at,omitempty"`
DurationMS int64 `json:"duration_ms,omitempty"`
QueueDurationMS int64 `json:"queue_duration_ms,omitempty"`
TimeToFirstOutputMS int64 `json:"time_to_first_output_ms,omitempty"`
QueueOwnerPID int `json:"queue_owner_pid,omitempty"`
OwnerPID int `json:"owner_pid,omitempty"`
WorkerPID int `json:"worker_pid,omitempty"`
OwnerAlive bool `json:"owner_alive"`
WorkerAlive bool `json:"worker_alive"`
ExitCode *int `json:"exit_code,omitempty"`
Failure string `json:"failure,omitempty"`
Result string `json:"result,omitempty"`
ToolCalls int `json:"tool_calls,omitempty"`
Usage *Usage `json:"usage,omitempty"`
Telemetry Telemetry `json:"telemetry"`
Cost CostRecord `json:"cost"`
Validation ValidationRecord `json:"validation"`
Review ReviewRecord `json:"review"`
Changes *ChangeSummary `json:"changes,omitempty"`
HarnessDiagnostics []string `json:"harness_diagnostics,omitempty"`
DiffPath string `json:"diff_path,omitempty"`
AcceptanceRequired bool `json:"acceptance_required"`
Retries int `json:"retries"`
TaskVisibility string `json:"task_visibility,omitempty"`
TaskNormalized bool `json:"task_normalized,omitempty"`
LogPath string `json:"log_path,omitempty"`
}
Result is the rendered projection of a Record, and the machine-readable document `status` and `await` emit. It is written out field by field rather than derived by embedding, so the private task can never reach a caller by accident: adding a field to Record does not add it here.
type ReviewEntry ¶
type ReviewEntry struct {
Status string `json:"status"`
Evaluator string `json:"evaluator"`
Note string `json:"note,omitempty"`
At time.Time `json:"at"`
}
ReviewEntry is one acceptance decision.
type ReviewRecord ¶
type ReviewRecord struct {
Status string `json:"status"`
Evaluator string `json:"evaluator,omitempty"`
Note string `json:"note,omitempty"`
At time.Time `json:"at,omitempty"`
History []ReviewEntry `json:"history,omitempty"`
}
ReviewRecord is the review axis of one execution. Status is `pending` until a reviewer appends an entry, and always reflects the most recent decision.
func (ReviewRecord) Latest ¶
func (record ReviewRecord) Latest() ReviewRecord
Latest projects the current decision without the history.
func (ReviewRecord) Reviewed ¶
func (record ReviewRecord) Reviewed() bool
Reviewed reports whether a human decided something about this run.
type RunRequest ¶
type RunRequest struct {
Task string
TaskType string
Complexity string
Effort string
Profile string
Harness string
Model string
Provider string
Variant string
// WorktreeMode is auto, current, path, new or existing. Worktree is an
// operation name, an absolute path, or an existing worktree name depending
// on the mode.
WorktreeMode string
Worktree string
AllowCanonical bool
AllowDirty bool
Timeout time.Duration
TimeoutSet bool
Validate []string
ValidateSet bool
NoValidate bool
Repository string
Base string
Branch string
// Acceptance overrides the task type's acceptance policy when set.
Acceptance string
}
RunRequest is everything a caller can decide about one execution. Every field is optional: the point of a task type is that the caller can name the work and nothing else.
type State ¶
type State string
State is the closed lifecycle vocabulary of one dispatched run. It is the legacy spelling kept for records an older WB wrote and read; new records also carry ExecutionStatus, which distinguishes cancellation from failure without adding a value an older build would not recognise as terminal.
type Store ¶
type Store struct {
Root string
}
Store persists agent run records under one root directory.
func (Store) AcquireLease ¶
func (store Store) AcquireLease(worktreeDir, agentID, experimentID, repository string, now time.Time) (*Lease, error)
AcquireLease takes the exclusive writer claim for a worktree, failing with LeaseHeldError when another execution holds it.
func (Store) AppendReview ¶
func (store Store) AppendReview(agentID string, entry ReviewEntry) (ReviewRecord, error)
AppendReview adds one decision and returns the resulting review record. The caller has already established that the execution is terminal, so nothing here can race an owner's save.
func (Store) BuildReport ¶
func (store Store) BuildReport(experiment Experiment) ExperimentReport
BuildReport joins an experiment with its member records. A run that cannot be loaded is skipped rather than failing the whole report: a partially completed experiment is exactly what an operator needs to see after a crash.
func (Store) Create ¶
Create prepares the run directory and persists the initial record before any process is started, so a launch that fails still leaves something to diagnose.
func (Store) CreateExperiment ¶
func (store Store) CreateExperiment(experiment Experiment) error
CreateExperiment writes the document once. A second write is refused so a planned experiment cannot be rewritten after results exist.
func (Store) ExperimentDir ¶
ExperimentDir is the private directory holding one experiment document.
func (Store) ExperimentPath ¶
ExperimentPath is the experiment document path.
func (Store) HarnessHomePath ¶
HarnessHomePath is the private per-run harness home. Pointing the harness at its own home is what keeps a dispatched worker from reading or writing the user's harness state while the parent harness keeps running normally.
func (Store) LastMessagePath ¶
LastMessagePath is where the harness is asked to write its final message.
func (Store) LeaseLive ¶
LeaseLive reports whether some process currently holds the writer claim. The lease file is retained after Release, so its existence alone proves nothing: only a failed non-blocking lock does.
func (Store) LeasePath ¶
LeasePath is the retained lease file for a worktree directory. It is keyed on the symlink-resolved path so two spellings of one checkout cannot take two leases.
func (Store) List ¶
List returns every run record, newest first. A directory that cannot be read is reported rather than silently skipped.
func (Store) LoadExperiment ¶
func (store Store) LoadExperiment(experimentID string) (Experiment, error)
LoadExperiment reads one experiment document.
func (Store) LoadReview ¶
func (store Store) LoadReview(agentID string) (ReviewRecord, error)
LoadReview reads the review sidecar. An absent sidecar is not an error: it means the execution has not been reviewed.
func (Store) RecordPath ¶
RecordPath is the persisted run record for one agent ID.
func (Store) Render ¶
Render projects a record for output, resolving a run whose owner vanished without recording a terminal state to the honest answer: abandoned. A run is never reported as completed merely because nothing contradicted it.
Abandoned is derived from the owner, not the worker: the owner is the only process that will ever record a terminal state, so once it is gone the run has no outcome and reporting it "running" indefinitely would be a lie. A worker that outlived its owner is still surfaced, through WorkerAlive, so a caller knows a stray process exists and can stop it.
func (Store) ReviewPath ¶
ReviewPath is the sidecar path for one execution.
type Target ¶
type Target struct {
Repository string
Dir string
Branch string
Base string
BaseSHA string
HeadSHA string
SnapshotSHA string
Dirty bool
DirtyFiles []string
Managed bool
Canonical bool
ClaimPath string
ClaimRunID string
// WorktreeName is the WB task name when the checkout carries a marker.
WorktreeName string
}
Target is one resolved writable directory and the facts that make a later diff and a cleanup decision honest.
func ResolveTarget ¶
func ResolveTarget(ctx context.Context, path string, allowCanonical, allowDirty bool, deps TargetDeps) (Target, error)
ResolveTarget inspects a directory a caller wants a worker to write in.
type TargetDeps ¶
type TargetDeps struct {
Git func(ctx context.Context, dir string, args ...string) (string, error)
ReadFile func(string) ([]byte, error)
OriginSlug func(context.Context, string) (string, error)
}
TargetDeps are the seams target resolution needs. They exist so the whole resolution can be exercised without a live Git checkout.
func DefaultTargetDeps ¶
func DefaultTargetDeps() TargetDeps
DefaultTargetDeps returns the production seams.
type TaskType ¶
type TaskType struct {
Profile string `yaml:"profile,omitempty" json:"profile,omitempty"`
Complexity map[string]string `yaml:"complexity,omitempty" json:"complexity,omitempty"`
// Fallback is the ordered list of profiles to try after Profile, so one
// provider or model being down does not stop the work. Order is the
// operator's cost decision: WB never reorders it.
Fallback []string `yaml:"fallback,omitempty" json:"fallback,omitempty"`
// FallbackOn selects when fallback applies: "preflight" (a capability WB
// can check before starting) and/or "runtime" (the provider failed the run
// itself). Preflight is the default; runtime is opt-in because it starts a
// second execution.
FallbackOn []string `yaml:"fallback_on,omitempty" json:"fallback_on,omitempty"`
Effort string `yaml:"effort,omitempty" json:"effort,omitempty"`
Worktree string `yaml:"worktree,omitempty" json:"worktree,omitempty"`
Timeout string `yaml:"timeout,omitempty" json:"timeout,omitempty"`
Validate []string `yaml:"validate,omitempty" json:"validate,omitempty"`
Acceptance string `yaml:"acceptance,omitempty" json:"acceptance,omitempty"`
}
TaskType is a named execution policy. It names no model: it points at profiles the operator configured.
type Telemetry ¶
type Telemetry struct {
Available bool `json:"available"`
Source string `json:"source"`
Tokens *Tokens `json:"tokens,omitempty"`
Raw json.RawMessage `json:"raw,omitempty"`
}
Telemetry is what the harness reported about usage, with its provenance. Available is explicit: a nil Tokens means "not reported", never zero.
type Tokens ¶
type Tokens struct {
Input *int `json:"input,omitempty"`
Output *int `json:"output,omitempty"`
CacheRead *int `json:"cache_read,omitempty"`
CacheWrite *int `json:"cache_write,omitempty"`
Reasoning *int `json:"reasoning,omitempty"`
}
Tokens is usage exactly as the harness reported it. Every field is a pointer so "not reported" stays distinguishable from a reported zero.
type UnknownAgentError ¶
UnknownAgentError is returned when a named run does not exist.
func (*UnknownAgentError) Error ¶
func (err *UnknownAgentError) Error() string
type UnknownExperimentError ¶
UnknownExperimentError is returned when a named experiment does not exist.
func (*UnknownExperimentError) Error ¶
func (err *UnknownExperimentError) Error() string
type Usage ¶
type Usage struct {
InputTokens int `json:"input_tokens"`
CachedInputTokens int `json:"cached_input_tokens,omitempty"`
CacheWriteInputTokens int `json:"cache_write_input_tokens,omitempty"`
OutputTokens int `json:"output_tokens"`
ReasoningOutputTokens int `json:"reasoning_output_tokens,omitempty"`
}
Usage is what the harness reported about the run. Every field is copied verbatim from the harness; a field the harness did not report stays absent rather than being estimated.
type ValidationOptions ¶
type ValidationOptions struct {
WorktreeDir string
RunDir string
Steps []ValidationStep
// Lease is inherited by every step, so a validation process still holds the
// worktree claim until it exits.
Lease *os.File
Now func() time.Time
// Command builds the process; it is a seam for tests, never a production
// override.
Command func(ctx context.Context, name string, args ...string) *exec.Cmd
}
ValidationOptions is one validation run's inputs.
type ValidationRecord ¶
type ValidationRecord struct {
Status string `json:"status"`
Steps []ValidationStepResult `json:"steps,omitempty"`
Reason string `json:"reason,omitempty"`
StartedAt *time.Time `json:"started_at,omitempty"`
FinishedAt *time.Time `json:"finished_at,omitempty"`
}
ValidationRecord is the objective-validation axis of one execution.
func RunValidation ¶
func RunValidation(ctx context.Context, options ValidationOptions) ValidationRecord
RunValidation executes the snapshotted steps and reports one record. It never takes a credential: a validation is repository-owned code, not a provider call, and the worker's credential must not reach it.
type ValidationStep ¶
type ValidationStep struct {
Name string `yaml:"name" json:"name"`
Argv []string `yaml:"argv" json:"argv"`
Timeout string `yaml:"timeout,omitempty" json:"timeout,omitempty"`
}
ValidationStep is one objective check a task type may require. Argv is a literal argument list, never a shell string, so a validation cannot smuggle quoting or piping into the worker's environment.
type ValidationStepResult ¶
type ValidationStepResult struct {
Name string `json:"name"`
Argv []string `json:"argv"`
Timeout string `json:"timeout,omitempty"`
Status string `json:"status"`
ExitCode *int `json:"exit_code,omitempty"`
DurationMS int64 `json:"duration_ms,omitempty"`
LogPath string `json:"log_path,omitempty"`
}
ValidationStepResult is one executed objective check.
Source Files
¶
- actions.go
- changes.go
- credential.go
- detach_common.go
- diff.go
- dispatch.go
- env.go
- errors.go
- exec_lookpath.go
- experiment.go
- harness.go
- harness_codex.go
- harness_dsh.go
- harness_opencode.go
- lease.go
- lease_mode_unix.go
- lease_unix.go
- owner.go
- plan.go
- preflight.go
- profile.go
- remote.go
- review.go
- run.go
- signal_unix.go
- tasktypes.go
- telemetry.go
- validation.go
- worktree_target.go