Help us shape the future of Go! Take the 2026 Go Developer Survey

delegation

package
v0.16.0 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Overview

Package delegation runs an explicit bounded local-first task policy. It can escalate once after a known complete durable answer fails declared checks; it never retries uncertain calls, intercepts an agent session, or picks models.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrQualityFailed = errors.New("delegated task did not satisfy every declared quality check")
	ErrStopped       = errors.New("delegated task stopped without escalating; inspect its recorded outcome")
)

Functions

func ApplyApprovedQuestions added in v0.16.0

func ApplyApprovedQuestions(request Request, approved ApprovedQuestionSet) (Request, ApprovedQuestionDecision, error)

ApplyApprovedQuestions prepares an ordinary request for exact reuse. A known form changes only Spec.Input and Spec.Revision; all context, checks, limits, TTL, tiers and accounting settings retain the normal delegation behavior. The caller must approve the set independently of request/model data.

This pure helper performs no I/O, provider work, lookup or publication. An unknown form returns the original request and a zero decision; its ordinary request validation is unchanged. An invalid policy or matched revision also returns the original request and a zero decision, with an error. Semantic reuse and shadow policies cannot be combined with this preparation. Apply once to an original request; execute or retry the prepared request directly. Preparing an already prepared revision is rejected so it cannot create a new identity around a pending or uncertain result.

func NewOutcomeRunID added in v0.9.0

func NewOutcomeRunID() (string, error)

func OutcomeRecord added in v0.9.0

func OutcomeRecord(request Request, result Result, runID string) outcomes.Run

func RecordOutcome added in v0.9.0

func RecordOutcome(ctx context.Context, broker inference.Broker, request Request, result *Result, runID string)

func RequestDigest added in v0.13.0

func RequestDigest(request Request) string

RequestDigest returns the canonical identity used by Router results. Callers must Validate the request before using the digest as an approval binding. Outcome tracking is excluded, matching the existing generation identity.

func ReusePartition added in v0.15.0

func ReusePartition(request Request, tier Tier, runtimeID string) (string, error)

ReusePartition keeps the broad retrieval contract separate from the verifier version. A new verifier can inspect the same original sources, while aliases bind its complete policy/runtime identity through ReuseResolver.Identity.

func ShadowPartition added in v0.14.0

func ShadowPartition(request Request, tier Tier, runtimeID string) (string, error)

ShadowPartition binds every approved non-question part of the task. Bindings must declare business variables embedded in the question; a partition alone is not a proof that two free-form questions have equivalent answers.

func SpecForTier added in v0.13.0

func SpecForTier(request Request, tierID string, allowPaid bool) (inference.Spec, error)

SpecForTier validates the entire approved request and returns the exact derived spec for a declared tier. It uses the Router's unchanged task and revision identities; it performs no inference or provider discovery.

func Validate

func Validate(request Request, allowPaid bool) error

Validate resolves all tier plans and checks before any factory/provider call. A configured hosted tier is rejected unless this caller explicitly opts in, even when the local tier could produce a passing answer.

Types

type ApprovedQuestionDecision added in v0.16.0

type ApprovedQuestionDecision struct {
	Matched      bool   `json:"matched"`
	PolicySHA256 string `json:"policy_sha256,omitempty"`
}

ApprovedQuestionDecision reports an exact membership match. PolicySHA256 binds the versioned, sorted policy and the original request revision; it is also the suffix of the prepared request revision. This is no model validity verdict.

type ApprovedQuestionSet added in v0.16.0

type ApprovedQuestionSet struct {
	ReadOnly          bool              `json:"read_only"`
	Revision          string            `json:"revision"`
	Intent            string            `json:"intent"`
	Bindings          map[string]string `json:"bindings,omitempty"`
	CanonicalQuestion string            `json:"canonical_question"`
	Forms             []string          `json:"forms"`
}

