backendplugin

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2026 License: Apache-2.0 Imports: 26 Imported by: 0

Documentation

Overview

Package backendplugin defines the public authoring, validation, and wire-conversion contracts for executable backend connector plugins.

Types in this package do not import internal/... packages. Wire messages live in api/backendplugin/v1. Domain protocol negotiation is independent of the process substrate.

Task 1.2 covers contracts, validation, and DTO↔proto conversion only. Live servers, process hosting, manifests, and conformance executables are later tasks.

Index

Constants

View Source
const (
	// ProtocolMajorV1 is the only major version accepted by this package.
	ProtocolMajorV1 = uint32(1)
	// ProtocolMinorExactReasoningParts adds dialect-tagged opaque reasoning parts
	// to invocation parts and canonical stream events.
	ProtocolMinorExactReasoningParts = uint32(1)
	// ProtocolMinorOrderedItems adds ordered item invocation fields, operation metadata,
	// and explicit protocol requirement DTOs.
	ProtocolMinorOrderedItems = uint32(2)
	// ProtocolMinorExactOpenResponsesFields adds exact OpenAI Responses semantics to
	// the ABI: Invocation.PromptCacheKey, inline FileData, opaque extension content
	// parts, reasoning Summary/Content/EncryptedContent presence, and compaction
	// EncryptedContent on invocation items and canonical stream events.
	ProtocolMinorExactOpenResponsesFields = uint32(3)
	// ProtocolMinorProxyOwnedSessionID adds the optional typed proxy-owned session
	// authority field. Hosts that negotiate an older minor must omit it and use
	// full-history/native-compaction bypass rather than losing the request.
	ProtocolMinorProxyOwnedSessionID = uint32(4)
	// ProtocolMinorAccountingEvidence adds host-only provider billing evidence.
	ProtocolMinorAccountingEvidence = uint32(5)
	// FeatureExactReasoningParts gates use of the additive v1.1 wire fields.
	FeatureExactReasoningParts = "exact_reasoning_parts"
	// FeatureOrderedItems gates ordered item invocation DTO fields.
	FeatureOrderedItems = "ordered_items"
	// FeatureExactOpenResponsesFields gates the additive v1.3 exact OpenAI
	// Responses wire fields on invocation items, canonical events, and Invocation.
	FeatureExactOpenResponsesFields = "exact_openresponses_fields"
	// FeatureProxyOwnedSessionID gates the optional typed session authority field.
	FeatureProxyOwnedSessionID = "proxy_owned_session_id"
	// FeatureAccountingEvidence gates the non-canonical accounting sideband.
	FeatureAccountingEvidence = "accounting_evidence_sideband"
	// FeatureSemanticExtensions gates the bounded protocol-neutral residual carrier.
	FeatureSemanticExtensions       = "semantic_extensions_v1"
	ProtocolMinorSemanticExtensions = uint32(6)
	// ProtocolMinorPromptCacheResidency adds optional prompt-cache profile,
	// observation sideband, and instance-scoped control RPCs.
	ProtocolMinorPromptCacheResidency = uint32(7)
	FeaturePromptCacheResidency       = "prompt_cache_residency_v1"
	// ProtocolMinorCancellationHandshake adds negotiated same-Execute cancellation handshake
	// with observed outcome mode and deadline propagation.
	ProtocolMinorCancellationHandshake = uint32(8)
	FeatureCancellationHandshake       = "cancellation_handshake_v1"
	// ProtocolMinorAccountingEvidenceV2 adds typed, host-only economic
	// observations to the existing V1 accounting sideband/finalizer messages.
	ProtocolMinorAccountingEvidenceV2 = uint32(9)
	FeatureAccountingEvidenceV2       = "accounting_evidence_v2"
	// Neutral aliases retain the same negotiated wire feature without creating
	// a second capability or transport format.
	FeatureEconomicsV2                 = FeatureAccountingEvidenceV2
	FeatureEconomicEvidenceV2          = FeatureAccountingEvidenceV2
	ProtocolMinorEconomicsV2           = ProtocolMinorAccountingEvidenceV2
	ProtocolMinorEconomicEvidenceV2    = ProtocolMinorAccountingEvidenceV2
	DefaultMaxAccountingDedupeKeyBytes = uint64(256)

	// DefaultMaxMessageBytes is the default whole-message size ceiling.
	DefaultMaxMessageBytes = uint64(4 << 20)
	// DefaultMaxStreamFrameBytes is the default Execute frame payload ceiling.
	DefaultMaxStreamFrameBytes = uint64(1 << 20)
	// DefaultMaxPendingEvents bounds host/plugin pending-event buffers.
	DefaultMaxPendingEvents = uint64(1024)
	// DefaultMaxRawJSONBytes bounds opaque JSON byte fields.
	DefaultMaxRawJSONBytes = uint64(256 << 10)
	// DefaultMaxConfigYAMLBytes bounds configure ConfigYAML.
	DefaultMaxConfigYAMLBytes = uint64(1 << 20)
	// DefaultMaxDiagnosticBytes bounds diagnostic frame text.
	DefaultMaxDiagnosticBytes = uint64(64 << 10)
	// DefaultMaxModelsPerResponse bounds ListModelsResponse.Models.
	DefaultMaxModelsPerResponse = uint32(10_000)
)

Protocol and default wire bounds for the v1 ABI.

View Source
const (
	// DefaultMaxEconomicObservationBytes bounds one canonical V2 observation
	// before it crosses the executable connector boundary.
	DefaultMaxEconomicObservationBytes = uint64(64 << 10)
	// DefaultMaxEconomicEvidencePerAttempt bounds retained sideband entries in a
	// single attempt. It is deliberately no larger than the V1 pending bound.
	DefaultMaxEconomicEvidencePerAttempt = uint64(1024)
)
View Source
const (
	MetaOperation        = "lip.operation"
	MetaDeliveryMode     = "lip.delivery_mode"
	MetaTransportMode    = "lip.transport_mode"
	MetaRouteParamPrefix = "route.param."
	MetaExtensionPrefix  = "ext."
)
View Source
const (
	// MetaProtocolRequirements is deprecated; use Invocation.ProtocolRequirements.
	MetaProtocolRequirements = "lip.protocol_requirements"
)

Variables

View Source
var (
	// ErrAccountingEvidenceV2Unsupported is returned when V2 evidence is used
	// without an explicit negotiated capability.
	ErrAccountingEvidenceV2Unsupported = errors.New("backendplugin: accounting evidence V2 unsupported")
	// ErrAccountingEvidenceV2Conflict identifies two payloads with one source
	// identity but different immutable content.
	ErrAccountingEvidenceV2Conflict = errors.New("backendplugin: conflicting accounting evidence V2")
)
View Source
var (
	// ErrIncompatibleMajor is returned when host and plugin protocol majors differ
	// or are not ProtocolMajorV1.
	ErrIncompatibleMajor = errors.New("backendplugin: incompatible protocol major version")
	ErrIncompatibleMinor = errors.New("backendplugin: incompatible protocol minor version")
	// ErrUnknownRequiredFeature is returned when a required feature is unknown to the peer.
	ErrUnknownRequiredFeature = errors.New("backendplugin: unknown required feature")
	// ErrDuplicateFeature is returned when a feature name appears more than once in an offer.
	ErrDuplicateFeature = errors.New("backendplugin: duplicate feature name")
	// ErrEmptyFeatureName is returned when a feature name is empty after trim.
	ErrEmptyFeatureName = errors.New("backendplugin: empty feature name")
	// ErrConfigureBeforeNegotiate is returned when configure is attempted without a compatible negotiation.
	ErrConfigureBeforeNegotiate = errors.New("backendplugin: configure before successful negotiation")
	// ErrTransportRetriesRequiredDisabled requires DisableAutomaticRetries.
	ErrTransportRetriesRequiredDisabled = errors.New("backendplugin: transport automatic retries must be disabled")
	// ErrInvalidBounds is returned for inconsistent size limits.
	ErrInvalidBounds = errors.New("backendplugin: invalid message or frame bounds")
	// ErrOversizedMessage is returned when a payload exceeds its configured bound.
	ErrOversizedMessage = errors.New("backendplugin: message exceeds configured bound")
	// ErrOversizedRawJSON is returned when raw JSON bytes exceed the configured bound.
	ErrOversizedRawJSON = errors.New("backendplugin: raw JSON exceeds configured bound")
	// ErrUnknownFrameKind is returned for unspecified or unknown frame kinds.
	ErrUnknownFrameKind = errors.New("backendplugin: unknown frame kind")
	// ErrUnknownEventKind is returned for unspecified or unknown event kinds.
	ErrUnknownEventKind = errors.New("backendplugin: unknown event kind")
	// ErrUnknownEnum is returned for unspecified or unknown closed enum values.
	ErrUnknownEnum = errors.New("backendplugin: unknown enum value")
	// ErrUnsupportedPartKind is returned when a content part kind has no
	// canonical<->ABI mapping; unmapped kinds fail closed, never silently drop.
	ErrUnsupportedPartKind = errors.New("backendplugin: unsupported part kind")
	// ErrInvalidRawJSON is returned for invalid or unset RawJSON oneof wire values.
	ErrInvalidRawJSON = errors.New("backendplugin: invalid raw JSON wire value")
	// ErrMultipleTerminals is returned when more than one terminal frame is observed.
	ErrMultipleTerminals = errors.New("backendplugin: multiple terminal frames")
	// ErrEventAfterTerminal is returned for any frame after a terminal.
	ErrEventAfterTerminal = errors.New("backendplugin: frame after terminal")
	// ErrSequenceGap is returned for non-monotonic or missing sequence numbers.
	ErrSequenceGap = errors.New("backendplugin: sequence gap or regression")
	// ErrAcceptedRequired is returned when a sequenced frame arrives before accepted.
	ErrAcceptedRequired = errors.New("backendplugin: accepted frame required first")
	// ErrInvalidDescriptor is returned for an invalid plugin descriptor.
	ErrInvalidDescriptor = errors.New("backendplugin: invalid plugin descriptor")
	// ErrInconsistentSecurityPosture is returned when a descriptor factory declares
	// credential_mode: oauth_user with an access scope other than local_only. Under
	// the host principal model a user-scoped OAuth credential is never valid in a
	// shared deployment, so advertising broad eligibility is self-contradictory. The
	// same rule is enforced on the packaged manifest
	// (manifest.ErrInconsistentExportSecurityPosture); keeping it here means a
	// connector cannot serve a runtime descriptor its own manifest would be rejected
	// for.
	ErrInconsistentSecurityPosture = errors.New("backendplugin: inconsistent factory security posture")
	// ErrInvalidInvocation is returned for an invalid invocation or usage presence mismatch.
	ErrInvalidInvocation = errors.New("backendplugin: invalid invocation")
	// ErrInvalidFrame is returned when a frame payload shape does not match its kind.
	ErrInvalidFrame = errors.New("backendplugin: invalid frame payload")
	// ErrNegotiationRequired is returned when configure lacks a bound negotiation token.
	ErrNegotiationRequired = errors.New("backendplugin: negotiation token required")
	// ErrUnknownNegotiationToken is returned for an unknown or spent negotiation token.
	ErrUnknownNegotiationToken = errors.New("backendplugin: unknown negotiation token")
	// ErrInstanceExists is returned when configure reuses an active instance id.
	ErrInstanceExists = errors.New("backendplugin: instance already exists")
	// ErrInstanceBusy is returned when close is attempted while execute leases remain.
	ErrInstanceBusy = errors.New("backendplugin: instance has active execute leases")
	// ErrOrderedItemsUnsupported is returned when item authority is requested against an older plugin ABI.
	ErrOrderedItemsUnsupported = errors.New("backendplugin: ordered item ABI not negotiated")
	// ErrExactOpenResponsesUnsupported is returned when a call or event requires exact
	// OpenAI Responses semantics against an ABI minor or feature that cannot represent them.
	ErrExactOpenResponsesUnsupported = errors.New("backendplugin: exact OpenResponses ABI not negotiated")
	// ErrProxyOwnedSessionUnsupported is returned when a call carries validated
	// session authority that the negotiated ABI cannot transport safely.
	ErrProxyOwnedSessionUnsupported = errors.New("backendplugin: proxy-owned session ABI not negotiated")
	// ErrPromptCacheUnsupported is returned when optional prompt-cache ABI/control
	// is used without compatible negotiation or an implementation.
	ErrPromptCacheUnsupported = errors.New("backendplugin: prompt-cache residency ABI unsupported")
)

