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

delegation

package
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Aug 13, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package delegation defines backend-neutral contracts for assigning work to another agent or execution target.

Mode distinguishes synchronous and asynchronous work. Directory owns discovery; Service owns execution and status lookup. The local service (LocalService), the deploy-bound directory (LocalDirectory), and the delegation resource factories live in this package; the model-facing delegate / delegation_status tools live in the tool subpackage.

A host can expose a Service to execution-time tools with WithService, and consumers recover it with ServiceFromHost.

Index

Constants

View Source
const (
	// ServiceKind is the deployment resource kind of the local
	// delegation service.
	ServiceKind = "delegation.Service"
	// BackendDep is the optional async backend dependency.
	BackendDep = "backend"
)

Variables

View Source
var (
	// ErrTargetNotFound identifies an unknown target.
	ErrTargetNotFound = errors.New("delegation: target not found")
	// ErrRequestNotFound identifies an unknown delegation request.
	ErrRequestNotFound = errors.New("delegation: request not found")
	// ErrUnsupportedMode identifies a valid mode unsupported by a backend.
	ErrUnsupportedMode = errors.New("delegation: mode not supported")
)

Functions

func NewServiceFactory

func NewServiceFactory(directory *LocalDirectory, opts ...Option) res.Factory

NewServiceFactory returns a deployment factory for the local delegation service. directory is app-owned and may be bound to a deploy result after assembly (it cannot be a DAG dep: it bridges to the deploy result itself). Options inject app-owned behavior the document cannot express (e.g. delegation.WithWorkerHost); the declarative settings are applied after them.

func RequestNotFound

func RequestNotFound(id string) error

RequestNotFound returns a not-found-classified request lookup error.

func TargetNotFound

func TargetNotFound(id string) error

TargetNotFound returns a not-found-classified target lookup error.

func UnsupportedMode

func UnsupportedMode(mode Mode) error

UnsupportedMode returns a not-available-classified backend capability error.

func WithService

func WithService(h agent.Host, service Service) agent.Host

WithService wraps h with a ServiceProvider capability. Install this wrapper before agent Host middleware so built-in decorators can preserve access through agent.CapabilityFromHost.

Types

type AsyncBackend

type AsyncBackend interface {
	Submit(ctx context.Context, req AsyncRequest) (id string, err error)
	Status(ctx context.Context, id string) (Response, error)
}

AsyncBackend stores asynchronous delegations and reports their status. Submit must safely replay the same non-empty Request.IdempotencyKey and identical AsyncRequest during the backend's declared retention window, returning the same id; reuse with different request semantics must return a conflict-classified error. The service borrows an injected backend and never closes it.

type AsyncRequest

type AsyncRequest struct {
	Request Request `json:"request"`
	Caller  string  `json:"caller,omitempty"`
	Depth   int     `json:"depth"`
}

AsyncRequest is the backend-neutral unit persisted by an AsyncBackend. Caller and Depth preserve delegation metadata across queue boundaries.

type Deployment

type Deployment interface {
	Agent(id string) (*agent.Agent, bool)
	AgentNames() []string
}

Deployment is the minimal read-only deployment view needed by LocalDirectory. *deploy.Result implements this interface.

type Directory

type Directory interface {
	List(ctx context.Context) ([]Target, error)
	Get(ctx context.Context, id string) (Target, error)
}

Directory discovers delegation targets independently of execution.

type IdempotencyRetentionProvider

type IdempotencyRetentionProvider interface {
	IdempotencyRetention() time.Duration
}

IdempotencyRetentionProvider optionally exposes an AsyncBackend's finite terminal replay and status-query window.

type LocalDirectory

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

Directory exposes the agents assembled by deploy.Build as local delegation targets. It may be constructed before Build and bound exactly once after it.

func NewDirectory

func NewDirectory() *LocalDirectory

NewDirectory creates an unbound directory.

func (*LocalDirectory) Bind

func (d *LocalDirectory) Bind(result Deployment) error

Bind installs Build's instances. A directory is immutable after a successful bind and borrows the instances; the result retains lifecycle ownership.

func (*LocalDirectory) Get

func (d *LocalDirectory) Get(_ context.Context, id string) (Target, error)

