Documentation
¶
Overview ¶
Package lipapi defines the canonical public contracts shared across frontends, backends, and future external integrations.
Ownership: this package is a stable contract surface, not the application policy core. Add canonical request, event, capability, and error shapes here. Keep routing, recovery, attempt lineage, extension-stage orchestration, and other product policy in internal/core. Do not import internal packages, provider SDKs, the stdhttp server layer, or composition roots from here; those stay at the edge or in the core (see internal/archtest).
Tool-call and assistant history (requirements 8.x): only a documented subset of provider-specific tool history is round-tripped through Message and Part values today. OpenAI Chat and OpenAI Responses frontends implement the supported shapes; other frontends may ignore or normalize unsupported tool rows. See frontend package docs next to each adapter for the exact supported subset per protocol.
Streaming assistant multimodal references: EventAssistantImageRef and EventAssistantFileRef carry URL- or id-style refs (see Event fields) and aggregate into Collected.AssistantMedia. Parity matrices: .kiro/specs/archive/llm-api-parity/design.md.
Index ¶
- Constants
- Variables
- func ApplyNegotiatedDowngrades(c *Call, down NegotiationResult)
- func CallReasoningPayloadBytes(c *Call) int64
- func CheckProjectionFeasibility(call Call, target LegacyProjectionTarget) error
- func CloneCollectedInto(dst, src *Collected)
- func DeriveExtensionNamespace(wireType string) string
- func HasExplicitCompletion(items []Item) bool
- func IsAllCandidatesContextLimitExceeded(err error) bool
- func IsExplicitCompletionItem(item Item) bool
- func IsExplicitCompletionToolName(name string) bool
- func IsHookMutation(err error) bool
- func IsPolicyDecisionError(err error) bool
- func IsPolicyDenied(err error) bool
- func IsPolicyFailure(err error) bool
- func IsPolicyMalformed(err error) bool
- func IsProjectionError(err error) bool
- func IsRecoverablePreOutput(err error) bool
- func IsReject(err error) bool
- func IsSessionDenial(err error) bool
- func JoinInstructionText(insts []Message) string
- func NewSessionDenialInvalidAuthority(internalReason string) error
- func NewSessionDenialMandatoryAuditFailure(internalReason string) error
- func NewSessionDenialMissingPrincipal(internalReason string) error
- func NewSessionDenialOwnerMismatch(internalReason string) error
- func NewSessionDenialPolicyUnavailable(internalReason string) error
- func NewSessionDenialQuarantined(internalReason string) error
- func NewSessionDenialResumeExpired(internalReason string) error
- func NewSessionDenialStorageUnavailable(internalReason string) error
- func NewSessionDenialWorkspace(internalReason string) error
- func NewStreamError(code, message string) error
- func NormalizeClientMessage(s string) string
- func OutputCommitted(ev Event) bool
- func ProjectLegacyToOrderedItems(call Call, target OrderedItemProjectionTarget) ([]Item, ProtocolRequirements, error)
- func ReasoningHasExactResponsesFields(rp *ReasoningPart) bool
- func ReasoningPayloadBytes(rp *ReasoningPart) int
- func ReconcileToolChoiceAfterToolListChange(c *Call)
- func RecoverablePreOutputError(err error) error
- func RequiresProjectionAdaptation(call Call, caps BackendCaps) bool
- func SaturatingAddInt64(a, b int64) int64
- func SessionDenialPublicCode(err error) string
- func StripDataURLBase64(dataURL string) (mime, b64 string, ok bool)
- func ValidateEventEnvelope(ev *Event) error
- func ValidateEventSequence(events []Event) error
- func ValidateToolChoice(tc ToolChoice, tools []ToolDef) error
- func WalkCallContentParts(c Call, fn func(item Item, part ContentPart) error) error
- func WalkCallItems(c Call, fn func(item Item) error) error
- func WalkCallOpaqueData(c Call, fn func(field string, data []byte) error) error
- func WalkCallTexts(c Call, fn func(field string, text string) error) error
- type ALegCancelRequest
- type AnnotationPart
- type AssistantPhase
- type AttemptOutcome
- type AttemptRecord
- type BackendCaps
- type BackendTransportCaps
- type Call
- type CancelCause
- type CancelKind
- type CancelMode
- type CancelResult
- type CandidateAdmissionInput
- type CandidateAdmissionResult
- type Capability
- type CapabilitySet
- type CloseOnlyManagedStream
- type CollectLimits
- type Collected
- type CompactionItem
- type ContentPart
- type ContentPartKind
- type DeliveryMode
- type DialectRequirement
- type DialectSupport
- type Event
- type EventKind
- type EventStream
- type ExtensionContentPart
- type ExtensionRequirement
- type FixedEventStream
- type GenerationOptions
- type HookMutationError
- type Invocation
- type Item
- type ItemKind
- type ItemReference
- type ItemStatus
- type LegacyProjectionResult
- type LegacyProjectionTarget
- type ManagedEventStream
- type Message
- type NegotiationKind
- type NegotiationResult
- type OpaqueExtension
- type Operation
- type OperationTransportSupport
- type OrderedItemProjectionTarget
- type OutputPhase
- type Part
- type PartKind
- type PolicyDecisionError
- func NewPolicyDeniedError(stage, providerID, reasonCode, clientCategory, clientMessage string, ...) *PolicyDecisionError
- func NewPolicyFailureError(stage, providerID, reasonCode, clientCategory, clientMessage string, ...) *PolicyDecisionError
- func NewPolicyMalformedError(stage, providerID, reasonCode, clientCategory, clientMessage string, ...) *PolicyDecisionError
- func PolicyDecisionErrorFrom(err error) *PolicyDecisionError
- type PolicyDecisionErrorKind
- type ProjectionError
- type ProjectionReason
- type ProtocolRequirements
- func DeriveCandidateRequirements(call Call, caps BackendCaps, target LegacyProjectionTarget) (ProtocolRequirements, error)
- func DeriveProtocolRequirements(c Call) ProtocolRequirements
- func NormalizeProtocolRequirements(r ProtocolRequirements) ProtocolRequirements
- func UnionProtocolRequirements(a, b ProtocolRequirements) ProtocolRequirements
- type ReasoningDialect
- type ReasoningItem
- type ReasoningPart
- type ReasoningReplaySupport
- type RejectError
- type RequirementsMatchResult
- type RequirementsRejectError
- type Role
- type RouteIntent
- type ScopedUsageDelta
- type SemanticExtension
- type SemanticExtensionPresence
- type SessionDenialCode
- type SessionDenialError
- type SessionRef
- type StreamError
- type TokenizerRef
- type ToolCallItem
- type ToolCallSummary
- type ToolCategory
- type ToolChoice
- type ToolChoiceMode
- type ToolDef
- type ToolEvent
- type ToolEventKind
- type ToolResultItem
- type TransportFallbackPolicy
- type TransportMode
- type TransportModeSet
- type TransportNegotiationResult
- type TransportRejectError
- type UpstreamFailureError
- type UsageAccountingMetadata
- type UsageAuthority
- type UsageEvidenceSource
- type UsagePlane
- type UsagePresence
- type UsageSource
- type ValidationError
- type VerbosityLevel
Examples ¶
Constants ¶
const ( MaxCallIDBytes = 512 MaxRouteSelectorBytes = 64 * 1024 MaxClientSessionIDBytes = 4 * 1024 MaxContinuityKeyBytes = 4 * 1024 MaxALegIDBytes = 4 * 1024 // MaxAuthoritativeSessionIDBytes bounds proxy-owned session ids (opaque strings). MaxAuthoritativeSessionIDBytes = 4 * 1024 // MaxResumeTokenBytes bounds bearer resume proofs presented on the canonical call (decoded by frontends). MaxResumeTokenBytes = 8 * 1024 MaxMessages = 4_096 MaxInstructionMessages = 1_024 MaxPartsPerMessage = 2_048 MaxTools = 2_048 MaxToolNameBytes = 256 MaxToolDescriptionBytes = 32 * 1024 MaxToolParametersBytes = 256 * 1024 MaxExtensionKeys = 256 MaxExtensionKeyBytes = 256 MaxExtensionValueBytes = 4 * 1024 * 1024 // Part content: align with typical HTTP request body caps (8 MiB) for text/JSON; // ref fields are path/URL length limits. MaxPartTextBytes = 8 * 1024 * 1024 MaxPartJSONBytes = 8 * 1024 * 1024 MaxRefStringBytes = 8 * 1024 // MaxFileDataBytes bounds inline file payloads (pinned profile input_file // file_data base64). It matches the part text cap so a single inline file // cannot force unbounded allocations. MaxFileDataBytes = MaxPartTextBytes // Canonical streaming Event field caps (adapter/hook mutations). MaxEventDeltaBytes = MaxPartTextBytes // TextDelta, ReasoningDelta, ToolCallArgsDelta MaxEventDiagMessageBytes = 4 << 20 // WarningMessage, ErrorMessage per event MaxEventCodeFieldBytes = MaxRefStringBytes // WarningCode, ErrorCode when non-empty MaxReasoningDialectBytes = MaxRefStringBytes MaxReasoningTextBytes = MaxPartTextBytes MaxReasoningSignatureBytes = MaxRefStringBytes MaxReasoningOpaqueBytes = MaxPartJSONBytes MaxReasoningPartsPerMessage = MaxPartsPerMessage MaxReasoningBytesPerCall = MaxPartTextBytes MaxItems = 4_096 MaxItemKindBytes = 64 MaxItemStatusBytes = 64 MaxAssistantPhaseBytes = 64 MaxItemReferenceIDBytes = 512 MaxCompactionDialectBytes = 8192 // MaxCompactionEncryptedContentBytes bounds the provider compaction blob on a // compaction item (pinned profile encrypted_content). Aligned with the 8 MiB // part cap so a single opaque blob cannot force unbounded allocations. MaxCompactionEncryptedContentBytes = MaxPartJSONBytes MaxExtensionNamespaceBytes = 256 MaxExtensionTypeBytes = 256 MaxExtensionImplementorBytes = 256 MaxExtensionDirectionBytes = 64 MaxExtensionDataBytes = 4 * 1024 * 1024 MaxSemanticExtensions = 64 MaxSemanticExtensionDataBytes = MaxExtensionDataBytes MaxContentPartsPerItem = 2_048 MaxJSONDepth = 64 // MaxAllowedToolRefs bounds the OpenResponses allowed_tools subset size to // the pinned wire schema maxLen (128 refs). MaxAllowedToolRefs = 128 )
Envelope size limits for Call validation. They bound how much work a single request can force in the core and protect against pathological or hostile clients. Frontends also cap raw HTTP body size; these apply to the decoded canonical call.
const ( SemanticExtensionDirectionRequest = "request" SemanticExtensionDirectionResponse = "response" SemanticExtensionDirectionBidirectional = "bidirectional" )
SemanticExtension directions are intentionally closed. A carrier must state which edge owns its value so it cannot become an unscoped envelope channel.
const MaxClientMessageBytes = 256
MaxClientMessageBytes is the wire-safe byte bound for PolicyDecisionError.ClientMessage (design §Evidence Normalization Contract; requirements 5.4, 7.7). It is the single source of truth shared with pkg/lipsdk/policydecision so the wire and evidence paths cannot diverge.
const MaxOptionStringBytes = 4 * 1024
ReasoningEffort / MIME strings and similar option strings.
Variables ¶
var ErrAllCandidatesContextLimitExceeded = errors.New("lipapi: all route candidates excluded by context limit")
ErrAllCandidatesContextLimitExceeded is returned when every evaluated route candidate was excluded before upstream open because known context limits are below the conservative request-size estimate (pre-output routing only).
var ErrAllCandidatesExcluded = errors.New("lipapi: all route candidates excluded: candidate_excluded")
ErrAllCandidatesExcluded is returned when every evaluated route candidate was excluded by attempt transforms with a non-canonical (but sanitized) reason.
var ErrAllCandidatesUnrepresentableReplay = errors.New("lipapi: all route candidates excluded: unrepresentable_replay")
ErrAllCandidatesUnrepresentableReplay is returned when every evaluated route candidate was excluded by attempt transforms with the canonical unrepresentable_replay reason.
var ErrCapabilityReject = errors.New("lipapi: capability reject")
ErrCapabilityReject is the stable root error for hard capability rejects.
var ErrCollectLimitExceeded = errors.New("lipapi: collect limit exceeded")
ErrCollectLimitExceeded is returned when stream aggregation in Collect would exceed the configured CollectLimits.
var ErrHookMutation = errors.New("lipapi: hook mutation invalid")
ErrHookMutation is the stable root for hook-produced canonical mutations that fail validation.
var ErrInvalidCall = errors.New("lipapi: invalid canonical call")
ErrInvalidCall is the shared root for call validation failures.
var ErrMaxRouteAttempts = errors.New("lipapi: routing max_attempts exhausted")
ErrMaxRouteAttempts is returned when routing.max_attempts would be exceeded by another B-leg.
var ErrNilContext = errors.New("lipapi: nil Context")
ErrNilContext is returned when a nil context.Context is passed to Recv, Collect, or other APIs that require a non-nil Context (same rule as context package: never pass nil; use context.Background if no cancellation/deadline is needed).
var ErrNilEventStream = errors.New("lipapi: nil EventStream")
ErrNilEventStream is returned by Collect, CollectUnbounded, and CollectWithLimits when the EventStream argument is nil.
var ErrNilFixedEventStream = errors.New("lipapi: nil FixedEventStream")
ErrNilFixedEventStream is returned by (*FixedEventStream).Recv when the receiver is nil.
var ErrPolicyDenied = errors.New("lipapi: policy denied")
ErrPolicyDenied is the stable root for policy denials before backend output and for active-stream policy denials after output (requirements 5.1, 5.6). It is distinct from capability, session, backend, auth, and internal error roots.
var ErrPolicyFailure = errors.New("lipapi: policy failure")
ErrPolicyFailure is the stable root for policy decision provider failures handled through configured fail-open/fail-closed behavior (requirements 6.1, 6.5, 7.2).
var ErrPolicyMalformed = errors.New("lipapi: malformed policy decision")
ErrPolicyMalformed is the stable root for malformed policy decisions: unknown stages, unknown outcomes, unknown effects, or illegal outcome/effect pairs (requirements 1.5, 6.6, 7.2).
var ErrProjectionNotRepresentable = errors.New("lipapi: projection not representable")
ErrProjectionNotRepresentable is returned when a projector cannot represent call semantics in the target view.
var ErrRecoverablePreOutput = errors.New("lipapi: recoverable pre-output upstream failure")
ErrRecoverablePreOutput is a stable sentinel for upstream failures that the core may swallow and retry on another route candidate before client-visible output begins.
var ErrSessionDenial = errors.New("lipapi: session denied")
ErrSessionDenial is the stable root for secure-session and resume denials before backend work.
var ErrStreamTerminal = errors.New("lipapi: stream error")
ErrStreamTerminal is the stable root for terminal upstream stream error events (EventError).
var ErrTTFTTimeout = errors.New("lipapi: time to first token timeout")
ErrTTFTTimeout is returned when a route-level time-to-first-token budget expires before output commits.
var ErrTransportReject = errors.New("lipapi: transport capability reject")
ErrTransportReject is returned when a backend lacks required operation+transport support.
var ErrUnresolvedModelOnlySelector = errors.New("lipapi: model-only route selector without default backend")
ErrUnresolvedModelOnlySelector is returned when a model-only route selector cannot be resolved because no default backend was configured.
Functions ¶
func ApplyNegotiatedDowngrades ¶
func ApplyNegotiatedDowngrades(c *Call, down NegotiationResult)
ApplyNegotiatedDowngrades mutates c.Options to strip capabilities classified as soft downgrade by Negotiate. Call only when NegotiationResult.Kind == NegotiationDowngrade.
func CallReasoningPayloadBytes ¶
CallReasoningPayloadBytes returns the saturating sum of reasoning Text+Signature+Opaque lengths across the normalized call trajectory (dialect and non-reasoning content excluded).
func CheckProjectionFeasibility ¶
func CheckProjectionFeasibility(call Call, target LegacyProjectionTarget) error
CheckProjectionFeasibility verifies that call semantics can be projected into target before upstream work.
func CloneCollectedInto ¶
func CloneCollectedInto(dst, src *Collected)
CloneCollectedInto copies the interior of src into dst. dst's Text/Reasoning builders are reset first, so writing into them is safe even if dst carried prior content. dst must outlive any use of its builders.
func DeriveExtensionNamespace ¶
DeriveExtensionNamespace deterministically derives the namespace of a prefixed wire extension discriminator from its leading segment before the first ':' or '/'. This mirrors the operator dialect declarations used by exact extension admission (namespace "acme" for wire type "acme:widget"). Types without a separator return the whole trimmed type unchanged.
func HasExplicitCompletion ¶
HasExplicitCompletion reports whether items contain at least one correlated completed explicit completion signal. A valid signal requires a completed ToolCall with an explicit name AND a matching completed ToolResult with the same CallID. Call-only, orphan, malformed, failed, or in-progress items return false and fall back to normal semantic policy.
func IsAllCandidatesContextLimitExceeded ¶
IsAllCandidatesContextLimitExceeded reports whether err is or wraps ErrAllCandidatesContextLimitExceeded.
func IsExplicitCompletionItem ¶
IsExplicitCompletionItem reports whether item is a valid explicit completion signal. Requirements for a valid signal:
- Kind is ToolCall
- ToolCall non-nil, CallID non-empty after trim, Name matches explicit set
- Arguments if present must be valid JSON (malformed -> false)
Absent, nameless, unknown, or malformed items return false and fall back to normal semantic policy per requirements 5.7/7.1.
func IsExplicitCompletionToolName ¶
IsExplicitCompletionToolName reports whether name, after trim and case-fold, matches a known explicit completion alias. Exact-match only, no substring or provider-specific logic.
func IsHookMutation ¶
IsHookMutation reports whether err is or wraps a HookMutationError or ErrHookMutation.
func IsPolicyDecisionError ¶
IsPolicyDecisionError reports whether err is or wraps a *PolicyDecisionError or one of the stable policy error roots (requirement 5.6, 7.2).
func IsPolicyDenied ¶
IsPolicyDenied reports whether err is or wraps a policy denial.
func IsPolicyFailure ¶
IsPolicyFailure reports whether err is or wraps a policy failure.
func IsPolicyMalformed ¶
IsPolicyMalformed reports whether err is or wraps a malformed policy decision.
func IsProjectionError ¶
IsProjectionError reports whether err is or wraps a ProjectionError.
func IsRecoverablePreOutput ¶
IsRecoverablePreOutput reports whether err should allow another backend attempt before client-visible output has been committed for the active attempt.
func IsSessionDenial ¶
IsSessionDenial reports whether err is or wraps a *SessionDenialError or ErrSessionDenial.
func JoinInstructionText ¶
JoinInstructionText concatenates non-empty text parts from a slice of system-style instruction messages, separated by a blank line, and trims outer whitespace. Non-text parts and empty/whitespace-only text parts are skipped.
func NewSessionDenialInvalidAuthority ¶
NewSessionDenialInvalidAuthority returns a denial for malformed, unrecognized, or non-proxy-issued resume proof.
func NewSessionDenialMandatoryAuditFailure ¶
NewSessionDenialMandatoryAuditFailure returns a denial when mandatory audit prerequisites fail before output.
func NewSessionDenialMissingPrincipal ¶
NewSessionDenialMissingPrincipal returns a denial when no trustworthy authenticated principal is available.
func NewSessionDenialOwnerMismatch ¶
NewSessionDenialOwnerMismatch returns a denial when the session owner does not match the authenticated user.
func NewSessionDenialPolicyUnavailable ¶
NewSessionDenialPolicyUnavailable returns a denial when required per-session policy metadata cannot be loaded.
func NewSessionDenialQuarantined ¶
NewSessionDenialQuarantined returns a denial when the session was quarantined and cannot be reused.
func NewSessionDenialResumeExpired ¶
NewSessionDenialResumeExpired returns a denial when resume is outside the allowed window.
func NewSessionDenialStorageUnavailable ¶
NewSessionDenialStorageUnavailable returns a denial when durable session storage is required but unavailable.
func NewSessionDenialWorkspace ¶
NewSessionDenialWorkspace returns a denial when workspace policy rejects the session.
func NewStreamError ¶
NewStreamError returns a *StreamError for propagation from adapters and encoders.
func NormalizeClientMessage ¶
NormalizeClientMessage returns a wire-safe, bounded copy of s: newline/tab and other Unicode control characters are removed, the result is trimmed, and it is truncated to MaxClientMessageBytes on a UTF-8 rune boundary. Empty input returns "".
It enforces the Decision Contract invariant that ClientMessage is safe for wire use (design §Decision Contract) at construction, and is reused by the evidence normalizer so observers/logs and client-facing messages apply identical bounds.
func OutputCommitted ¶
OutputCommitted reports whether ev is the first class of canonical stream item that commits the active attempt for failover purposes (no silent retry afterward).
Aligned with streaming-first execution: lifecycle frames alone do not commit; user-visible deltas and tool argument streaming do.
EventReasoningSignatureDelta is intentionally excluded: it is Anthropic integrity metadata that arrives after reasoning text (which already commits), not user-visible output content.
EventReasoningOpaqueDelta commits: redacted_thinking is a first-class content block that can arrive without a preceding reasoning_delta.
EventReasoningPart commits: a complete dialect-tagged reasoning part is first-class content (exact historical reasoning) and must block retry/failover.
func ProjectLegacyToOrderedItems ¶
func ProjectLegacyToOrderedItems(call Call, target OrderedItemProjectionTarget) ([]Item, ProtocolRequirements, error)
ProjectLegacyToOrderedItems constructs ordered items from a legacy message-authority call.
func ReasoningHasExactResponsesFields ¶
func ReasoningHasExactResponsesFields(rp *ReasoningPart) bool
ReasoningHasExactResponsesFields reports whether rp carries any official OpenResponses reasoning-item fields rather than only the legacy text carrier.
func ReasoningPayloadBytes ¶
func ReasoningPayloadBytes(rp *ReasoningPart) int
ReasoningPayloadBytes returns Text+Signature+Opaque byte length (dialect excluded).
func ReconcileToolChoiceAfterToolListChange ¶
func ReconcileToolChoiceAfterToolListChange(c *Call)
ReconcileToolChoiceAfterToolListChange adjusts ToolChoice after tools were removed or reordered so Call.Validate can succeed (R9). It mutates only c.ToolChoice.
Rules (deterministic):
- ToolChoiceNone with remaining tools → ToolChoiceAuto (tools survived filtering).
- ToolChoiceRequired with no tools, or required name missing from Tools → ToolChoiceAuto, Name cleared.
- Empty Mode → treated as ToolChoiceAuto after normalization.
func RequiresProjectionAdaptation ¶
func RequiresProjectionAdaptation(call Call, caps BackendCaps) bool
RequiresProjectionAdaptation reports whether call authority differs from the candidate view.
func SaturatingAddInt64 ¶
SaturatingAddInt64 returns a+b clamped at math.MaxInt64 (negatives treated as 0).
func SessionDenialPublicCode ¶
SessionDenialPublicCode returns the stable SessionDenialCode for err when it wraps *SessionDenialError.
func StripDataURLBase64 ¶
StripDataURLBase64 parses a "data:<mime>;base64,<payload>" URL and returns the mime type and base64 body. ok is false when the input is not a base64 data URL.
func ValidateEventEnvelope ¶
ValidateEventEnvelope applies maximum sizes and kind-specific structural checks to canonical event fields (codec output, backend mapping, or hook mutations) so one stream chunk cannot force unbounded allocations. It does not mutate ev.
func ValidateEventSequence ¶
ValidateEventSequence checks ordering rules for a replayed event slice. A well-formed sequence ends with EventResponseFinished or EventError after EventResponseStarted.
func ValidateToolChoice ¶
func ValidateToolChoice(tc ToolChoice, tools []ToolDef) error
ValidateToolChoice checks tool choice against declared tools.
func WalkCallContentParts ¶
func WalkCallContentParts(c Call, fn func(item Item, part ContentPart) error) error
WalkCallContentParts visits every ContentPart in c's normalized item trajectory.
func WalkCallItems ¶
WalkCallItems visits every Item in c's normalized trajectory.
func WalkCallOpaqueData ¶
WalkCallOpaqueData visits all raw JSON/opaque data blobs across items/extensions for redaction and inspection.
Types ¶
type ALegCancelRequest ¶
type ALegCancelRequest struct {
ALegID string
SessionID string
ResumeToken string
FrontendID string
Reason string
}
ALegCancelRequest is the frontend-to-core request for explicit A-leg cancellation.
func (ALegCancelRequest) Trimmed ¶
func (r ALegCancelRequest) Trimmed() ALegCancelRequest
type AnnotationPart ¶
type AnnotationPart struct {
Type string `json:"type,omitempty"`
Data json.RawMessage `json:"data,omitempty"`
}
AnnotationPart holds annotation metadata for text/content.
type AssistantPhase ¶
type AssistantPhase string
AssistantPhase identifies assistant output phase (commentary vs final answer).
const ( AssistantPhaseCommentary AssistantPhase = "commentary" AssistantPhaseFinalAnswer AssistantPhase = "final_answer" )
type AttemptOutcome ¶
type AttemptOutcome string
AttemptOutcome classifies how a single B-leg attempt ended for lineage and diagnostics.
const ( AttemptSuccess AttemptOutcome = "success" AttemptSwallowedFailure AttemptOutcome = "swallowed_failure" AttemptSurfacedFailure AttemptOutcome = "surfaced_failure" AttemptCancelled AttemptOutcome = "cancelled" )
type AttemptRecord ¶
type AttemptRecord struct {
BLegID string
ALegID string
Seq int
BackendID string
EffectiveModel string
StartedAt time.Time
FinishedAt time.Time
Outcome AttemptOutcome
Reason string
}
AttemptRecord is one row of B2BUA attempt lineage (protocol-neutral).
type BackendCaps ¶
type BackendCaps map[Capability]struct{}
BackendCaps is a set of capabilities supported by a backend adapter instance.
func NewBackendCaps ¶
func NewBackendCaps(caps ...Capability) BackendCaps
NewBackendCaps builds a set for negotiation helpers and tests.
Example ¶
package main
import (
"fmt"
"github.com/matdev83/go-llm-interactive-proxy/pkg/lipapi"
)
func main() {
caps := lipapi.NewBackendCaps(lipapi.CapabilityStreaming, lipapi.CapabilityTools)
_, hasStream := caps[lipapi.CapabilityStreaming]
_, hasVision := caps[lipapi.CapabilityVision]
fmt.Println(hasStream, hasVision)
}
Output: true false
type BackendTransportCaps ¶
type BackendTransportCaps map[Operation]TransportModeSet
BackendTransportCaps is the operation+transport capability surface for one backend adapter.
func NewBackendTransportCaps ¶
func NewBackendTransportCaps(entries ...OperationTransportSupport) BackendTransportCaps
NewBackendTransportCaps builds transport caps for negotiation helpers and tests.
func (BackendTransportCaps) DeclaredFor ¶
func (c BackendTransportCaps) DeclaredFor(op Operation) bool
DeclaredFor reports whether transport support was explicitly declared for an operation.
func (BackendTransportCaps) Supports ¶
func (c BackendTransportCaps) Supports(op Operation, mode TransportMode) bool
Supports reports whether an operation+transport pair is explicitly declared.
type Call ¶
type Call struct {
ID string
Session SessionRef
Route RouteIntent
Instructions []Message
Messages []Message
Items []Item
// PreviousResponseID identifies a proxy-owned continuation parent. It allows
// an item-authoritative continuation request to carry an intentionally empty
// input item slice; the continuation resolver supplies the materialized items.
PreviousResponseID string
// PromptCacheKey is a proxy-carried prompt-caching hint for the remote
// OpenResponses endpoint. It is protocol-neutral metadata (never a canonical
// trajectory control); the OpenResponses backend forwards it on compact
// requests so a schema-permitted client hint is never silently dropped.
PromptCacheKey string
// SemanticExtensions carries bounded residual semantics whose identity and
// presence participate in admission. PromptCacheKey is a source-compatible
// alias; when both forms are present they must agree.
SemanticExtensions []SemanticExtension
Tools []ToolDef
ToolChoice ToolChoice
Options GenerationOptions
Extensions map[string]json.RawMessage
Invocation Invocation `json:"-"`
// MaxPendingWireEvents caps backend adapter-internal pending event queues per stream (0 = unlimited).
// Not client API; the core executor sets this from server config when non-zero.
MaxPendingWireEvents int `json:"-"`
}
Call is the canonical request envelope shared across frontends.
func AdaptCallForCandidate ¶
func AdaptCallForCandidate(call Call, target LegacyProjectionTarget) (Call, error)
AdaptCallForCandidate projects the call into the candidate's authority/view when required.
func CloneCall ¶
CloneCall returns a deep copy of c suitable as an immutable baseline for per-attempt derivation.
func (Call) HasItemAuthority ¶
HasItemAuthority reports whether this call uses ordered item authority (non-nil Items slice).
func (Call) PromptCacheKeyValue ¶
PromptCacheKeyValue returns the one effective prompt-cache value. The legacy field is accepted only as an equal source-compatible alias to its carrier.
func (Call) Validate ¶
Validate checks canonical invariants and unsupported combinations for this call.
Example ¶
package main
import (
"fmt"
"github.com/matdev83/go-llm-interactive-proxy/pkg/lipapi"
)
func main() {
c := lipapi.Call{
ID: "call-1",
Messages: []lipapi.Message{{
Role: lipapi.RoleUser,
Parts: []lipapi.Part{lipapi.TextPart("ping")},
}},
}
if err := c.Validate(); err != nil {
fmt.Println("invalid:", err)
return
}
fmt.Println("valid")
}
Output: valid
type CancelCause ¶
type CancelCause struct {
Kind CancelKind
Detail string
}
CancelCause carries low-cardinality cancellation reason metadata across core and adapters.
type CancelKind ¶
type CancelKind string
CancelKind classifies why a proxy-owned A-leg or B-leg is being cancelled.
const ( CancelExplicit CancelKind = "explicit" CancelClientGone CancelKind = "client_gone" CancelContextDone CancelKind = "context_done" CancelRaceLoser CancelKind = "race_loser" )
type CancelMode ¶
type CancelMode string
CancelMode reports how a backend stream attempted to stop remote token generation.
const ( CancelModeNone CancelMode = "none" CancelModeProvider CancelMode = "provider" CancelModeTransport CancelMode = "transport" CancelModeCloseOnly CancelMode = "close_only" )
type CancelResult ¶
type CancelResult struct {
Mode CancelMode
Err error
}
CancelResult records adapter-level cancellation behavior for audit and billing reconciliation.
type CandidateAdmissionInput ¶
type CandidateAdmissionInput struct {
Call Call
Invocation Invocation
BackendCaps BackendCaps
TransportCaps BackendTransportCaps
TransportPolicy TransportFallbackPolicy
ReplaySupport ReasoningReplaySupport
DialectSupport DialectSupport
ProjectionTarget LegacyProjectionTarget
RequireProjection bool
// FrozenRequirements, when set, is the immutable baseline requirement set every
// candidate must satisfy; transforms must not weaken it during failover.
FrozenRequirements *ProtocolRequirements
}
CandidateAdmissionInput carries everything required to reject incompatible candidates before upstream work.
type CandidateAdmissionResult ¶
type CandidateAdmissionResult struct {
Kind NegotiationKind
Capability NegotiationResult
Transport TransportNegotiationResult
Requirements RequirementsMatchResult
ProjectionError error
}
CandidateAdmissionResult is the deterministic admission outcome for one candidate.
func AdmitCandidate ¶
func AdmitCandidate(in CandidateAdmissionInput) CandidateAdmissionResult
AdmitCandidate evaluates operation/transport, semantic capability, exact dialect, and projector feasibility.
func (CandidateAdmissionResult) Err ¶
func (r CandidateAdmissionResult) Err() error
Err returns the first hard reject error, if any.
type Capability ¶
type Capability string
Capability names the semantic features a frontend call may require and a backend may provide.
const ( CapabilityStreaming Capability = "streaming" CapabilityTools Capability = "tools" CapabilityVision Capability = "vision" CapabilityDocuments Capability = "documents" CapabilityStructuredOutputs Capability = "structured_outputs" CapabilityReasoning Capability = "reasoning" CapabilityReasoningReplay Capability = "reasoning_replay" // hard; required when historical reasoning parts are present CapabilityParallelToolCalls Capability = "parallel_tool_calls" // OpenResponses ordered-item semantic capabilities (Task 1.4). CapabilityOrderedItems Capability = "ordered_items" CapabilityAssistantPhase Capability = "assistant_phase" CapabilityVideoInput Capability = "video_input" CapabilityItemReferences Capability = "item_references" CapabilityCompaction Capability = "compaction" CapabilityOpaqueExtensions Capability = "opaque_extensions" CapabilityAnnotations Capability = "annotations" CapabilityAssistantMediaRefs Capability = "assistant_media_refs" )
func RequiredCapabilities ¶
func RequiredCapabilities(c Call) []Capability
RequiredCapabilities derives required capabilities from call shape.
type CapabilitySet ¶
type CapabilitySet struct {
Provides []Capability
}
CapabilitySet is a declared capability bundle for a plugin registration surface.
type CloseOnlyManagedStream ¶
type CloseOnlyManagedStream struct {
Stream EventStream
}
CloseOnlyManagedStream adapts streams with no provider-native cancel API into ManagedEventStream.
func (CloseOnlyManagedStream) Cancel ¶
func (s CloseOnlyManagedStream) Cancel(context.Context, CancelCause) CancelResult
func (CloseOnlyManagedStream) Close ¶
func (s CloseOnlyManagedStream) Close() error
type CollectLimits ¶
type CollectLimits struct {
MaxTextBytes int
MaxReasoningBytes int
MaxToolArgsTotalBytes int
MaxWarnings int
MaxAssistantMediaParts int // assistant_image_ref / assistant_file_ref events aggregated into Collected.AssistantMedia; 0 = unlimited
MaxAggregatePayloadBytes int // aggregate retained bytes across Text + Reasoning (delta + exact ReasoningPart payload) + ToolArgs; 0 = unlimited (backward-compatible). Overflow-safe.
}
CollectLimits bounds memory growth while aggregating streaming events into Collected. A zero value disables all limits (CollectUnbounded). Individual fields use zero to mean “no limit” for that dimension only when using CollectWithLimits with a partially filled struct.
func DefaultCollectLimits ¶
func DefaultCollectLimits() CollectLimits
DefaultCollectLimits returns conservative defaults for Collect (non-streaming aggregation).
type Collected ¶
type Collected struct {
Text strings.Builder
Reasoning strings.Builder
ToolArgs map[string]*strings.Builder // keyed by tool_call_id
// ToolNames maps tool_call_id to the function name from EventToolCallStarted.
ToolNames map[string]string
// ToolCallOrder is the order tool_call_ids first appear (started or first args delta).
ToolCallOrder []string
Warnings []string
InputTokens int
OutputTokens int
CacheReadTokens int
CacheWriteTokens int
ReasoningTokens int
TotalTokens int
CostNanoUnits int64
Currency string
CostSource string
TerminalError *Event
FinishReceived bool
// FinishReason is copied from the terminal EventResponseFinished when set.
FinishReason string
// AssistantMedia collects EventAssistantImageRef / EventAssistantFileRef in order.
AssistantMedia []Part
// ReasoningParts collects EventReasoningPart payloads in stream emission order.
// It does not encode placement among text/tool parts; feature observers own
// cross-part positioning for restore. Distinct from Reasoning, which aggregates
// progressive EventReasoningDelta text only.
ReasoningParts []ReasoningPart
}
Collected aggregates a canonical stream for non-streaming responses.
func CloneCollected ¶
CloneCollected returns a deep copy of a collected event aggregation.
The copy is heap-allocated and owned by the returned pointer, so its Text/Reasoning builders remain valid and writable after the call. Nil stays nil. Every mutable interior is independent of the source: tool-argument builders, name/order/warning maps and slices, assistant media parts, reasoning parts, and the terminal error event graph.
Use CloneCollectedInto when the result must be stored by value at a caller-owned address (the builders of that value host stay valid as long as the host object does).
func Collect ¶
func Collect(ctx context.Context, s EventStream) (Collected, error)
Collect drains a stream until a terminal event or an error using DefaultCollectLimits. Terminal success is EventResponseFinished. Terminal failure is EventError followed by optional EOF. ctx must be non-nil; nil returns ErrNilContext.
func CollectUnbounded ¶
func CollectUnbounded(ctx context.Context, s EventStream) (Collected, error)
CollectUnbounded aggregates without CollectLimits checks (legacy / testing only). ctx must be non-nil; nil returns ErrNilContext.
func CollectWithLimits ¶
func CollectWithLimits(ctx context.Context, s EventStream, limits CollectLimits) (out Collected, err error)
CollectWithLimits drains a stream until a terminal event or an error. Terminal success is EventResponseFinished. Terminal failure is EventError followed by optional EOF. ctx must be non-nil; nil returns ErrNilContext.
func (*Collected) AccumulateUsage ¶
func (Collected) OrderedToolCalls ¶
func (c Collected) OrderedToolCalls() []ToolCallSummary
OrderedToolCalls returns tool calls in first-seen order for stable encoding.
func (Collected) TotalOrDerived ¶
TotalOrDerived returns TotalTokens when present, otherwise derives a protocol-safe total from input and output token counts.
func (Collected) UncachedInputTokens ¶
UncachedInputTokens returns input tokens billed outside provider cache reads.
type CompactionItem ¶
type CompactionItem struct {
EncapsulatedID string `json:"encapsulated_id,omitempty"`
Dialect string `json:"dialect,omitempty"`
Implementor string `json:"implementor,omitempty"`
// EncryptedContent carries the provider compaction blob (pinned profile
// encrypted_content). It is protocol-neutral opaque data that the
// OpenResponses wire encoder renders verbatim on response.compaction output.
EncryptedContent string `json:"encrypted_content,omitempty"`
Opaque json.RawMessage `json:"opaque,omitempty"`
}
CompactionItem encapsulates a context compaction item within an item trajectory.
type ContentPart ¶
type ContentPart struct {
Kind ContentPartKind `json:"kind"`
Text string `json:"text,omitempty"`
ImageRef string `json:"image_ref,omitempty"`
ImageMIME string `json:"image_mime,omitempty"`
FileRef string `json:"file_ref,omitempty"`
FileData string `json:"file_data,omitempty"`
FileMIME string `json:"file_mime,omitempty"`
FileName string `json:"file_name,omitempty"`
VideoRef string `json:"video_ref,omitempty"`
VideoMIME string `json:"video_mime,omitempty"`
Refusal string `json:"refusal,omitempty"`
Reasoning *ReasoningPart `json:"reasoning,omitempty"`
Summary string `json:"summary,omitempty"`
Annotation *AnnotationPart `json:"annotation,omitempty"`
AssistantRef string `json:"assistant_ref,omitempty"`
// Extension carries a vendor-prefixed custom content part preserved
// opaquely when Kind is ContentPartExtension.
Extension *ExtensionContentPart `json:"extension,omitempty"`
}
ContentPart is one ordered content fragment within a canonical item.
type ContentPartKind ¶
type ContentPartKind string
ContentPartKind classifies canonical content part forms inside items.
const ( ContentPartText ContentPartKind = "text" ContentPartImageRef ContentPartKind = "image_ref" ContentPartFileRef ContentPartKind = "file_ref" ContentPartVideoRef ContentPartKind = "video_ref" ContentPartRefusal ContentPartKind = "refusal" ContentPartReasoning ContentPartKind = "reasoning" ContentPartSummary ContentPartKind = "summary" ContentPartAnnotation ContentPartKind = "annotation" ContentPartAssistantRef ContentPartKind = "assistant_ref" ContentPartJSON ContentPartKind = "json" ContentPartToolResult ContentPartKind = "tool_result" // ContentPartExtension is an opaque vendor-prefixed custom content part that // the canonical model cannot interpret but must preserve losslessly. Its // structured payload is carried as raw JSON (never stringified to text). ContentPartExtension ContentPartKind = "extension" )
type DeliveryMode ¶
type DeliveryMode string
DeliveryMode records whether the client requested streaming or non-streaming delivery.
const ( // DeliveryModeStreaming means the client requested incremental response delivery. DeliveryModeStreaming DeliveryMode = "streaming" // DeliveryModeNonStreaming means the client requested one completed response body. DeliveryModeNonStreaming DeliveryMode = "non_streaming" )
func DeliveryModeFromClientStream ¶
func DeliveryModeFromClientStream(stream bool) DeliveryMode
DeliveryModeFromClientStream converts protocol stream flags into canonical delivery mode metadata.
type DialectRequirement ¶
type DialectRequirement struct {
Kind string // "item", "reasoning", "compaction"
Dialect string
Implementor string
}
DialectRequirement identifies an exact item, reasoning, or compaction dialect a call requires.
type DialectSupport ¶
type DialectSupport struct {
ItemDialects []DialectRequirement
ReasoningDialects []DialectRequirement
CompactionDialects []DialectRequirement
ExtensionTypes []ExtensionRequirement
}
DialectSupport declares exact dialects a backend candidate can satisfy.
func NormalizeDialectSupport ¶
func NormalizeDialectSupport(s DialectSupport) DialectSupport
NormalizeDialectSupport normalizes dialect support slices deterministically.
type Event ¶
type Event struct {
Kind EventKind
MessageIndex int
Delta string
// Signature carries the Anthropic thinking-block signature on
// EventReasoningSignatureDelta; it is empty for other kinds.
Signature string
// Opaque carries provider opaque reasoning bytes on EventReasoningOpaqueDelta
// (Anthropic redacted_thinking JSON envelope). Empty for other kinds.
Opaque []byte
// Reasoning carries one complete dialect-tagged reasoning part on
// EventReasoningPart. Nil for other kinds. Callers must not mutate Opaque
// bytes after the event is handed to streams/collectors; receivers deep-copy.
Reasoning *ReasoningPart
// Item carries one complete canonical Item on EventItem (for example a
// compaction item preserved in a compacted ordered window). Nil for other
// kinds; EventItem events must not carry content-class fields. Receivers
// deep-copy before retaining.
Item *Item
ToolCallID string
ToolName string
// Usage fields apply to EventUsageDelta. InputTokens and OutputTokens are
// retained as the compatibility totals used by existing frontends.
InputTokens int
OutputTokens int
// CacheReadTokens are submitted/input tokens served from a provider cache.
CacheReadTokens int
// CacheWriteTokens are submitted/input tokens written to a provider cache.
CacheWriteTokens int
// ReasoningTokens are response/output tokens used for hidden reasoning or
// thinking when the provider reports them separately.
ReasoningTokens int
// TotalTokens is the provider-reported total when available.
TotalTokens int
// UsagePresence distinguishes explicitly reported zero counters from
// counters omitted by a partial provider response.
UsagePresence UsagePresence
// CostNanoUnits is a high-precision per-response cost amount in Currency.
// One whole currency unit is 1e9 nano-units.
CostNanoUnits int64
Currency string
CostSource string
// CostPresent distinguishes an explicitly reported monetary value (including
// authoritative zero) from a usage event that omits cost. CostSource alone
// is provenance metadata and must not imply a present monetary value.
CostPresent bool
// RawUsageJSON stores bounded provider usage metadata for audit/backfill.
RawUsageJSON string
// Accounting annotates the compatibility usage totals on EventUsageDelta.
Accounting UsageAccountingMetadata
// UsageScopes carries per-plane usage entries for EventUsageDelta.
UsageScopes []ScopedUsageDelta
WarningCode string
WarningMessage string
ErrorCode string
ErrorMessage string
// FinishReason is optional metadata on EventResponseFinished (vendor stop/finish taxonomy).
FinishReason string
// ResponseStatus is explicit terminal status on EventResponseFinished
// ("completed" or "incomplete"). It is authoritative when set: producers that
// know the upstream response status (for example an OpenResponses backend
// mapping an upstream resource whose status is "incomplete") set it so
// downstream state machines never have to infer incompleteness solely from
// FinishReason, which is ambiguous (a completed response may legitimately
// carry finish_reason "content_filter"). Empty means the producer left the
// terminal semantics to the frontend's legacy inference.
ResponseStatus string
// AssistantRef / AssistantMIME / AssistantName apply to EventAssistantImageRef and
// EventAssistantFileRef (same meaning as Part.ImageRef / Part.FileRef fields).
AssistantRef string
AssistantMIME string
AssistantName string
}
Event is one canonical streaming item.
func MergeToolEventInto ¶
MergeToolEventInto applies tool-reactor output onto a single canonical stream event. The event kind must match the tool event kind; only tool-call fields are updated.
type EventKind ¶
type EventKind string
EventKind identifies canonical stream events.
const ( EventResponseStarted EventKind = "response_started" EventMessageStarted EventKind = "message_started" EventTextDelta EventKind = "text_delta" EventReasoningDelta EventKind = "reasoning_delta" // EventReasoningSignatureDelta carries a provider-specific thinking-block // signature (Anthropic extended-thinking integrity metadata) as a canonical // carrier distinct from reasoning text. The value is provider-specific and is // ignored by non-Anthropic frontends via their default switch case; the carrier // is canonical. Mirrors the EventReasoningDelta precedent of carrying provider // reasoning text through the canonical stream. EventReasoningSignatureDelta EventKind = "reasoning_signature_delta" // EventReasoningOpaqueDelta carries a provider opaque reasoning payload // (Anthropic redacted_thinking envelope bytes). Non-Anthropic frontends ignore // it via their default switch case; the carrier is canonical. EventReasoningOpaqueDelta EventKind = "reasoning_opaque_delta" // EventReasoningPart carries one complete dialect-tagged historical reasoning // part (see Event.Reasoning). Distinct from EventReasoningOpaqueDelta (Anthropic // redacted_thinking byte stream) and from progressive EventReasoningDelta text. // Dialect must already be normalized; provider envelope schema is adapter-owned. EventReasoningPart EventKind = "reasoning_part" EventToolCallStarted EventKind = "tool_call_started" EventToolCallArgsDelta EventKind = "tool_call_args_delta" EventToolCallFinished EventKind = "tool_call_finished" EventUsageDelta EventKind = "usage_delta" EventWarning EventKind = "warning" EventError EventKind = "error" EventResponseFinished EventKind = "response_finished" // EventItem carries one complete validated canonical Item (for example a // provider compaction item in a compacted ordered window). It is a // standalone item carrier: it must not be treated as content-class output // and is not synthesized by legacy normalizers. The OR state machine maps it // into the canonical output trajectory; other frontends ignore it. EventItem EventKind = "item" // Assistant-side multimodal references (streaming). Adapters emit these instead of // overloading text_delta when the vendor returns image/file output items. EventAssistantImageRef EventKind = "assistant_image_ref" EventAssistantFileRef EventKind = "assistant_file_ref" )
type EventStream ¶
type EventStream interface {
Recv(ctx context.Context) (Event, error) // io.EOF means normal completion after terminal event
Close() error
}
EventStream is the primary execution result from backends and the executor. Implementations assume a single goroutine calls Recv until completion or error (no concurrent Recv on the same stream). Close may run concurrently with a blocked Recv only when the implementation documents that guarantee locally. See each concrete stream type for its Close/Recv concurrency contract.
Cancellation: Recv should respect ctx when the underlying source supports it (for example blocking on a channel that also selects on ctx.Done). Some vendor SDKs block without consulting ctx; in those cases Recv may remain blocked until Close unblocks the SDK. Callers that cancel ctx must still call Close (typically via defer right after obtaining the stream) so blocked reads and background work tear down promptly.
Recv requires a non-nil ctx (Go context contract). Passing nil returns ErrNilContext from core and reference implementations in this module; other implementations should follow the same rule or document divergent behavior.
type ExtensionContentPart ¶
type ExtensionContentPart struct {
Namespace string `json:"namespace,omitempty"`
Type string `json:"type"`
Implementor string `json:"implementor,omitempty"`
Data json.RawMessage `json:"data,omitempty"`
}
ExtensionContentPart carries a vendor-prefixed custom content part that the canonical model cannot interpret but must preserve losslessly. Type is the prefixed wire discriminator (for example "acme:input_file" or "acme.com/part"); Data is the full raw wire part object (including its type field) so encoding can emit it verbatim without stringifying the structured payload.
Namespace and Implementor are the exact ExtensionRequirement identity of the part. When Namespace is empty it is derived deterministically from the prefixed Type (the leading segment before the first ':' or '/'), matching the operator dialect declarations used by exact admission. Namespace and Implementor are canonical metadata; the wire object in Data remains the authoritative lossless carrier, so an explicit namespace that diverges from the deterministic derivation is merged into the emitted wire object rather than silently dropped.
type ExtensionRequirement ¶
ExtensionRequirement identifies a namespaced extension type a call requires.
type FixedEventStream ¶
type FixedEventStream struct {
// contains filtered or unexported fields
}
FixedEventStream is a finite stream for tests and in-memory adapters. It is not safe for concurrent Recv; use one consumer at a time. Recv on a nil *FixedEventStream returns ErrNilFixedEventStream. Close on nil returns nil.
func NewFixedEventStream ¶
func NewFixedEventStream(events []Event) *FixedEventStream
NewFixedEventStream returns a copied finite stream for tests and in-memory adapters.
Example ¶
package main
import (
"context"
"fmt"
"github.com/matdev83/go-llm-interactive-proxy/pkg/lipapi"
)
func main() {
ctx := context.Background()
st := lipapi.NewFixedEventStream([]lipapi.Event{
{Kind: lipapi.EventResponseStarted},
{Kind: lipapi.EventMessageStarted},
{Kind: lipapi.EventTextDelta, Delta: "hi"},
{Kind: lipapi.EventResponseFinished},
})
out, err := lipapi.Collect(ctx, st)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(out.Text.String())
}
Output: hi
func (*FixedEventStream) Cancel ¶
func (f *FixedEventStream) Cancel(context.Context, CancelCause) CancelResult
func (*FixedEventStream) Close ¶
func (f *FixedEventStream) Close() error
type GenerationOptions ¶
type GenerationOptions struct {
Temperature *float64
MaxOutputTokens *int
TopP *float64
ReasoningEffort string
Verbosity VerbosityLevel
ResponseMIMEType string
ParallelToolCalls *bool
}
GenerationOptions captures cross-protocol generation controls. Pointer fields mean "unset" (no override). Non-pointer strings use "" as unset; validation applies only when a field participates in an invariant (see validateOptionStrings).
func CloneGenerationOptions ¶
func CloneGenerationOptions(o GenerationOptions) GenerationOptions
CloneGenerationOptions returns a copy with independent pointer fields.
func MergeRouteQueryIntoGenerationOptions ¶
func MergeRouteQueryIntoGenerationOptions(base GenerationOptions, q url.Values) (GenerationOptions, error)
MergeRouteQueryIntoGenerationOptions overlays URL query parameters from a route primary onto base options. URI params are explicit routing directives and OVERRIDE any corresponding value already set on base (the per-request body/call settings). Keys absent from the query leave the base value unchanged.
Recognized keys (first value wins per key): temperature, top_p, max_output_tokens, reasoning_effort, verbosity, parallel_tool_calls (true/false/1/0).
type HookMutationError ¶
HookMutationError reports a part or event rewrite that violated canonical invariants.
func (*HookMutationError) Error ¶
func (e *HookMutationError) Error() string
func (*HookMutationError) Unwrap ¶
func (e *HookMutationError) Unwrap() error
type Invocation ¶
type Invocation struct {
Operation Operation
DeliveryMode DeliveryMode
TransportMode TransportMode
// ClientUserAgent is the trimmed inbound HTTP User-Agent captured by frontends.
// It is protocol-neutral invocation metadata and must not be serialized as provider JSON.
ClientUserAgent string `json:"-"`
}
Invocation carries protocol operation, delivery, and selected transport metadata from driving adapters to backends.
type Item ¶
type Item struct {
Kind ItemKind `json:"kind"`
ID string `json:"id,omitempty"`
Status ItemStatus `json:"status,omitempty"`
Role Role `json:"role,omitempty"`
Phase AssistantPhase `json:"phase,omitempty"`
Content []ContentPart `json:"content,omitempty"`
Reference *ItemReference `json:"reference,omitempty"`
ToolCall *ToolCallItem `json:"tool_call,omitempty"`
ToolResult *ToolResultItem `json:"tool_result,omitempty"`
Reasoning *ReasoningItem `json:"reasoning,omitempty"`
Compaction *CompactionItem `json:"compaction,omitempty"`
Extension *OpaqueExtension `json:"extension,omitempty"`
}
Item is one canonical ordered item in a conversation trajectory.
func NormalizedItems ¶
NormalizedItems returns the item trajectory for c. If c has item authority (len(c.Items) > 0), it returns c.Items. Otherwise, it projects legacy c.Instructions and c.Messages into a normalized slice of Item.
type ItemKind ¶
type ItemKind string
ItemKind classifies ordered canonical item types.
const ( ItemKindMessage ItemKind = "message" ItemKindItemReference ItemKind = "item_reference" ItemKindToolCall ItemKind = "tool_call" ItemKindToolResult ItemKind = "tool_result" ItemKindReasoning ItemKind = "reasoning" ItemKindCompaction ItemKind = "compaction" ItemKindExtension ItemKind = "extension" )
type ItemReference ¶
type ItemReference struct {
ID string `json:"id"`
}
ItemReference references a previously produced or existing item by ID.
type ItemStatus ¶
type ItemStatus string
ItemStatus identifies the lifecycle status of an item.
const ( ItemStatusInProgress ItemStatus = "in_progress" ItemStatusCompleted ItemStatus = "completed" ItemStatusIncomplete ItemStatus = "incomplete" )
type LegacyProjectionResult ¶
type LegacyProjectionResult struct {
Instructions []Message
Messages []Message
Requirements ProtocolRequirements
}
LegacyProjectionResult is the deterministic legacy-message view produced from item authority.
func ProjectItemsToLegacyView ¶
func ProjectItemsToLegacyView(call Call, target LegacyProjectionTarget) (LegacyProjectionResult, error)
ProjectItemsToLegacyView projects an item-authority call into a legacy message-authority view. It returns a complete representation or a stable ProjectionError; partial results are forbidden.
type LegacyProjectionTarget ¶
type LegacyProjectionTarget struct {
Caps BackendCaps
ReplaySupport ReasoningReplaySupport
SupportsPhase bool
SupportsItemReferences bool
SupportsCompaction bool
SupportsVideoInput bool
SupportsOpaqueExtensions bool
SupportsAnnotations bool
SupportsAssistantRefs bool
SupportsSummaries bool
SupportedExtensions []ExtensionRequirement
}
LegacyProjectionTarget describes the portable intersection a legacy-message backend can consume.
func DefaultLegacyProjectionTarget ¶
func DefaultLegacyProjectionTarget(caps BackendCaps, replay ReasoningReplaySupport) LegacyProjectionTarget
DefaultLegacyProjectionTarget returns the portable intersection shared by existing legacy backends.
func LegacyProjectionTargetFromCaps ¶
func LegacyProjectionTargetFromCaps(caps BackendCaps, replay ReasoningReplaySupport) LegacyProjectionTarget
LegacyProjectionTargetFromCaps derives projection feature flags from backend capabilities.
type ManagedEventStream ¶
type ManagedEventStream interface {
EventStream
Cancel(ctx context.Context, cause CancelCause) CancelResult
}
ManagedEventStream is the canonical backend stream lifecycle contract. Close must promptly return and unblock any in-flight Cancel.
type Message ¶
type Message struct {
Role Role
Parts []Part
// Metadata carries proxy-owned message-level traceability (for example
// interleaved-thinking injection markers). It is never serialized to wire
// payloads and never treated as client input.
Metadata map[string]string `json:"-"`
}
Message is one ordered turn in the conversation.
type NegotiationKind ¶
type NegotiationKind string
NegotiationKind classifies the outcome of comparing a call against backend capabilities.
const ( NegotiationLossless NegotiationKind = "lossless" NegotiationDowngrade NegotiationKind = "downgrade" NegotiationReject NegotiationKind = "reject" )
type NegotiationResult ¶
type NegotiationResult struct {
Kind NegotiationKind
Missing []Capability // hard rejects only
Downgraded []Capability // capabilities that will be stripped or softened
}
NegotiationResult is a deterministic capability negotiation outcome.
func Negotiate ¶
func Negotiate(required []Capability, backend BackendCaps) NegotiationResult
Negotiate compares required capabilities with backend-provided capabilities.
Downgrade is returned only when every missing capability is explicitly soft: reasoning and parallel tool calls may be stripped by the executor before upstream calls. Any other missing capability is a hard reject before upstream work begins.
func (NegotiationResult) Err ¶
func (r NegotiationResult) Err() error
Err returns a typed reject error for Kind==NegotiationReject, otherwise nil.
type OpaqueExtension ¶
type OpaqueExtension struct {
Namespace string `json:"namespace"`
Type string `json:"type"`
Implementor string `json:"implementor,omitempty"`
Direction string `json:"direction,omitempty"`
Data json.RawMessage `json:"data,omitempty"`
}
OpaqueExtension carries namespaced extensions attached to items or calls.
type Operation ¶
type Operation string
const ( // OperationOpenAIChatCompletions identifies OpenAI-compatible Chat Completions requests. OperationOpenAIChatCompletions Operation = "openai.chat_completions" // OperationOpenAIResponses identifies OpenAI Responses API requests. OperationOpenAIResponses Operation = "openai.responses" // OperationOpenResponsesCreate identifies OpenResponses create requests. OperationOpenResponsesCreate Operation = "openresponses.create" // OperationAnthropicMessages identifies Anthropic Messages API requests. OperationAnthropicMessages Operation = "anthropic.messages" // OperationGeminiGenerateContent identifies Gemini generateContent requests. OperationGeminiGenerateContent Operation = "gemini.generate_content" // OperationContextCompaction identifies protocol-neutral context compaction. OperationContextCompaction Operation = "context.compaction" )
type OperationTransportSupport ¶
type OperationTransportSupport struct {
Operation Operation
Modes []TransportMode
}
OperationTransportSupport declares supported transport modes for one protocol operation.
type OrderedItemProjectionTarget ¶
type OrderedItemProjectionTarget struct {
SupportsCallExtensions bool
SupportedExtensions []ExtensionRequirement
}
OrderedItemProjectionTarget describes the ordered-item surface an OpenResponses-style backend accepts.
func DefaultOrderedItemProjectionTarget ¶
func DefaultOrderedItemProjectionTarget() OrderedItemProjectionTarget
DefaultOrderedItemProjectionTarget returns the default OpenResponses ordered-item constructor target.
func OrderedItemProjectionTargetFromCaps ¶
func OrderedItemProjectionTargetFromCaps(caps BackendCaps) OrderedItemProjectionTarget
OrderedItemProjectionTargetFromCaps derives ordered-item constructor flags from backend capabilities.
type OutputPhase ¶
type OutputPhase string
OutputPhase classifies whether visible output had started when the failure occurred.
const ( PhasePreOutput OutputPhase = "pre_output" PhasePostOutput OutputPhase = "post_output" )
type Part ¶
type Part struct {
Kind PartKind
Text string
ImageRef string
ImageMIME string
FileRef string
FileMIME string
FileName string
ToolCallID string
ToolName string
Content json.RawMessage
// Reasoning carries historical assistant reasoning when Kind is PartReasoning.
Reasoning *ReasoningPart
}
Part is one ordered content fragment inside a message.
func FilePart ¶
FilePart constructs a file reference part for documents, PDFs, and other binary attachments.
type PolicyDecisionError ¶
type PolicyDecisionError struct {
Kind PolicyDecisionErrorKind
Stage string
ProviderID string
ReasonCode string
ClientCategory string
ClientMessage string
Cause error
}
PolicyDecisionError is the stable executor error root for policy denial, failure, and malformed decisions (requirements 5.1, 5.4, 5.5, 5.6, 6.1, 6.5, 6.6, 7.2).
Only Stage, ProviderID, ReasonCode, ClientCategory, ClientMessage, and Kind are client-safe. Cause is preserved for operator/diagnostic use and must not be rendered to clients verbatim when it may carry raw prompts, raw backend payloads, secrets, or unsafe claim values.
func NewPolicyDeniedError ¶
func NewPolicyDeniedError(stage, providerID, reasonCode, clientCategory, clientMessage string, cause error) *PolicyDecisionError
NewPolicyDeniedError returns a stable denial error. clientMessage and clientCategory are the only fields intended for frontend rendering; cause is preserved for diagnostics only. clientMessage is normalized to the wire-safe bound at construction.
func NewPolicyFailureError ¶
func NewPolicyFailureError(stage, providerID, reasonCode, clientCategory, clientMessage string, cause error) *PolicyDecisionError
NewPolicyFailureError returns a stable policy failure error for fail-closed provider failures (requirement 6.1). clientMessage is normalized to the wire-safe bound at construction.
func NewPolicyMalformedError ¶
func NewPolicyMalformedError(stage, providerID, reasonCode, clientCategory, clientMessage string, cause error) *PolicyDecisionError
NewPolicyMalformedError returns a stable malformed-policy error for unknown stages, unknown outcomes, unknown effects, or illegal outcome/effect pairs (requirements 1.5, 6.6). clientMessage is normalized to the wire-safe bound at construction.
func PolicyDecisionErrorFrom ¶
func PolicyDecisionErrorFrom(err error) *PolicyDecisionError
PolicyDecisionErrorFrom returns the *PolicyDecisionError wrapped by err, or nil.
func (*PolicyDecisionError) Error ¶
func (e *PolicyDecisionError) Error() string
Error returns a stable, client-safe message. It never includes Cause text, raw prompts, backend payloads, secrets, or unsafe claim values.
func (*PolicyDecisionError) Unwrap ¶
func (e *PolicyDecisionError) Unwrap() []error
Unwrap returns the stable root error for the kind so errors.Is and errors.As classify policy denials, failures, and malformed decisions separately from capability, session, backend, auth, and internal errors (requirement 5.6). When a cause is present it is also exposed so callers can inspect the underlying failure through errors.Is/errors.As without rendering Cause text in Error().
type PolicyDecisionErrorKind ¶
type PolicyDecisionErrorKind string
PolicyDecisionErrorKind identifies which stable policy error root a PolicyDecisionError wraps. It is the only field besides ClientCategory and ClientMessage intended for frontend classification (requirement 5.6).
const ( // PolicyErrorKindDenied wraps ErrPolicyDenied. PolicyErrorKindDenied PolicyDecisionErrorKind = "policy_denied" // PolicyErrorKindFailure wraps ErrPolicyFailure. PolicyErrorKindFailure PolicyDecisionErrorKind = "policy_failure" // PolicyErrorKindMalformed wraps ErrPolicyMalformed. PolicyErrorKindMalformed PolicyDecisionErrorKind = "policy_malformed" )
func PolicyDecisionErrorKindOf ¶
func PolicyDecisionErrorKindOf(err error) PolicyDecisionErrorKind
PolicyDecisionErrorKindOf returns the stable kind for err when it wraps a *PolicyDecisionError, otherwise the empty kind.
type ProjectionError ¶
type ProjectionError struct {
Reason ProjectionReason
Field string
Detail string
}
ProjectionError records a deterministic all-or-nothing projector failure.
func (*ProjectionError) Error ¶
func (e *ProjectionError) Error() string
func (*ProjectionError) Unwrap ¶
func (e *ProjectionError) Unwrap() error
type ProjectionReason ¶
type ProjectionReason string
ProjectionReason identifies stable projector rejection causes.
const ( ProjectionReasonConflictingAuthority ProjectionReason = "conflicting_authority" ProjectionReasonAssistantPhase ProjectionReason = "assistant_phase" ProjectionReasonItemReference ProjectionReason = "item_reference" ProjectionReasonCompaction ProjectionReason = "compaction" ProjectionReasonOpaqueExtension ProjectionReason = "opaque_extension" ProjectionReasonVideoInput ProjectionReason = "video_input" ProjectionReasonAnnotation ProjectionReason = "annotation" ProjectionReasonAssistantMediaRef ProjectionReason = "assistant_media_ref" ProjectionReasonReasoningReplay ProjectionReason = "reasoning_replay" ProjectionReasonUnsupportedContent ProjectionReason = "unsupported_content" ProjectionReasonUnsupportedItemKind ProjectionReason = "unsupported_item_kind" ProjectionReasonRefusal ProjectionReason = "refusal" ProjectionReasonSummary ProjectionReason = "summary" )
type ProtocolRequirements ¶
type ProtocolRequirements struct {
Capabilities []Capability
ItemDialects []DialectRequirement
ReasoningDialects []DialectRequirement
CompactionDialects []DialectRequirement
ExtensionTypes []ExtensionRequirement
}
ProtocolRequirements carries semantic capability and exact dialect/extension requirements derived from a canonical call trajectory.
func DeriveCandidateRequirements ¶
func DeriveCandidateRequirements(call Call, caps BackendCaps, target LegacyProjectionTarget) (ProtocolRequirements, error)
DeriveCandidateRequirements derives admission requirements against the candidate target view. When projection applies, semantic obligations are computed from the adapted call shape.
func DeriveProtocolRequirements ¶
func DeriveProtocolRequirements(c Call) ProtocolRequirements
DeriveProtocolRequirements derives complete protocol requirements from call shape.
func NormalizeProtocolRequirements ¶
func NormalizeProtocolRequirements(r ProtocolRequirements) ProtocolRequirements
NormalizeProtocolRequirements deduplicates and sorts requirement slices deterministically.
func UnionProtocolRequirements ¶
func UnionProtocolRequirements(a, b ProtocolRequirements) ProtocolRequirements
UnionProtocolRequirements returns the deterministic union of two requirement sets. Obligations present in either set are retained; baseline entries from a are never weakened by b, and b may add capabilities, dialects, or extensions.
type ReasoningDialect ¶
type ReasoningDialect string
ReasoningDialect identifies a provider-neutral replay payload shape for historical reasoning. Dialects are adapter-owned vocabulary; canonical contracts store the ID only.
const ( ReasoningDialectOpenAIChatTextV1 ReasoningDialect = "openai.chat.reasoning_text.v1" ReasoningDialectOpenAIResponsesItemV1 ReasoningDialect = "openai.responses.reasoning_item.v1" ReasoningDialectAnthropicThinkingV1 ReasoningDialect = "anthropic.thinking.v1" ReasoningDialectAnthropicRedactedThinkingV1 ReasoningDialect = "anthropic.redacted_thinking.v1" )
Initial reasoning replay dialect IDs. Adapters own wire meaning; these IDs are stable catalog keys.
func NormalizeReasoningDialect ¶
func NormalizeReasoningDialect(d ReasoningDialect) ReasoningDialect
NormalizeReasoningDialect returns the canonical dialect form: trim space and lowercase. Unknown dialect IDs remain valid when non-empty after normalization and within bounds.
func NormalizeReasoningDialects ¶
func NormalizeReasoningDialects(in []ReasoningDialect) []ReasoningDialect
NormalizeReasoningDialects normalizes, omits empty, deduplicates, and sorts dialect IDs.
type ReasoningItem ¶
type ReasoningItem struct {
Reasoning *ReasoningPart `json:"reasoning,omitempty"`
}
ReasoningItem encapsulates reasoning payload within an item.
type ReasoningPart ¶
type ReasoningPart struct {
Dialect ReasoningDialect
Text string
Signature string
Opaque json.RawMessage
// Summary and Content preserve the official OpenResponses reasoning-item
// arrays when the canonical adapter can carry them without flattening.
// They remain raw JSON because their element vocabulary is protocol-owned.
Summary json.RawMessage
SummaryPresent bool
Content json.RawMessage
ContentPresent bool
// EncryptedContent preserves the official encrypted_content value,
// including JSON null. EncryptedContentPresent distinguishes an omitted
// field from an explicitly present null value.
EncryptedContent json.RawMessage
EncryptedContentPresent bool
}
ReasoningPart is the provider-neutral historical reasoning payload for PartReasoning. At least one of the legacy carriers or official exact fields must be present.
type ReasoningReplaySupport ¶
type ReasoningReplaySupport struct {
Dialects []ReasoningDialect
}
ReasoningReplaySupport declares which historical reasoning dialects a backend candidate can replay.
type RejectError ¶
type RejectError struct {
Missing []Capability
Reason string
}
RejectError is returned when capability negotiation deterministically rejects a request before any upstream work begins.
func (*RejectError) Error ¶
func (e *RejectError) Error() string
func (*RejectError) Unwrap ¶
func (e *RejectError) Unwrap() error
type RequirementsMatchResult ¶
type RequirementsMatchResult struct {
Kind NegotiationKind
MissingCaps []Capability
MissingDialects []DialectRequirement
MissingExtensions []ExtensionRequirement
}
RequirementsMatchResult is the outcome of exact protocol requirement matching.
func MatchRequirements ¶
func MatchRequirements(required, supported ProtocolRequirements, replay ReasoningReplaySupport) RequirementsMatchResult
MatchRequirements compares required protocol requirements against candidate support. Every required capability, dialect, and extension must be satisfied; otherwise Kind is reject.
func (RequirementsMatchResult) Err ¶
func (r RequirementsMatchResult) Err() error
Err returns a typed reject error for Kind==NegotiationReject.
type RequirementsRejectError ¶
type RequirementsRejectError struct {
MissingCaps []Capability
MissingDialects []DialectRequirement
MissingExtensions []ExtensionRequirement
}
RequirementsRejectError records hard rejects from exact requirement matching.
func (*RequirementsRejectError) Error ¶
func (e *RequirementsRejectError) Error() string
func (*RequirementsRejectError) Unwrap ¶
func (e *RequirementsRejectError) Unwrap() error
type RouteIntent ¶
type RouteIntent struct {
Selector string
}
RouteIntent captures routing input produced by a frontend decoder. The planner owns interpretation; this stays an opaque intent string at the API layer.
type ScopedUsageDelta ¶
type ScopedUsageDelta struct {
InputTokens int
OutputTokens int
CacheReadTokens int
CacheWriteTokens int
ReasoningTokens int
TotalTokens int
UsagePresence UsagePresence
Accounting UsageAccountingMetadata
}
ScopedUsageDelta carries usage for one accounting plane while preserving Event legacy totals.
func ClientVisibleUsage ¶
func ClientVisibleUsage(ev Event) ScopedUsageDelta
ClientVisibleUsage returns the usage scope safe to expose on frontend protocols. When no scoped client-visible usage is present it falls back to legacy Event totals.
type SemanticExtension ¶
type SemanticExtension struct {
Namespace string
Type string
Implementor string
Direction string
Presence SemanticExtensionPresence
Data json.RawMessage
}
SemanticExtension is one bounded negotiated residual semantic carrier. Data is never a complete request or response envelope.
type SemanticExtensionPresence ¶
type SemanticExtensionPresence string
SemanticExtensionPresence distinguishes explicit JSON states.
const ( SemanticExtensionAbsent SemanticExtensionPresence = "absent" SemanticExtensionNull SemanticExtensionPresence = "null" SemanticExtensionValue SemanticExtensionPresence = "value" )
type SessionDenialCode ¶
type SessionDenialCode string
SessionDenialCode is a stable machine-readable category for frontends and metrics (not user-facing prose).
const ( SessionDeniedMissingPrincipal SessionDenialCode = "session_denied_missing_principal" SessionDeniedInvalidAuthority SessionDenialCode = "session_denied_invalid_authority" SessionDeniedOwnerMismatch SessionDenialCode = "session_denied_owner_mismatch" SessionDeniedResumeExpired SessionDenialCode = "session_denied_resume_expired" SessionDeniedQuarantined SessionDenialCode = "session_denied_quarantined" SessionDeniedWorkspace SessionDenialCode = "session_denied_workspace" SessionDeniedMandatoryAuditFailure SessionDenialCode = "session_denied_mandatory_audit_failure" )
type SessionDenialError ¶
type SessionDenialError struct {
// contains filtered or unexported fields
}
SessionDenialError is a typed session denial with a public-safe SessionDenialError.Error string and optional internal diagnostics that must not appear in Error().
func (*SessionDenialError) Code ¶
func (e *SessionDenialError) Code() SessionDenialCode
Code returns the stable denial category.
func (*SessionDenialError) Error ¶
func (e *SessionDenialError) Error() string
func (*SessionDenialError) InternalReason ¶
func (e *SessionDenialError) InternalReason() string
InternalReason returns operator/diagnostic detail; it is not included in SessionDenialError.Error.
func (*SessionDenialError) PublicMessage ¶
func (e *SessionDenialError) PublicMessage() string
PublicMessage returns the client-safe message used by SessionDenialError.Error when set.
func (*SessionDenialError) Unwrap ¶
func (e *SessionDenialError) Unwrap() error
type SessionRef ¶
type SessionRef struct {
ClientSessionID string
ContinuityKey string
ALegID string
AuthoritativeSessionID string `json:"SessionID,omitempty"`
ResumeToken string
// Metadata carries validated client session metadata. It is never treated as
// proxy authority unless a separate trusted carrier establishes that field.
Metadata map[string]string `json:"-"`
}
SessionRef carries client hints, core continuity identifiers, and optional proxy-owned session authority.
ClientSessionID, ContinuityKey, and ALegID are hints or correlation values unless validated through proxy-owned secure-session state. AuthoritativeSessionID is the proxy-owned session id when issued by the secure session layer. ResumeToken is a bearer resume proof; it must never be forwarded to backends or persisted raw by adapters—only validated via secure-session fingerprints.
JSON name remains "SessionID" for wire compatibility.
func (SessionRef) CorrelationID ¶
func (s SessionRef) CorrelationID() string
CorrelationID returns a stable identifier for diagnostics and traffic capture: authoritative id when set, otherwise the client hint.
type StreamError ¶
StreamError carries provider-specific codes/messages for a terminal stream failure without putting variable text in Error() (use Code and Message in structured logs).
func (*StreamError) Error ¶
func (e *StreamError) Error() string
func (*StreamError) Unwrap ¶
func (e *StreamError) Unwrap() error
type TokenizerRef ¶
TokenizerRef records provider-neutral tokenizer metadata used to derive usage.
type ToolCallItem ¶
type ToolCallItem struct {
CallID string `json:"call_id"`
Name string `json:"name"`
Arguments json.RawMessage `json:"arguments,omitempty"`
}
ToolCallItem represents a function/tool invocation request in an item trajectory.
type ToolCallSummary ¶
ToolCallSummary is one completed tool invocation aggregated from the stream.
type ToolCategory ¶
type ToolCategory string
ToolCategory is a coarse, protocol-neutral category for coding-agent tool names. It is derived metadata for tool-policy/reactor consumers, never user or provider authority, and never an allow/deny decision by itself.
const ( ToolCategoryFileRead ToolCategory = "file_read" ToolCategoryFileSearch ToolCategory = "file_search" ToolCategoryOSCommand ToolCategory = "os_command" ToolCategoryFileEdit ToolCategory = "file_edit" ToolCategoryFileRemove ToolCategory = "file_remove" ToolCategoryWebAccess ToolCategory = "web_access" ToolCategoryUnknown ToolCategory = "unknown" )
func ClassifyToolName ¶
func ClassifyToolName(name string) (ToolCategory, bool)
ClassifyToolName derives a coarse category and a conservative may-mutate-local-filesystem hint from a coding-agent tool name.
The classifier trims surrounding whitespace, case-folds, and matches an exact static alias set. It does not inspect tool arguments, shell command text, schemas, descriptions, provider identity, or execution results, and it does not infer from arbitrary prefixes/suffixes/substrings. Empty or unrecognized names return (ToolCategoryUnknown, true) so an unfamiliar tool is never falsely asserted to be filesystem-safe.
The returned bool means the named tool family has the capability to mutate the local filesystem; it is not evidence that a specific invocation did so.
type ToolChoice ¶
type ToolChoice struct {
Mode ToolChoiceMode
// Name is used when Mode requires a specific tool.
Name string
// AllowedTools is the OpenResponses allowed_tools subset: when non-empty,
// only tools named here may be invoked, while the full Tools list stays
// visible to the model (cache-preserving control surface). Mode still
// governs whether tools may/should/must be called (auto/none/any).
// Empty means no subset restriction.
AllowedTools []string
}
ToolChoice constrains tool usage for the call.
type ToolChoiceMode ¶
type ToolChoiceMode string
ToolChoiceMode selects how tool calls are admitted for this request.
const ( ToolChoiceAuto ToolChoiceMode = "auto" ToolChoiceNone ToolChoiceMode = "none" ToolChoiceAny ToolChoiceMode = "any" ToolChoiceRequired ToolChoiceMode = "required" )
type ToolDef ¶
type ToolDef struct {
Name string
Description string
Parameters json.RawMessage
}
ToolDef is a canonical function/tool declaration (not a raw provider blob).
type ToolEvent ¶
type ToolEvent struct {
Kind ToolEventKind
ToolCallID string
ToolName string
// Category is the coarse category derived from ToolName (or from lifecycle
// correlation when a later fragment omits ToolName). It is informational
// metadata, never an allow/deny decision by itself.
Category ToolCategory
// MayMutateLocalFS is a conservative potential-capability hint: true when the
// named tool family can mutate the local filesystem. It is not evidence that
// a specific invocation mutated anything.
//
// The zero value is false and is not a classified result. Unknown names
// classify as true; project via ToolEventFromEvent or ClassifyToolName
// rather than inspecting an unprojected ToolEvent literal.
MayMutateLocalFS bool
// ArgsDelta carries incremental JSON/tool arguments fragments for ToolEventArgsDelta.
ArgsDelta string
}
ToolEvent is the canonical tool-call subset exposed to tool reactors.
func ToolEventFromEvent ¶
ToolEventFromEvent maps a single stream Event to a ToolEvent when applicable. The second return value is false for non-tool event kinds.
type ToolEventKind ¶
type ToolEventKind string
ToolEventKind classifies tool-call lifecycle items passed to tool reactors.
const ( ToolEventStarted ToolEventKind = "tool_call_started" ToolEventArgsDelta ToolEventKind = "tool_call_args_delta" ToolEventFinished ToolEventKind = "tool_call_finished" )
type ToolResultItem ¶
type ToolResultItem struct {
CallID string `json:"call_id"`
Name string `json:"name"`
Output string `json:"output,omitempty"`
Parts []ContentPart `json:"parts,omitempty"`
}
ToolResultItem represents function output in an item trajectory.
type TransportFallbackPolicy ¶
type TransportFallbackPolicy string
TransportFallbackPolicy controls how missing backend transport declarations are handled.
const ( TransportFallbackCompatibility TransportFallbackPolicy = "compatibility" TransportFallbackExact TransportFallbackPolicy = "exact" )
type TransportMode ¶
type TransportMode string
TransportMode identifies the upstream transport shape selected for one backend attempt.
const ( TransportModeStreaming TransportMode = "streaming" TransportModeNonStreaming TransportMode = "non_streaming" )
func PreferredTransportMode ¶
func PreferredTransportMode(delivery DeliveryMode) TransportMode
PreferredTransportMode maps client delivery mode to the preferred backend transport mode.
type TransportModeSet ¶
type TransportModeSet map[TransportMode]struct{}
TransportModeSet is a set of supported transport modes.
type TransportNegotiationResult ¶
type TransportNegotiationResult struct {
Kind NegotiationKind
Selected TransportMode
Operation Operation
Mode TransportMode
}
TransportNegotiationResult is the outcome of operation+transport capability matching.
func NegotiateTransport ¶
func NegotiateTransport(inv Invocation, caps BackendTransportCaps, policy TransportFallbackPolicy) TransportNegotiationResult
NegotiateTransport selects the backend transport mode for one invocation.
Compatibility policy preserves legacy behavior when transport caps are omitted or the requested operation is undeclared. Exact policy requires explicit operation+mode support.
func (TransportNegotiationResult) Err ¶
func (r TransportNegotiationResult) Err() error
Err returns a typed reject error for Kind==NegotiationReject, otherwise nil.
type TransportRejectError ¶
type TransportRejectError struct {
Operation Operation
Mode TransportMode
}
TransportRejectError records a hard transport capability mismatch.
func (*TransportRejectError) Error ¶
func (e *TransportRejectError) Error() string
func (*TransportRejectError) Is ¶
func (e *TransportRejectError) Is(target error) bool
type UpstreamFailureError ¶
type UpstreamFailureError struct {
Phase OutputPhase
Recoverable bool
Reason string
CandidateKey string
}
UpstreamFailureError is a structured upstream error for orchestration (executor, diagnostics).
func (*UpstreamFailureError) Error ¶
func (e *UpstreamFailureError) Error() string
func (*UpstreamFailureError) Unwrap ¶
func (e *UpstreamFailureError) Unwrap() error
Unwrap returns ErrRecoverablePreOutput when a pre-output failure is recoverable.
type UsageAccountingMetadata ¶
type UsageAccountingMetadata struct {
Plane UsagePlane
Source UsageSource
Authority UsageAuthority
Tokenizer TokenizerRef
// Provider identifiers are opaque, bounded correlation values captured by
// an adapter. They are never credentials and do not grant runtime
// attribution authority; the host still supplies the trusted B-leg/store.
ProviderAccountKey string
ProviderRequestID string
ProviderChargeID string
// ServiceContext is an optional provider-returned context lexeme (for
// example a service tier or endpoint class). It is retained for host-side
// evidence diagnostics and is never interpreted as a tariff.
ServiceContext string
// DedupeKey is an internal accounting correlation key. It is never encoded
// by frontend adapters and is used only to apply provider evidence once.
DedupeKey string
}
UsageAccountingMetadata annotates usage deltas without replacing legacy token totals.
type UsageAuthority ¶
type UsageAuthority string
UsageAuthority describes how strongly callers may rely on a usage delta.
const ( // UsageAuthorityUnknown is the zero value for absent or unspecified authority metadata. UsageAuthorityUnknown UsageAuthority = "" UsageAuthorityAuthoritative UsageAuthority = "authoritative" UsageAuthorityDelegated UsageAuthority = "delegated" UsageAuthorityEstimated UsageAuthority = "estimated" UsageAuthorityAdvisory UsageAuthority = "advisory" )
type UsageEvidenceSource ¶
type UsageEvidenceSource interface {
DrainUsageEvidence() []Event
}
UsageEvidenceSource is an internal accounting seam. Evidence is drained by the host and never returned from Recv, so frontends and hooks cannot observe provider-only charges.
type UsagePlane ¶
type UsagePlane string
UsagePlane identifies the accounting perspective for a usage delta.
const ( // UsagePlaneUnknown is the zero value for absent or unspecified usage plane metadata. UsagePlaneUnknown UsagePlane = "" // UsagePlaneProviderBillable is the provider-reported or provider-derived billable plane. UsagePlaneProviderBillable UsagePlane = "provider_billable" // UsagePlaneClientVisible is the usage visible to the upstream client protocol. UsagePlaneClientVisible UsagePlane = "client_visible" // UsagePlaneProxyBillable is usage billed by proxy policy rather than directly by a provider. UsagePlaneProxyBillable UsagePlane = "proxy_billable" )
type UsagePresence ¶
type UsagePresence struct {
InputTokens bool
OutputTokens bool
CacheReadTokens bool
CacheWriteTokens bool
ReasoningTokens bool
TotalTokens bool
}
UsagePresence records which token counters were explicitly supplied by the usage source. A false field means the counter was omitted, not that it was explicitly reported as zero. The zero value preserves compatibility with legacy events that predate per-field presence metadata.
func (UsagePresence) Any ¶
func (p UsagePresence) Any() bool
Any reports whether at least one token counter was explicitly supplied.
func (UsagePresence) Union ¶
func (p UsagePresence) Union(other UsagePresence) UsagePresence
Union retains explicit presence from either usage candidate.
type UsageSource ¶
type UsageSource string
UsageSource identifies where usage accounting metadata came from.
const ( // UsageSourceUnknown is the zero value for absent or unspecified usage source metadata. UsageSourceUnknown UsageSource = "" UsageSourceProviderReported UsageSource = "provider_reported" UsageSourceProviderCountAPI UsageSource = "provider_count_api" UsageSourceLocalTokenizer UsageSource = "local_tokenizer" UsageSourceLocalEstimator UsageSource = "local_estimator" UsageSourcePolicyReserved UsageSource = "policy_reserved" UsageSourceProxyAdjusted UsageSource = "proxy_adjusted" )
type ValidationError ¶
ValidationError reports a canonical request invariant violation.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
func (*ValidationError) Unwrap ¶
func (e *ValidationError) Unwrap() error
type VerbosityLevel ¶
type VerbosityLevel string
VerbosityLevel controls the amount of reasoning/detail requested from a provider that exposes the OpenAI-compatible verbosity contract.
const ( VerbosityLow VerbosityLevel = "low" VerbosityMedium VerbosityLevel = "medium" VerbosityHigh VerbosityLevel = "high" )
func ParseVerbosityLevel ¶
func ParseVerbosityLevel(raw string) (VerbosityLevel, error)
ParseVerbosityLevel trims and normalizes an external verbosity value. An empty value means unset and is returned without error.
Source Files
¶
- admission.go
- call.go
- call_clone.go
- call_instructions.go
- capabilities.go
- collected_clone.go
- dataurl.go
- doc.go
- errors.go
- events.go
- explicit_completion.go
- extensions_internal.go
- invocation.go
- items.go
- lifecycle.go
- limits.go
- lineage.go
- output_commit.go
- parts.go
- policy_errors.go
- projection.go
- reasoning.go
- requirements.go
- route_params.go
- semantic_extension.go
- session_errors.go
- token_accounting.go
- tool_choice_reconcile.go
- tool_classification.go
- tool_event.go
- tool_event_merge.go
- transport.go
- upstream.go
- verbosity.go
- walkers.go