Sentinel errors for fail-closed public validation and conversion.

Functions

func AccountingEvidenceNegotiated

func AccountingEvidenceNegotiated(neg Negotiation) bool

AccountingEvidenceNegotiated reports whether the V1 host-only sideband is available for the current session. It is intentionally separate from the typed V2 negotiation gate: V1 carries only the six legacy token counters.

func AccountingEvidenceV2Negotiated

func AccountingEvidenceV2Negotiated(neg Negotiation) bool

AccountingEvidenceV2Negotiated reports the exact feature/minor pair needed for lossless V2 transport.

func AccountingEvidenceV2ToProto

func AccountingEvidenceV2ToProto(e *AccountingEvidenceV2) (*backendpluginv1.AccountingEvidenceV2, error)

AccountingEvidenceV2ToProto encodes the V2 host-only wrapper.

func ApplyCallWireMetadata

func ApplyCallWireMetadata(inv *Invocation, call lipapi.Call, routeParams map[string]string)

ApplyCallWireMetadata projects the legacy-safe operation, delivery, transport, route params, ordered item wire fields, and Call.Extensions into an invocation. It intentionally does not project proxy-owned session authority: that typed field exists only on the negotiated minor-4 ABI.

func ApplyCallWireMetadataWithNegotiation

func ApplyCallWireMetadataWithNegotiation(inv *Invocation, call lipapi.Call, routeParams map[string]string, neg Negotiation) error

ApplyCallWireMetadataWithNegotiation projects wire metadata and enforces ordered-item and exact OpenResponses ABI gates before execution.

func ApplyItemAuthorityMetadata

func ApplyItemAuthorityMetadata(inv *Invocation, call lipapi.Call)

ApplyItemAuthorityMetadata is deprecated; ordered item wire uses first-class invocation fields via ApplyOrderedItemWire.

func ApplyOrderedItemWire

func ApplyOrderedItemWire(inv *Invocation, call lipapi.Call)

ApplyOrderedItemWire projects item authority, operation metadata, and requirements into plugin DTO fields.

func CallFromInvocation

func CallFromInvocation(inv Invocation) (lipapi.Call, error)

CallFromInvocation maps a public plugin Invocation into a canonical lipapi.Call for connector-local protocol engines (ACP support, OpenAI-compat mappers, etc.). Validate uses this same mapper so ABI gates cannot accept a shape production rejects.

func CancelCauseFromCancelReason

func CancelCauseFromCancelReason(reason CancelReason) lipapi.CancelCause

CancelCauseFromCancelReason maps wire CancelReason to canonical lipapi.CancelCause.

func CancelOutcomeToProto

func CancelOutcomeToProto(c *CancelOutcome) (*backendpluginv1.CancelOutcome, error)

CancelOutcomeToProto encodes cancel outcomes.

func CancellationHandshakeNegotiated

func CancellationHandshakeNegotiated(neg Negotiation) bool

CancellationHandshakeNegotiated reports whether the cancellation handshake feature was negotiated.

func CanonicalEventToProto

func CanonicalEventToProto(e *CanonicalEvent) (*backendpluginv1.CanonicalEvent, error)

CanonicalEventToProto encodes stream events.

func ClientFrameToProto

func ClientFrameToProto(f ClientFrame) (*backendpluginv1.ExecuteClientFrame, error)

ClientFrameToProto encodes host-to-plugin frames.

func ConfigureRequestToProto

func ConfigureRequestToProto(r ConfigureRequest) *backendpluginv1.ConfigureRequest

ConfigureRequestToProto encodes configure wire fields (Negotiation is not on the wire).

func CountTokensRequestToProto

func CountTokensRequestToProto(r CountTokensRequest) (*backendpluginv1.CountTokensRequest, error)

CountTokensRequestToProto encodes count requests.

func CountTokensResponseToProto

func CountTokensResponseToProto(r CountTokensResponse) *backendpluginv1.CountTokensResponse

CountTokensResponseToProto encodes count results.

func DialectSupportToLipapi

func DialectSupportToLipapi(d DialectSupport) lipapi.DialectSupport

DialectSupportToLipapi maps plugin dialect support into canonical form.

func EconomicDecimalV2FromProto

func EconomicDecimalV2FromProto(p *backendpluginv1.EconomicDecimalV2) (metering.Decimal, error)

EconomicDecimalV2FromProto decodes an exact decimal without floating-point coercion. A missing message is an invalid top-level value; optional measure and charge values use the private pointer helper below.

func EconomicDecimalV2ToProto

func EconomicDecimalV2ToProto(d metering.Decimal) (*backendpluginv1.EconomicDecimalV2, error)

EconomicDecimalV2ToProto encodes an exact canonical decimal.

func EconomicEvidenceV2Negotiated

func EconomicEvidenceV2Negotiated(neg Negotiation) bool

EconomicEvidenceV2Negotiated is an alias for compatibility with neutral connector terminology.

func EconomicObservationV2FromProto

func EconomicObservationV2FromProto(p *backendpluginv1.EconomicObservationV2) (metering.Observation, error)

EconomicObservationV2FromProto converts the typed wire envelope into the canonical metering model. Conversion is deliberately strict and does not retain unknown raw protobuf fields as economic evidence.

func EconomicObservationV2ToProto

func EconomicObservationV2ToProto(o metering.Observation) (*backendpluginv1.EconomicObservationV2, error)

EconomicObservationV2ToProto encodes the canonical V2 observation with explicit decimal and nested-field presence.

func EconomicsV2Negotiated

func EconomicsV2Negotiated(neg Negotiation) bool

EconomicsV2Negotiated is the shorter spelling used by host policy callers.

func FinalizeBillingRequestToProto

func FinalizeBillingRequestToProto(r FinalizeBillingRequest) *backendpluginv1.FinalizeBillingRequest

FinalizeBillingRequestToProto encodes finalize requests.

func FinalizeBillingResponseToProto

func FinalizeBillingResponseToProto(r FinalizeBillingResponse) (*backendpluginv1.FinalizeBillingResponse, error)

FinalizeBillingResponseToProto encodes finalize results.

func ForwardExecute

func ForwardExecute(stream ExecuteStream, open OpenManagedStream) error

ForwardExecute accepts the start frame, opens the upstream managed stream via open, and coordinates bidirectional execution:

  • exactly one client-control reader owns ExecuteStream.Recv after START;
  • exactly one upstream reader owns ManagedEventStream.Recv;
  • the calling goroutine acts as coordinator and is the sole sender through frameSequencer;
  • in-band CANCEL is consumed against the active upstream stream, calling upstream.Cancel with effective deadline and emitting a sequenced CancelOutcome before the cancelled terminal;
  • CLOSE_INPUT remains distinct from CANCEL (no upstream cancellation);
  • all goroutines cleanly terminate and join when execution completes.

func GracefulShutdownRequestToProto

func GracefulShutdownRequestToProto(r GracefulShutdownRequest) *backendpluginv1.GracefulShutdownRequest

GracefulShutdownRequestToProto encodes shutdown request.

func GracefulShutdownResponseToProto

func GracefulShutdownResponseToProto(r GracefulShutdownResponse) *backendpluginv1.GracefulShutdownResponse