ApprovedQuestionSet is a trusted application's assertion that its exact Forms ask the same read-only question. Questlock does not infer that equivalence. CanonicalQuestion must be one of the 2..32 unique Forms. Questions are matched byte for byte, without trimming, case folding, Unicode normalization or regex. Bindings scope the request identity. Supply every fact the model needs through the canonical question, instructions and context; Bindings adds no prompt text.

Revision and Intent are nonempty labels of at most 128 UTF-8 bytes. Bindings has at most 32 entries, with nonempty labels of at most 64 bytes for keys and 256 bytes for values. Each question is at most 8192 UTF-8 bytes. The complete encoded policy and original request revision must fit within 32KiB. These are caller approvals, never a list learned from model decisions.

type Attempt

type Attempt struct {
	BudgetDiagnostic *inference.BudgetDiagnostic `json:"budget_diagnostic,omitempty"`
	TierID           string                      `json:"tier_id"`
	Result           inference.Result            `json:"result"` // Response.Text is always stripped.
	Checks           []evaluation.CheckResult    `json:"checks"`
	QualityPassed    bool                        `json:"quality_passed"`
	OutputSHA256     string                      `json:"output_sha256,omitempty"`
	ErrorCategory    string                      `json:"error_category,omitempty"`
}

type ControlledReuser added in v0.15.0

type ControlledReuser struct {
	Broker          inference.Broker
	Index           semantic.Index
	EmbedderFactory func(context.Context, semantic.Config) (semantic.Embedder, error)
	VerifierFactory func(context.Context, semantic.ReuseConfig) (semantic.Verifier, error)
	Resources       admission.Source
	// contains filtered or unexported fields
}

ControlledReuser serves only explicitly enabled, checked text answers. It never performs or replays an external action, cancels another worker, or clears a pending/uncertain claim. Instantiate one per bounded worker.

type LocalVerifier added in v0.15.0

type LocalVerifier struct {
	DailyTokenBudget *inference.TokenBudget
	// contains filtered or unexported fields
}

func NewLocalVerifier added in v0.15.0

func NewLocalVerifier(ctx context.Context, broker inference.Broker, baseURL string, c semantic.ReuseConfig) (*LocalVerifier, error)

NewLocalVerifier only discovers already-installed literal-loopback Ollama weights. Verification uses normal durable inference claims and token accounting; no hosted provider, model pull or second verifier is available.

func (*LocalVerifier) Close added in v0.15.0

func (v *LocalVerifier) Close()

func (*LocalVerifier) Identity added in v0.15.0

func (v *LocalVerifier) Identity() string

func (*LocalVerifier) Verify added in v0.15.0

type OutcomeTracking added in v0.4.0

type OutcomeTracking struct {
	Status        string            `json:"status"` // recorded or failed
	ErrorCategory string            `json:"error_category,omitempty"`
	RunID         string            `json:"run_id"`
	Task          outcomes.Task     `json:"task"`
	Receipt       *outcomes.Receipt `json:"receipt,omitempty"`
	Record        *outcomes.Run     `json:"record,omitempty"`
}

OutcomeTracking is separate from answer quality. Registration failure never changes a checked answer or authorizes another model call. Record is returned on failure so the exact metadata can be reconciled without regenerating text.

type Policy

type Policy struct {
	Local      Tier  `json:"local"`
	Escalation *Tier `json:"escalation,omitempty"`
}

type Request

type Request struct {
	TrackOutcome   bool                  `json:"track_outcome,omitempty"` // Opt-in shared accounting; excluded from generation identity.
	Spec           inference.Spec        `json:"spec"`
	Policy         Policy                `json:"policy"`
	Checks         []evaluation.Check    `json:"checks"`
	SemanticShadow *semantic.Config      `json:"semantic_shadow,omitempty"` // Advisory observation; excluded from generation identity.
	SemanticReuse  *semantic.ReuseConfig `json:"semantic_reuse,omitempty"`  // Explicit controlled answer reuse; excluded from generation identity.
}

Request.Spec supplies approved task, revision, prompt and context only. Every model and resource setting comes from the explicit tier templates.

func Load

func Load(reader io.Reader) (Request, error)

