Documentation
¶
Overview ¶
Package moe implements the Mixture-of-Experts orchestration primitives: an expert registry, a keyword+context router, a model-tier classifier, a planner-style orchestrator, and the central / delegate cross-expert tools.
The framework is consumer-driven: a project supplies its own expert definitions (with associated skill IDs, tool-set names, and prompts), a skills.Registry, and a tool resolver. The orchestrator returns a Plan the caller executes by running its own agentic loop.
Index ¶
- Variables
- func CentralPromptAugmentation(reg *Registry, skillReg *skills.Registry) string
- func CentralPromptAugmentationFor(experts []*ExpertDefinition, skillReg *skills.Registry) string
- func ConsultTool(reg *Registry) llms.Tool
- func ConsultToolFor(experts []*ExpertDefinition) llms.Tool
- func DelegateTool(reg *Registry) llms.Tool
- func DelegateToolFor(experts []*ExpertDefinition) llms.Tool
- func DelegationArtifactRef(artifact DelegationArtifact) string
- func DelegationTokenGrantFromContext(ctx context.Context) int
- func RegisterConsult(base *agent.BaseAgent, reg *Registry, fn ConsultFn) error
- func RegisterConsultWithOptions(base *agent.BaseAgent, reg *Registry, fn ConsultFn, opts ConsultOptions) error
- func RegisterDelegate(base *agent.BaseAgent, reg *Registry, fn DelegateFn) error
- func RegisterDelegateWithOptions(base *agent.BaseAgent, reg *Registry, fn DelegateFn, opts DelegateOptions) error
- func WithDelegationLease(ctx context.Context, lease *DelegationLease) context.Context
- type AdaptiveDecision
- type AdaptiveInput
- type AdaptivePlanner
- type ArtifactFinding
- type ArtifactSource
- type CandidateSource
- type CapabilityCeiling
- type CapabilityResolver
- type ChildProfile
- type ComplexityClassifier
- type Config
- type ConsultFn
- type ConsultOptions
- type ConsultRequest
- type ContextFragment
- type ContextResolver
- type DefaultAdaptivePlanner
- type DelegateFn
- type DelegateOptions
- type DelegateRequest
- type DelegateResult
- type DelegationAdmission
- type DelegationArtifact
- type DelegationLease
- type DelegationLeaseStore
- type DelegationLimits
- type DelegationNode
- type DelegationOutcome
- type DelegationPressure
- type DelegationSnapshot
- type DelegationUsage
- type EWMAStore
- type Event
- type EventEmitter
- type EventType
- type ExpertDefinition
- type ExpertID
- type LearningConfig
- type LoopOptions
- type MemoryDelegationLeaseStore
- func (s *MemoryDelegationLeaseStore) CompareAndSwap(runID string, expectedRevision uint64, next DelegationSnapshot) (StoredDelegationLease, error)
- func (s *MemoryDelegationLeaseStore) Create(snapshot DelegationSnapshot) (StoredDelegationLease, error)
- func (s *MemoryDelegationLeaseStore) Load(runID string) (StoredDelegationLease, bool, error)
- type ModelTier
- type Orchestrator
- func (o *Orchestrator) Plan(query string, ctx RoutingContext) (*Plan, error)
- func (o *Orchestrator) PlanCentral() (*Plan, error)
- func (o *Orchestrator) PlanForExpert(id ExpertID) (*Plan, error)
- func (o *Orchestrator) PlanForExpertUnrestricted(id ExpertID) (*Plan, error)
- func (o *Orchestrator) PlanForExpertWithAdmission(id ExpertID, admission DelegationAdmission) (*Plan, error)
- func (o *Orchestrator) PlanForExpertWithCeiling(id ExpertID, ceiling CapabilityCeiling) (*Plan, error)
- func (o *Orchestrator) RecordOutcome(plan *Plan, sample RunSample) error
- func (o *Orchestrator) RecordSample(sample RunSample) error
- type Plan
- type ProviderCandidate
- type ProviderHealth
- type ProviderResourceProfile
- type ProviderScore
- type Registry
- type Router
- type RouterConfig
- type RoutingContext
- type RoutingObjective
- type RunSample
- type RunStats
- type Selection
- type StatsKey
- type StatsLookup
- type StatsRecorder
- type StoredDelegationLease
- type TierDecision
- type TierMapping
- type ToolBinding
- type ToolResolver
- type VerifiedEffect
Constants ¶
This section is empty.
Variables ¶
var ErrLeaseRevisionConflict = errors.New("delegation lease revision conflict")
Functions ¶
func CentralPromptAugmentation ¶
CentralPromptAugmentation returns the system-prompt block describing the available experts to a "central" agent (one allowed to call consult_expert and delegate_to_expert).
func CentralPromptAugmentationFor ¶
func CentralPromptAugmentationFor(experts []*ExpertDefinition, skillReg *skills.Registry) string
func ConsultTool ¶
ConsultTool returns the consult_expert tool definition. The description enumerates available experts so the central agent knows valid IDs.
func ConsultToolFor ¶
func ConsultToolFor(experts []*ExpertDefinition) llms.Tool
func DelegateTool ¶
DelegateTool returns the delegate_to_expert tool definition.
func DelegateToolFor ¶
func DelegateToolFor(experts []*ExpertDefinition) llms.Tool
func DelegationArtifactRef ¶
func DelegationArtifactRef(artifact DelegationArtifact) string
DelegationArtifactRef returns the canonical provenance reference a child uses when it relies on a retained artifact from an earlier node.
func DelegationTokenGrantFromContext ¶
DelegationTokenGrantFromContext returns the maximum child-model tokens reserved for the active node. Child loops must enforce this as a hard cap.
func RegisterConsult ¶
RegisterConsult attaches the consult_expert callable on a BaseAgent.
func RegisterConsultWithOptions ¶
func RegisterConsultWithOptions(base *agent.BaseAgent, reg *Registry, fn ConsultFn, opts ConsultOptions) error
RegisterConsultWithOptions attaches consult_expert with canonical context resolution. Calls without selected context need no resolver.
func RegisterDelegate ¶
func RegisterDelegate(base *agent.BaseAgent, reg *Registry, fn DelegateFn) error
RegisterDelegate attaches the bounded delegate callable. A shared lease must be installed with WithDelegationLease before execution; this prevents independent tool calls from silently resetting run-wide budgets.
func RegisterDelegateWithOptions ¶
func RegisterDelegateWithOptions(base *agent.BaseAgent, reg *Registry, fn DelegateFn, opts DelegateOptions) error
RegisterDelegateWithOptions attaches the bounded delegate callable and emits lifecycle events when configured.
func WithDelegationLease ¶
func WithDelegationLease(ctx context.Context, lease *DelegationLease) context.Context
WithDelegationLease installs the root run's shared lease.
Types ¶
type AdaptiveDecision ¶
type AdaptiveInput ¶
type AdaptiveInput struct {
Key StatsKey
EstimatedInputTokens int
EffectiveContext int
HasTools bool
Base LoopOptions
}
type AdaptivePlanner ¶
type AdaptivePlanner interface {
Recommend(AdaptiveInput, StatsLookup) AdaptiveDecision
}
type ArtifactFinding ¶
type ArtifactFinding struct {
Claim string `json:"claim"`
SourceRefs []string `json:"source_refs,omitempty"`
}
ArtifactFinding is one claim and the server-selected sources supporting it.
type ArtifactSource ¶
type CandidateSource ¶
type CandidateSource interface{ Candidates() []ProviderCandidate }
type CapabilityCeiling ¶
type CapabilityCeiling struct {
// contains filtered or unexported fields
}
CapabilityCeiling is the exact set of tool names a delegated plan may expose. Its zero value denies every tool, so callers must opt in to each delegated capability.
func NewCapabilityCeiling ¶
func NewCapabilityCeiling(names ...string) CapabilityCeiling
NewCapabilityCeiling constructs a fail-closed ceiling for the supplied tool names.
func UnrestrictedCapabilityCeiling ¶
func UnrestrictedCapabilityCeiling() CapabilityCeiling
UnrestrictedCapabilityCeiling explicitly permits every resolved tool. It is intended for trusted/manual expert runs, not model-directed delegation.
func (CapabilityCeiling) Allows ¶
func (c CapabilityCeiling) Allows(name string) bool
Allows reports whether a named tool is inside the ceiling.
type CapabilityResolver ¶
type CapabilityResolver func(toolSetName string) []ToolBinding
func CapabilityResolverFromCatalog ¶
func CapabilityResolverFromCatalog(catalog execution.CatalogSnapshot, snapshot policy.Snapshot) CapabilityResolver
CapabilityResolverFromCatalog makes the model-visible schema and execution dispatcher consume the same immutable catalog and policy snapshots.
type ChildProfile ¶
type ChildProfile struct {
InheritTranscript bool `json:"inherit_transcript"`
AllowPersistence bool `json:"allow_persistence"`
AllowMemory bool `json:"allow_memory"`
AllowMutation bool `json:"allow_mutation"`
AllowApprovals bool `json:"allow_approvals"`
AllowNetwork bool `json:"allow_network"`
WorkspaceLease string `json:"workspace_lease,omitempty"`
ContextSources []string `json:"context_sources,omitempty"`
OutputTokenBudget int `json:"output_token_budget,omitempty"`
}
ChildProfile makes child isolation explicit. Its zero value is the secure default: no transcript, memory, persistence, mutation, approval, or network inheritance.
type ComplexityClassifier ¶
type ComplexityClassifier struct {
// LongQueryRunes: queries longer than this push the tool-call step up
// one tier. Default: 600.
LongQueryRunes int
// DeepHistoryTurns: when history depth exceeds this, push tool-call up
// one tier. Default: 8.
DeepHistoryTurns int
// MultiDomainSecondaryConfidence: when secondaries exist above this
// confidence, push synthesis up one tier. Default: 0.4.
MultiDomainSecondaryConfidence float64
}
ComplexityClassifier picks a tier per step (tool-calling vs synthesis) based on cheap, deterministic heuristics. It is intentionally simple — consumers can replace it with their own classifier by writing a function with the same signature and ignoring this struct entirely.
func DefaultClassifier ¶
func DefaultClassifier() ComplexityClassifier
DefaultClassifier returns a ComplexityClassifier with sensible defaults.
func (ComplexityClassifier) Classify ¶
func (c ComplexityClassifier) Classify( query string, ctx RoutingContext, sel *Selection, expertDefault ModelTier, ) TierDecision
Classify produces a TierDecision given the routing inputs and selection. expertDefault is the expert's DefaultTier (may be ModelTierUnspecified).
type Config ¶
type Config struct {
Experts *Registry
Skills *skills.Registry
Router *Router
ToolResolver ToolResolver
// CapabilityResolver is the authoritative versioned discovery source.
// ToolResolver remains a migration path for unversioned callers.
CapabilityResolver CapabilityResolver
Policy *policy.Snapshot
CatalogVersion string
ContextDigest string
ProviderForModel map[string]string
EffectiveContextWindows map[string]int
Classifier ComplexityClassifier
Tiers TierMapping
Emit EventEmitter
DefaultOptions LoopOptions
Learning LearningConfig
Adaptive AdaptivePlanner
// DelegatedToolCeiling is applied by PlanForExpert. Its zero value denies
// all tools, requiring the host to authorize delegated capabilities.
DelegatedToolCeiling CapabilityCeiling
// MaxInjectedSkillTokens bounds static skill prompt augmentation. Zero uses
// a conservative 4096-token default; omitted skills remain loadable via
// load_skill when the host exposes that tool.
MaxInjectedSkillTokens int
// CentralToolSet is the tool-set name used when planning a central run.
// The orchestrator appends consult_expert + delegate_to_expert tool
// definitions automatically on top of whatever the resolver returns.
CentralToolSet string
}
Config bundles the inputs the orchestrator needs to build plans.
type ConsultFn ¶
type ConsultFn func(ctx context.Context, req ConsultRequest, expert *ExpertDefinition) (string, error)
ConsultFn is the consumer-supplied callback that handles a consult call. Implementations typically pull the expert's skill bodies and run a single LLM completion (no full sub-agent loop). Compare with DelegateFn which runs a full sub-loop.
type ConsultOptions ¶
type ConsultOptions struct {
ResolveContext ContextResolver
}
ConsultOptions provides canonical context resolution for advisory calls.
type ConsultRequest ¶
type ConsultRequest struct {
ExpertID ExpertID `json:"expert_id"`
Question string `json:"question"`
SelectedContext []string `json:"selected_context,omitempty"`
ContextFrames []ContextFragment `json:"-"`
}
ConsultRequest is the parsed argument shape for consult_expert.
type ContextFragment ¶
ContextFragment is untrusted source material selected for a child. Content must be supplied to the child as data, never concatenated into its trusted task or system instructions.
type ContextResolver ¶
type ContextResolver func(ctx context.Context, ref string) (ContextFragment, error)
ContextResolver resolves a model-selected opaque reference to canonical host-owned content. It must reject unknown or unauthorized references.
type DefaultAdaptivePlanner ¶
func (DefaultAdaptivePlanner) Recommend ¶
func (p DefaultAdaptivePlanner) Recommend(input AdaptiveInput, lookup StatsLookup) AdaptiveDecision
type DelegateFn ¶
type DelegateFn func(ctx context.Context, req DelegateRequest, expert *ExpertDefinition) (*DelegateResult, error)
DelegateFn runs a child loop and returns a typed artifact plus measured usage. The callback must give SelectedContext to its compiler as untrusted data, use the supplied context, and return when that context is cancelled.
type DelegateOptions ¶
type DelegateOptions struct {
Emit EventEmitter
ResolveContext ContextResolver
// Checkpoint persists a lease whenever a child completes at a safe
// boundary with no other in-flight children.
Checkpoint func(context.Context, DelegationSnapshot) error
}
DelegateOptions controls lifecycle telemetry. Resource limits live on the DelegationLease installed in the execution context.
type DelegateRequest ¶
type DelegateRequest struct {
ExpertID ExpertID `json:"expert_id"`
Task string `json:"task"`
Kind string `json:"kind,omitempty"`
SelectedContext []string `json:"selected_context,omitempty"`
Artifacts []DelegationArtifact `json:"artifacts,omitempty"`
// ContextFrames contains canonical host-resolved data and is never decoded
// from model arguments.
ContextFrames []ContextFragment `json:"-"`
}
DelegateRequest is the strict argument shape for delegate_to_expert. SelectedContext remains untrusted data and must not be promoted into the child's system prompt or task string by the consumer callback.
type DelegateResult ¶
type DelegateResult struct {
Artifact DelegationArtifact `json:"artifact"`
Usage DelegationUsage `json:"usage"`
}
DelegateResult is returned by a consumer's child-loop callback.
type DelegationAdmission ¶
type DelegationAdmission struct {
ToolCeiling CapabilityCeiling
Policy *policy.Snapshot
ChildProfile ChildProfile
ToolCallModel string
SynthesisModel string
ContextDigest string
CatalogVersion string
}
DelegationAdmission is the host-authorized execution envelope for a child. Model fields let the host preserve an owner/user model selection instead of allowing heuristic tier routing to silently switch delegated credentials.
type DelegationArtifact ¶
type DelegationArtifact struct {
Version int `json:"version"`
NodeID string `json:"node_id"`
ParentNodeID string `json:"parent_node_id,omitempty"`
Depth int `json:"depth"`
ExpertID ExpertID `json:"expert_id"`
Goal string `json:"goal,omitempty"`
Constraints []string `json:"constraints,omitempty"`
Summary string `json:"summary"`
Findings []ArtifactFinding `json:"findings,omitempty"`
Sources []ArtifactSource `json:"sources,omitempty"`
SourceRefs []string `json:"source_refs,omitempty"`
SourceDigest string `json:"source_digest,omitempty"`
WorkingSetRevision string `json:"working_set_revision,omitempty"`
SnapshotRevision uint64 `json:"snapshot_revision,omitempty"`
Trust string `json:"trust,omitempty"`
OutputTokens int `json:"output_tokens,omitempty"`
VerifiedEffects []VerifiedEffect `json:"verified_effects,omitempty"`
Conflicts []string `json:"conflicts,omitempty"`
ArtifactRefs []string `json:"artifact_refs,omitempty"`
Coverage []string `json:"coverage"`
OpenQuestions []string `json:"open_questions,omitempty"`
NextActions []string `json:"next_actions,omitempty"`
}
DelegationArtifact is the only successful value allowed to cross from a child back to its parent. Identity fields are assigned by the lease.
type DelegationLease ¶
type DelegationLease struct {
// contains filtered or unexported fields
}
DelegationLease owns cumulative resource accounting for one root run. Persist or reconstruct its Snapshot when a root run can be resumed later.
func DelegationLeaseFromContext ¶
func DelegationLeaseFromContext(ctx context.Context) *DelegationLease
DelegationLeaseFromContext returns the installed run-level lease.
func NewDelegationLease ¶
func NewDelegationLease(runID string, limits DelegationLimits) *DelegationLease
NewDelegationLease creates a shared run-level lease.
func RestoreDelegationLease ¶
func RestoreDelegationLease(snapshot DelegationSnapshot) (*DelegationLease, error)
RestoreDelegationLease restores cumulative budget and provenance state for a continuation of the same root run.
func (*DelegationLease) RootFinalizationReserve ¶
func (l *DelegationLease) RootFinalizationReserve() int
RootFinalizationReserve returns tokens held back from delegated children.
func (*DelegationLease) Snapshot ¶
func (l *DelegationLease) Snapshot() (DelegationSnapshot, error)
Snapshot returns a deep copy suitable for durable continuation state. It fails while children are active because in-flight reservations cannot be resumed safely.
func (*DelegationLease) SnapshotIfSafe ¶
func (l *DelegationLease) SnapshotIfSafe() (DelegationSnapshot, bool, error)
SnapshotIfSafe reports false instead of failing while a sibling or parent is active, making it suitable for automatic safe-boundary checkpoints.
type DelegationLeaseStore ¶
type DelegationLeaseStore interface {
Create(DelegationSnapshot) (StoredDelegationLease, error)
Load(runID string) (StoredDelegationLease, bool, error)
CompareAndSwap(runID string, expectedRevision uint64, next DelegationSnapshot) (StoredDelegationLease, error)
}
DelegationLeaseStore prevents concurrent continuations from spending the same restored budget. CompareAndSwap must be atomic in durable adapters.
type DelegationLimits ¶
type DelegationLimits struct {
MaxDepth int
MaxReasoningDepth int
MaxNodes int
MaxChildren int
MaxReasoningChildren int
MaxParallel int
MaxTotalTokens int
MaxNodeTokens int
RootFinalizationTokens int
MaxWorkUnits int
MaxRequestTokens int
MaxArtifactBytes int
MaxTotalArtifactBytes int
MaxArtifactItems int
Timeout time.Duration
}
DelegationLimits bounds one root run, including every recursive child.
func DefaultDelegationLimits ¶
func DefaultDelegationLimits() DelegationLimits
DefaultDelegationLimits returns conservative process-local limits.
type DelegationNode ¶
DelegationNode identifies one child within a root run.
func DelegationNodeFromContext ¶
func DelegationNodeFromContext(ctx context.Context) (DelegationNode, bool)
DelegationNodeFromContext returns the active child node, if any.
type DelegationOutcome ¶
type DelegationOutcome struct {
Kind string `json:"kind"`
Artifact *DelegationArtifact `json:"artifact,omitempty"`
Pressure *DelegationPressure `json:"pressure,omitempty"`
}
DelegationOutcome is the JSON tool result returned to the parent.
type DelegationPressure ¶
type DelegationPressure struct {
Code string `json:"code"`
NodeID string `json:"node_id,omitempty"`
Resource string `json:"resource"`
Used int `json:"used"`
Limit int `json:"limit"`
Retryable bool `json:"retryable"`
Guidance string `json:"guidance"`
}
DelegationPressure is a typed, model-actionable resource or contract error.
func (*DelegationPressure) Error ¶
func (p *DelegationPressure) Error() string
type DelegationSnapshot ¶
type DelegationSnapshot struct {
Version int `json:"version"`
RunID string `json:"run_id"`
Limits DelegationLimits `json:"limits"`
Deadline time.Time `json:"deadline"`
Nodes int `json:"nodes"`
Consumed int `json:"consumed_tokens"`
WorkUnits int `json:"work_units"`
ArtifactBytes int `json:"artifact_bytes"`
Children map[string]int `json:"children"`
ReasoningChildren map[string]int `json:"reasoning_children"`
Seen []string `json:"seen_requests"`
Artifacts map[string]DelegationArtifact `json:"artifacts"`
}
DelegationSnapshot is the durable form of a lease. Checkpoint it whenever the root run can pause, then restore it before processing a continuation so cumulative limits cannot reset.
type DelegationUsage ¶
type DelegationUsage struct {
TotalTokens int `json:"total_tokens"`
}
DelegationUsage reports child-model consumption to the shared lease.
type EWMAStore ¶
type EWMAStore struct {
// contains filtered or unexported fields
}
EWMAStore is a concurrency-safe reference learning store.
func NewEWMAStore ¶
type Event ¶
type Event struct {
Type EventType `json:"type"`
ExpertID ExpertID `json:"expert_id,omitempty"`
ExpertName string `json:"expert_name,omitempty"`
Confidence float64 `json:"confidence,omitempty"`
Skills []string `json:"skills,omitempty"`
Tier string `json:"tier,omitempty"`
Message string `json:"message"`
Reasoning string `json:"reasoning,omitempty"`
FromExpert ExpertID `json:"from_expert,omitempty"`
ToExpert ExpertID `json:"to_expert,omitempty"`
NodeID string `json:"node_id,omitempty"`
ParentNodeID string `json:"parent_node_id,omitempty"`
Depth int `json:"depth,omitempty"`
Tokens int `json:"tokens,omitempty"`
DurationMS int64 `json:"duration_ms,omitempty"`
}
Event is the observability record emitted by the orchestrator. Consumers typically forward these to the UI / tracing layer.
type EventEmitter ¶
type EventEmitter func(Event)
EventEmitter is a callback the orchestrator calls when planning produces observability events. nil is safe (drops events).
type EventType ¶
type EventType string
EventType is the kind of observability event emitted during planning.
const ( EventTypeRouting EventType = "routing" EventTypeExpert EventType = "expert_activated" EventTypeSecondary EventType = "secondary_consulted" EventTypeSynthesis EventType = "synthesis_triggered" EventTypeFallback EventType = "fallback" EventTypeDelegation EventType = "delegation" EventTypeCentral EventType = "central_dispatch" EventTypeDelegationStarted EventType = "delegation_started" EventTypeDelegationCompleted EventType = "delegation_completed" EventTypeDelegationFailed EventType = "delegation_failed" EventTypeDelegationPressure EventType = "delegation_pressure" )
type ExpertDefinition ¶
type ExpertDefinition struct {
ID ExpertID
Name string
Description string
// SkillIDs the orchestrator will pull from the skills registry and inject
// into the system prompt for this expert.
SkillIDs []string
// ToolSetName the consumer's tool resolver maps to a []llms.Tool.
ToolSetName string
// Keywords contribute positive routing score on overlap with the query.
Keywords []string
// NegativeKeywords contribute negative routing score.
NegativeKeywords []string
// Priority is a tie-breaker (lower = preferred) when scores are equal.
Priority int
// CanSynthesize: true for experts that handle cross-domain synthesis.
// When a non-synthesis expert wins routing but a second expert is also
// confident, the router escalates to the synthesis expert if one exists.
CanSynthesize bool
// DefaultTier is the model tier this expert prefers when no
// per-request override is supplied. ModelTierBalanced when zero.
DefaultTier ModelTier
// Loop overrides — zero values mean "use the caller's defaults".
MaxIterations int
MaxToolCalls int
MinToolCallsBeforeFinish int
// PromptAugmentation is appended to the system prompt after the
// skill context.
PromptAugmentation string
}
ExpertDefinition describes one expert's behavior. Consumers register definitions at startup; the router scores queries against keywords, negative keywords, and routing context.
func (*ExpertDefinition) AssembleSkillContext ¶
func (e *ExpertDefinition) AssembleSkillContext(reg *skills.Registry) string
AssembleSkillContext renders this expert's skill bodies via the registry.
type LearningConfig ¶
type LearningConfig struct {
Disabled bool
Lookup StatsLookup
Recorder StatsRecorder
}
type LoopOptions ¶
type LoopOptions struct {
ToolCallModel string
SynthesisModel string
ResponseTokenBudget int
EnableChunking bool
MaxIterations int
MaxToolCalls int
MinToolCallsBeforeFinish int
}
LoopOptions are the per-plan execution caps. Consumers feed these into their own agentic loop; the orchestrator does not run the loop itself.
type MemoryDelegationLeaseStore ¶
type MemoryDelegationLeaseStore struct {
// contains filtered or unexported fields
}
MemoryDelegationLeaseStore is a concurrency-safe reference implementation.
func NewMemoryDelegationLeaseStore ¶
func NewMemoryDelegationLeaseStore() *MemoryDelegationLeaseStore
func (*MemoryDelegationLeaseStore) CompareAndSwap ¶
func (s *MemoryDelegationLeaseStore) CompareAndSwap(runID string, expectedRevision uint64, next DelegationSnapshot) (StoredDelegationLease, error)
func (*MemoryDelegationLeaseStore) Create ¶
func (s *MemoryDelegationLeaseStore) Create(snapshot DelegationSnapshot) (StoredDelegationLease, error)
func (*MemoryDelegationLeaseStore) Load ¶
func (s *MemoryDelegationLeaseStore) Load(runID string) (StoredDelegationLease, bool, error)
type ModelTier ¶
type ModelTier int
ModelTier is a coarse complexity bucket the orchestrator hands the caller so they can pick a concrete model name from their own catalog.
Consumers map each tier to one or more model identifiers via TierMapping.
const ( // ModelTierUnspecified means "no preference — caller uses its default". ModelTierUnspecified ModelTier = iota // ModelTierFast is for cheap, latency-sensitive steps (routing, // keyword extraction, short tool-arg generation). ModelTierFast // ModelTierBalanced is the default for most tool-calling turns. ModelTierBalanced // ModelTierStrong is reserved for multi-domain synthesis, long-context // reasoning, and complex planning. ModelTierStrong )
type Orchestrator ¶
type Orchestrator struct {
// contains filtered or unexported fields
}
Orchestrator builds Plans. It does not run agentic loops; that's the caller's job.
func New ¶
func New(cfg Config) *Orchestrator
New constructs an Orchestrator. Defaults: empty classifier (uses internal defaults), no-op emitter, DefaultRouterConfig if Router is nil.
func (*Orchestrator) Plan ¶
func (o *Orchestrator) Plan(query string, ctx RoutingContext) (*Plan, error)
Plan routes the query to an expert and returns the execution plan.
func (*Orchestrator) PlanCentral ¶
func (o *Orchestrator) PlanCentral() (*Plan, error)
PlanCentral builds a plan for the central coordinator agent. The central agent gets consult_expert + delegate_to_expert in addition to whatever tools cfg.CentralToolSet resolves to.
func (*Orchestrator) PlanForExpert ¶
func (o *Orchestrator) PlanForExpert(id ExpertID) (*Plan, error)
PlanForExpert builds a plan for a specific expert (bypasses routing). Useful for delegate_to_expert sub-loops or manual expert overrides.
func (*Orchestrator) PlanForExpertUnrestricted ¶
func (o *Orchestrator) PlanForExpertUnrestricted(id ExpertID) (*Plan, error)
PlanForExpertUnrestricted builds a trusted/manual expert plan. Prefer PlanForExpert or PlanForExpertWithCeiling for model-directed children.
func (*Orchestrator) PlanForExpertWithAdmission ¶
func (o *Orchestrator) PlanForExpertWithAdmission(id ExpertID, admission DelegationAdmission) (*Plan, error)
PlanForExpertWithAdmission builds a child plan inside the exact model and capability envelope authorized by the host at root-run admission.
func (*Orchestrator) PlanForExpertWithCeiling ¶
func (o *Orchestrator) PlanForExpertWithCeiling(id ExpertID, ceiling CapabilityCeiling) (*Plan, error)
PlanForExpertWithCeiling builds a delegated plan using an exact capability ceiling supplied at admission time.
func (*Orchestrator) RecordOutcome ¶
func (o *Orchestrator) RecordOutcome(plan *Plan, sample RunSample) error
RecordOutcome records both the selected expert and the MoE strategy from one host-reported outcome, avoiding missing strategy-level feedback.
func (*Orchestrator) RecordSample ¶
func (o *Orchestrator) RecordSample(sample RunSample) error
type Plan ¶
type Plan struct {
Expert *ExpertDefinition
Selection *Selection
SkillContext string
Tools []llms.Tool
ToolNames []string
Options LoopOptions
Tier TierDecision
Adaptive AdaptiveDecision
ChildProfile ChildProfile
LoadedSkills []string
OmittedSkills []string
PolicyVersion string
CatalogVersion string
ContextDigest string
ToolBindings map[string]ToolBinding
// SystemPromptAugmentation is the text the caller appends to its base
// system prompt (skills + expert-specific prompt + optional central
// network description for central plans).
SystemPromptAugmentation string
// IsCentral is true for plans produced by PlanCentral.
IsCentral bool
}
Plan is the orchestrator's output: everything the caller needs to compose a system prompt + run an agentic loop for the selected expert.
type ProviderCandidate ¶
type ProviderCandidate struct {
Provider string `json:"provider"`
Model string `json:"model"`
Tier ModelTier `json:"tier"`
ContextWindow int `json:"context_window"`
MaxParallel int `json:"max_parallel"`
ToolCalling bool `json:"tool_calling"`
StructuredOutput bool `json:"structured_output"`
Placement string `json:"placement"`
Ready bool `json:"ready"`
AccountBinding string `json:"account_binding,omitempty"`
Resources ProviderResourceProfile `json:"resources,omitempty"`
Health ProviderHealth `json:"health,omitempty"`
}
ProviderCandidate describes routing-relevant capacity without embedding a concrete provider SDK or credential source.
func (ProviderCandidate) Validate ¶
func (c ProviderCandidate) Validate() error
type ProviderHealth ¶
type ProviderResourceProfile ¶
type ProviderResourceProfile struct {
ResidentMemoryBytes int64 `json:"resident_memory_bytes,omitempty"`
CacheBytesPerToken int64 `json:"cache_bytes_per_token,omitempty"`
ColdStart time.Duration `json:"cold_start,omitempty"`
Warmup time.Duration `json:"warmup,omitempty"`
Platforms []string `json:"platforms,omitempty"`
BundleDigest string `json:"bundle_digest,omitempty"`
}
type ProviderScore ¶
type ProviderScore struct {
Candidate ProviderCandidate `json:"candidate"`
Score float64 `json:"score"`
Eligible bool `json:"eligible"`
Reason string `json:"reason"`
Samples int64 `json:"samples"`
}
func RankProviders ¶
func RankProviders(candidates []ProviderCandidate, taskType string, lookup StatsLookup, objective RoutingObjective, now time.Time) ([]ProviderScore, error)
RankProviders returns every candidate, eligible candidates first and then by descending score. Unknown providers receive a prior plus an uncertainty penalty rather than being mistaken for proven high-quality routes.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry holds expert definitions.
func (*Registry) All ¶
func (r *Registry) All() []*ExpertDefinition
All returns every registered expert, in registration order.
func (*Registry) Get ¶
func (r *Registry) Get(id ExpertID) (*ExpertDefinition, bool)
Get fetches an expert by ID.
func (*Registry) Register ¶
func (r *Registry) Register(e *ExpertDefinition)
Register adds (or replaces) an expert.
func (*Registry) SynthesisExpert ¶
func (r *Registry) SynthesisExpert() (*ExpertDefinition, bool)
SynthesisExpert returns the first registered expert with CanSynthesize.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router scores experts against a query + routing context.
func NewRouter ¶
func NewRouter(reg *Registry, cfg RouterConfig) *Router
NewRouter constructs a Router. Pass DefaultRouterConfig() for sensible defaults.
type RouterConfig ¶
type RouterConfig struct {
// SynthesisThreshold: when the second-best expert score is at least this
// fraction of the best, the router escalates to the synthesis expert.
// Default: 0.6.
SynthesisThreshold float64
// MinConfidence: if the best score is below this, the router falls back
// to the general expert (or the highest-priority non-synthesis expert).
// Default: 0.15.
MinConfidence float64
// SecondaryThreshold: secondaries reported on Selection must score at
// least this fraction of the primary's score. Default: 0.5.
SecondaryThreshold float64
// KeywordWeight, NegativeWeight, ContextWeight are the per-source
// score weights. Defaults: 1.0, 1.5, 0.4.
KeywordWeight float64
NegativeWeight float64
ContextWeight float64
}
RouterConfig tunes the router's behavior.
func DefaultRouterConfig ¶
func DefaultRouterConfig() RouterConfig
DefaultRouterConfig returns sensible defaults.
type RoutingContext ¶
type RoutingContext struct {
// Topics is a free-form set of tags about the active session
// (e.g. service names, repo names, "trace", "build", "issue").
Topics []string
// HasTraceContext: the user is looking at telemetry / a trace.
HasTraceContext bool
// HasBuildContext: the user is looking at a CI build / pipeline.
HasBuildContext bool
// HasIssueContext: the user is looking at an issue / ticket.
HasIssueContext bool
// HasCodeContext: the user is looking at code / a diff.
HasCodeContext bool
// HistoryDepth is the count of prior turns in the conversation.
HistoryDepth int
}
RoutingContext is the optional ambient context the router can use to boost expert scores when explicit query keywords are sparse. All fields are optional.
type RoutingObjective ¶
type RoutingObjective struct {
MinSamples int64
RequiredContext int
RequireTools bool
RequireStructured bool
QualityWeight float64
LatencyWeight float64
CostWeight float64
ReliabilityWeight float64
ColdStartWeight float64
UncertaintyWeight float64
LatencyScale time.Duration
CostScaleUSD float64
ColdStartScale time.Duration
}
RoutingObjective weights measured quality against operational cost. Zero values receive conservative defaults so selection remains deterministic.
type RunStats ¶
type RunStats struct {
Samples int64
SuccessRate float64
AvgInputTokens float64
AvgOutputTokens float64
AvgLatency time.Duration
AvgToolFailures float64
AvgChunks float64
AvgPeakUtilization float64
ContinuationRate float64
PreflightSuccessRate float64
AvgCostUSD float64
AvgQualityScore float64
ColdStartRate float64
}
type Selection ¶
type Selection struct {
Primary *ExpertDefinition
Secondary []*ExpertDefinition
Confidences map[ExpertID]float64
Reasoning string
}
Selection is a router decision: a primary expert, zero or more secondaries, per-expert confidence scores, and a short reasoning trace.
type StatsLookup ¶
type StatsRecorder ¶
type StoredDelegationLease ¶
type StoredDelegationLease struct {
Revision uint64 `json:"revision"`
Snapshot DelegationSnapshot `json:"snapshot"`
}
StoredDelegationLease is one revisioned durable checkpoint.
type TierDecision ¶
TierDecision is the per-step tier assignment for one planning request.
type TierMapping ¶
TierMapping resolves a tier to a concrete model identifier. The empty string means "no override". Consumers typically build this once at startup from their config.
func (TierMapping) Resolve ¶
func (m TierMapping) Resolve(tier ModelTier) string
Resolve returns the model name for `tier`, falling back to the Balanced entry, then to "".
type ToolBinding ¶
type ToolResolver ¶
ToolResolver maps a tool-set name (e.g. "observability", "code") to the concrete []llms.Tool the consumer wants exposed for that expert. The resolver is supplied by the consumer at orchestrator construction.