GracefulShutdownResponseToProto encodes shutdown response.

func HasItemAuthorityInvocation

func HasItemAuthorityInvocation(inv Invocation) bool

HasItemAuthorityInvocation reports item authority from first-class invocation fields.

func HasItemAuthorityMetadata

func HasItemAuthorityMetadata(meta map[string]string) bool

HasItemAuthorityMetadata reports whether the invocation declares item authority.

func HasItemAuthorityWire

func HasItemAuthorityWire(inv Invocation) bool

HasItemAuthorityWire reports whether the invocation carries ordered item authority.

func HealthResponseToProto

func HealthResponseToProto(h HealthResponse) *backendpluginv1.HealthResponse

HealthResponseToProto encodes health.

func InvocationToProto

func InvocationToProto(inv Invocation) (*backendpluginv1.Invocation, error)

InvocationToProto encodes an invocation.

func ListModelsResponseToProto

func ListModelsResponseToProto(r ListModelsResponse) *backendpluginv1.ListModelsResponse

ListModelsResponseToProto encodes inventory.

func MustNegotiateBeforeConfigure

func MustNegotiateBeforeConfigure(neg Negotiation) error

MustNegotiateBeforeConfigure rejects configure when negotiation was not compatible.

func NegotiationToNegotiateResponse

func NegotiationToNegotiateResponse(n Negotiation) (*backendpluginv1.NegotiateResponse, error)

NegotiationToNegotiateResponse encodes a negotiation outcome.

func ObservationV2FromProto

func ObservationV2FromProto(p *backendpluginv1.EconomicObservationV2) (metering.Observation, error)

ObservationV2FromProto and ObservationV2ToProto are short neutral aliases.

func OutputCommittedEvent

func OutputCommittedEvent(kind EventKind) bool

OutputCommittedEvent reports whether an event kind commits output for failover.

func PluginDescriptorToProto

func PluginDescriptorToProto(d PluginDescriptor) (*backendpluginv1.PluginDescriptor, error)

PluginDescriptorToProto encodes a descriptor.

func PluginErrorToProto

func PluginErrorToProto(e *PluginError) (*backendpluginv1.PluginError, error)

PluginErrorToProto encodes a classified error.

func PromptCacheNegotiated

func PromptCacheNegotiated(neg Negotiation) bool

func ProtocolOfferToNegotiateRequest

func ProtocolOfferToNegotiateRequest(o ProtocolOffer) (*backendpluginv1.NegotiateRequest, error)

func ProtocolRequirementsFromInvocation

func ProtocolRequirementsFromInvocation(inv Invocation) (lipapi.ProtocolRequirements, bool)

ProtocolRequirementsFromInvocation decodes requirements from first-class invocation fields.

func ProtocolRequirementsFromMetadata

func ProtocolRequirementsFromMetadata(meta map[string]string) (lipapi.ProtocolRequirements, bool)

ProtocolRequirementsFromMetadata is deprecated; requirements are carried on Invocation.ProtocolRequirements.

func ProxyOwnedSemanticExtensionsSupported

func ProxyOwnedSemanticExtensionsSupported(neg Negotiation) bool

func ProxyOwnedSessionIDSupported

func ProxyOwnedSessionIDSupported(neg Negotiation) bool

ProxyOwnedSessionIDSupported reports whether the negotiated ABI can carry proxy-owned session authority. It is intentionally optional: an older connector must continue the request without native compaction state.

func RawJSONToProto

func RawJSONToProto(r RawJSON) *backendpluginv1.RawJSONValue

RawJSONToProto encodes RawJSON. Absent encodes as nil.

func RequireAccountingEvidenceV2

func RequireAccountingEvidenceV2(neg Negotiation) error

RequireAccountingEvidenceV2 fails before provider execution when a strict offer requires the V2 evidence contract but the negotiated peer lacks it.

func RequireExactOpenResponsesABISupport

func RequireExactOpenResponsesABISupport(neg Negotiation, call lipapi.Call) error

RequireExactOpenResponsesABISupport rejects calls that require exact OpenAI Responses semantics (PromptCacheKey, inline FileData, opaque extension content parts, reasoning Summary/Content/EncryptedContent presence, compaction EncryptedContent) when negotiation did not reach minor 3 with the feature enabled. Plain calls without those semantics remain backward-compatible.

func RequireExactOpenResponsesEventABISupport

func RequireExactOpenResponsesEventABISupport(neg Negotiation, ev *CanonicalEvent) error

RequireExactOpenResponsesEventABISupport rejects canonical events that carry exact OpenAI Responses reasoning fields when negotiation cannot represent them, so hosts never silently drop encrypted content or summary/content presence.

func RequireOrderedItemABISupport

func RequireOrderedItemABISupport(neg Negotiation, call lipapi.Call) error

RequireOrderedItemABISupport rejects ordered-item calls when negotiation did not reach minor 2.

func RequireSemanticExtensionsABISupport

func RequireSemanticExtensionsABISupport(neg Negotiation, call lipapi.Call) error

RequireSemanticExtensionsABISupport rejects a required residual carrier when the negotiated ABI cannot carry its exact identity/presence/data.

func ResolvedProfileToProto

func ResolvedProfileToProto(p ResolvedProfile) *backendpluginv1.ResolvedProfile

ResolvedProfileToProto encodes a resolved profile.

func RestoreCallWireMetadata

func RestoreCallWireMetadata(call *lipapi.Call, meta map[string]string)

RestoreCallWireMetadata rebuilds lipapi.Call wire fields from SafeMetadata.

func RouteParam

func RouteParam(meta map[string]string, name string) string

RouteParam returns a route.param.* value from SafeMetadata.

func RuntimePolicyToProto

func RuntimePolicyToProto(p RuntimePolicy) *backendpluginv1.RuntimePolicy

RuntimePolicyToProto encodes runtime policy.

func ServerFrameConservativeBytes

func ServerFrameConservativeBytes(f ServerFrame) uint64

ServerFrameConservativeBytes sums raw payloads without relying on marshal success.

func ServerFrameSizeBytes

func ServerFrameSizeBytes(f ServerFrame) uint64

ServerFrameSizeBytes returns a fail-closed frame size: max(protobuf wire, conservative payload).

func ServerFrameToProto

func ServerFrameToProto(f ServerFrame) (*backendpluginv1.ExecuteServerFrame, error)

ServerFrameToProto encodes plugin-to-host frames.

func TerminalToProto

func TerminalToProto(t *Terminal) (*backendpluginv1.Terminal, error)

TerminalToProto encodes terminals.

func ToolChoiceFromWire

func ToolChoiceFromWire(s *string) (lipapi.ToolChoice, error)

ToolChoiceFromWire decodes the plugin ABI tool choice string into canonical form.

func ToolChoiceToWire

func ToolChoiceToWire(tc lipapi.ToolChoice) *string

ToolChoiceToWire maps canonical tool choice into the plugin ABI optional string field. Default auto with no named tool is represented as absent (nil). The allowed_tools subset is encoded as "allowed:<mode>:<n1>,<n2>".

func UsageEvidenceToProto

func UsageEvidenceToProto(u UsageEvidence) (*backendpluginv1.UsageEvidence, error)

UsageEvidenceToProto encodes usage evidence.

func UsagePresenceToProto

func UsagePresenceToProto(p UsagePresence) *backendpluginv1.UsagePresence

UsagePresenceToProto encodes usage presence flags.

func ValidateAccessScope

func ValidateAccessScope(s AccessScope) error

ValidateAccessScope rejects unspecified and unknown access scopes.

func ValidateAccountingEvidence

func ValidateAccountingEvidence(e AccountingEvidence) error

ValidateAccountingEvidence validates the bounded, provider-billable sideband payload. Presence is authoritative: a nil counter is omitted, not zero.

func ValidateCancelMode

func ValidateCancelMode(m CancelMode) error

ValidateCancelMode rejects unspecified and unknown cancel modes.

func ValidateClientFrameBounds

func ValidateClientFrameBounds(f ClientFrame) error

ValidateClientFrameBounds enforces client-frame wire size using protobuf encoding size.

func ValidateCredentialMode

func ValidateCredentialMode(m CredentialMode) error

ValidateCredentialMode rejects unspecified and unknown credential modes.

func ValidateEventKind

func ValidateEventKind(k EventKind) error

ValidateEventKind rejects unspecified and unknown canonical event kinds (fail closed).

func ValidateNegotiationResult

func ValidateNegotiationResult(host ProtocolOffer, neg Negotiation) error

ValidateNegotiationResult verifies a peer's compatible response against the host offer. It prevents a compromised or buggy peer from enabling features it did not advertise, claiming a minor above either side, or bypassing required feature gates after the initial Negotiate RPC.

func ValidateRawJSONSize

func ValidateRawJSONSize(n, limit uint64) error

ValidateRawJSONSize rejects raw JSON payloads over limit.

func ValidateServerFrameBounds

func ValidateServerFrameBounds(f ServerFrame) error

ValidateServerFrameBounds enforces stream-frame wire size using the default frame ceiling.

func ValidateServerFrameSize

func ValidateServerFrameSize(f ServerFrame, limit uint64) error

ValidateServerFrameSize enforces shape plus full-frame size against limit.

func ValidateSize

func ValidateSize(n, limit uint64) error

ValidateSize rejects n when it exceeds limit.

func ValidateToolChoiceABI

func ValidateToolChoiceABI(tc lipapi.ToolChoice) error

ValidateToolChoiceABI reports whether the canonical tool choice can be represented by the plugin ABI optional string without semantic loss. The allowed_tools subset is encoded as "allowed:<mode>:<n1>,<n2>", so a tool name containing a comma cannot round-trip and is rejected explicitly. Mode required combined with a subset is rejected too: the ABI decoder accepts only auto/none/any as the allowed mode, so the encoder could otherwise emit an "allowed:required:..." string the decoder rejects.

Types

type AccessScope

