bgagent

package
v0.219.0 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: MIT Imports: 12 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 bgagent is the server's common runner for background agents (design 2026-10-30 §3): one place that owns the session book of an agent kind (job_check, summarizer, steward), decides before every run whether to continue, clear or replace the session, enforces the hard stops (daily limit, budget, timeout) and leaves an audit trail. The kinds are adapters: each supplies the prompt and the way to actually run a turn (Executor), and keeps its own business logic.

The package sits beside work / steward in the layering: it imports only the data layer (config, jobstore, runner) and never the job service, the entry layers or the orchestration packages; the job layer is reached through the Executor seam the entry layer fills in.

Index

Constants

View Source
const (
	KindJobCheck   = "job_check"
	KindSummarizer = jobstore.BackgroundKindSummarizer
	KindSteward    = "steward"
)

The background agent kinds. They are the first dimension of a session's key: a kind never reuses another kind's session.

View Source
const (
	ReasonNone             = ""
	ReasonManualReset      = "manual_reset"
	ReasonContextRatio     = "context_ratio"
	ReasonMaxRuns          = "max_runs"
	ReasonMaxAge           = "max_age"
	ReasonKeyChanged       = "key_changed"
	ReasonNotResumable     = "not_resumable"
	ReasonSessionLost      = "session_lost"
	ReasonClearUnsupported = "clear_unsupported"
)

Why a decision was taken (Decision.Reason, audit detail, background_agent_*.rotation_reason).

View Source
const (
	StopDailyLimit  = "daily_limit"
	StopDailyCost   = "daily_cost_budget"
	StopDailyTokens = "daily_token_budget"
	StopTimeout     = "timeout"
)

Hard-stop reasons (HardStopError.Reason, the audit detail).

View Source
const ViewVersion = 1

ViewVersion is the version of the wire view of the background-agent status (GET /v1/background-agents). A reader treats fields it does not know as additive and ignores them; the version only changes when an existing field changes meaning.

Variables

View Source
var (
	// ErrSessionLost: the recorded session cannot be continued (deleted, the agent refused).
	ErrSessionLost = errors.New("background agent session cannot be continued")
	// ErrClearUnsupported: the agent does not support clearing the context.
	ErrClearUnsupported = errors.New("background agent cannot clear its context")
)

Functions

func Kinds

func Kinds() []string

Kinds lists the background agent kinds in the order the status view shows them.

func KnownKind

func KnownKind(kind string) bool

KnownKind reports whether kind is one of Kinds().

func ModelFromArgs

func ModelFromArgs(args []string) string

ModelFromArgs reads the model an agent argv selects (`--model X`, `--model=X`, `-m X`), "" when it names none: the model is part of the session key, so changing it opens a new session. Arguments it cannot parse are left alone.

Types

type Caps

type Caps struct {
	// CanResume: the agent can continue a finished session (its resume / load argv).
	CanResume bool
	// CanClearContext: the agent can start a clean context inside the same session id
	// (suga run --sid <id> --clear-ctx). It only matters for an agent that can resume.
	CanClearContext bool
}

Caps is what the agent behind a kind can do with a recorded session.

type DecideInput

type DecideInput struct {
	Policy Policy
	Caps   Caps
	Now    int64
	// Active is the active session recorded for the exact key (nil = none).
	Active *jobstore.BackgroundSession
	// Reset reports that the newest session of the key was manually reset.
	Reset bool
	// OtherBinding reports an active session of the same kind / project / work_dir that
	// belongs to another agent or model.
	OtherBinding bool
}

DecideInput is everything Decide looks at.

type Decision

type Decision struct {
	Mode Mode
	// Reason is why the previous session is not simply continued ("" = it is, or there
	// never was one).
	Reason string
	// Session is the recorded session the run continues or clears (zero for ModeFresh).
	Session Session
	// Rotated reports that an existing session was replaced or cleared by a rule
	// (context ratio, run count, age) — the audited events.
	Rotated bool
}

Decision is what to do for the next run.

func Decide

func Decide(in DecideInput) Decision

Decide is the unified rotation rule (design §3.3), evaluated before every run:

  1. manual reset: the next run is fresh;
  2. context ratio at or over the limit, or runs at or over the limit: rotate — clear the context in the same session when the agent can, else a fresh session;
  3. a changed agent / model / work_dir (no session for this exact key), or a session that cannot be continued: fresh;
  4. an explicit max age over its limit: rotate the same way;
  5. otherwise continue.