Get returns one target by id.

func (*LocalDirectory) List

func (d *LocalDirectory) List(context.Context) ([]Target, error)

List returns targets in deploy.Result.InstanceNames order.

func (*LocalDirectory) Lookup

func (d *LocalDirectory) Lookup(_ context.Context, id string) (*agent.Agent, error)

Lookup resolves a target to the runnable agent.

type LocalService

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

LocalService executes local sync delegations and coordinates optional async storage/workers.

func NewService

func NewService(directory *LocalDirectory, backend AsyncBackend, opts ...Option) (*LocalService, error)

NewService constructs a local service. Successful responses in every mode retain one shared idempotency key and request fingerprint. Async Accepted responses use the shorter of the service retention and a positive backend retention declaration, so replay cannot outlive backend queryability. If the backend also implements WorkSource, bounded workers start immediately. The backend remains owned by the deploy Result or caller.

func (*LocalService) BindDeployment

func (s *LocalService) BindDeployment(deployment any) error

BindDeployment implements resource.DeploymentBinder: it binds the assembled deployment into the service's directory once agents are ready. The deployment view is the read-only interface exposed by *deploy.Result; binding is idempotent.

func (*LocalService) Close

func (s *LocalService) Close() error

Close rejects new operations, cancels service-owned workers, and waits for every admitted operation and worker to finish. It is idempotent.

func (*LocalService) Delegate

func (s *LocalService) Delegate(ctx context.Context, req Request) (Response, error)

Delegate implements core/delegation.Service.

func (*LocalService) Get

func (s *LocalService) Get(ctx context.Context, id string) (Response, error)

Get returns a normalized backend status snapshot.

func (*LocalService) Run

func (s *LocalService) Run(ctx context.Context, req AsyncRequest) (Response, error)

Run executes a backend-neutral work item through the same depth, timeout, host-propagation, and concurrency limits as a sync call.

func (*LocalService) Start

func (s *LocalService) Start() error

Start begins asynchronous workers when the backend supports WorkSource. Repeated calls are safe and do not create duplicate workers.

type Mode

type Mode string

Mode selects the lifecycle expected by a delegation request.

const (
	// ToolName is the canonical LLM-facing delegation tool name.
	ToolName = "delegate"

	// ModeSync waits for the delegated work and returns its terminal response.
	ModeSync Mode = "sync"
	// ModeAsync admits work and returns before it reaches a terminal state.
	ModeAsync Mode = "async"
)

func (Mode) Validate

func (m Mode) Validate() error

Validate checks that m is a defined delegation mode.

type Option

type Option func(*serviceConfig) error

Option configures a local Service.

func WithDeferredWorkers

func WithDeferredWorkers() Option

WithDeferredWorkers defers asynchronous worker startup until Start. This is useful when a lifecycle owner must finish binding all dependencies before background work begins.

func WithIdempotencyRetention

func WithIdempotencyRetention(retention time.Duration) Option

WithIdempotencyRetention sets how long successful responses remain safely replayable. The retention must be positive.

func WithMaxConcurrency

func WithMaxConcurrency(limit int) Option

WithMaxConcurrency bounds all local agent executions, including sync calls and work claimed by asynchronous workers.

func WithMaxDepth

func WithMaxDepth(limit int) Option

WithMaxDepth sets the largest allowed delegation depth. A top-level delegation executes at depth one.

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout caps each local agent execution. Zero leaves the caller's deadline unchanged.

func WithWorkerHost

func WithWorkerHost(host agent.Host) Option

WithWorkerHost sets the stable base Host used by asynchronous workers. Service adds its delegation capability without replacing optional capabilities such as EventBusProvider. The caller retains Host ownership.

type Request

type Request struct {
	Mode           Mode              `json:"mode"`
	Target         string            `json:"target"`
	Input          string            `json:"input"`
	Metadata       map[string]string `json:"metadata,omitempty"`
	IdempotencyKey string            `json:"idempotency_key,omitempty"`
}

Request is the portable input accepted by a Service.

func (Request) Validate

func (r Request) Validate() error

Validate checks fields required by every delegation backend.

type Response