type AccessScope = lipsdk.BackendAccessScope

AccessScope is the closed multi-user access posture for a factory export. Wire values match lipsdk.BackendAccessScope; Validate() is the ABI gate.

const (
	AccessScopeUnspecified AccessScope = ""
	AccessScopeAny         AccessScope = lipsdk.BackendAccessAny
	AccessScopeLocalOnly   AccessScope = lipsdk.BackendAccessLocalOnly
)

func AccessScopeFromLipsdk

func AccessScopeFromLipsdk(s lipsdk.BackendAccessScope) (AccessScope, error)

AccessScopeFromLipsdk maps public lipsdk access scopes into ABI scopes.

type AccountingAuthority

type AccountingAuthority string
const (
	AccountingAuthorityUnknown       AccountingAuthority = ""
	AccountingAuthorityAuthoritative AccountingAuthority = "authoritative"
	AccountingAuthorityEstimated     AccountingAuthority = "estimated"
	AccountingAuthorityDelegated     AccountingAuthority = "delegated"
	AccountingAuthorityAdvisory      AccountingAuthority = "advisory"
)

type AccountingEvidence

type AccountingEvidence struct {
	InputTokens      *int64
	OutputTokens     *int64
	CacheReadTokens  *int64
	CacheWriteTokens *int64
	ReasoningTokens  *int64
	TotalTokens      *int64
	Presence         UsagePresence
	Source           AccountingSource
	Authority        AccountingAuthority
	Plane            AccountingPlane
	DedupeKey        string
}

AccountingEvidence is host-only provider billing evidence and is never a canonical stream event. DedupeKey identifies one provider charge.

type AccountingEvidenceSource

type AccountingEvidenceSource interface {
	DrainAccountingEvidence() []AccountingEvidence
}

AccountingEvidenceSource is the internal seam used to drain host-only evidence without yielding it from the canonical EventStream.

type AccountingEvidenceV2

type AccountingEvidenceV2 struct {
	Observation    metering.Observation
	Coverage       EvidenceCoverage
	CoverageReason string
}

AccountingEvidenceV2 is host-only provider evidence. Observation is the canonical metering DTO; this wrapper adds a bounded capability disposition so a V1 bridge cannot be mistaken for full-fidelity V2 support.

func AccountingEvidenceV2FromProto

func AccountingEvidenceV2FromProto(p *backendpluginv1.AccountingEvidenceV2) (AccountingEvidenceV2, error)

AccountingEvidenceV2FromProto converts the V2 host-only wrapper.

func AccountingEvidenceV2FromV1

func AccountingEvidenceV2FromV1(e AccountingEvidence, id V1EvidenceIdentity) (AccountingEvidenceV2, error)

AccountingEvidenceV2FromV1 is a descriptive alias for LiftAccountingEvidenceV1.

func LiftAccountingEvidenceV1

func LiftAccountingEvidenceV1(e AccountingEvidence, id V1EvidenceIdentity) (AccountingEvidenceV2, error)

LiftAccountingEvidenceV1 creates an explicitly partial V2 observation. The six legacy counters are losslessly mapped to directional token components; missing multimodal, charge, qualifier and safe-lexeme detail remains absent.

func (AccountingEvidenceV2) Validate

func (e AccountingEvidenceV2) Validate() error

Validate checks the wrapper and delegates economic identity, decimal, component, coverage and safe-lexeme rules to metering.Observation.

type AccountingEvidenceV2Source

type AccountingEvidenceV2Source interface {
	DrainAccountingEvidenceV2() []AccountingEvidenceV2
}

AccountingEvidenceV2Source is the host-only drain seam for typed economic observations. Implementations must return copies and retain no caller-owned mutable buffers.

type AccountingPlane

type AccountingPlane string
const (
	AccountingPlaneUnknown          AccountingPlane = ""
	AccountingPlaneProviderBillable AccountingPlane = "provider_billable"
)

type AccountingSource

type AccountingSource string
const (
	AccountingSourceUnknown          AccountingSource = ""
	AccountingSourceProviderReported AccountingSource = "provider_reported"
	AccountingSourceProviderCountAPI AccountingSource = "provider_count_api"
	AccountingSourceLocalEstimator   AccountingSource = "local_estimator"
	AccountingSourceLocalTokenizer   AccountingSource = "local_tokenizer"
)

type BillingFinalizer

type BillingFinalizer interface {
	// FinalizeBilling finalizes billing for an attempt lineage idempotently.
	FinalizeBilling(ctx context.Context, req FinalizeBillingRequest) (FinalizeBillingResponse, error)
}

BillingFinalizer is an optional advertised billing finalization capability.

type CancelMode

type CancelMode = lipapi.CancelMode

CancelMode reports how cancellation was performed (alias of lipapi.CancelMode).

const (
	CancelModeUnspecified CancelMode = ""
	CancelModeNone        CancelMode = lipapi.CancelModeNone
	CancelModeProvider    CancelMode = lipapi.CancelModeProvider
	CancelModeTransport   CancelMode = lipapi.CancelModeTransport
	CancelModeCloseOnly   CancelMode = lipapi.CancelModeCloseOnly
)

type CancelOutcome

type CancelOutcome struct {
	Acknowledged bool
	Detail       string
	Reason       CancelReason
	Mode         CancelMode
}

CancelOutcome reports cancellation handling.

func CancelOutcomeFromProto

func CancelOutcomeFromProto(p *backendpluginv1.CancelOutcome) (*CancelOutcome, error)

CancelOutcomeFromProto converts cancel outcomes.

type CancelReason

type CancelReason string

CancelReason classifies cancellation.

const (
	CancelReasonUnspecified CancelReason = ""
	CancelReasonClient      CancelReason = "client"
	CancelReasonHost        CancelReason = "host"
	CancelReasonDeadline    CancelReason = "deadline"
	CancelReasonShutdown    CancelReason = "shutdown"
)

type CanonicalEvent

type CanonicalEvent struct {
	Kind             EventKind
	MessageIndex     *int32
	Delta            *string
	Signature        *string
	Opaque           []byte
	ToolCallID       *string
	ToolName         *string
	Usage            *UsageEvidence
	Warning          *string
	Error            *PluginError
	ImageRef         *string
	FileRef          *string
	ReasoningDialect *string
	ReasoningOpaque  []byte

	// ReasoningSummary, ReasoningContent, and ReasoningEncryptedContent preserve
	// exact OpenAI Responses reasoning-item fields with absent/null/value presence.
	// Additive v1.3 fields gated by FeatureExactOpenResponsesFields.
	ReasoningSummary          RawJSON
	ReasoningContent          RawJSON
	ReasoningEncryptedContent RawJSON
}

CanonicalEvent is one ordered stream event payload (sequence lives on the frame).

func CanonicalEventFromLipapi

func CanonicalEventFromLipapi(ev lipapi.Event) *CanonicalEvent

CanonicalEventFromLipapi maps a canonical stream event into the plugin wire DTO.

func CanonicalEventFromProto

func CanonicalEventFromProto(p *backendpluginv1.CanonicalEvent) (*CanonicalEvent, error)

CanonicalEventFromProto converts stream events.

type CapabilitySummary

type CapabilitySummary struct {
	Streaming          bool
	Tools              bool
	Vision             bool
	Documents          bool
	StructuredOutputs  bool
	Reasoning          bool
	ReasoningReplay    bool
	ParallelToolCalls  bool
	OrderedItems       bool
	ItemReferences     bool
	Compaction         bool
	AssistantPhase     bool
	OpaqueExtensions   bool
	VideoInput         bool
	Annotations        bool
	AssistantMediaRefs bool
}

CapabilitySummary summarizes canonical backend capabilities.

func CapabilitySummaryFromLipapi

func CapabilitySummaryFromLipapi(caps lipapi.BackendCaps) CapabilitySummary

CapabilitySummaryFromLipapi maps canonical backend caps into plugin DTO form.

type ClientFrame

type ClientFrame struct {
	Kind                 ClientFrameKind
	Sequence             uint64
	InstanceID           string
	Invocation           *Invocation
	CancelReason         CancelReason
	CancelDeadlineUnixMS int64
}

ClientFrame is a host-to-plugin Execute frame.

func ClientFrameFromProto

func ClientFrameFromProto(p *backendpluginv1.ExecuteClientFrame) (ClientFrame, error)

ClientFrameFromProto converts host-to-plugin frames.

func (ClientFrame) ValidateShape

func (f ClientFrame) ValidateShape() error

ValidateShape reports whether the client frame kind matches an exclusive payload.

type ClientFrameKind

type ClientFrameKind string

ClientFrameKind is a host-to-plugin Execute frame kind.

const (
	ClientFrameUnspecified ClientFrameKind = ""
	ClientFrameStart       ClientFrameKind = "start"
	ClientFrameCancel      ClientFrameKind = "cancel"
	ClientFrameCloseInput  ClientFrameKind = "close_input"
)

type ConfigureRequest

type ConfigureRequest struct {
	InstanceID       string
	FactoryKind      string
	ConfigYAML       []byte
	Secrets          SecretBundle
	RuntimePolicy    RuntimePolicy
	Negotiation      Negotiation
	NegotiationToken string
}

ConfigureRequest configures one backend instance after negotiation and peer auth. External plugin configure receives only opaque ConfigYAML, Secrets, RuntimePolicy, and negotiation metadata — never *http.Client, internal identity, or a registry.

func ConfigureRequestFromProto

func ConfigureRequestFromProto(p *backendpluginv1.ConfigureRequest, neg Negotiation) (ConfigureRequest, error)

ConfigureRequestFromProto converts configure wire input. Negotiation is domain-only and must be supplied by the host after Negotiate.

func (ConfigureRequest) Validate

func (r ConfigureRequest) Validate() error

Validate reports whether configure may proceed.

type ConfiguredInstance