type ExecRequest

type ExecRequest struct {
	Key
	Mode   Mode
	Prompt string
	Title  string
	Args   []string
	// Origin is the ceiling owner the run is submitted under ("" = none).
	Origin  string
	Timeout time.Duration
	// SessionID / LastJobID are the recorded session a resume or clear continues.
	SessionID string
	LastJobID string
}

ExecRequest is what an adapter's Executor is asked to run.

type ExecResult

type ExecResult struct {
	JobID     string
	SessionID string
	Output    []byte
	Usage     *runner.Usage
}

ExecResult is what one turn produced.

type Executor

type Executor interface {
	// Caps says what the agent can do with a recorded session.
	Caps(agent string) Caps
	// Execute runs one turn in the requested mode. For ModeResume / ModeClearContext it
	// returns an error wrapping ErrSessionLost or ErrClearUnsupported when the recorded
	// session cannot be used, which makes the runner fall back to a fresh session.
	Execute(ctx context.Context, r ExecRequest) (ExecResult, error)
}

Executor is the seam to whatever actually runs a turn (the entry layer adapts the job service). It must not be handed anything but what ExecRequest carries.

type HardStopError

type HardStopError struct {
	Kind   string
	Reason string
	// Limit / Used are the figure that tripped (runs, USD, tokens or seconds).
	Limit float64
	Used  float64
}

HardStopError says a hard stop refused or ended a run: the daily run limit or a budget was reached before the run, or the run hit its timeout. It is never retried by the runner: a protection that trips must stay tripped until the day rolls over or the operator changes the limit.

func (*HardStopError) Error

func (e *HardStopError) Error() string

type Key

type Key struct {
	Kind    string
	Agent   string
	Project string
	WorkDir string
	Model   string
}

Key is the ownership key of a session: kind is a hard isolation dimension, and a session is only continued by a run whose key is identical.

type KindStatus

type KindStatus struct {
	Kind     string
	Sessions []SessionStatus
	Today    jobstore.BackgroundDayStats
	Policy   Policy
}

KindStatus is the read model of one kind: its sessions, today's totals and the policy.

type KindView

type KindView struct {
	Kind     string        `json:"kind"`
	Sessions []SessionView `json:"sessions"`
	Today    TodayView     `json:"today"`
	Policy   PolicyView    `json:"policy"`
}

KindView is one kind: its active sessions (an empty list when there are none), today's totals and the rotation policy that applies to it.

func NewKindView

func NewKindView(st KindStatus) KindView

NewKindView converts a Status result into its wire form.

type Limits

type Limits struct {
	// DailyRuns caps the runs that started today (per kind, UTC day by default).
	DailyRuns int
	// DailyCostUSD / DailyTokens cap today's reported usage (per kind). Runs that
	// reported no usage add nothing: the budget is checked against what is known.
	DailyCostUSD float64
	DailyTokens  int64
	// Timeout bounds one run (0 = no bound).
	Timeout time.Duration
}

Limits are the cost protections of one kind; a zero field is off.

func LimitsFromConfig

func LimitsFromConfig(c config.BackgroundAgentsConfig) Limits