Load reads at most 1MiB of request JSON. Authorization is deliberately not a JSON field: only the caller can enable paid escalation on Router.AllowPaid.

type Result

type Result struct {
	SemanticReuse    *ReuseObservation           `json:"semantic_reuse,omitempty"`
	SemanticShadow   *semantic.Observation       `json:"semantic_shadow,omitempty"`
	BudgetDiagnostic *inference.BudgetDiagnostic `json:"budget_diagnostic,omitempty"`
	OutcomeTracking  *OutcomeTracking            `json:"outcome_tracking,omitempty"`
	RequestSHA256    string                      `json:"request_sha256"`
	Attempts         []Attempt                   `json:"attempts"`
	SelectedTier     string                      `json:"selected_tier,omitempty"`
	Response         *inference.Response         `json:"response,omitempty"` // Only a passing answer is exposed.
	Status           string                      `json:"status"`             // completed, quality_failed, stopped
}

type ReuseObservation added in v0.15.0

type ReuseObservation struct {
	Mode                   string                    `json:"mode"`
	Status                 string                    `json:"status"`
	ResourceAdmission      *ReuseResourceAdmission   `json:"resource_admission,omitempty"`
	Partition              string                    `json:"partition,omitempty"`
	Source                 *semantic.Source          `json:"source,omitempty"`
	Similarity             float64                   `json:"similarity,omitempty"`
	EmbeddingInputTokens   *int64                    `json:"embedding_input_tokens"`
	EmbeddingMS            float64                   `json:"embedding_ms,omitempty"`
	Searches               int                       `json:"searches"`
	WaitMS                 float64                   `json:"wait_ms"`
	Verifications          []semantic.ValidityResult `json:"verifications"`
	Rejections             []string                  `json:"rejections"`
	Indexed                bool                      `json:"indexed"`
	GenerationAvoided      bool                      `json:"generation_avoided"`
	HistoricalUsageIsProxy bool                      `json:"historical_usage_is_proxy"`
}

type ReuseResourceAdmission added in v0.16.0

type ReuseResourceAdmission struct {
	Reason               string             `json:"reason"`
	MemoryPressure       admission.Pressure `json:"memory_pressure,omitempty"`
	AvailableMemoryBytes *int64             `json:"available_memory_bytes"`
}

ReuseResourceAdmission explains an actual optional-reuse resource probe. Availability is advisory headroom; nil means no valid measurement was read. No command output, source label or probe error is included.

type Router

type Router struct {
	Factory   RunnerFactory
	AllowPaid bool // Caller permission, never read from request JSON or environment.
	Shadow    *ShadowObserver
	Reuse     *ControlledReuser
}

func (Router) Run

func (router Router) Run(ctx context.Context, request Request) (Result, error)

Run executes at most two explicitly configured tiers. A second tier is reached only after error-free, known complete and durable output fails the declared checks. Every provider/accounting error stops the whole policy. Repeated calls retain the same request/tier identity and the Runner's reuse behavior; the Router never changes a revision to force another generation.

type Runner

type Runner interface {
	Run(context.Context, inference.Spec) (inference.Result, error)
}

type RunnerFactory

type RunnerFactory func(Tier) (Runner, error)

type ShadowObserver added in v0.14.0

type ShadowObserver struct {
	Broker          inference.Broker
	Index           semantic.Index
	EmbedderFactory func(context.Context, semantic.Config) (semantic.Embedder, error)
	Resources       admission.Source // nil lets a Go caller provide its own admission.
	// contains filtered or unexported fields
}

ShadowObserver is optional, local-only opportunity measurement. One observer admits one bounded observation at a time and retains no waiting task history. Failures never change a generated answer, its accounting, or its claims.

type Tier

type Tier struct {
	ID   string         `json:"id"`
	Spec inference.Spec `json:"spec"`
}

Tier.Spec must omit task, revision, instructions, input and context. Hosted escalation requires explicit prices and positive per-call and daily budgets.

Jump to

Keyboard shortcuts

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