type ConfiguredInstance interface {
	// Resolve returns static or model-aware capability profiles.
	Resolve(ctx context.Context, modelID *string) (ResolvedProfile, error)
	// ListModels returns a bounded inventory snapshot when advertised.
	ListModels(ctx context.Context, maxModels uint32) (ListModelsResponse, error)
	// Execute runs one bidirectional attempt stream.
	Execute(stream ExecuteStream) error
	// Close releases instance resources.
	Close(ctx context.Context) error
}

ConfiguredInstance is one configured backend factory instance.

type CountTokensRequest

type CountTokensRequest struct {
	InstanceID string
	ModelID    string
	Invocation Invocation
}

CountTokensRequest asks a plugin to count tokens for an invocation.

func CountTokensRequestFromProto

func CountTokensRequestFromProto(p *backendpluginv1.CountTokensRequest) (CountTokensRequest, error)

CountTokensRequestFromProto converts count requests.

type CountTokensResponse

type CountTokensResponse struct {
	InputTokens     *int64
	Presence        UsagePresence
	EvidenceQuality string
}

CountTokensResponse returns count evidence with presence.

func CountTokensResponseFromProto

func CountTokensResponseFromProto(p *backendpluginv1.CountTokensResponse) (CountTokensResponse, error)

CountTokensResponseFromProto converts count results.

type CredentialMode

type CredentialMode = lipsdk.BackendCredentialMode

CredentialMode is the closed credential posture for a factory export. Wire values match lipsdk.BackendCredentialMode; Validate() is the ABI gate.

const (
	CredentialModeUnspecified CredentialMode = ""
	CredentialModeStatic      CredentialMode = lipsdk.CredentialStatic
	CredentialModeWorkload    CredentialMode = lipsdk.CredentialWorkload
	CredentialModeOAuthUser   CredentialMode = lipsdk.CredentialOAuthUser
	CredentialModeNone        CredentialMode = lipsdk.CredentialNone
	CredentialModeUnknown     CredentialMode = lipsdk.CredentialUnknown
)

func CredentialModeFromLipsdk

func CredentialModeFromLipsdk(m lipsdk.BackendCredentialMode) (CredentialMode, error)

CredentialModeFromLipsdk maps public lipsdk registration modes into ABI modes.

type DialectRequirementDTO

type DialectRequirementDTO struct {
	Kind        string
	Dialect     string
	Implementor string
}

DialectRequirementDTO identifies an exact dialect requirement on the plugin ABI.

type DialectSupport

type DialectSupport struct {
	ItemDialects       []DialectRequirementDTO
	ReasoningDialects  []DialectRequirementDTO
	CompactionDialects []DialectRequirementDTO
	ExtensionTypes     []ExtensionRequirementDTO
}

DialectSupport carries exact dialect/extension support advertised by a plugin profile.

func DialectSupportFromLipapi

func DialectSupportFromLipapi(s lipapi.DialectSupport) DialectSupport

DialectSupportFromLipapi maps canonical dialect support into plugin DTO form.

type EconomicEvidenceSource

type EconomicEvidenceSource interface {
	DrainEconomicEvidence() []AccountingEvidenceV2
}

EconomicEvidenceSource is a neutral alias for AccountingEvidenceV2Source.

type EconomicEvidenceV2

type EconomicEvidenceV2 = AccountingEvidenceV2

EconomicEvidenceV2 is an additive alias used by connector authors.

type EconomicObservation

type EconomicObservation = metering.Observation

EconomicObservation is a source-compatible name for the canonical V2 DTO. There is intentionally no second observation model in backendplugin.

type ErrorCode

type ErrorCode string

ErrorCode classifies plugin errors.

const (
	ErrorCodeUnspecified        ErrorCode = ""
	ErrorCodeInvalidArgument    ErrorCode = "invalid_argument"
	ErrorCodeUnauthenticated    ErrorCode = "unauthenticated"
	ErrorCodePermissionDenied   ErrorCode = "permission_denied"
	ErrorCodeNotFound           ErrorCode = "not_found"
	ErrorCodeResourceExhausted  ErrorCode = "resource_exhausted"
	ErrorCodeFailedPrecondition ErrorCode = "failed_precondition"
	ErrorCodeAborted            ErrorCode = "aborted"
	ErrorCodeUnavailable        ErrorCode = "unavailable"
	ErrorCodeInternal           ErrorCode = "internal"
	ErrorCodeProviderTransient  ErrorCode = "provider_transient"
	ErrorCodeProviderTerminal   ErrorCode = "provider_terminal"
	ErrorCodeProtocolViolation  ErrorCode = "protocol_violation"
	ErrorCodeCancelled          ErrorCode = "cancelled"
)

type EventKind

type EventKind = lipapi.EventKind

EventKind identifies a canonical stream event (alias of lipapi.EventKind). Validate() rejects values outside the ABI wire subset (no reasoning_part on the plugin ABI).

const (
	EventUnspecified             EventKind = ""
	EventResponseStarted         EventKind = lipapi.EventResponseStarted
	EventMessageStarted          EventKind = lipapi.EventMessageStarted
	EventTextDelta               EventKind = lipapi.EventTextDelta
	EventReasoningDelta          EventKind = lipapi.EventReasoningDelta
	EventReasoningSignatureDelta EventKind = lipapi.EventReasoningSignatureDelta
	EventReasoningOpaqueDelta    EventKind = lipapi.EventReasoningOpaqueDelta
	EventReasoningPart           EventKind = lipapi.EventReasoningPart
	EventToolCallStarted         EventKind = lipapi.EventToolCallStarted
	EventToolCallArgsDelta       EventKind = lipapi.EventToolCallArgsDelta
	EventToolCallFinished        EventKind = lipapi.EventToolCallFinished
	EventUsageDelta              EventKind = lipapi.EventUsageDelta
	EventWarning                 EventKind = lipapi.EventWarning
	EventError                   EventKind = lipapi.EventError
	EventResponseFinished        EventKind = lipapi.EventResponseFinished
	EventAssistantImageRef       EventKind = lipapi.EventAssistantImageRef
	EventAssistantFileRef        EventKind = lipapi.EventAssistantFileRef
)

type EvidenceCoverage

type EvidenceCoverage string

EvidenceCoverage records whether a connector transported the complete V2 evidence contract or an explicitly reduced compatibility projection.

const (
	EvidenceCoverageComplete    EvidenceCoverage = "complete"
	EvidenceCoveragePartial     EvidenceCoverage = "partial"
	EvidenceCoverageUnsupported EvidenceCoverage = "unsupported"
)

type ExecuteStream

type ExecuteStream interface {
	// Context is the stream lifetime context.
	Context() context.Context
	// Recv returns the next host-to-plugin frame or a terminal read error.
	Recv() (ClientFrame, error)
	// Send sends one plugin-to-host frame.
	Send(frame ServerFrame) error
}

Session.Execute uses that optional close seam to unblock caller-owned streams before joining its client-to-server pump. For legacy streams without Close, the caller owns cancellation of Context; Session cannot cancel an arbitrary caller-owned context without changing this public interface. Such streams must therefore return from Recv when their Context is cancelled.

type ExtensionRequirementDTO

type ExtensionRequirementDTO struct {
	Namespace   string
	Type        string
	Implementor string
}

ExtensionRequirementDTO identifies a required extension type on the plugin ABI.

type FactoryDescriptor

type FactoryDescriptor struct {
	Kind                      string
	DisplayName               string
	Description               string
	CredentialMode            CredentialMode
	AccessScope               AccessScope
	RoutePrefixes             []string
	SupportsCountTokens       bool
	SupportsFinalizeBilling   bool
	SupportsDynamicInventory  bool
	SupportsModelAwareProfile bool
	ProcessSharing            ProcessSharing
	Experimental              bool
	Deprecated                bool
	StaticCapabilities        CapabilitySummary
	TransportCapabilities     TransportCapabilitySummary
	// SupportsAccountingEvidenceV2 is an explicit descriptor capability. The
	// negotiated feature remains the transport authority for each session.
	SupportsAccountingEvidenceV2 bool
}

FactoryDescriptor is generic export metadata for one factory kind.

type Feature

type Feature struct {
	// Name is the feature identifier.
	Name string
	// Required means the peer must understand the feature or negotiation fails.
	Required bool
}

Feature is a negotiable protocol feature advertisement.

type FinalizeBillingRequest

type FinalizeBillingRequest struct {
	InstanceID     string
	ALegID         string
	BLegID         string
	ModelID        string
	Reason         string
	IdempotencyKey string
}

FinalizeBillingRequest finalizes billing for an immutable attempt lineage.

func FinalizeBillingRequestFromProto

func FinalizeBillingRequestFromProto(p *backendpluginv1.FinalizeBillingRequest) (FinalizeBillingRequest, error)

FinalizeBillingRequestFromProto converts finalize requests.

func (FinalizeBillingRequest) Validate

func (r FinalizeBillingRequest) Validate() error

Validate reports finalize request completeness.

type FinalizeBillingResponse

type FinalizeBillingResponse struct {
	Usage           UsageEvidence
	EvidenceQuality string
	// AccountingV2 retains every provider observation returned by the finalizer.
	// It is host-only and may include multiple charge events for one attempt.
	AccountingV2 []AccountingEvidenceV2
}

FinalizeBillingResponse returns billing/usage evidence.

func FinalizeBillingResponseFromProto

func FinalizeBillingResponseFromProto(p *backendpluginv1.FinalizeBillingResponse) (FinalizeBillingResponse, error)

FinalizeBillingResponseFromProto converts finalize results.

type GRPCServer

type GRPCServer struct {
	backendpluginv1.UnimplementedBackendPluginServer

	PluginOffer ProtocolOffer
	Service     Service
	// contains filtered or unexported fields
}

GRPCServer adapts a public Service to the generated BackendPlugin gRPC contract. It does not launch processes; hosts supply transport separately.