type Response struct {
	ID       string            `json:"id"`
	Status   Status            `json:"status"`
	Output   string            `json:"output,omitempty"`
	Error    string            `json:"error,omitempty"`
	Metadata map[string]string `json:"metadata,omitempty"`
}

Response is a snapshot of delegated work.

func (Response) Validate

func (r Response) Validate() error

Validate checks lifecycle-dependent response invariants.

type Runner

type Runner interface {
	Run(ctx context.Context, req AsyncRequest) (Response, error)
}

Runner is the restricted execution seam a queue-owned worker may use.

type Service

type Service interface {
	Delegate(ctx context.Context, req Request) (Response, error)
	Get(ctx context.Context, id string) (Response, error)
}

Service starts delegated work and retrieves its latest response. Implementations must declare and guarantee a finite idempotency retention window. Within that window, requests with the same non-empty idempotency key and business fields must safely replay the same operation, and its response must remain queryable; reusing the key for a semantically different request must return a conflict-classified error. After the declared window expires, the key may start a new operation: this contract is bounded idempotency, not permanent exactly-once execution.

func ServiceFromHost

func ServiceFromHost(h agent.Host) (Service, bool)

ServiceFromHost returns the delegation service borrowed from h.

type ServiceProvider

type ServiceProvider interface {
	DelegationService() Service
}

ServiceProvider is the optional Host capability exposing delegation.

type ServiceSettings

type ServiceSettings struct {
	MaxConcurrency       *int    `json:"max_concurrency,omitempty"`
	MaxDepth             *int    `json:"max_depth,omitempty"`
	Timeout              *string `json:"timeout,omitempty"`
	IdempotencyRetention *string `json:"idempotency_retention,omitempty"`
	DeferWorkers         bool    `json:"defer_workers,omitempty"`
}

ServiceSettings is the strict settings subtree of the local service factory. Zero fields leave the service defaults.

type Status

type Status string

Status describes the backend-neutral lifecycle of delegated work.

const (
	StatusAccepted  Status = "accepted"
	StatusRunning   Status = "running"
	StatusSucceeded Status = "succeeded"
	StatusFailed    Status = "failed"
	StatusCanceled  Status = "canceled"
)

func (Status) Terminal

func (s Status) Terminal() bool

Terminal reports whether no further status transition is expected.

func (Status) Validate

func (s Status) Validate() error

Validate checks that s is a defined delegation status.

type Target

type Target struct {
	ID          string            `json:"id"`
	Description string            `json:"description,omitempty"`
	Modes       []Mode            `json:"modes,omitempty"`
	Metadata    map[string]string `json:"metadata,omitempty"`
}

Target describes a backend-neutral delegation destination. Modes is an explicit allowlist; an empty Modes list means unrestricted support for every defined delegation mode.

func (Target) Validate

func (t Target) Validate() error

Validate checks the target identity and any advertised modes.

type Work

type Work struct {
	ID         string          `json:"id"`
	LeaseToken string          `json:"lease_token"`
	Request    AsyncRequest    `json:"request"`
	Context    context.Context `json:"-"`
}

Work is one claimed asynchronous request. LeaseToken uniquely identifies this claim generation and must be supplied to WorkSource.Complete. Context optionally carries the backend-owned execution lease; canceling it must stop the claimed execution.

type WorkSource

type WorkSource interface {
	Claim(ctx context.Context) (Work, error)
	Complete(ctx context.Context, id, leaseToken string, response Response) error
}

WorkSource is the optional worker side of an AsyncBackend. When implemented, Service starts bounded workers that claim backend-neutral work and complete it through the same backend. Claim must return a unique, non-empty lease token and unblock when ctx is canceled. Complete must only apply a terminal response when the token identifies the current lease; stale completions are ignored.

Directories

Path Synopsis
Package kanban provides an in-memory core/delegation AsyncBackend and WorkSource.
Package kanban provides an in-memory core/delegation AsyncBackend and WorkSource.
resource
Package resource adapts kanban delegation backends to deployment resources.
Package resource adapts kanban delegation backends to deployment resources.
Package delegation exposes backend-neutral delegate, delegation_status, and delegation_targets tools.
Package delegation exposes backend-neutral delegate, delegation_status, and delegation_targets tools.

Jump to

Keyboard shortcuts

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