Documentation
¶
Overview ¶
Package feature defines typed extension planes and the contribution lifecycle for feature plugins in Go-LIP.
Contribution Lifecycle ¶
A feature plugin contributes capabilities by assembling typed extension plane values into a ContributionSet. The lifecycle proceeds as follows:
- Construct a mutable set using NewContributionSet.
- Add typed values using the package-level Contribute function. Contribute tags contributions with SourceFeature and enforces fail-before-mutate semantics: if validation or combination fails, the set remains unmodified and an AttributedError attributing the contributor ID and plane ID is returned.
- Once all contributions are accumulated, call ContributionSet.Freeze to produce an immutable FrozenPlaneSet.
- Wrap the frozen planes and any optional plugin lifecycles into a FeatureBundle by calling BundleFromPlanes. BundleFromPlanes assigns SchemaVersionV1 and defensively clones the frozen plane set and lifecycle slices, preserving nil vs explicit empty slice semantics without validation side effects.
The frozen plane set lifecycle transitions through well-defined stages:
- Accumulation: ContributionSet provides mutable staging with typed generated storage.
- Freezing: ContributionSet.Freeze creates an immutable FrozenPlaneSet, providing top-level collection isolation: slice backing arrays and metadata maps are isolated; element values (e.g. interface handlers) are shallow-copied, not deep-cloned.
- Bundle packaging: BundleFromPlanes bundles the FrozenPlaneSet into a versioned FeatureBundle. Note that FeatureBundle contains no per-plane named fields or slices; all extension planes are stored in FeatureBundle.PlaneSet.
- Reading: Values are read from FrozenPlaneSet via Get. If an ungenerated plane is requested or a plane was not contributed, Get returns the zero value of the plane type and does not search dynamic fallback storage.
- Replay & Thaw: An existing set can be replayed to another set via FrozenPlaneSet.ReplayTo or thawed back into a mutable staging set via FrozenPlaneSet.ToContributions.
- Request snapshot: FreezeRequestPlanes evaluates declared request materializers to produce an immutable request-scoped execution snapshot.
Plugin lifecycles (plugin.Lifecycle) are managed on a dedicated runtime side channel and are distinct from extension planes. (Historical note: named extension plane fields on FeatureBundle were removed in favor of FrozenPlaneSet.)
Reading Values ¶
Plane values are read from a FrozenPlaneSet using the generic package-level function Get:
values := feature.Get(bundle.PlaneSet, feature.PlaneRequestTransforms)
Package-level generic functions are used because Go methods on structs cannot introduce type parameters. Key read semantics include:
- If a plane was not contributed or is absent from the set, Get returns the zero value of the plane's type (e.g. nil for slice-valued planes, 0 for scalar planes).
- Slice-valued planes return defensive copies on ordinary Get calls to guarantee that caller modifications do not corrupt the frozen snapshot.
- Runtime borrowed request execution views (RequestExecutionView) are internal generated optimizations used on executor hot paths and must not be used by plugin authors.
Plane Declarations ¶
An extension plane is declared as a Plane specification defining its types, combination rules, validation, and diagnostics metadata:
- ID: A globally unique, non-empty, stable string identifier.
- Multiplicity: Must be MultOrdered (multiple ordered contributions combined in registration order) or MultExclusive (at most one occupant permitted, failing fast on conflict).
- Rules (SourceRules): Explicit per-source combination rules for SourceFeature, SourceHost, and SourceGenerationBinder. Unsupported sources remain the zero value CombUnsupported.
- NilPolicy: Defines handling of nil contributions (NilNotApplicable, NilReject, NilSkip), evaluated before validation or combination. For interface-valued planes, an explicit IsNil predicate must be provided to detect typed-nil pointers boxed in interfaces without runtime reflection.
- Validate: Optional validator function for incoming contribution values.
- Combine: Folding function that combines incoming values with the accumulated state and returns the retained value for the specified source rule. It must not mutate caller-owned or current stored state on failure; ContributionSet supplies defensive clones so failed combination leaves the set unchanged.
- Identity & ValidateIdentity: Required for exclusive planes and replace-by-identity sources to extract and validate stable identity strings.
- ExclusiveConflictError: Optional compatibility error; valid only when at least one source rule is CombExclusive; conflict still preserves generic exclusive conflict classification (ErrExclusiveConflict).
- Diagnostics (DiagnosticDescriptor): Configures operator inventory and privilege projection. Descriptor fields include:
- StageID: Identifies a legal lifecycle stage (ValidateStageID).
- Materialize: Creates diagnostic occupants from plane values.
- Privileges: Projects privilege flags from plane values.
- CoalesceGroup: Groups compatible stage occupancy across planes.
- Order: Gives deterministic ordering across stage diagnostics. When a StageID is set, Materialize must be non-nil, Order must be > 0, and the stage ID must be valid. If StageID is absent, descriptor metadata must be empty.
- RequestMaterializer & RequestBorrow: An optional sorting/materialization transform for request execution snapshots. When RequestBorrow is enabled, a non-nil RequestMaterializer is required.
- Plane.ValidateDeclaration and ValidateManifest enforce these rules and check catalog consistency across all declarations.
Closed Manifest and Policy Authority ¶
In v1, Go-LIP enforces a closed standard-plane catalog declared in the canonical manifest (pkg/lipsdk/feature/plane_manifest.go). The closed manifest guarantees that every supported extension plane has generated typed storage, deterministic dispatch, and full freeze/replay coverage.
Key contract rules for the closed catalog include:
- No dynamic planes in v1: Arbitrary unbound or dynamically declared planes are not supported. Contributing through an ungenerated or unbound plane fails immediately before candidate mutation with ErrUngeneratedPlane.
- Canonical generated-policy authority: Exported Plane descriptors (such as PlaneSubmitHooks) act as typed descriptors and identifiers. The generated binding is the sole authority for production combination, source rules, nil policy, validator, and identity extraction. Copying or mutating exported fields on a Plane descriptor (e.g. copying PlaneX and changing its rules or combiner) does not redefine the plane; production contribution always executes the canonical generated policy. If an altered copy has a modified plane ID, contribution is rejected with ErrUngeneratedPlane.
- Adding a new extension plane requires an upstream manifest and platform change: declaring the plane in plane_manifest.go and regenerating code via scripts/generate-feature-planes.go.
Generated-File Policy ¶
The extension plane catalog and dispatch machinery follow a strict code generation policy:
pkg/lipsdk/feature/plane_manifest.go is the canonical hand-authored catalog of standard plane declarations.
pkg/lipsdk/feature/plane_generated.go is checked in and must not be edited manually.
After modifying or adding plane declarations, run:
go run ./scripts/generate-feature-planes.go
Verify that generated files are up to date with:
go run ./scripts/generate-feature-planes.go -check
The generator produces typed storage and ordinal dispatch adapters that eliminate runtime reflection, unsafe type conversions, and request-path key lookup.
Standard Distribution Registration ¶
Adding a standard in-process feature implementation to Go-LIP involves:
- The feature implementation package lives under internal/plugins/features/<feature>. Feature plugins own their configuration decoding and bundle construction via a feature-owned constructor or factory (e.g. NewFeatureBundle or FeatureBundle) in the target architecture (demonstrated by migrated plugins toolcallrepair, secretguard, and reasoningpreservation). Standard factories where internal/standardplugins/features_install.go still directly constructs the ContributionSet and FeatureBundle (such as Agent Loop Guard at features_install.go:38 and Pre-request Policy at features_install.go:220) are deferred with inventory tracking rather than universally completed; new features follow the feature-owned model.
- Standard distribution wiring in internal/standardplugins/features_install.go provides only explicit registration and adaptation to connect the feature factory to the standard bundle.
- The sole registration table edit is adding exactly one FeatureRegistration row to internal/standardplugins/standard_table.go in StandardBundle().Features.
- Do not add feature-specific branches or types to core/runtime or any other registry. Features own their policy; neither internal/core nor internal/infra/runtimebundle imports concrete feature packages. If a feature requires process- or generation-bound capabilities, explicit typed composition adapters outside runtimebundle (such as internal/infra/*compose) are used.
- Optional executable backend connectors use an independent gRPC manifest discovery mechanism and are out of this feature-registration path.
Index ¶
- Constants
- Variables
- func Contribute[P any](s *ContributionSet, p Plane[P], pluginID string, v P) error
- func ContributeSource[P any](s *ContributionSet, p Plane[P], source SourceKind, contributorID string, v P) error
- func FrozenIdentity[P any](s FrozenPlaneSet, p Plane[P]) (string, bool)
- func Get[P any](s FrozenPlaneSet, p Plane[P]) P
- func LegalPipelineStageIDs() []string
- func LegalStageDescriptorIndex(id string) int
- func ValidateManifest(declarations ...PlaneDeclaration) error
- func ValidateStageID(id string) bool
- type AttributedError
- type Combination
- type ContributionSet
- func (s *ContributionSet) BindAttemptTransforms(contributorID string, v []request.AttemptTransform) error
- func (s *ContributionSet) BindCompactionPreservers(contributorID string, v []compaction.Preserver) error
- func (s *ContributionSet) BindStreamObserverFactories(contributorID string, v []response.StreamObserverFactory) error
- func (s *ContributionSet) Clone() *ContributionSet
- func (s *ContributionSet) ContributeCandidate(cand FrozenPlaneSet) error
- func (s *ContributionSet) Freeze() FrozenPlaneSet
- func (s *ContributionSet) Has(planeID string) bool
- func (s *ContributionSet) ReplaceAttemptTransforms(contributorID string, v []request.AttemptTransform) error
- func (s *ContributionSet) ReplaceCompactionPreservers(contributorID string, v []compaction.Preserver) error
- func (s *ContributionSet) ReplaceStreamObserverFactories(contributorID string, v []response.StreamObserverFactory) error
- type DiagnosticDescriptor
- type DiagnosticOccupant
- type DiagnosticPlaneProjection
- type FeatureBundle
- type FrozenPlaneSet
- func (s FrozenPlaneSet) Clone() FrozenPlaneSet
- func (s FrozenPlaneSet) ContributeCandidateTo(dst *ContributionSet, source SourceKind, contributorID string) error
- func (s FrozenPlaneSet) IsZero() bool
- func (s FrozenPlaneSet) ReplaySourceTo(dst *ContributionSet, source SourceKind, contributorID string) error
- func (s FrozenPlaneSet) ReplayTo(dst *ContributionSet, contributorID string) error
- func (s FrozenPlaneSet) ToContributions() *ContributionSet
- func (s FrozenPlaneSet) Validate() error
- type HookConfig
- type HookTarget
- type Multiplicity
- type NilPolicy
- type Plane
- func (p Plane[T]) DiagnosticCoalesceGroup() string
- func (p Plane[T]) DiagnosticOrder() int
- func (p Plane[T]) DiagnosticStageID() string
- func (p Plane[T]) MaterializeOccupants(v T) []DiagnosticOccupant
- func (p Plane[T]) PlaneID() string
- func (p Plane[T]) ProjectPrivileges(v T) PrivilegeProjection
- func (p Plane[T]) ValidateDeclaration() error
- type PlaneDeclaration
- type PrivilegeProjection
- type RequestBodyAccess
- type RequestExecutionView
- type SourceKind
- type SourceRules
- type StageDescriptor
- type StageMutationRole
Examples ¶
Constants ¶
const ( PrivilegeRawCapture = "raw_capture" PrivilegeAuxiliaryRequests = "auxiliary_requests" PrivilegeAuthProvider = "auth_provider" PrivilegeCompletionGate = "completion_gate" )
Canonical privilege flag constants.
const ( StageIDTransportAuth = "transport_authentication" StageIDSessionOpen = "session_open" StageIDSecretGuard = "secret_guard" StageIDSessionClassification = "session_classification" StageIDSubmit = "submit_request" StageIDToolCatalog = "tool_catalog_filter" StageIDRequestWide = "request_wide_shaping" StageIDPreRequest = "pre_request_admission" StageIDRouteHinting = "route_hinting" StageIDCandidateAttemptTransform = "candidate_attempt_transform" StageIDAttemptLifecycle = "attempt_lifecycle" StageIDStreamEventMutation = "stream_event_mutation" StageIDToolEventReaction = "tool_event_reaction" StageIDCompletionGating = "completion_gating" StageIDFinalStreamObservation = "final_stream_observation" StageIDTrafficObservation = "traffic_observation" StageIDEgressEncoding = "egress_encoding" )
Stable stage IDs for the legal extension pipeline (R2, ADR 0006). Core and diagnostics use the same strings; plugins must not invent ad hoc stage names.
const SchemaVersionV1 = 1
SchemaVersionV1 is the initial FeatureBundle wire/compile contract. New optional fields may be added in backward-compatible ways; bump only when breaking stable fields.
Variables ¶
var ( // ErrInvalidPlane indicates an invalid or incomplete plane declaration. ErrInvalidPlane = errors.New("feature: invalid plane declaration") // ErrInvalidContribution indicates an invalid contribution to a plane. ErrInvalidContribution = errors.New("feature: invalid contribution") // ErrUnsupportedSource indicates a contribution from a source not supported by the plane. ErrUnsupportedSource = errors.New("feature: unsupported contribution source") // ErrExclusiveConflict reports an attempted second contribution to an exclusive plane slot. ErrExclusiveConflict = errors.New("feature: exclusive slot conflict") // ErrTerminalDecisionProviderConflict reports a conflict when multiple terminal-decision providers are registered. ErrTerminalDecisionProviderConflict = errors.New("featurebundle: terminal-decision provider conflict") // ErrControlToolProviderConflict reports a conflict when multiple proxy control-tool providers are registered. ErrControlToolProviderConflict = errors.New("featurebundle: control-tool provider conflict") // ErrNilContribution reports a nil contribution rejected by plane nil policy. ErrNilContribution = errors.New("feature: nil contribution") // ErrUnsupportedReplaySource reports a source that all-plane frozen replay cannot apply safely. ErrUnsupportedReplaySource = errors.New("feature: unsupported frozen replay source") // ErrUngeneratedPlane indicates an attempt to contribute through an ungenerated or unbound plane. // In v1, the standard-plane catalog is closed; arbitrary dynamic planes are rejected with this error. ErrUngeneratedPlane = errors.New("feature: ungenerated plane") )
var PlaneAttemptTransforms = Plane[[]request.AttemptTransform]{ ID: "attempt_transforms", RequestAccess: RequestBodyCanonicalRequired, Multiplicity: MultOrdered, Rules: SourceRules{ Feature: CombConcatenate, GenerationBinder: CombReplaceByIdentity, }, NilPolicy: NilReject, Identity: func(v []request.AttemptTransform) (string, bool) { if len(v) > 0 && !isNilValue(v[0]) { return v[0].ID(), true } return "", false }, Validate: func(v []request.AttemptTransform) error { for i, at := range v { if isNilValue(at) { return fmt.Errorf("AttemptTransforms[%d] must not be nil", i) } } return nil }, ValidateIdentity: validateNonEmptyCachedIdentity, Combine: func(source SourceKind, current, incoming []request.AttemptTransform) ([]request.AttemptTransform, error) { if source == SourceGenerationBinder { if len(incoming) == 0 || isNilValue(incoming[0]) { return current, nil } incID := incoming[0].ID() out := make([]request.AttemptTransform, 0, len(current)+len(incoming)) for _, t := range current { if !isNilValue(t) && t.ID() == incID { continue } out = append(out, t) } out = append(out, incoming...) return out, nil } return append(current, incoming...), nil }, RequestMaterializer: func(v []request.AttemptTransform) []request.AttemptTransform { return request.MaterializeAttemptsSorted(requireNonNilAttemptTransforms(v)) }, Diagnostics: DiagnosticDescriptor[[]request.AttemptTransform]{ StageID: StageIDCandidateAttemptTransform, Order: 120, Materialize: func(v []request.AttemptTransform) []DiagnosticOccupant { nonNil := make([]request.AttemptTransform, 0, len(v)) for _, tr := range v { if !isNilValue(tr) { nonNil = append(nonNil, tr) } } if len(nonNil) == 0 { return nil } sorted := request.MaterializeAttemptsSorted(nonNil) occupants := make([]DiagnosticOccupant, 0, len(sorted)) for _, tr := range sorted { occupants = append(occupants, DiagnosticOccupant{Label: "attempt_transform:" + tr.ID()}) } return occupants }, Privileges: func(v []request.AttemptTransform) PrivilegeProjection { if len(v) > 0 { return PrivilegeProjection{Flags: []string{PrivilegeAuxiliaryRequests}} } return PrivilegeProjection{} }, }, }
PlaneAttemptTransforms declares the AttemptTransforms extension plane.
var PlaneCompactionObservers = Plane[[]compaction.Observer]{ ID: "compaction_observers", RequestAccess: RequestBodyCanonicalRequired, Multiplicity: MultOrdered, Rules: SourceRules{ Feature: CombConcatenate, }, NilPolicy: NilNotApplicable, Combine: func(source SourceKind, current, incoming []compaction.Observer) ([]compaction.Observer, error) { return append(current, incoming...), nil }, }
PlaneCompactionObservers declares the CompactionObservers extension plane.
var PlaneCompactionPreservers = Plane[[]compaction.Preserver]{ ID: "compaction_preservers", RequestAccess: RequestBodyCanonicalRequired, Multiplicity: MultOrdered, Rules: SourceRules{ Feature: CombConcatenate, GenerationBinder: CombReplaceByIdentity, }, NilPolicy: NilNotApplicable, Identity: func(v []compaction.Preserver) (string, bool) { if len(v) > 0 && v[0] != nil { id := safePreserverID(v[0]) if id != "" { return id, true } } return "", false }, Validate: func(v []compaction.Preserver) error { for i, p := range v { if p == nil { return fmt.Errorf("CompactionPreservers[%d] must not be nil", i) } } return nil }, ValidateIdentity: validateNonEmptyCachedIdentity, Combine: func(source SourceKind, current, incoming []compaction.Preserver) ([]compaction.Preserver, error) { if source == SourceGenerationBinder { if len(incoming) == 0 || incoming[0] == nil { return current, nil } incID := safePreserverID(incoming[0]) if incID == "" { return append(current, incoming...), nil } out := make([]compaction.Preserver, 0, len(current)+len(incoming)) for _, p := range current { if p != nil && safePreserverID(p) == incID { continue } out = append(out, p) } out = append(out, incoming...) return out, nil } return append(current, incoming...), nil }, }
PlaneCompactionPreservers declares the CompactionPreservers extension plane.
var PlaneCompletionGates = Plane[[]completion.Gate]{ ID: "completion_gates", RequestAccess: RequestBodyResponseOnly, Multiplicity: MultOrdered, Rules: SourceRules{ Feature: CombConcatenate, }, NilPolicy: NilNotApplicable, Combine: func(source SourceKind, current, incoming []completion.Gate) ([]completion.Gate, error) { return append(current, incoming...), nil }, Diagnostics: DiagnosticDescriptor[[]completion.Gate]{ StageID: StageIDCompletionGating, Order: 110, Materialize: func(v []completion.Gate) []DiagnosticOccupant { sorted := completion.MaterializeSorted(v) occupants := make([]DiagnosticOccupant, 0, len(sorted)) for _, g := range sorted { if g == nil { continue } occupants = append(occupants, DiagnosticOccupant{Label: "completion_gate:" + g.ID()}) } return occupants }, Privileges: func(v []completion.Gate) PrivilegeProjection { if len(v) > 0 { return PrivilegeProjection{Flags: []string{PrivilegeAuxiliaryRequests, PrivilegeCompletionGate}} } return PrivilegeProjection{} }, }, }
PlaneCompletionGates declares the CompletionGates extension plane.
var PlaneControlToolProvider = Plane[controltool.Provider]{ ID: "control_tool_provider", RequestAccess: RequestBodyCanonicalRequired, Multiplicity: MultExclusive, Rules: SourceRules{ Feature: CombExclusive, }, NilPolicy: NilReject, Identity: func(v controltool.Provider) (string, bool) { id, err := controltool.ProviderIdentity(v) if err != nil { return "", false } return id, true }, Validate: func(v controltool.Provider) error { return controltool.ValidateProvider(v) }, ValidateIdentity: controltool.ValidateProviderID, Combine: func(source SourceKind, current, incoming controltool.Provider) (controltool.Provider, error) { return incoming, nil }, ExclusiveConflictError: ErrControlToolProviderConflict, }
PlaneControlToolProvider declares the ControlToolProvider extension plane: at most one optional proxy-owned model control tool owner per generation. It mirrors PlaneTerminalDecisionProvider: feature-only exclusive admission, typed-nil rejection before publication, and provider validation delegated to the generic controltool contract.
var PlaneLocalTurnHandlers = Plane[[]localturn.Handler]{ ID: "local_turn_handlers", RequestAccess: RequestBodyCanonicalRequired, Multiplicity: MultOrdered, Rules: SourceRules{ Feature: CombConcatenate, }, NilPolicy: NilReject, Validate: func(v []localturn.Handler) error { for i, h := range v { if localturn.IsNilHandler(h) { return fmt.Errorf("LocalTurnHandlers[%d] must not be nil", i) } if err := localturn.ValidateHandlerID(h.ID()); err != nil { return fmt.Errorf("LocalTurnHandlers[%d] invalid id: %w", i, err) } } return nil }, Combine: func(source SourceKind, current, incoming []localturn.Handler) ([]localturn.Handler, error) { return append(current, incoming...), nil }, RequestMaterializer: localturn.MaterializeSorted, RequestBorrow: true, Diagnostics: DiagnosticDescriptor[[]localturn.Handler]{ StageID: StageIDPreRequest, Order: 45, Materialize: func(v []localturn.Handler) []DiagnosticOccupant { sorted := localturn.MaterializeSorted(v) if len(sorted) == 0 { return nil } occupants := make([]DiagnosticOccupant, 0, len(sorted)) for _, h := range sorted { if h == nil || localturn.IsNilHandler(h) { continue } occupants = append(occupants, DiagnosticOccupant{Label: "local_turn:" + h.ID()}) } return occupants }, }, }
PlaneLocalTurnHandlers declares the LocalTurnHandlers extension plane.
var PlanePreRequestHandlers = Plane[[]prerequest.Handler]{ ID: "pre_request_handlers", RequestAccess: RequestBodyCanonicalRequired, Multiplicity: MultOrdered, Rules: SourceRules{ Feature: CombConcatenate, }, Combine: func(source SourceKind, current, incoming []prerequest.Handler) ([]prerequest.Handler, error) { return append(current, incoming...), nil }, RequestMaterializer: prerequest.MaterializeSorted, Diagnostics: DiagnosticDescriptor[[]prerequest.Handler]{ StageID: StageIDPreRequest, Order: 40, Materialize: func(v []prerequest.Handler) []DiagnosticOccupant { nonNil := make([]prerequest.Handler, 0, len(v)) for _, h := range v { if !isNilValue(h) { nonNil = append(nonNil, h) } } if len(nonNil) == 0 { return nil } sorted := prerequest.MaterializeSorted(nonNil) occupants := make([]DiagnosticOccupant, 0, len(sorted)) for _, h := range sorted { occupants = append(occupants, DiagnosticOccupant{Label: "pre_request:" + h.ID()}) } return occupants }, Privileges: func(v []prerequest.Handler) PrivilegeProjection { if len(v) > 0 { return PrivilegeProjection{Flags: []string{PrivilegeAuxiliaryRequests}} } return PrivilegeProjection{} }, }, }
PlanePreRequestHandlers declares the PreRequestHandlers extension plane.
var PlaneRawCaptureSinks = Plane[[]traffic.RawCaptureSink]{ ID: "raw_capture_sinks", RequestAccess: RequestBodyCanonicalRequired, Multiplicity: MultOrdered, Rules: SourceRules{ Feature: CombConcatenate, }, NilPolicy: NilNotApplicable, Combine: func(source SourceKind, current, incoming []traffic.RawCaptureSink) ([]traffic.RawCaptureSink, error) { return append(current, incoming...), nil }, Diagnostics: DiagnosticDescriptor[[]traffic.RawCaptureSink]{ StageID: StageIDTrafficObservation, CoalesceGroup: "traffic_observation", Order: 142, Materialize: func(v []traffic.RawCaptureSink) []DiagnosticOccupant { occupants := make([]DiagnosticOccupant, 0, len(v)) for i, s := range v { if s == nil { continue } occupants = append(occupants, DiagnosticOccupant{Label: fmt.Sprintf("raw_capture:%d", i)}) } return occupants }, Privileges: func(v []traffic.RawCaptureSink) PrivilegeProjection { if len(v) > 0 { return PrivilegeProjection{Flags: []string{PrivilegeRawCapture}} } return PrivilegeProjection{} }, }, }
PlaneRawCaptureSinks declares the RawCaptureSinks extension plane.
var PlaneRequestPartHooks = Plane[[]hooks.RequestPartHook]{ ID: "request_part_hooks", RequestAccess: RequestBodyCanonicalRequired, Multiplicity: MultOrdered, Rules: SourceRules{ Feature: CombConcatenate, }, NilPolicy: NilNotApplicable, HookTarget: HookTargetRequestPartHooks, Combine: func(source SourceKind, current, incoming []hooks.RequestPartHook) ([]hooks.RequestPartHook, error) { return append(current, incoming...), nil }, Diagnostics: DiagnosticDescriptor[[]hooks.RequestPartHook]{ StageID: StageIDRequestWide, Order: 60, Materialize: func(v []hooks.RequestPartHook) []DiagnosticOccupant { sorted := sortHooks(v) occupants := make([]DiagnosticOccupant, 0, len(sorted)) for _, h := range sorted { occupants = append(occupants, DiagnosticOccupant{Label: "request_part:" + h.ID()}) } return occupants }, }, }
PlaneRequestPartHooks declares the RequestPartHooks extension plane.
var PlaneRequestTransforms = Plane[[]request.Transform]{ ID: "request_transforms", RequestAccess: RequestBodyCanonicalRequired, Multiplicity: MultOrdered, Rules: SourceRules{ Feature: CombConcatenate, }, Combine: func(source SourceKind, current, incoming []request.Transform) ([]request.Transform, error) { return append(current, incoming...), nil }, Diagnostics: DiagnosticDescriptor[[]request.Transform]{ StageID: StageIDRequestWide, Order: 30, Materialize: func(v []request.Transform) []DiagnosticOccupant { nonNil := make([]request.Transform, 0, len(v)) for _, tr := range v { if !isNilValue(tr) { nonNil = append(nonNil, tr) } } if len(nonNil) == 0 { return nil } sorted := request.MaterializeSorted(nonNil) occupants := make([]DiagnosticOccupant, 0, len(sorted)) for _, tr := range sorted { occupants = append(occupants, DiagnosticOccupant{Label: "request_transform:" + tr.ID()}) } return occupants }, Privileges: func(v []request.Transform) PrivilegeProjection { if len(v) > 0 { return PrivilegeProjection{Flags: []string{PrivilegeAuxiliaryRequests}} } return PrivilegeProjection{} }, }, }
PlaneRequestTransforms declares the RequestTransforms extension plane.
var PlaneResponsePartHooks = Plane[[]hooks.ResponsePartHook]{ ID: "response_part_hooks", RequestAccess: RequestBodyResponseOnly, Multiplicity: MultOrdered, Rules: SourceRules{ Feature: CombConcatenate, }, NilPolicy: NilNotApplicable, HookTarget: HookTargetResponsePartHooks, Combine: func(source SourceKind, current, incoming []hooks.ResponsePartHook) ([]hooks.ResponsePartHook, error) { return append(current, incoming...), nil }, Diagnostics: DiagnosticDescriptor[[]hooks.ResponsePartHook]{ StageID: StageIDStreamEventMutation, Order: 70, Materialize: func(v []hooks.ResponsePartHook) []DiagnosticOccupant { sorted := sortHooks(v) occupants := make([]DiagnosticOccupant, 0, len(sorted)) for _, h := range sorted { occupants = append(occupants, DiagnosticOccupant{Label: h.ID()}) } return occupants }, }, }
PlaneResponsePartHooks declares the ResponsePartHooks extension plane.
var PlaneRouteHintProviders = Plane[[]routehint.Provider]{ ID: "route_hint_providers", RequestAccess: RequestBodyCanonicalRequired, Multiplicity: MultOrdered, Rules: SourceRules{ Feature: CombConcatenate, }, NilPolicy: NilNotApplicable, Combine: func(source SourceKind, current, incoming []routehint.Provider) ([]routehint.Provider, error) { return append(current, incoming...), nil }, Diagnostics: DiagnosticDescriptor[[]routehint.Provider]{ StageID: StageIDRouteHinting, Order: 50, Materialize: func(v []routehint.Provider) []DiagnosticOccupant { sorted := routehint.MaterializeSorted(v) occupants := make([]DiagnosticOccupant, 0, len(sorted)) for _, p := range sorted { if p == nil { continue } occupants = append(occupants, DiagnosticOccupant{Label: "route_hint:" + p.ID()}) } return occupants }, }, }
PlaneRouteHintProviders declares the RouteHintProviders extension plane.
var PlaneSecretGuardExecution = Plane[*secretguard.ExecutionConfig]{ ID: "secret_guard_execution", RequestAccess: RequestBodyCanonicalRequired, Multiplicity: MultExclusive, Rules: SourceRules{ Feature: CombUnsupported, Host: CombUnsupported, GenerationBinder: CombExclusive, }, NilPolicy: NilSkip, RequestMaterializer: secretguard.CloneExecutionConfig, Identity: func(v *secretguard.ExecutionConfig) (string, bool) { if v == nil { return "", false } return "secret-guard-execution", true }, ValidateIdentity: validateNonEmptyCachedIdentity, Combine: func(source SourceKind, current, incoming *secretguard.ExecutionConfig) (*secretguard.ExecutionConfig, error) { if incoming == nil { return incoming, nil } return secretguard.CloneExecutionConfig(incoming), nil }, }
PlaneSecretGuardExecution declares the generation-composed secret-guard execution configuration plane. Guards travel on PlaneSecretGuards; this exclusive generation-binder plane carries the engine-composed matcher, audit, policy, and diagnostics posture bound by the standard distribution for one generation. It is never candidate-overlaid.
var PlaneSecretGuards = Plane[[]secretguard.Guard]{ ID: "secret_guards", RequestAccess: RequestBodyCanonicalRequired, Multiplicity: MultOrdered, Rules: SourceRules{ Feature: CombConcatenate, }, NilPolicy: NilNotApplicable, Combine: func(source SourceKind, current, incoming []secretguard.Guard) ([]secretguard.Guard, error) { return append(current, incoming...), nil }, RequestMaterializer: secretguard.MaterializeSorted, RequestBorrow: true, Diagnostics: DiagnosticDescriptor[[]secretguard.Guard]{ StageID: StageIDSecretGuard, Order: 100, Materialize: func(v []secretguard.Guard) []DiagnosticOccupant { sorted := secretguard.MaterializeSorted(v) occupants := make([]DiagnosticOccupant, 0, len(sorted)) for _, g := range sorted { if g == nil { continue } occupants = append(occupants, DiagnosticOccupant{Label: "secret_guard:" + g.ID()}) } return occupants }, }, }
PlaneSecretGuards declares the SecretGuards extension plane.
var PlaneSessionClassifier = Plane[sessionclassification.Classifier]{ ID: "session_classifier", RequestAccess: RequestBodyMetadataOnly, Multiplicity: MultExclusive, Rules: SourceRules{ Feature: CombExclusive, }, NilPolicy: NilReject, Identity: func(v sessionclassification.Classifier) (string, bool) { id, err := sessionclassification.ClassifierIdentity(v) if err != nil { return "", false } return id, true }, Validate: func(v sessionclassification.Classifier) error { _, err := sessionclassification.ClassifierIdentity(v) return err }, ValidateIdentity: sessionclassification.ValidateClassifierID, Combine: func(_ SourceKind, _ sessionclassification.Classifier, incoming sessionclassification.Classifier) (sessionclassification.Classifier, error) { return incoming, nil }, Diagnostics: DiagnosticDescriptor[sessionclassification.Classifier]{ StageID: StageIDSessionClassification, Order: 101, Materialize: func(v sessionclassification.Classifier) []DiagnosticOccupant { if v == nil { return nil } return []DiagnosticOccupant{{Label: "classifier"}} }, }, }
PlaneSessionClassifier declares the exclusive metadata-only session-classification plane.
var PlaneSessionOpeners = Plane[[]session.Opener]{ ID: "session_openers", RequestAccess: RequestBodyMetadataOnly, Multiplicity: MultOrdered, Rules: SourceRules{ Feature: CombConcatenate, }, NilPolicy: NilNotApplicable, Combine: func(source SourceKind, current, incoming []session.Opener) ([]session.Opener, error) { return append(current, incoming...), nil }, RequestMaterializer: func(v []session.Opener) []session.Opener { if len(v) == 0 { return nil } return cloneSlice(v) }, Diagnostics: DiagnosticDescriptor[[]session.Opener]{ StageID: StageIDSessionOpen, CoalesceGroup: "session_open", Order: 90, Materialize: func(v []session.Opener) []DiagnosticOccupant { occupants := make([]DiagnosticOccupant, 0, len(v)) for _, o := range v { if o == nil { continue } occupants = append(occupants, DiagnosticOccupant{Label: "opener:" + o.ID()}) } return occupants }, }, }
PlaneSessionOpeners declares the SessionOpeners extension plane.
var PlaneStreamObserverFactories = Plane[[]response.StreamObserverFactory]{ ID: "stream_observer_factories", RequestAccess: RequestBodyResponseOnly, Multiplicity: MultOrdered, Rules: SourceRules{ Feature: CombConcatenate, GenerationBinder: CombReplaceByIdentity, }, NilPolicy: NilReject, Identity: func(v []response.StreamObserverFactory) (string, bool) { if len(v) > 0 && v[0] != nil { return v[0].ID(), true } return "", false }, Validate: func(v []response.StreamObserverFactory) error { for i, f := range v { if f == nil { return fmt.Errorf("StreamObserverFactories[%d] must not be nil", i) } } return nil }, ValidateIdentity: validateNonEmptyCachedIdentity, Combine: func(source SourceKind, current, incoming []response.StreamObserverFactory) ([]response.StreamObserverFactory, error) { if source == SourceGenerationBinder { if len(incoming) == 0 || incoming[0] == nil { return current, nil } incID := incoming[0].ID() out := make([]response.StreamObserverFactory, 0, len(current)+len(incoming)) for _, f := range current { if f != nil && f.ID() == incID { continue } out = append(out, f) } out = append(out, incoming...) return out, nil } return append(current, incoming...), nil }, RequestMaterializer: func(v []response.StreamObserverFactory) []response.StreamObserverFactory { return response.MaterializeSorted(requireNonNilStreamObserverFactories(v)) }, Diagnostics: DiagnosticDescriptor[[]response.StreamObserverFactory]{ StageID: StageIDFinalStreamObservation, Order: 130, Materialize: func(v []response.StreamObserverFactory) []DiagnosticOccupant { nonNil := make([]response.StreamObserverFactory, 0, len(v)) for _, f := range v { if f != nil { nonNil = append(nonNil, f) } } if len(nonNil) == 0 { return nil } sorted := response.MaterializeSorted(nonNil) occupants := make([]DiagnosticOccupant, 0, len(sorted)) for _, f := range sorted { occupants = append(occupants, DiagnosticOccupant{Label: "stream_observer:" + f.ID()}) } return occupants }, }, }
PlaneStreamObserverFactories declares the StreamObserverFactories extension plane.
var PlaneSubmitHooks = Plane[[]hooks.SubmitHook]{ ID: "submit_hooks", RequestAccess: RequestBodyCanonicalRequired, Multiplicity: MultOrdered, Rules: SourceRules{ Feature: CombConcatenate, }, NilPolicy: NilNotApplicable, HookTarget: HookTargetSubmitHooks, Combine: func(source SourceKind, current, incoming []hooks.SubmitHook) ([]hooks.SubmitHook, error) { return append(current, incoming...), nil }, Diagnostics: DiagnosticDescriptor[[]hooks.SubmitHook]{ StageID: StageIDSubmit, Order: 10, Materialize: func(v []hooks.SubmitHook) []DiagnosticOccupant { sorted := sortHooks(v) occupants := make([]DiagnosticOccupant, 0, len(sorted)) for _, h := range sorted { occupants = append(occupants, DiagnosticOccupant{Label: h.ID()}) } return occupants }, }, }
PlaneSubmitHooks declares the SubmitHooks extension plane.
var PlaneTerminalDecisionProvider = Plane[terminaldecision.Provider]{ ID: "terminal_decision_provider", RequestAccess: RequestBodyCanonicalRequired, Multiplicity: MultExclusive, Rules: SourceRules{ Feature: CombExclusive, }, NilPolicy: NilReject, Identity: func(v terminaldecision.Provider) (string, bool) { id, err := terminaldecision.ProviderIdentity(v) if err != nil { return "", false } return id, true }, Validate: func(v terminaldecision.Provider) error { _, err := terminaldecision.ProviderIdentity(v) return err }, ValidateIdentity: terminaldecision.ValidateProviderID, Combine: func(source SourceKind, current, incoming terminaldecision.Provider) (terminaldecision.Provider, error) { return incoming, nil }, ExclusiveConflictError: ErrTerminalDecisionProviderConflict, }
PlaneTerminalDecisionProvider declares the TerminalDecisionProvider extension plane.
var PlaneToolCallFinalizationMaxArgsBytes = Plane[int]{ ID: "tool_call_finalization_max_args_bytes", RequestAccess: RequestBodyMetadataOnly, Multiplicity: MultOrdered, Rules: SourceRules{ Feature: CombReduce, }, NilPolicy: NilNotApplicable, Validate: func(v int) error { if v < 0 { return fmt.Errorf("must be >= 0, got %d", v) } return nil }, Combine: func(source SourceKind, current, incoming int) (int, error) { if incoming <= 0 { return current, nil } if current <= 0 || incoming < current { return incoming, nil } return current, nil }, }
PlaneToolCallFinalizationMaxArgsBytes declares the ToolCallFinalizationMaxArgsBytes extension plane.
var PlaneToolCallFinalizers = Plane[[]toolcall.Finalizer]{ ID: "tool_call_finalizers", RequestAccess: RequestBodyCanonicalRequired, Multiplicity: MultOrdered, Rules: SourceRules{ Feature: CombConcatenate, }, NilPolicy: NilNotApplicable, Combine: func(source SourceKind, current, incoming []toolcall.Finalizer) ([]toolcall.Finalizer, error) { return append(current, incoming...), nil }, RequestMaterializer: toolcall.MaterializeSorted, RequestBorrow: true, Diagnostics: DiagnosticDescriptor[[]toolcall.Finalizer]{ StageID: StageIDToolEventReaction, CoalesceGroup: "tool_reaction", Order: 81, Materialize: func(v []toolcall.Finalizer) []DiagnosticOccupant { sorted := toolcall.MaterializeSorted(v) occupants := make([]DiagnosticOccupant, 0, len(sorted)) for _, f := range sorted { if f == nil { continue } occupants = append(occupants, DiagnosticOccupant{Label: "tool_finalizer:" + f.ID()}) } return occupants }, }, }
PlaneToolCallFinalizers declares the ToolCallFinalizers extension plane.
var PlaneToolCallPolicies = Plane[[]toolpolicy.Policy]{ ID: "tool_call_policies", RequestAccess: RequestBodyCanonicalRequired, Multiplicity: MultOrdered, Rules: SourceRules{ Feature: CombConcatenate, }, NilPolicy: NilNotApplicable, Combine: func(source SourceKind, current, incoming []toolpolicy.Policy) ([]toolpolicy.Policy, error) { return append(current, incoming...), nil }, RequestMaterializer: toolpolicy.MaterializeSorted, RequestBorrow: true, Diagnostics: DiagnosticDescriptor[[]toolpolicy.Policy]{ StageID: StageIDToolEventReaction, CoalesceGroup: "tool_reaction", Order: 80, Materialize: func(v []toolpolicy.Policy) []DiagnosticOccupant { sorted := toolpolicy.MaterializeSorted(v) occupants := make([]DiagnosticOccupant, 0, len(sorted)) for _, p := range sorted { if p == nil { continue } occupants = append(occupants, DiagnosticOccupant{Label: "tool_policy:" + p.ID()}) } return occupants }, }, }
PlaneToolCallPolicies declares the ToolCallPolicies extension plane.
var PlaneToolCatalogFilters = Plane[[]toolcatalog.Filter]{ ID: "tool_catalog_filters", RequestAccess: RequestBodyCanonicalRequired, Multiplicity: MultOrdered, Rules: SourceRules{ Feature: CombConcatenate, }, NilPolicy: NilNotApplicable, Combine: func(source SourceKind, current, incoming []toolcatalog.Filter) ([]toolcatalog.Filter, error) { return append(current, incoming...), nil }, Diagnostics: DiagnosticDescriptor[[]toolcatalog.Filter]{ StageID: StageIDToolCatalog, Order: 20, Materialize: func(v []toolcatalog.Filter) []DiagnosticOccupant { sorted := toolcatalog.MaterializeSorted(v) occupants := make([]DiagnosticOccupant, 0, len(sorted)) for _, f := range sorted { if f == nil { continue } occupants = append(occupants, DiagnosticOccupant{Label: "tool_catalog:" + f.ID()}) } return occupants }, Privileges: func(v []toolcatalog.Filter) PrivilegeProjection { if len(v) > 0 { return PrivilegeProjection{Flags: []string{PrivilegeAuxiliaryRequests}} } return PrivilegeProjection{} }, }, }
PlaneToolCatalogFilters declares the ToolCatalogFilters extension plane.
var PlaneToolReactors = Plane[[]hooks.ToolReactor]{ ID: "tool_reactors", RequestAccess: RequestBodyCanonicalRequired, Multiplicity: MultOrdered, Rules: SourceRules{ Feature: CombConcatenate, }, NilPolicy: NilNotApplicable, HookTarget: HookTargetToolReactors, Combine: func(source SourceKind, current, incoming []hooks.ToolReactor) ([]hooks.ToolReactor, error) { return append(current, incoming...), nil }, Diagnostics: DiagnosticDescriptor[[]hooks.ToolReactor]{ StageID: StageIDToolEventReaction, CoalesceGroup: "tool_reaction", Order: 82, Materialize: func(v []hooks.ToolReactor) []DiagnosticOccupant { sorted := sortHooks(v) occupants := make([]DiagnosticOccupant, 0, len(sorted)) for _, r := range sorted { occupants = append(occupants, DiagnosticOccupant{Label: r.ID()}) } return occupants }, }, }
PlaneToolReactors declares the ToolReactors extension plane.
var PlaneTrafficObservers = Plane[[]traffic.Observer]{ ID: "traffic_observers", RequestAccess: RequestBodyCanonicalRequired, Multiplicity: MultOrdered, Rules: SourceRules{ Feature: CombConcatenate, Host: CombConcatenate, }, NilPolicy: NilNotApplicable, Combine: func(source SourceKind, current, incoming []traffic.Observer) ([]traffic.Observer, error) { return append(current, incoming...), nil }, Diagnostics: DiagnosticDescriptor[[]traffic.Observer]{ StageID: StageIDTrafficObservation, CoalesceGroup: "traffic_observation", Order: 140, Materialize: func(v []traffic.Observer) []DiagnosticOccupant { occupants := make([]DiagnosticOccupant, 0, len(v)) for i, o := range v { if o == nil { continue } occupants = append(occupants, DiagnosticOccupant{Label: fmt.Sprintf("traffic_observer:%d", i)}) } return occupants }, }, }
PlaneTrafficObservers declares the TrafficObservers extension plane.
var PlaneTrafficRedactors = Plane[[]traffic.Redactor]{ ID: "traffic_redactors", RequestAccess: RequestBodyCanonicalRequired, Multiplicity: MultOrdered, Rules: SourceRules{ Feature: CombConcatenate, }, NilPolicy: NilNotApplicable, Combine: func(source SourceKind, current, incoming []traffic.Redactor) ([]traffic.Redactor, error) { return append(current, incoming...), nil }, RequestMaterializer: traffic.MaterializeSortedRedactors, Diagnostics: DiagnosticDescriptor[[]traffic.Redactor]{ StageID: StageIDTrafficObservation, CoalesceGroup: "traffic_observation", Order: 143, Materialize: func(v []traffic.Redactor) []DiagnosticOccupant { occupants := make([]DiagnosticOccupant, 0, len(v)) for _, r := range v { if r == nil { continue } occupants = append(occupants, DiagnosticOccupant{Label: "traffic_redactor:" + r.ID()}) } return occupants }, }, }
PlaneTrafficRedactors declares the TrafficRedactors extension plane.
var PlaneUsageObservers = Plane[[]usage.Observer]{ ID: "usage_observers", RequestAccess: RequestBodyResponseOnly, Multiplicity: MultOrdered, Rules: SourceRules{ Feature: CombConcatenate, Host: CombConcatenate, }, NilPolicy: NilNotApplicable, Combine: func(source SourceKind, current, incoming []usage.Observer) ([]usage.Observer, error) { return append(current, incoming...), nil }, Diagnostics: DiagnosticDescriptor[[]usage.Observer]{ StageID: StageIDTrafficObservation, CoalesceGroup: "traffic_observation", Order: 141, Materialize: func(v []usage.Observer) []DiagnosticOccupant { occupants := make([]DiagnosticOccupant, 0, len(v)) for i, o := range v { if o == nil { continue } occupants = append(occupants, DiagnosticOccupant{Label: fmt.Sprintf("usage_observer:%d", i)}) } return occupants }, }, }
PlaneUsageObservers declares the UsageObservers extension plane.
var PlaneWorkspaceResolvers = Plane[[]workspace.Resolver]{ ID: "workspace_resolvers", RequestAccess: RequestBodyMetadataOnly, Multiplicity: MultOrdered, Rules: SourceRules{ Feature: CombConcatenate, }, NilPolicy: NilNotApplicable, Combine: func(source SourceKind, current, incoming []workspace.Resolver) ([]workspace.Resolver, error) { return append(current, incoming...), nil }, Diagnostics: DiagnosticDescriptor[[]workspace.Resolver]{ StageID: StageIDSessionOpen, CoalesceGroup: "session_open", Order: 91, Materialize: func(v []workspace.Resolver) []DiagnosticOccupant { occupants := make([]DiagnosticOccupant, 0, len(v)) for i, r := range v { if r == nil { continue } occupants = append(occupants, DiagnosticOccupant{Label: fmt.Sprintf("workspace_resolver:%d", i)}) } return occupants }, }, }
PlaneWorkspaceResolvers declares the WorkspaceResolvers extension plane.
var StandardCandidatePlanes = []string{
"session_openers",
"workspace_resolvers",
"tool_catalog_filters",
"tool_call_policies",
"tool_call_finalizers",
"tool_call_finalization_max_args_bytes",
"request_transforms",
"pre_request_handlers",
"route_hint_providers",
"completion_gates",
"attempt_transforms",
"secret_guards",
"compaction_observers",
"compaction_preservers",
"local_turn_handlers",
"terminal_decision_provider",
}
StandardCandidatePlanes defines the canonical list of plane IDs allowed in candidate overlay contribution.
var StandardPlanes = []PlaneDeclaration{ PlaneSubmitHooks, PlaneRequestPartHooks, PlaneResponsePartHooks, PlaneToolReactors, PlaneSessionOpeners, PlaneWorkspaceResolvers, PlaneToolCatalogFilters, PlaneToolCallPolicies, PlaneToolCallFinalizers, PlaneToolCallFinalizationMaxArgsBytes, PlaneRequestTransforms, PlanePreRequestHandlers, PlaneRouteHintProviders, PlaneCompletionGates, PlaneAttemptTransforms, PlaneStreamObserverFactories, PlaneTrafficObservers, PlaneUsageObservers, PlaneRawCaptureSinks, PlaneTrafficRedactors, PlaneCompactionObservers, PlaneCompactionPreservers, PlaneSecretGuards, PlaneSecretGuardExecution, PlaneLocalTurnHandlers, PlaneTerminalDecisionProvider, PlaneSessionClassifier, PlaneControlToolProvider, }
StandardPlanes is the ordered slice of all standard feature planes.
Functions ¶
func Contribute ¶
func Contribute[P any](s *ContributionSet, p Plane[P], pluginID string, v P) error
Contribute adds a typed contribution from a feature plugin under SourceFeature to the ContributionSet. If any validation or combination fails, the set is left unmodified (fail-before-mutate) and an AttributedError attributing the plugin ID and plane ID is returned. Host and generation-binder contributions must use ContributeSource or dedicated internal binders instead.
Example ¶
package main
import (
"context"
"fmt"
"log"
"github.com/matdev83/go-llm-interactive-proxy/pkg/lipapi"
"github.com/matdev83/go-llm-interactive-proxy/pkg/lipsdk/feature"
"github.com/matdev83/go-llm-interactive-proxy/pkg/lipsdk/hooks"
"github.com/matdev83/go-llm-interactive-proxy/pkg/lipsdk/request"
)
type exampleTransform struct {
id string
}
func (t exampleTransform) ID() string { return t.id }
func (t exampleTransform) Order() int { return 10 }
func (t exampleTransform) FailureMode() hooks.FailureMode { return hooks.FailOpen }
func (t exampleTransform) Handle(ctx context.Context, call *lipapi.Call, meta request.RequestMeta, svc request.Services) error {
return nil
}
func main() {
cs := feature.NewContributionSet()
xform := exampleTransform{id: "example.transform"}
if err := feature.Contribute(cs, feature.PlaneRequestTransforms, "example.plugin", []request.Transform{xform}); err != nil {
log.Fatalf("contribute failed: %v", err)
}
bundle := feature.BundleFromPlanes(cs.Freeze(), nil)
if err := bundle.Validate(); err != nil {
log.Fatalf("bundle validation failed: %v", err)
}
transforms := feature.Get(bundle.PlaneSet, feature.PlaneRequestTransforms)
fmt.Printf("%d %s\n", len(transforms), transforms[0].ID())
}
Output: 1 example.transform
func ContributeSource ¶
func ContributeSource[P any](s *ContributionSet, p Plane[P], source SourceKind, contributorID string, v P) error
ContributeSource adds a typed contribution from an explicit source (e.g. SourceFeature, SourceHost, SourceGenerationBinder) to the ContributionSet. If any validation or combination fails, the set is left unmodified (fail-before-mutate) and an AttributedError attributing the contributor ID and plane ID is returned.
func FrozenIdentity ¶
func FrozenIdentity[P any](s FrozenPlaneSet, p Plane[P]) (string, bool)
FrozenIdentity retrieves the validated identity string associated with an exclusive or replace-by-identity plane in the frozen set, if present. FrozenIdentity reads validated cached identity metadata and does not invoke live identity methods. For planes bound to generated storage, FrozenIdentity dispatches directly with zero map lookups.
func Get ¶
func Get[P any](s FrozenPlaneSet, p Plane[P]) P
Get retrieves the typed value for plane p from the frozen set. If the plane was not contributed, is ungenerated, or is absent, the zero value of P is returned. For slice-valued planes, ordinary Get calls return defensive copies to ensure that caller modifications cannot corrupt the frozen snapshot. For planes bound to generated storage, Get dispatches directly with zero map lookups, zero reflection, and zero type assertions.
Example (Absent) ¶
package main
import (
"fmt"
"github.com/matdev83/go-llm-interactive-proxy/pkg/lipsdk/feature"
)
func main() {
var empty feature.FrozenPlaneSet
// Reading an unpopulated or absent plane returns the zero value for that plane type.
transforms := feature.Get(empty, feature.PlaneRequestTransforms)
fmt.Println(len(transforms))
}
Output: 0
func LegalPipelineStageIDs ¶
func LegalPipelineStageIDs() []string
LegalPipelineStageIDs returns a copy of the ordered legal stage id list (R2).
func LegalStageDescriptorIndex ¶
LegalStageDescriptorIndex returns the 0-based pipeline index for id, or -1 if unknown.
func ValidateManifest ¶
func ValidateManifest(declarations ...PlaneDeclaration) error
ValidateManifest checks that a collection of plane declarations contains no duplicate IDs, consistent diagnostic orders and coalesce groups, no duplicate hook targets, and that every plane declaration is valid.
func ValidateStageID ¶
ValidateStageID reports whether id is one of the legal pipeline stages.
Types ¶
type AttributedError ¶
AttributedError wraps an underlying error with the plugin ID and plane ID where the contribution or validation failure occurred.
func (*AttributedError) Error ¶
func (e *AttributedError) Error() string
func (*AttributedError) Is ¶
func (e *AttributedError) Is(target error) bool
func (*AttributedError) Unwrap ¶
func (e *AttributedError) Unwrap() error
type Combination ¶
type Combination uint8
Combination specifies how contributions are combined for a particular source.
const ( // CombUnsupported is the zero value and the only unsupported-source sentinel. CombUnsupported Combination = iota // CombConcatenate appends incoming contributions to existing ones. CombConcatenate // CombExclusive allows exactly one contribution and rejects conflicts. CombExclusive // CombReduce deterministically folds incoming contributions in order. CombReduce // CombReplaceByIdentity replaces matching identity entries or appends new ones. CombReplaceByIdentity )
func (Combination) String ¶
func (c Combination) String() string
type ContributionSet ¶
type ContributionSet struct {
// contains filtered or unexported fields
}
ContributionSet accumulates typed, validated plane contributions during feature plugin construction. It is mutable during assembly and converted to an immutable FrozenPlaneSet via ContributionSet.Freeze.
func ContributionSetFromFrozen ¶
func ContributionSetFromFrozen(s FrozenPlaneSet) *ContributionSet
ContributionSetFromFrozen reconstructs a mutable ContributionSet from a FrozenPlaneSet.
func NewContributionSet ¶
func NewContributionSet() *ContributionSet
NewContributionSet creates a new empty, mutable ContributionSet.
func (*ContributionSet) BindAttemptTransforms ¶
func (s *ContributionSet) BindAttemptTransforms(contributorID string, v []request.AttemptTransform) error
BindAttemptTransforms replaces AttemptTransforms under SourceGenerationBinder semantics.
func (*ContributionSet) BindCompactionPreservers ¶
func (s *ContributionSet) BindCompactionPreservers(contributorID string, v []compaction.Preserver) error
BindCompactionPreservers replaces CompactionPreservers under SourceGenerationBinder semantics.
func (*ContributionSet) BindStreamObserverFactories ¶
func (s *ContributionSet) BindStreamObserverFactories(contributorID string, v []response.StreamObserverFactory) error
BindStreamObserverFactories replaces StreamObserverFactories under SourceGenerationBinder semantics.
func (*ContributionSet) Clone ¶
func (s *ContributionSet) Clone() *ContributionSet
Clone returns a deep copy of the ContributionSet.
func (*ContributionSet) ContributeCandidate ¶
func (s *ContributionSet) ContributeCandidate(cand FrozenPlaneSet) error
ContributeCandidate contributes candidate planes under SourceFeature.
func (*ContributionSet) Freeze ¶
func (s *ContributionSet) Freeze() FrozenPlaneSet
Freeze produces an immutable FrozenPlaneSet from the accumulated contributions. Slice backing arrays and metadata maps are isolated via shallow copy so that subsequent mutations to the ContributionSet or source slices do not affect the frozen snapshot; element values (e.g. interface handlers) are shallow-copied, not deep-cloned.
func (*ContributionSet) Has ¶
func (s *ContributionSet) Has(planeID string) bool
Has reports whether a contribution for planeID exists in the set.
func (*ContributionSet) ReplaceAttemptTransforms ¶
func (s *ContributionSet) ReplaceAttemptTransforms(contributorID string, v []request.AttemptTransform) error
ReplaceAttemptTransforms replaces AttemptTransforms under SourceGenerationBinder semantics.
func (*ContributionSet) ReplaceCompactionPreservers ¶
func (s *ContributionSet) ReplaceCompactionPreservers(contributorID string, v []compaction.Preserver) error
ReplaceCompactionPreservers replaces CompactionPreservers under SourceGenerationBinder semantics.
func (*ContributionSet) ReplaceStreamObserverFactories ¶
func (s *ContributionSet) ReplaceStreamObserverFactories(contributorID string, v []response.StreamObserverFactory) error
ReplaceStreamObserverFactories replaces StreamObserverFactories under SourceGenerationBinder semantics.
type DiagnosticDescriptor ¶
type DiagnosticDescriptor[T any] struct { StageID string CoalesceGroup string Order int Materialize func(T) []DiagnosticOccupant Privileges func(T) PrivilegeProjection }
DiagnosticDescriptor describes how a plane's frozen values are materialized for diagnostics.
type DiagnosticOccupant ¶
DiagnosticOccupant represents an occupant in the diagnostics inventory.
type DiagnosticPlaneProjection ¶
type DiagnosticPlaneProjection struct {
PlaneID string
StageID string
CoalesceGroup string
Order int
Occupants []DiagnosticOccupant
Privileges PrivilegeProjection
}
DiagnosticPlaneProjection represents the type-erased diagnostic projection of a single plane.
func ProjectDiagnostics ¶
func ProjectDiagnostics(in FrozenPlaneSet) []DiagnosticPlaneProjection
ProjectDiagnostics projects diagnostic occupants and privileges from a frozen plane set.
type FeatureBundle ¶
type FeatureBundle struct {
SchemaVersion int
// PlaneSet is the immutable composed extension plane snapshot (V1).
PlaneSet FrozenPlaneSet
Lifecycles []lipplugin.Lifecycle
}
FeatureBundle is the versioned unit a feature factory contributes: schema version metadata, an immutable FrozenPlaneSet, and optional plugin lifecycles. Note: FeatureBundle contains no per-plane named fields or slices; all extension planes are stored in the immutable FrozenPlaneSet.
func BundleFromPlanes ¶
func BundleFromPlanes(planes FrozenPlaneSet, lifecycles []lipplugin.Lifecycle) FeatureBundle
BundleFromPlanes constructs a FeatureBundle from a FrozenPlaneSet and optional lifecycles. It sets SchemaVersion to SchemaVersionV1, defensively clones the FrozenPlaneSet and lifecycles (preserving nil vs explicit empty slice semantics), and performs no validation side effects.
Example ¶
package main
import (
"context"
"fmt"
"github.com/matdev83/go-llm-interactive-proxy/pkg/lipsdk/feature"
"github.com/matdev83/go-llm-interactive-proxy/pkg/lipsdk/plugin"
)
type exampleLifecycle struct {
id string
}
func (l exampleLifecycle) Start(ctx context.Context) error { return nil }
func (l exampleLifecycle) Stop(ctx context.Context) error { return nil }
func main() {
lifecycles := []plugin.Lifecycle{exampleLifecycle{id: "original"}}
bundle := feature.BundleFromPlanes(feature.FrozenPlaneSet{}, lifecycles)
// Mutate the local slice to demonstrate that BundleFromPlanes defensively cloned it at call time.
lifecycles[0] = exampleLifecycle{id: "mutated"}
if lc, ok := bundle.Lifecycles[0].(exampleLifecycle); ok {
fmt.Println(lc.id)
}
}
Output: original
func (FeatureBundle) Validate ¶
func (b FeatureBundle) Validate() error
Validate checks schema metadata against bundle contents. An empty bundle may use SchemaVersion 0 (unset) or SchemaVersionV1; any non-empty bundle must declare SchemaVersionV1.
type FrozenPlaneSet ¶
type FrozenPlaneSet struct {
// contains filtered or unexported fields
}
FrozenPlaneSet holds an immutable collection of composed feature plane values.
func FreezeRequestPlanes ¶
func FreezeRequestPlanes(in FrozenPlaneSet) FrozenPlaneSet
FreezeRequestPlanes materializes request-scoped feature planes into an immutable FrozenPlaneSet. Planes with a declared RequestMaterializer (e.g. sorted execution planes) are materialized once at snapshot construction; all other planes are preserved in their frozen order.
func (FrozenPlaneSet) Clone ¶
func (s FrozenPlaneSet) Clone() FrozenPlaneSet
Clone returns a deep copy of the FrozenPlaneSet with independent slice backing arrays.
func (FrozenPlaneSet) ContributeCandidateTo ¶
func (s FrozenPlaneSet) ContributeCandidateTo(dst *ContributionSet, source SourceKind, contributorID string) error
ContributeCandidateTo contributes candidate plane values in s into dst under the given source and contributor ID.
func (FrozenPlaneSet) IsZero ¶
func (s FrozenPlaneSet) IsZero() bool
IsZero reports whether s is an uninitialized, zero-value FrozenPlaneSet.
func (FrozenPlaneSet) ReplaySourceTo ¶
func (s FrozenPlaneSet) ReplaySourceTo(dst *ContributionSet, source SourceKind, contributorID string) error
ReplaySourceTo replays all planes in s into dst under source with contributorID transactionally. If any plane fails validation or combination, dst is left unmodified (fail-before-mutate).
func (FrozenPlaneSet) ReplayTo ¶
func (s FrozenPlaneSet) ReplayTo(dst *ContributionSet, contributorID string) error
ReplayTo replays all planes in s into dst under SourceFeature with contributorID transactionally. If any plane fails validation or combination, dst is left unmodified (fail-before-mutate).
func (FrozenPlaneSet) ToContributions ¶
func (s FrozenPlaneSet) ToContributions() *ContributionSet
ToContributions reconstructs a mutable ContributionSet from the frozen snapshot.
func (FrozenPlaneSet) Validate ¶
func (s FrozenPlaneSet) Validate() error
Validate checks that all planes in s conform to their declared plane validation rules.
type HookConfig ¶
type HookConfig struct {
SubmitHooks []hooks.SubmitHook
RequestPartHooks []hooks.RequestPartHook
ResponsePartHooks []hooks.ResponsePartHook
ToolReactors []hooks.ToolReactor
ToolReactorErrorPolicy hooks.ToolReactorErrorPolicy
}
HookConfig contains the projected hook slices and error policy for core execution.
func ProjectHookConfig ¶
func ProjectHookConfig(frozen FrozenPlaneSet, policy hooks.ToolReactorErrorPolicy) HookConfig
ProjectHookConfig projects a FrozenPlaneSet into typed HookConfig.
type HookTarget ¶
type HookTarget string
HookTarget defines the target field name in generated hook configuration.
const ( // HookTargetSubmitHooks targets generated HookConfig.SubmitHooks. HookTargetSubmitHooks HookTarget = "SubmitHooks" // HookTargetRequestPartHooks targets generated HookConfig.RequestPartHooks. HookTargetRequestPartHooks HookTarget = "RequestPartHooks" // HookTargetResponsePartHooks targets generated HookConfig.ResponsePartHooks. HookTargetResponsePartHooks HookTarget = "ResponsePartHooks" // HookTargetToolReactors targets generated HookConfig.ToolReactors. HookTargetToolReactors HookTarget = "ToolReactors" )
type Multiplicity ¶
type Multiplicity uint8
Multiplicity defines whether a plane accepts multiple ordered contributions or a single exclusive slot.
const ( // MultUnknown is the uninitialized multiplicity sentinel. MultUnknown Multiplicity = iota // MultOrdered allows multiple contributions combined in registration order. MultOrdered // MultExclusive permits at most one contribution, failing fast on conflict. MultExclusive )
func (Multiplicity) String ¶
func (m Multiplicity) String() string
type NilPolicy ¶
type NilPolicy uint8
NilPolicy defines how typed-nil interface values are handled before validation and combination.
const ( // NilNotApplicable indicates nil policy is not applicable (e.g. non-pointer/non-interface types). NilNotApplicable NilPolicy = iota // NilReject causes typed nil contributions to be rejected with an error before candidate mutation. NilReject // NilSkip causes typed nil contributions to be silently ignored/skipped. NilSkip )
type Plane ¶
type Plane[T any] struct { ID string Multiplicity Multiplicity Rules SourceRules // NilPolicy defines how nil contributions are handled before validation and combination. // NilReject fails before candidate mutation; NilSkip silently skips the contribution; // NilNotApplicable proceeds to validation and combination. NilPolicy NilPolicy // HookTarget defines the optional generated hook configuration target for this plane. HookTarget HookTarget // RequestAccess declares the request-body access class for large-payload // wire eligibility. The zero value Unclassified is rejected by plane // generation and census CI; declaration validation accepts it so // synthetic test planes stay focused on the rule under test. RequestAccess RequestBodyAccess // IsNil is an optional predicate used to detect nil values for NilPolicy checks. // For interface-valued planes (e.g. Plane[MyInterface]), Go's untyped nil check (anyVal == nil) // returns false for typed nil pointers boxed in an interface (e.g. (*ConcreteStub)(nil)). // Because reflection is banned on composition paths per architecture, detecting typed-nil // values in interface-valued planes requires supplying this IsNil predicate. // When IsNil is omitted, untyped nil checks (anyVal == nil) serve as the fast path. IsNil func(v T) bool // Validate validates incoming contribution values. Validate func(v T) error // ValidateIdentity validates a cached identity string (e.g. for exclusive planes). ValidateIdentity func(string) error // Combine combines an incoming contribution with current accumulated state for a source, // returning the retained value for the specified source rule. Combiners must not mutate // caller-owned or current stored state on failure (fail-before-mutate). Combine func(source SourceKind, current, incoming T) (T, error) // Identity extracts the stable identity string for an exclusive or replace-by-identity plane value. Identity func(v T) (string, bool) // ExclusiveConflictError is an optional legacy compatibility error joined with ErrExclusiveConflict on conflict. ExclusiveConflictError error // RequestMaterializer is an optional function that materializes/sorts the plane value // for request-scoped snapshot execution. When nil, the value is preserved as-is. RequestMaterializer func(v T) T // RequestBorrow indicates whether this plane exposes a narrow, immutable borrowed execution accessor // on RequestExecutionView for the runtime executor hot path. RequestBorrow bool // Diagnostics configures operator inventory and privilege projection metadata for this plane. Diagnostics DiagnosticDescriptor[T] // contains filtered or unexported fields }
Plane declares an extension plane contract with multiplicity, per-source combination rules, validation, nil policy, and diagnostics metadata.
In v1, Plane descriptors represent published standard planes in the closed canonical manifest. Production contribution policy (source combination rules, nil handling, validation, identity, combination) is authoritatively enforced by the canonical generated binding. Copying or mutating exported fields on a Plane descriptor does not redefine the plane; production contribution always executes the canonical generated policy. If an altered copy has a modified plane ID or is unbound, contribution is rejected with ErrUngeneratedPlane. Adding a new extension plane is an upstream platform change requiring a manifest declaration in plane_manifest.go and code regeneration.
func (Plane[T]) DiagnosticCoalesceGroup ¶
DiagnosticCoalesceGroup returns the diagnostics coalesce group of the plane.
func (Plane[T]) DiagnosticOrder ¶
DiagnosticOrder returns the explicit diagnostic order of the plane.
func (Plane[T]) DiagnosticStageID ¶
DiagnosticStageID returns the diagnostics stage ID of the plane.
func (Plane[T]) MaterializeOccupants ¶
func (p Plane[T]) MaterializeOccupants(v T) []DiagnosticOccupant
MaterializeOccupants materializes diagnostic occupants for value v using the plane's descriptor. If Materialize is nil, it returns nil.
func (Plane[T]) ProjectPrivileges ¶
func (p Plane[T]) ProjectPrivileges(v T) PrivilegeProjection
ProjectPrivileges projects privilege flags for value v using the plane's descriptor. If Privileges is nil, it returns an empty PrivilegeProjection.
func (Plane[T]) ValidateDeclaration ¶
ValidateDeclaration verifies that the plane declaration is well-formed, complete, and that multiplicity, nil policy, diagnostics metadata, and source rules are mutually consistent. For exclusive and replace-by-identity rules, p.Identity is required. When generated access closures are attached (e.g. via test-local bindings or generated adapters), p.generated.identity is also required. Unbound declarations rely on manifest-collection validation in code generation tooling (task 2.3).
type PlaneDeclaration ¶
type PlaneDeclaration interface {
PlaneID() string
ValidateDeclaration() error
DiagnosticOrder() int
DiagnosticStageID() string
DiagnosticCoalesceGroup() string
}
PlaneDeclaration allows non-generic validation of plane declarations across a manifest.
type PrivilegeProjection ¶
type PrivilegeProjection struct {
Flags []string
}
PrivilegeProjection represents privilege metadata projected from a plane contribution.
type RequestBodyAccess ¶
type RequestBodyAccess uint8
RequestBodyAccess classifies how a plane's content relates to the request body for large-payload wire eligibility (Task 3.1 authority classification). The zero value Unclassified fails generation and census CI so a new or unannotated plane fails closed; Task 3.5+ consumes the classification in the generation-frozen eligibility summary.
const ( // RequestBodyAccessUnclassified is the zero value: the plane has no wire // classification and fails generation/CI. RequestBodyAccessUnclassified RequestBodyAccess = iota // RequestBodyCanonicalRequired marks planes that receive or mutate the // full canonical request and block the wire lane when occupied. RequestBodyCanonicalRequired // RequestBodyMetadataOnly marks planes carrying only bounded // session/workspace/int metadata. RequestBodyMetadataOnly // RequestBodyResponseOnly marks planes operating on canonical output // events only. RequestBodyResponseOnly // RequestBodyWireContract marks planes carrying an explicit certified // wire contract. RequestBodyWireContract )
func (RequestBodyAccess) String ¶
func (a RequestBodyAccess) String() string
type RequestExecutionView ¶
type RequestExecutionView struct {
// contains filtered or unexported fields
}
RequestExecutionView is an immutable borrowed view over request-materialized planes. Its returned slices must not be mutated.
func RequestExecution ¶
func RequestExecution(in FrozenPlaneSet) RequestExecutionView
RequestExecution constructs a RequestExecutionView over the request-materialized planes in in.
func (RequestExecutionView) LocalTurnHandlers ¶
func (v RequestExecutionView) LocalTurnHandlers() []localturn.Handler
LocalTurnHandlers returns the request-materialized LocalTurnHandlers without cloning. The returned slice is immutable borrowed storage and MUST NOT be mutated.
func (RequestExecutionView) SecretGuards ¶
func (v RequestExecutionView) SecretGuards() []secretguard.Guard
SecretGuards returns the request-materialized SecretGuards without cloning. The returned slice is immutable borrowed storage and MUST NOT be mutated.
func (RequestExecutionView) ToolCallFinalizers ¶
func (v RequestExecutionView) ToolCallFinalizers() []toolcall.Finalizer
ToolCallFinalizers returns the request-materialized ToolCallFinalizers without cloning. The returned slice is immutable borrowed storage and MUST NOT be mutated.
func (RequestExecutionView) ToolCallPolicies ¶
func (v RequestExecutionView) ToolCallPolicies() []toolpolicy.Policy
ToolCallPolicies returns the request-materialized ToolCallPolicies without cloning. The returned slice is immutable borrowed storage and MUST NOT be mutated.
type SourceKind ¶
type SourceKind uint8
SourceKind identifies the composition source contributing to an extension plane.
const ( // SourceUnknown is the uninitialized or unknown source sentinel. SourceUnknown SourceKind = iota // SourceFeature represents contributions from feature plugins. SourceFeature // SourceHost represents contributions or overlays injected by the host runtime. SourceHost // SourceGenerationBinder represents generation-scoped binder contributions. SourceGenerationBinder )
func (SourceKind) String ¶
func (s SourceKind) String() string
type SourceRules ¶
type SourceRules struct {
Feature Combination
Host Combination
GenerationBinder Combination
}
SourceRules defines per-source combination rules for an extension plane.
func (SourceRules) RuleFor ¶
func (r SourceRules) RuleFor(source SourceKind) Combination
RuleFor returns the combination rule declared for source.
type StageDescriptor ¶
type StageDescriptor struct {
ID string
MutationRole StageMutationRole
R12LayerNotes string
}
StageDescriptor is a compile-time description of one legal pipeline stage.
func LegalStageDescriptors ¶
func LegalStageDescriptors() []StageDescriptor
LegalStageDescriptors returns a copy of the canonical stage descriptor table.
func StageDescriptorByID ¶
func StageDescriptorByID(id string) (StageDescriptor, bool)
StageDescriptorByID reports whether id is a legal stage and returns its descriptor.
type StageMutationRole ¶
type StageMutationRole uint8
StageMutationRole documents what a stage may do to traffic or control flow (R2).
const ( // StageRoleUnknown is the zero value: invalid or unset until assigned from the legal descriptor table. StageRoleUnknown StageMutationRole = iota StageRoleMutate StageRoleReject StageRoleObserve StageRoleReplace StageRoleMutateReject )