Concurrency/security limitation (Phase 1 helper): negotiation tokens and instances are stored in this server's process memory and are not bound to a live connection/session. Do not share one GRPCServer across mutually untrusted clients without an outer session boundary. Phase 3 replaces this with a connection-scoped host.

Negotiate incompatibility (mismatched major/required features/transport policy) is returned as a NegotiateResponse with Compatible=false and a nil RPC error. Malformed wire/protocol offers return gRPC InvalidArgument.

func NewGRPCServer

func NewGRPCServer(offer ProtocolOffer, svc Service) *GRPCServer

NewGRPCServer constructs a registration/dispatch adapter around svc.

func (*GRPCServer) CloseInstance

CloseInstance closes a configured instance when no execute leases remain. The map entry is retained until Close succeeds so a failed Close remains retryable. Waiters are woken via leaseCond when leases drop or an in-flight close finishes. Context cancellation while waiting for leases clears the closing mark so later Close can retry.

func (*GRPCServer) Configure

Configure creates and stores a configured instance bound to a prior negotiation token. The negotiation token is consumed atomically under the server mutex before Service.Configure runs. Fail-closed: a consumed token is not restored when ConfigureRequestFromProto or Service.Configure fails.

func (*GRPCServer) CountTokens

CountTokens delegates when the instance implements TokenCounter.

func (*GRPCServer) Describe

Describe returns the plugin descriptor.

func (*GRPCServer) Execute

Execute bridges a bidirectional gRPC stream to ConfiguredInstance.Execute.

func (*GRPCServer) GracefulShutdown

GracefulShutdown acknowledges drain requests.

func (*GRPCServer) Health

Health returns serving status.

func (*GRPCServer) ListModels

ListModels returns inventory when supported.

func (*GRPCServer) Negotiate

Negotiate validates the host offer, negotiates against the plugin offer, and on a compatible outcome mints a negotiation_token bound to the negotiated set.

func (*GRPCServer) RenewPromptCache

FinalizeBilling delegates when the instance implements BillingFinalizer.

func (*GRPCServer) ResolveProfile

ResolveProfile resolves capabilities for an instance.

type GenerationOptions

type GenerationOptions struct {
	MaxOutputTokens    *uint32
	TemperatureMillis  *int32
	ReasoningEffort    *string
	ParallelToolCalls  *bool
	ResponseMIMEType   *string
	ResponseSchemaJSON RawJSON
}

GenerationOptions carries optional generation controls with presence.

type GracefulShutdownRequest

type GracefulShutdownRequest struct {
	DrainTimeoutMS int64
}

GracefulShutdownRequest asks the plugin to drain.

func GracefulShutdownRequestFromProto

func GracefulShutdownRequestFromProto(p *backendpluginv1.GracefulShutdownRequest) GracefulShutdownRequest

GracefulShutdownFromProto converts shutdown request/response.

type GracefulShutdownResponse

type GracefulShutdownResponse struct {
	Accepted bool
}

GracefulShutdownResponse acknowledges shutdown.

func GracefulShutdownResponseFromProto

func GracefulShutdownResponseFromProto(p *backendpluginv1.GracefulShutdownResponse) GracefulShutdownResponse

GracefulShutdownResponseFromProto converts shutdown response.

type HealthResponse

type HealthResponse struct {
	Serving bool
	Detail  string
}

HealthResponse reports plugin health.

func HealthResponseFromProto

func HealthResponseFromProto(p *backendpluginv1.HealthResponse) HealthResponse

HealthResponseFromProto converts health.

type Invocation

type Invocation struct {
	RequestID        string
	AttemptID        string
	ALegID           string
	BLegID           string
	CanonicalModelID string
	NativeModelID    string
	Instructions     []Message
	Messages         []Message
	Tools            []ToolDef
	ToolChoice       *string
	Options          GenerationOptions
	SafeMetadata     map[string]string
	// ProxyOwnedSessionID is injected by the proxy host from lipapi.Call.Session.
	// It is not client metadata and must not be populated from SafeMetadata.
	ProxyOwnedSessionID string

	// PromptCacheKey is a source-compatible legacy alias. SemanticExtensions is
	// the sole authority for new carrier-aware paths; bridges reject conflicting
	// values rather than choosing between two representations.
	PromptCacheKey     string
	SemanticExtensions []SemanticExtension

	// Ordered-item ABI fields (protocol minor >= ProtocolMinorOrderedItems).
	Operation            string
	DeliveryMode         string
	TransportMode        string
	ItemAuthority        bool
	Items                []InvocationItem
	ProtocolRequirements ProtocolRequirements
}

Invocation is the canonical attempt payload for execute/count.

func InvocationFromProto

func InvocationFromProto(p *backendpluginv1.Invocation) (Invocation, error)

InvocationFromProto converts a wire invocation.

func (Invocation) Validate

func (inv Invocation) Validate() error

Validate reports whether the invocation is well-formed and within bounds. It uses the same mapper as CallFromInvocation.

type InvocationCompactionItem

type InvocationCompactionItem struct {
	EncapsulatedID string
	Dialect        string
	Implementor    string
	Opaque         RawJSON
	// EncryptedContent is the exact provider compaction blob (pinned profile
	// encrypted_content). Additive v1.3 field gated by FeatureExactOpenResponsesFields.
	EncryptedContent string
}

InvocationCompactionItem carries compaction payload on an ordered item.

type InvocationContentPart

type InvocationContentPart struct {
	Kind           PartKind
	Text           *string
	ImageRef       *string
	ImageMIME      *string
	FileRef        *string
	FileMIME       *string
	FileName       *string
	VideoRef       *string
	VideoMIME      *string
	Reasoning      *InvocationReasoningPart
	Refusal        *string
	Summary        *string
	AnnotationType *string
	AnnotationData RawJSON
	AssistantRef   *string

	// FileData carries an inline base64 file payload (pinned profile file_data).
	// Additive v1.3 field gated by FeatureExactOpenResponsesFields.
	FileData *string

	// ExtensionType and ExtensionData preserve an opaque vendor-prefixed custom
	// content part (ContentPartExtension) losslessly. ExtensionType is the
	// prefixed wire discriminator; ExtensionData is the full raw part object.
	// Additive v1.3 fields gated by FeatureExactOpenResponsesFields.
	ExtensionType *string
	ExtensionData RawJSON
	// ExtensionNamespace and ExtensionImplementor preserve canonical extension
	// identity metadata independently of the derived Type namespace.
	ExtensionNamespace   *string
	ExtensionImplementor *string
}

InvocationContentPart is one content fragment within an invocation item.

type InvocationExtensionItem

type InvocationExtensionItem struct {
	Namespace   string
	Type        string
	Implementor string
	Direction   string
	Opaque      RawJSON
}

InvocationExtensionItem carries opaque extension payload on an ordered item.

type InvocationItem

type InvocationItem struct {
	Kind          string
	ID            string
	Status        string
	Role          Role
	Phase         string
	Content       []InvocationContentPart
	ToolCall      *InvocationToolCall
	ToolResult    *InvocationToolResult
	ItemReference *InvocationItemReference
	Reasoning     *InvocationReasoningItem
	Compaction    *InvocationCompactionItem
	Extension     *InvocationExtensionItem
}

InvocationItem is one ordered item on the plugin ABI.

type InvocationItemReference

type InvocationItemReference struct {
	ID string
}

InvocationItemReference references a prior item by ID.

type InvocationReasoningItem

type InvocationReasoningItem struct {
	Dialect   *string
	Text      *string
	Signature *string
	Opaque    RawJSON

	// Summary, Content, and EncryptedContent preserve exact OpenAI Responses
	// reasoning-item fields with absent/null/value presence (RawJSON states).
	// Additive v1.3 fields gated by FeatureExactOpenResponsesFields.
	Summary          RawJSON
	Content          RawJSON
	EncryptedContent RawJSON
}

InvocationReasoningItem carries reasoning payload on an ordered item.

type InvocationReasoningPart

type InvocationReasoningPart struct {
	Dialect   *string
	Text      *string
	Signature *string
	Opaque    RawJSON

	// Summary, Content, and EncryptedContent preserve exact OpenAI Responses
	// reasoning-item fields with absent/null/value presence (RawJSON states).
	// Additive v1.3 fields gated by FeatureExactOpenResponsesFields.
	Summary          RawJSON
	Content          RawJSON
	EncryptedContent RawJSON
}

InvocationReasoningPart carries reasoning payload on the plugin ABI.

type InvocationToolCall

type InvocationToolCall struct {
	CallID    string
	Name      string
	Arguments RawJSON
}

InvocationToolCall carries tool call payload on the plugin ABI.

type InvocationToolResult

type InvocationToolResult struct {
	CallID          string
	Name            string
	Output          *string
	StructuredParts []InvocationContentPart
}

InvocationToolResult carries tool result payload on the plugin ABI.

type ListModelsResponse

type ListModelsResponse struct {
	Models             []ModelDescriptor
	InventorySource    string
	FetchedUnixMS      int64
	RefreshAfterUnixMS *int64
	ErrorCode          string
}

ListModelsResponse is a bounded inventory result.

func ListModelsResponseFromProto

func ListModelsResponseFromProto(p *backendpluginv1.ListModelsResponse) (ListModelsResponse, error)

ListModelsResponseFromProto converts inventory.

func (ListModelsResponse) Validate

func (r ListModelsResponse) Validate(maxModels uint32) error

Validate reports inventory size bounds.

type Message

type Message struct {
	Role  Role
	Parts []Part
}

Message is an ordered role + parts unit.

type ModeError

type ModeError struct {
	Code string
}

ModeError is a typed conformance/fake diagnostic with a stable Code.

func ModeErrorf

func ModeErrorf(code string, args ...any) ModeError

ModeErrorf builds a ModeError with a formatted Code.

func (ModeError) Error

func (e ModeError) Error() string

type ModelDescriptor