LimitsFromConfig reads the budget hard stops of server.background_agents (the daily run limit and the timeout belong to the kind's own configuration, the caller adds them).

type Mode

type Mode string

Mode is how a run relates to the session book.

const (
	// ModeFresh opens a new agent session.
	ModeFresh Mode = "fresh"
	// ModeResume continues the recorded session (the agent's resume / load).
	ModeResume Mode = "resume"
	// ModeClearContext keeps the session id and starts a clean logical context in it.
	ModeClearContext Mode = "clear_context"
)

type Options

type Options struct {
	// Now is the clock (nil = time.Now).
	Now func() time.Time
	// StartOfDay returns the start (unix seconds) of the day now belongs to; nil = the UTC day.
	StartOfDay func(now time.Time) int64
}

Options configures a Runner.

type Outcome

type Outcome struct {
	JobID     string
	SessionID string
	Usage     *runner.Usage
	// Mode is the mode the run actually used (it differs from the plan's after a
	// fallback); empty = the planned one.
	Mode        Mode
	InputBytes  int64
	OutputBytes int64
}

Outcome is what a finished run reports to Commit.

type Plan

type Plan struct {
	Key
	Decision Decision
	Started  int64
	// contains filtered or unexported fields
}

Plan is the decision for one run plus what Commit / Fail need to record it.

type Policy

type Policy struct {
	MaxRuns         int
	MaxContextRatio float64
	MaxAge          time.Duration
}

Policy is the rotation policy: the main rule is the context fill, the run count is the secondary rule (it also covers an agent that reports no usage), and MaxAge is only an explicit last-resort bound. A zero field disables its rule, so a policy with no MaxAge never rotates by time.

func PolicyFromConfig

func PolicyFromConfig(c config.BackgroundAgentSessionConfig) Policy

PolicyFromConfig reads server.background_agents.session (defaults: ratio 0.7, 20 runs, no age bound).

type PolicyView

type PolicyView struct {
	MaxRuns         int     `json:"max_runs"`
	MaxContextRatio float64 `json:"max_context_ratio"`
	MaxAgeSec       int64   `json:"max_age_sec"`
}

PolicyView is the rotation policy; a zero field means that rule is off.

type Request

type Request struct {
	Key
	Prompt string
	Title  string
	Args   []string
	Origin string
	Policy Policy
	Limits Limits
}

Request is one run through Run.

type ResetView

type ResetView struct {
	Version int      `json:"version"`
	Reset   int64    `json:"reset"`
	Kind    KindView `json:"kind"`
}

ResetView is the answer of a manual reset: how many sessions it ended and the kind as it reads afterwards.

type Result

type Result struct {
	ExecResult
	// Mode is the mode the answer was produced in (after any fallback); Reason why the
	// previous session was not simply continued.
	Mode   Mode
	Reason string
}

Result is what Run returns.

type Runner

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

Runner is the common background-agent runner: session book, rotation decisions, hard stops, run log and audit events. Its methods are safe for concurrent use; callers serialise runs of one session themselves (the kinds already claim their sessions).

func New

func New(store *jobstore.Store, opt Options) *Runner

New builds a Runner over the store.

func (*Runner) Commit

func (r *Runner) Commit(p Plan, o Outcome) error

Commit records a successful run: the session book follows the mode actually used (a resume adds a run, a fresh or cleared session starts counting from this one), the run is logged with its usage, and a rotation by rule is audited.

func (*Runner) Fail

func (r *Runner) Fail(p Plan, cause error, dropSession bool)

Fail records a run that did not produce an answer. dropSession ends the recorded session (state 'dropped': the continuation failed, the next run opens a new one). Cancellation and timeout get their own run status; they never drop the session.

func (*Runner) Fallback

func (r *Runner) Fallback(p Plan, cause error, reason string) Plan

Fallback ends the recorded session of a plan whose continuation failed (the session is gone, the agent refused) and returns the plan for a fresh session instead. The failed attempt is logged; it is not a failure of the run.

func (*Runner) Guard

func (r *Runner) Guard(key Key, lim Limits) error

Guard checks the daily limit and the budgets of a kind before a run. A trip is a hard stop: it is logged as a blocked run, audited, and returned as *HardStopError.

func (*Runner) Observe

func (r *Runner) Observe(key Key, jobID, sessionID string, u *runner.Usage)

Observe folds in what a finished job reported after its run was committed: a resident session's turn only knows its usage (and the agent-side session id) once it has ended. The usage joins the run's log row, and when jobID is still the session's newest job the session's context level follows it, so the next Plan sees the real fill. Nothing here fails a run: a store error only warns.

func (*Runner) Plan

func (r *Runner) Plan(key Key, pol Policy, caps Caps) Plan

Plan loads the session of the key and decides how the next run uses it. A session book that cannot be read is treated as empty (the run must not fail over bookkeeping).

func (*Runner) Reset

func (r *Runner) Reset(kind, project, workDir, actor string) (int64, error)

Reset marks the active sessions of kind + project + work_dir as manually reset: the next run is fresh. It leaves history and usage alone and does not stop a run in flight. n is how many sessions it ended.

func (*Runner) ResetKind

func (r *Runner) ResetKind(kind, actor string) (int64, error)

ResetKind marks every active session of kind (all projects and work dirs) as manually reset, so the next run of each is fresh; see Reset. n is how many sessions it ended.

func (*Runner) Run

func (r *Runner) Run(ctx context.Context, exec Executor, req Request) (Result, error)

Run is the whole lifecycle of one run for an adapter that only needs "ask the agent": guard the hard stops, plan the session, execute (falling back to a fresh session when a resume or clear fails because the session is unusable), then record the run.

func (*Runner) Status

func (r *Runner) Status(kind string, pol Policy) (KindStatus, error)

Status reads the status of a kind. DC3's management page builds on it.

type Session

type Session struct {
	ID           string
	LastJobID    string
	Runs         int
	CreatedAt    int64
	LastUsedAt   int64
	ContextUsed  int64
	ContextLimit int64
}

Session is the recorded state of one background session.

func (Session) ContextRatio

func (s Session) ContextRatio() (float64, bool)

ContextRatio is the context fill and whether it is known (a missing window is unknown, never 0).

type SessionStatus

type SessionStatus struct {
	Session
	Agent   string
	Project string
	WorkDir string
	Model   string
	// ContextRatio is nil when the context fill is unknown (not 0).
	ContextRatio *float64
	// RotationReason is why this session replaced its predecessor.
	RotationReason string
	LastUsage      *runner.Usage
}

SessionStatus is one session as the status view shows it.

type SessionView

type SessionView struct {
	ID                 string        `json:"id"`
	LastJobID          string        `json:"last_job_id,omitempty"`
	Agent              string        `json:"agent,omitempty"`
	Project            string        `json:"project,omitempty"`
	WorkDir            string        `json:"work_dir,omitempty"`
	Model              string        `json:"model,omitempty"`
	Runs               int           `json:"runs"`
	CreatedAt          int64         `json:"created_at"`
	LastUsedAt         int64         `json:"last_used_at"`
	ContextUsedTokens  *int64        `json:"context_used_tokens"`
	ContextLimitTokens *int64        `json:"context_limit_tokens"`
	ContextRatio       *float64      `json:"context_ratio"`
	RotationReason     string        `json:"rotation_reason,omitempty"`
	LastUsage          *runner.Usage `json:"last_usage"`
}

SessionView is one active session. A context figure the agent never reported is null (not 0): ContextUsedTokens / ContextLimitTokens / ContextRatio are all nil together or individually when unknown.

type TodayView

type TodayView struct {
	Runs         int     `json:"runs"`
	Blocked      int     `json:"blocked"`
	InputTokens  int64   `json:"input_tokens"`
	OutputTokens int64   `json:"output_tokens"`
	TotalTokens  int64   `json:"total_tokens"`
	CostUSD      float64 `json:"cost_usd"`
	// UsageRuns is how many of Runs reported usage: the token and cost figures only
	// cover those.
	UsageRuns  int    `json:"usage_runs"`
	LastStatus string `json:"last_status,omitempty"`
	LastError  string `json:"last_error,omitempty"`
	LastJobID  string `json:"last_job_id,omitempty"`
	LastAt     int64  `json:"last_at,omitempty"`
}

TodayView is the totals of the kind's runs since the start of the day.

type UsageSnapshot

type UsageSnapshot struct {
	Usage *runner.Usage
	// ContextUsed / ContextLimit are 0 when unknown (never a made-up window).
	ContextUsed  int64
	ContextLimit int64
	// Ratio is the context fill; RatioKnown is false when the agent reported no level.
	Ratio      float64
	RatioKnown bool
	// Source names where the context level came from (runner.ContextSource*).
	Source string
}

UsageSnapshot is the one usage figure a run leaves behind, normalised across providers: the billing counters of the run and the context level the rotation reads. The parsing of each provider's NDJSON lives in runner / runner/ndjsonfilter (one reader per dialect, shared with the job layer); this is the projection the runner stores.

func SnapshotFromUsage

func SnapshotFromUsage(u *runner.Usage) UsageSnapshot

SnapshotFromUsage projects a run's usage (nil = the agent reported none).

type View

type View struct {
	Version int        `json:"version"`
	Kinds   []KindView `json:"kinds"`
}

View is the wire form of the status of every kind.

func NewView

func NewView(kinds ...KindStatus) View

NewView assembles the versioned view of the given kinds.

Jump to

Keyboard shortcuts

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