type ModelDescriptor struct {
	CanonicalModelID string
	NativeModelID    string
	DisplayName      string
	RoutePrefix      string
	FactoryKind      string
	Capabilities     CapabilitySummary
}

ModelDescriptor is one inventory row.

type Negotiation

type Negotiation struct {
	// Compatible is true when majors match and required features are mutual.
	Compatible bool
	// NegotiatedMinor is min(host.Minor, plugin.Minor).
	NegotiatedMinor uint32
	// EnabledFeatures is the sorted intersection of host-requested features present on the plugin.
	EnabledFeatures []string
	// RejectReason explains incompatibility when Compatible is false.
	RejectReason string
	// TransportPolicy is the accepted transport policy.
	TransportPolicy TransportPolicy
	// PluginMajor is the plugin-advertised major carried on NegotiateResponse.
	PluginMajor uint32
	// PluginMinor is the plugin-advertised minor carried on NegotiateResponse.
	PluginMinor uint32
	// PluginFeatures is the plugin-advertised feature set carried on NegotiateResponse.
	PluginFeatures []Feature
	// NegotiationToken binds a compatible outcome to a later ConfigureRequest (wire field).
	NegotiationToken string
}

Negotiation is the deterministic outcome of Negotiate.

func Negotiate

func Negotiate(host, plugin ProtocolOffer) (Negotiation, error)

Negotiate performs fail-closed domain protocol negotiation.

func NegotiationFromNegotiateResponse

func NegotiationFromNegotiateResponse(p *backendpluginv1.NegotiateResponse) (Negotiation, error)

NegotiationFromNegotiateResponse converts a wire negotiate response.

type OpenManagedStream

type OpenManagedStream func(ctx context.Context, inv Invocation, call lipapi.Call) (lipapi.ManagedEventStream, error)

OpenManagedStream opens an upstream managed event stream for one Execute attempt. ctx is the incoming plugin Execute stream context and must be respected for cancellation.

type OptionalExecuteStreamCloser

type OptionalExecuteStreamCloser interface {
	Close() error
}

ExecuteStream is the public bidirectional execute abstraction using DTOs only. Recv must return when Context is cancelled. Implementations that can block in Recv should also implement the optional interface:

OptionalExecuteStreamCloser is an optional stream interface for unblocking Recv.

type OptionalNegotiatedStream

type OptionalNegotiatedStream interface {
	Negotiation() Negotiation
}

OptionalNegotiatedStream is an optional ExecuteStream extension for inspecting the negotiated protocol capabilities.

type Part

type Part struct {
	Kind             PartKind
	Text             *string
	ImageRef         *string
	FileRef          *string
	ReasoningText    *string
	ReasoningDialect *string
	ReasoningOpaque  RawJSON
	ToolArgsJSON     RawJSON
	ToolCallID       *string
	ToolName         *string

	// ReasoningSummary, ReasoningContent, and ReasoningEncryptedContent preserve
	// exact OpenAI Responses reasoning-item fields with absent/null/value presence.
	// Additive v1.3 fields gated by FeatureExactOpenResponsesFields.
	ReasoningSummary          RawJSON
	ReasoningContent          RawJSON
	ReasoningEncryptedContent RawJSON
}

Part is one canonical content part with explicit optional fields.

type PartKind

type PartKind string

PartKind identifies a canonical content part.

const (
	PartKindUnspecified  PartKind = ""
	PartKindText         PartKind = "text"
	PartKindImageRef     PartKind = "image_ref"
	PartKindFileRef      PartKind = "file_ref"
	PartKindReasoning    PartKind = "reasoning"
	PartKindToolCall     PartKind = "tool_call"
	PartKindToolResult   PartKind = "tool_result"
	PartKindJSON         PartKind = "json"
	PartKindVideoRef     PartKind = "video_ref"
	PartKindRefusal      PartKind = "refusal"
	PartKindSummary      PartKind = "summary"
	PartKindAnnotation   PartKind = "annotation"
	PartKindAssistantRef PartKind = "assistant_ref"
	// PartKindExtension is an opaque vendor-prefixed custom content part preserved
	// losslessly (minor >= ProtocolMinorExactOpenResponsesFields).
	PartKindExtension PartKind = "extension"
)

type PluginDescriptor

type PluginDescriptor struct {
	ProtocolMajor uint32
	ProtocolMinor uint32
	PluginID      string
	Version       string
	BuildID       string
	Features      []Feature
	Factories     []FactoryDescriptor
}

PluginDescriptor describes a plugin executable and its factory exports.

func PluginDescriptorFromProto

func PluginDescriptorFromProto(p *backendpluginv1.PluginDescriptor) (PluginDescriptor, error)

PluginDescriptorFromProto converts a wire descriptor.

func (PluginDescriptor) Validate

func (d PluginDescriptor) Validate() error

Validate reports whether the descriptor is a valid v1 export table.

type PluginError

type PluginError struct {
	Code            ErrorCode
	Message         string
	Retryable       bool
	OutputCommitted bool
}

PluginError is a classified plugin error.

func PluginErrorFromProto

func PluginErrorFromProto(p *backendpluginv1.PluginError) (*PluginError, error)

PluginErrorFromProto converts a classified error.

type ProcessSharing

type ProcessSharing string

ProcessSharing declares the plugin process model.

const (
	ProcessSharingUnspecified    ProcessSharing = ""
	ProcessSharingPerInstance    ProcessSharing = "per_instance"
	ProcessSharingSharedArtifact ProcessSharing = "shared_artifact"
)

func (ProcessSharing) Validate

func (p ProcessSharing) Validate() error

type PromptCacheController

type PromptCacheController interface {
	RenewPromptCache(context.Context, promptcache.RenewRequest) (promptcache.RenewResponse, error)
	ReleasePromptCache(context.Context, promptcache.ReleaseRequest) error
}

type PromptCacheObservationSource

type PromptCacheObservationSource interface{ promptcache.ObservationSource }

type ProtocolOffer

type ProtocolOffer struct {
	// Major is the protocol major version.
	Major uint32
	// Minor is the protocol minor version.
	Minor uint32
	// Features is the advertised feature set.
	Features []Feature
	// DisableTransportRetries must be true on both sides.
	DisableTransportRetries bool
}

ProtocolOffer is one side's protocol advertisement.

func ProtocolOfferFromNegotiateRequest

func ProtocolOfferFromNegotiateRequest(p *backendpluginv1.NegotiateRequest) (ProtocolOffer, error)

ProtocolOfferFromNegotiateRequest converts a wire negotiate request into a host offer.

type ProtocolRequirements

type ProtocolRequirements struct {
	Capabilities       []string
	ItemDialects       []DialectRequirementDTO
	ReasoningDialects  []DialectRequirementDTO
	CompactionDialects []DialectRequirementDTO
	ExtensionTypes     []ExtensionRequirementDTO
}

ProtocolRequirements carries exact semantic/dialect/extension requirements on the plugin ABI.

type RawJSON

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

RawJSON is a presence-preserving opaque JSON carrier.

func RawJSONAbsentValue

func RawJSONAbsentValue() RawJSON

RawJSONAbsentValue returns an omitted raw JSON field.

func RawJSONFromBytes

func RawJSONFromBytes(b []byte) RawJSON

RawJSONFromBytes returns a present JSON value (empty or non-empty).

func RawJSONFromProto

func RawJSONFromProto(v *backendpluginv1.RawJSONValue) (RawJSON, error)

RawJSONFromProto converts a wire RawJSONValue. Nil means absent. Unset oneof and is_null=false fail closed.

func RawJSONNullValue

func RawJSONNullValue() RawJSON

RawJSONNullValue returns an explicit JSON null field.

func (RawJSON) Bytes

func (r RawJSON) Bytes() []byte

Bytes returns a copy of present JSON bytes, or nil when absent/null.

func (RawJSON) State

func (r RawJSON) State() RawJSONState

State returns the presence state.

func (RawJSON) Validate

func (r RawJSON) Validate(maxBytes uint64) error

Validate enforces size, syntax, and depth bounds for present values.

type RawJSONState

type RawJSONState int

RawJSONState distinguishes absent, JSON null, and present JSON bytes.

const (
	// RawJSONAbsent means the field was omitted.
	RawJSONAbsent RawJSONState = iota
	// RawJSONNull means the field was explicitly JSON null.
	RawJSONNull
	// RawJSONValue means the field contains empty or non-empty JSON bytes.
	RawJSONValue
)

type ResolvedProfile

type ResolvedProfile struct {
	Capabilities             CapabilitySummary
	TransportCapabilities    TransportCapabilitySummary
	DialectSupport           DialectSupport
	ReasoningReplaySupported bool
	RoutePrefixes            []string
	EnforceMaxOutput         bool
	MaxOutputTokens          *uint32
	SupportsCountTokens      bool
	SupportsFinalizeBilling  bool
	SupportsDynamicInventory bool
	EvidenceSource           string
	ProfileVersion           string
	PromptCacheProfile       promptcache.Profile
	// SupportsAccountingEvidenceV2 is the resolved instance capability bit.
	SupportsAccountingEvidenceV2 bool
}

ResolvedProfile is the capability/transport profile for an instance or model.

func ResolvedProfileFromProto

func ResolvedProfileFromProto(p *backendpluginv1.ResolvedProfile) (ResolvedProfile, error)

ResolvedProfileFromProto converts a resolved profile.

type Role

type Role = lipapi.Role

Role is a canonical message role (alias of lipapi.Role).

const (
	RoleUnspecified Role = ""
	RoleSystem      Role = lipapi.RoleSystem
	RoleDeveloper   Role = lipapi.RoleDeveloper
	RoleUser        Role = lipapi.RoleUser
	RoleAssistant   Role = lipapi.RoleAssistant
	RoleTool        Role = lipapi.RoleTool
)

type RuntimePolicy

type RuntimePolicy struct {
	MaxRequestBytes         uint64
	MaxStreamFrameBytes     uint64
	MaxPendingEvents        uint64
	RequestTimeoutMS        int64
	CancelDeadlineMS        int64
	DiagnosticsVerbosity    string
	MaxConcurrentExecutions uint32
	LocalOnly               bool
	AllowedEnvNames         []string
	DisableTransportRetries bool
}

RuntimePolicy is the stable DTO projection of host runtime policy for external executable plugins. Hosts must project policy into this type (and its wire form in api/backendplugin/v1) rather than sharing *http.Client, internal identity config, or mutable registries across the process boundary.

func RuntimePolicyFromProto

func RuntimePolicyFromProto(p *backendpluginv1.RuntimePolicy) RuntimePolicy

RuntimePolicyFromProto converts runtime policy.

type SecretBundle

type SecretBundle struct {
	Values map[string][]byte
}

SecretBundle carries configure-time secrets (never logged by this package).

type SemanticExtension

type SemanticExtension struct {
	Namespace   string
	Type        string
	Implementor string
	Direction   string
	Presence    SemanticExtensionPresence
	Data        RawJSON
}

SemanticExtension is the SDK form of lipapi.SemanticExtension.

type SemanticExtensionPresence

type SemanticExtensionPresence string
const (
	SemanticExtensionNull  SemanticExtensionPresence = "null"
	SemanticExtensionValue SemanticExtensionPresence = "value"
)

type ServerFrame

type ServerFrame struct {
	Kind          ServerFrameKind
	Sequence      uint64
	Event         *CanonicalEvent
	Diagnostic    string
	CancelOutcome *CancelOutcome
	Terminal      *Terminal
	Accounting    *AccountingEvidence
	// AccountingV2 is the additive typed V2 sideband. It is never a canonical
	// client event and is legal only after explicit feature negotiation.
	AccountingV2           *AccountingEvidenceV2
	PromptCacheObservation *promptcache.Observation
}

ServerFrame is a plugin-to-host Execute frame.

func ServerFrameFromProto

func ServerFrameFromProto(p *backendpluginv1.ExecuteServerFrame) (ServerFrame, error)

ServerFrameFromProto converts plugin-to-host frames.

func (ServerFrame) ValidateShape

func (f ServerFrame) ValidateShape() error

ValidateShape reports whether the server frame kind matches an exclusive payload.

type ServerFrameKind

type ServerFrameKind string

ServerFrameKind is a plugin-to-host Execute frame kind.

const (
	ServerFrameUnspecified            ServerFrameKind = ""
	ServerFrameAccepted               ServerFrameKind = "accepted"
	ServerFrameEvent                  ServerFrameKind = "event"
	ServerFrameDiagnostic             ServerFrameKind = "diagnostic"
	ServerFrameCancelOutcome          ServerFrameKind = "cancel_outcome"
	ServerFrameTerminal               ServerFrameKind = "terminal"
	ServerFrameAccountingEvidence     ServerFrameKind = "accounting_evidence"
	ServerFramePromptCacheObservation ServerFrameKind = "prompt_cache_observation"
)

type Service

type Service interface {
	// Describe returns plugin identity and factory exports.
	Describe(ctx context.Context) (PluginDescriptor, error)
	// Configure creates a configured instance after negotiation and peer authentication.
	Configure(ctx context.Context, req ConfigureRequest) (ConfiguredInstance, error)
}

Service is the public plugin authoring entrypoint before instance configuration.

type StreamValidator

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

StreamValidator enforces accepted-before-sequence, monotonic sequences, and one terminal.

func (*StreamValidator) Push

func (v *StreamValidator) Push(frame ServerFrame) error

Push validates one plugin-to-host frame against stream rules.

type Terminal

type Terminal struct {
	Status TerminalStatus
	Error  *PluginError
}

Terminal ends an execute attempt exactly once.

func TerminalFromProto

func TerminalFromProto(p *backendpluginv1.Terminal) (*Terminal, error)

TerminalFromProto converts terminals.

type TerminalStatus

type TerminalStatus string

TerminalStatus is the execute terminal outcome.

const (
	TerminalUnspecified TerminalStatus = ""
	TerminalSuccess     TerminalStatus = "success"
	TerminalFailure     TerminalStatus = "failure"
	TerminalCancelled   TerminalStatus = "cancelled"
)

type TokenCounter

type TokenCounter interface {
	// CountTokens estimates tokens for an invocation.
	CountTokens(ctx context.Context, req CountTokensRequest) (CountTokensResponse, error)
}

TokenCounter is an optional advertised counting capability.

type ToolDef

type ToolDef struct {
	Name           string
	Description    string
	ParametersJSON RawJSON
}

ToolDef describes a tool the model may call.

type TransportCapabilitySummary

type TransportCapabilitySummary struct {
	Keepalive           bool
	Cancellation        bool
	BidirectionalStream bool
}

TransportCapabilitySummary summarizes transport capabilities.

type TransportPolicy

type TransportPolicy struct {
	// DisableAutomaticRetries must be true; transport retries are prohibited.
	DisableAutomaticRetries bool
	// MaxMessageBytes is the whole-message ceiling.
	MaxMessageBytes uint64
	// MaxStreamFrameBytes is the per-frame ceiling and must be <= MaxMessageBytes.
	MaxStreamFrameBytes uint64
}

TransportPolicy encodes host/plugin transport constraints for the ABI.

func DefaultTransportPolicy

func DefaultTransportPolicy() TransportPolicy

DefaultTransportPolicy returns the required v1 transport policy.

func (TransportPolicy) Validate

func (p TransportPolicy) Validate() error

Validate reports whether the transport policy satisfies ABI requirements.

type UsageEvidence

type UsageEvidence struct {
	InputTokens      *int64
	OutputTokens     *int64
	CacheReadTokens  *int64
	CacheWriteTokens *int64
	ReasoningTokens  *int64
	TotalTokens      *int64
	Presence         UsagePresence
	RawUsageJSON     RawJSON
}

UsageEvidence is canonical usage/billing evidence with explicit presence.

func UsageEvidenceFromProto

func UsageEvidenceFromProto(p *backendpluginv1.UsageEvidence) (UsageEvidence, error)

UsageEvidenceFromProto converts wire usage evidence.

func (UsageEvidence) ValidatePresence

func (u UsageEvidence) ValidatePresence() error

ValidatePresence ensures counters and presence flags agree and raw JSON is bounded.

type UsageEvidenceBuffer

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

UsageEvidenceBuffer is the connector-local bridge for the negotiated V1 accounting sideband. It carries only the six presence-aware token counters; the host owns B-leg/store binding and any V2 identity or native measure lifting. Provider adapters must keep unsupported cost, media, gauge, and revision detail out of this bridge rather than coercing it into tokens.

The buffer is safe for a stream reader and the forwarding coordinator to use concurrently. Exact replay is ignored; changed payloads remain available as separate V1 records so the host can apply its own source-key policy.

func NewUsageEvidenceBuffer

func NewUsageEvidenceBuffer() *UsageEvidenceBuffer

NewUsageEvidenceBuffer creates a stream-local V1 accounting bridge.

func (*UsageEvidenceBuffer) AccountingEvidenceEnabled

func (b *UsageEvidenceBuffer) AccountingEvidenceEnabled() bool

AccountingEvidenceEnabled reports whether this bridge is negotiated for the current connector session. Producers use it when projecting canonical usage events: an enabled sideband owns the durable key, while a disabled bridge leaves that key available to the legacy canonical capture path.

func (*UsageEvidenceBuffer) AddUsageEvent

func (b *UsageEvidenceBuffer) AddUsageEvent(event lipapi.Event, fallbackDedupeKey string)

AddUsageEvent adds a provider-billable usage event when every represented counter has explicit presence. Invalid, client-visible, unknown-source, or otherwise unsafe events are omitted; the canonical event remains the source of any non-V1 detail and no value is inferred here.

func (*UsageEvidenceBuffer) DrainAccountingEvidence

func (b *UsageEvidenceBuffer) DrainAccountingEvidence() []AccountingEvidence

DrainAccountingEvidence returns immutable copies of pending V1 records.

func (*UsageEvidenceBuffer) SetEnabled

func (b *UsageEvidenceBuffer) SetEnabled(enabled bool)

SetEnabled controls whether this bridge emits V1 sideband records. A connector sets it from the negotiated host feature before reading a stream; disabling also discards any constructor-seeded records so a legacy host cannot receive an unnegotiated host-only frame.

type UsagePresence

type UsagePresence = lipapi.UsagePresence

UsagePresence records which usage counters were explicitly supplied (alias of lipapi.UsagePresence).

func UsagePresenceFromProto

func UsagePresenceFromProto(p *backendpluginv1.UsagePresence) UsagePresence

UsagePresenceFromProto converts usage presence flags.

type V1EvidenceIdentity

type V1EvidenceIdentity struct {
	StoreID        string
	ObservationID  string
	SourceEventKey string
	Revision       uint64
	StreamID       string
	Sequence       uint64
	Subject        metering.SubjectRef
	Correlation    metering.CorrelationV2
	Scope          scope.PrincipalScopeView
	ObservedAt     time.Time
	ReceivedAt     time.Time
	MappingRef     string
}

V1EvidenceIdentity supplies trusted host-owned identity while lifting the representable token counters from the legacy sideband. Provider request evidence must carry a concrete B-leg; the bridge never invents one.

Directories

Path Synopsis
Package conformance defines advertised-capability-only checks for backend plugins.
Package conformance defines advertised-capability-only checks for backend plugins.
Package host provides the supported public construction path for executable backend-plugin contract clients.
Package host provides the supported public construction path for executable backend-plugin contract clients.
Package manifest defines the closed public v1 installation metadata model for executable backend plugins.
Package manifest defines the closed public v1 installation metadata model for executable backend plugins.

Jump to

Keyboard shortcuts

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