Documentation
¶
Index ¶
- Constants
- func AgentName(label string) string
- func AgentSpellings(name string) []string
- func CanonicalAgent(name string) string
- func DurationBetween(from, to time.Time) time.Duration
- func DurationSince(start time.Time) time.Duration
- func FoldAgentNames(agents map[string]string) map[string]string
- func GetState[T any](pctx *Context, key string) *T
- func HasControlRunes(s string) bool
- func IsControlRune(r rune) bool
- func IsKnownAgent(name string) bool
- func LateOpsDropped() int64
- func PromptContextOf(events []SessionEvent) int
- func PromptTokensOf(resp *InferenceExtension) int
- func RoutedServer(in *Invocations) string
- func SanitizeControlRunes(s string) string
- func SanitizeLogValue(s string) string
- func SetState[T any](pctx *Context, key string, v *T)
- func SnapshotPlugins(custom map[string]any) map[string]json.RawMessage
- func StatusFromCode(code string) int
- func TruncateLabel(s string, n int) string
- type A2AExtension
- type A2APart
- type Action
- func Challenge(realm, reason string) Action
- func Deny(code, reason string) Action
- func DenyStatus(status int, code, reason string) Action
- func DenyWithDetails(code, reason string, details map[string]any) Action
- func MocaRefusal(status int, code, name string) Action
- func RateLimited(retryAfter time.Duration, code, reason string) Action
- type ActionType
- type AgentIdentity
- type AgentRole
- type ArchiveUsage
- type Configurable
- type Context
- func (c *Context) AccountingThread() (id, parent string, ok bool)
- func (c *Context) Allow(reason string)
- func (c *Context) AttributedClientProc() string
- func (c *Context) AttributedProc() string
- func (c *Context) BilledBody(forwarded []byte) (billed []byte, unplaced bool)
- func (c *Context) BillingOverride() (mode accountant.BillingMode, ok bool)
- func (c *Context) BillingSnapshot() accountant.Billing
- func (c *Context) BodyMutated() bool
- func (c *Context) Classification() (anyAction, anyBypass bool)
- func (c *Context) ClearCurrentPlugin()
- func (c *Context) ClientBody() []byte
- func (c *Context) ClientCompaction() accountant.CompactionTrigger
- func (c *Context) ClientInfo() *EventClient
- func (c *Context) ContentSources() []capabilities.ContentSource
- func (c *Context) CurrentPhase() InvocationPhase
- func (c *Context) DenyAndRecord(reason, code, message string) Action
- func (c *Context) InferenceHosts() (InferenceHosts, bool)
- func (c *Context) LastInference() SessionFact
- func (c *Context) LastIntent() SessionFact
- func (c *Context) MarkRedirectable()
- func (c *Context) MarkResend(reason string)
- func (c *Context) MarkResponseDelivered()
- func (c *Context) Modify(reason string)
- func (c *Context) NamedSession() string
- func (c *Context) NamingHeader() string
- func (c *Context) NoRecord() bool
- func (c *Context) Observe(reason string)
- func (c *Context) Observing() bool
- func (c *Context) OpReporter() OpReporter
- func (c *Context) Outcome() *Outcome
- func (c *Context) ParentProject() string
- func (c *Context) ParentSession() string
- func (c *Context) ParentSubagent() string
- func (c *Context) PeerCertificate() *x509.Certificate
- func (c *Context) Project() string
- func (c *Context) Record(inv Invocation)
- func (c *Context) RecordHeaderSeen() bool
- func (c *Context) RecordStrippedUpgrade(h http.Header)
- func (c *Context) Redirect(target *url.URL) error
- func (c *Context) RedirectPath() (string, bool)
- func (c *Context) RedirectTarget() (scheme, host string, ok bool)
- func (c *Context) Redirectable() bool
- func (c *Context) Redirected() bool
- func (c *Context) RejectingPlugin() string
- func (c *Context) RenewRequestID()
- func (c *Context) ReportOps(ops ...accountant.Operation)
- func (c *Context) ReportedOps() []accountant.Operation
- func (c *Context) RequestID() string
- func (c *Context) RequestModel() (name string, ok bool)
- func (c *Context) RequestedHost() string
- func (c *Context) ResendReasons() []string
- func (c *Context) Resendable() bool
- func (c *Context) ResolveClient()
- func (c *Context) ResponseBodyMutated() bool
- func (c *Context) ResponseDelivered() bool
- func (c *Context) SetAccountingThread(id, parent string)
- func (c *Context) SetAttribution(proc, clientProc, header string)
- func (c *Context) SetBilledBody(f func(forwarded []byte) (billed []byte, unplaced bool))
- func (c *Context) SetBillingOverride(mode accountant.BillingMode)
- func (c *Context) SetBody(newBody []byte) bool
- func (c *Context) SetClientCompaction(t accountant.CompactionTrigger)
- func (c *Context) SetCurrentPlugin(name string, phase InvocationPhase)
- func (c *Context) SetNamedSession(id string)
- func (c *Context) SetParent(session, project string)
- func (c *Context) SetProject(label string)
- func (c *Context) SetRedirectPath(path string) error
- func (c *Context) SetRequestModel(name string) error
- func (c *Context) SetResendable()
- func (c *Context) SetResponseBody(newBody []byte) bool
- func (c *Context) SetSessionFacts(f SessionFacts)
- func (c *Context) SetUpstreamHeaders(h http.Header) error
- func (c *Context) Skip(reason string)
- func (c *Context) Subagent() string
- func (c *Context) SubagentKind() string
- func (c *Context) Translate(source, target, path string) error
- func (c *Context) TranslateTarget() (source, target, path string, ok bool)
- func (c *Context) TypedPrompts() []intent.Prompt
- func (c *Context) UpstreamHeaders() http.Header
- func (c *Context) WithholdsSession() bool
- type DelegationExtension
- type DelegationHop
- type Direction
- type ErrorPolicy
- type EventClient
- type EventError
- type EventIdentity
- type EventTLS
- type Extensions
- type FactState
- type FieldSchema
- type Finisher
- type Holder
- func (h *Holder) ForPctx(pctx *Context) *Pipeline
- func (h *Holder) HasResenders() bool
- func (h *Holder) HasStreamingResponders() bool
- func (h *Holder) Load() *Pipeline
- func (h *Holder) NeedsBody() bool
- func (h *Holder) NeedsRequestBody() bool
- func (h *Holder) NeedsResponseBody() bool
- func (h *Holder) NotReadyPlugin() string
- func (h *Holder) Pin(pctx *Context) *Pipeline
- func (h *Holder) Plugins() []Plugin
- func (h *Holder) Ready() bool
- func (h *Holder) Resend(ctx context.Context, pctx *Context, status int, body []byte) bool
- func (h *Holder) Run(ctx context.Context, pctx *Context) Action
- func (h *Holder) RunFinish(ctx context.Context, pctx *Context, outcome Outcome)
- func (h *Holder) RunResponse(ctx context.Context, pctx *Context) Action
- func (h *Holder) RunResponseFrame(ctx context.Context, pctx *Context, frame []byte, last bool) Action
- func (h *Holder) Store(p *Pipeline)
- func (h *Holder) WritesRequestBody() bool
- func (h *Holder) WritesResponseBody() bool
- type Identity
- type InferenceExtension
- type InferenceHostSeen
- type InferenceHosts
- type InferenceMessage
- type InferenceThinking
- type InferenceTool
- type InferenceToolCall
- type InferenceToolResult
- type Initializer
- type Invocation
- type InvocationAction
- type InvocationPhase
- type Invocations
- type LateOpsAccountant
- type ListenerSupport
- type MCPError
- type MCPExtension
- type Metric
- type MetricsProvider
- type OpReporter
- type Option
- type Outcome
- type OutcomeAction
- type Pipeline
- func (p *Pipeline) Drained() <-chan struct{}
- func (p *Pipeline) HasResenders() bool
- func (p *Pipeline) HasStreamingResponders() bool
- func (p *Pipeline) Held() int64
- func (p *Pipeline) NeedsBody() bool
- func (p *Pipeline) NeedsRequestBody() bool
- func (p *Pipeline) NeedsResponseBody() bool
- func (p *Pipeline) NotReadyPlugin() string
- func (p *Pipeline) Plugins() []Plugin
- func (p *Pipeline) PolicyAt(i int) ErrorPolicy
- func (p *Pipeline) ReadsEveryResponseBody() bool
- func (p *Pipeline) Ready() bool
- func (p *Pipeline) Resend(ctx context.Context, pctx *Context, status int, body []byte) bool
- func (p *Pipeline) Run(ctx context.Context, pctx *Context) Action
- func (p *Pipeline) RunFinish(ctx context.Context, pctx *Context, outcome Outcome)
- func (p *Pipeline) RunResponse(ctx context.Context, pctx *Context) Action
- func (p *Pipeline) RunResponseFrame(ctx context.Context, pctx *Context, frame []byte, last bool) Action
- func (p *Pipeline) Start(ctx context.Context) error
- func (p *Pipeline) Stop(ctx context.Context)
- func (p *Pipeline) WritesDestination() bool
- func (p *Pipeline) WritesRequestBody() bool
- func (p *Pipeline) WritesResponseBody() bool
- type Plugin
- type PluginCapabilities
- type PromptContext
- type PromptContextFold
- type RawBody
- type RawCapture
- type RawConfigProvider
- type RawJSON
- type Readier
- type RequestAccountant
- type RequestCapture
- type Resender
- type ResponseCapture
- type SchemaProvider
- type SecurityExtension
- type SessionEraser
- type SessionEvent
- type SessionFact
- type SessionFacts
- type SessionPhase
- type SessionSource
- type SessionView
- type SharedStore
- type Shutdowner
- type StreamingResponder
- type TunnelReason
- type Violation
Constants ¶
const ( FactNone = model.FactNone FactNoSession = model.FactNoSession FactPresent = model.FactPresent )
const ( Inbound = model.Inbound Outbound = model.Outbound )
const ( PluginEventSuffix = model.PluginEventSuffix AgentRoleMain = model.AgentRoleMain AgentRoleSubagent = model.AgentRoleSubagent SubagentKindSubagent = model.SubagentKindSubagent SubagentKindSubtask = model.SubagentKindSubtask ActionAllow = model.ActionAllow ActionDeny = model.ActionDeny ActionSkip = model.ActionSkip ActionModify = model.ActionModify ActionObserve = model.ActionObserve InvocationPhaseRequest = model.InvocationPhaseRequest InvocationPhaseResponse = model.InvocationPhaseResponse )
const ( SessionRequest = model.SessionRequest SessionResponse = model.SessionResponse SessionDenied = model.SessionDenied TunnelClientRejectedCA = model.TunnelClientRejectedCA TunnelClientHungUp = model.TunnelClientHungUp TunnelHandshakeFailed = model.TunnelHandshakeFailed TunnelOriginUnverified = model.TunnelOriginUnverified TunnelSkipCached = model.TunnelSkipCached TunnelProgramRefused = model.TunnelProgramRefused TunnelOSTrustOnly = model.TunnelOSTrustOnly TunnelBridgeDisabled = model.TunnelBridgeDisabled TunnelPassthroughPort = model.TunnelPassthroughPort TunnelPassthroughNonTLS = model.TunnelPassthroughNonTLS TunnelPassthroughHost = model.TunnelPassthroughHost TunnelDialFailed = model.TunnelDialFailed TunnelPassthroughUnknown = model.TunnelPassthroughUnknown TunnelWebSocket = model.TunnelWebSocket TunnelDestPrivate = model.TunnelDestPrivate TunnelSNIMismatch = model.TunnelSNIMismatch TunnelRefusedNonTLS = model.TunnelRefusedNonTLS ErrorKindUpgradeDeclined = model.ErrorKindUpgradeDeclined ErrorKindTurnInterrupted = model.ErrorKindTurnInterrupted ErrorKindDestinationPrivate = model.ErrorKindDestinationPrivate ErrorKindUpstreamUnverified = model.ErrorKindUpstreamUnverified ErrorKindMisdirectedRequest = model.ErrorKindMisdirectedRequest ErrorKindNotTLS = model.ErrorKindNotTLS SessionSourceHeader = model.SessionSourceHeader SessionSourceProcess = model.SessionSourceProcess SessionSourcePending = model.SessionSourcePending SessionSourceAffinity = model.SessionSourceAffinity SessionSourceActive = model.SessionSourceActive SessionSourceConnection = model.SessionSourceConnection )
const ( BobTaskIDHeader = model.BobTaskIDHeader BobParentTaskIDHeader = model.BobParentTaskIDHeader )
BobTaskIDHeader and BobParentTaskIDHeader are model's, aliased here: session reads them too, and session must not import pipeline (#1502). See their doc in core/model.
const ( // CodexThreadIDHeader is the thread that made a Codex request. A subagent has its own. CodexThreadIDHeader = "Thread-Id" // CodexParentThreadIDHeader names the parent thread. Only a Codex subagent sends it. CodexParentThreadIDHeader = "X-Codex-Parent-Thread-Id" // OpenCodeSessionIDHeader is the OpenCode session of the request. A subagent has its own. OpenCodeSessionIDHeader = "X-Opencode-Session-Id" // OpenCodeParentSessionIDHeader names the parent session. Only an OpenCode subagent sends it. OpenCodeParentSessionIDHeader = "X-Opencode-Parent-Session-Id" )
The headers Codex and OpenCode name a subagent with. context-guru reads the same headers (agent/codex, agent/opencode, and agent.Client.SubagentID). core/pipeline may not import context-guru (core/accounting's boundary test forbids it in accounting's whole dependency closure, and accounting imports this package), so the rule is copied here. plugins/contextguru's TestSubagentMatchesContextGuru fails when the two disagree.
const ClaudeCodeAgentIDHeader = "X-Claude-Code-Agent-Id"
ClaudeCodeAgentIDHeader is the request header Claude Code sets on the requests of an agent other than the main conversation, naming that agent. Verified on claude-cli/2.1.302: the CLI sets it from any non-main agent context that holds an id — a subagent's, and an agent-team teammate's — and the main conversation's requests do not carry it. A teammate is NOT a subagent to the rest of this package: the CLI writes the cc_is_subagent marker only for agentType "subagent", so a teammate's rows have this header and Inference.AgentRole "main". For a subagent the value is the same id the CLI names its transcript after — ~/.claude/projects/<dir>/<session>/subagents/agent-<id>.jsonl, beside an agent-<id>.meta.json carrying its agentType and description — so an event keyed on it lines up with what the user's own client wrote.
Here rather than beside session.ClaudeCodeSessionHeader because session imports pipeline, and the reader of this one is Context. Canonical HTTP casing, for the reason session.BobSessionHeader gives.
NOT A SESSION ID HEADER, and it must not be added to session.id_headers. A subagent's requests carry their parent's X-Claude-Code-Session-Id, so they are filed in the parent's session and counted in its cost; bucketing on this header instead would give every subagent a session row of its own and take its spend away from the conversation that started it.
const ClaudeCodeParentAgentIDHeader = "X-Claude-Code-Parent-Agent-Id"
ClaudeCodeParentAgentIDHeader is the request header Claude Code sets on a subagent's requests when another AGENT started it, naming that agent. Verified on claude-cli/2.1.302: a subagent's context takes its parent's agentId at spawn, and the main conversation has none, so the header appears only from the second level down — a subagent a subagent started, or one an agent-team teammate started. A subagent the main conversation started sends ClaudeCodeAgentIDHeader alone.
That is why there is no value naming the main conversation: its parent IS the session, so a reader building the tree takes an absent parent to mean "the session this row is filed in". The same id is the parentAgentId field of the child's agent-<id>.meta.json, written under the same rule.
Not a session id header either, for the reason ClaudeCodeAgentIDHeader gives.
const DefaultFinishTimeout = 2 * time.Second
DefaultFinishTimeout bounds how long each plugin's OnFinish may run. OnFinish commonly does network I/O (flush audits, release distributed leases) so the budget needs to be realistic, not minimal. 2s matches the order of magnitude of typical side-effect I/O without blocking the finish chain indefinitely when a plugin's sink hangs. Configurable per-listener via WithFinishTimeout; the per-plugin ctx is derived from context.Background() so client disconnect during the request never cancels OnFinish.
const MaxResends = 2
MaxResends is how many times a listener asks the Resenders about one request: once after each refused attempt, so at most MaxResends+1 attempts reach the upstream.
const MaxResponseCapture = model.MaxResponseCapture
const ResendPeekLimit = 64 << 10
ResendPeekLimit is how much of a refused answer's body a Resender is shown. An error body is small; a larger one is cut, not refused.
const StatusClientClosedRequest = model.StatusClientClosedRequest
snapshot.go: see core/model for the docs. The helpers that take *Context stay in snapshot_context.go.
const UnknownClientLabel = model.UnknownClientLabel
Variables ¶
This section is empty.
Functions ¶
func AgentSpellings ¶
func CanonicalAgent ¶
func GetState ¶
GetState retrieves a typed value previously stored via SetState. Returns nil when the key is absent or when the stored value is not a *T — safe-fails rather than panicking so a mid-pipeline type migration (plugin version skew) degrades instead of crashing the handler.
func HasControlRunes ¶
func IsControlRune ¶
func IsKnownAgent ¶
func LateOpsDropped ¶
func LateOpsDropped() int64
LateOpsDropped returns how many context operations this process dropped because they were reported after their request was handed to the accountant (OpReporter.Report), and the accountant did not book them: it has no LateOpsAccountant, or the request had no session, or the op was not a spend.
func PromptContextOf ¶
func PromptContextOf(events []SessionEvent) int
func PromptTokensOf ¶
func PromptTokensOf(resp *InferenceExtension) int
tokens.go: see core/model for the docs.
func RoutedServer ¶
func RoutedServer(in *Invocations) string
func SanitizeControlRunes ¶
func SanitizeLogValue ¶
func SetState ¶
SetState stashes a typed value on pctx under key. Intended for plugin- private per-request state — e.g., a rate-limiter remembering how many tokens were available when OnRequest saw the call, for OnResponse to consult. The generic type parameter is documentary: it forces callers to pass *T rather than an unrelated interface, which pairs with the symmetric type-assert in GetState.
Convention: `key` should be the plugin's Name() so keys from unrelated plugins don't collide. SetState is not safe for concurrent use — pctx is single-threaded per request in the pipeline.
func SnapshotPlugins ¶
func SnapshotPlugins(custom map[string]any) map[string]json.RawMessage
func StatusFromCode ¶
StatusFromCode returns the HTTP status a Violation maps to when its Status field is unset. Falls back to 500 for unknown codes.
func TruncateLabel ¶
Types ¶
type A2AExtension ¶
type A2AExtension = model.A2AExtension
extensions.go: see core/model for the docs.
func SnapshotA2A ¶
func SnapshotA2A(ext *A2AExtension) *A2AExtension
type Action ¶
type Action struct {
Type ActionType
Violation *Violation
}
Action is returned by a plugin to indicate how the pipeline should proceed. For Continue, Violation is nil. For Reject, Violation is populated (either by the plugin itself or by a helper constructor such as Deny / Challenge).
func Challenge ¶
Challenge returns a 401 with a Bearer challenge so clients know to present credentials. The realm appears in the WWW-Authenticate header per RFC 6750.
func Deny ¶
Deny returns a Reject action with a code and short reason. HTTP status is derived from the code via StatusFromCode.
func DenyStatus ¶
DenyStatus overrides the HTTP status inferred from Code. Use when the code-to-status default doesn't match the caller's intent (e.g. a policy plugin that wants a 451 Unavailable For Legal Reasons).
func DenyWithDetails ¶
DenyWithDetails attaches plugin-arbitrary structured context. The details map surfaces as a "details" object in the default JSON body and is available to clients parsing the error programmatically.
func MocaRefusal ¶
MocaRefusal builds the MOCA egress contract's refusal shape: a Reject whose rendered response is the status, the header "X-Moca-Egress-Error: <code>", Content-Type text/plain, and the body "<code>: <name>\n" — exactly what the moca egress conformance suite's wantRefusal asserts for every refusal family (destination_denied, destination_private, plaintext_credential, conn_cap, upstream_unreachable). name is family-specific: destination_denied names the host, conn_cap the VM, upstream_unreachable the host.
"X-Moca-Egress-Error" is that contract's wire identifier, used verbatim for the same reason x-authbridge-* is: another system's harness matches it byte for byte, and a "nicer" spelling here breaks the conformance run.
Because the Violation carries a pre-rendered body, Violation.Render emits it unchanged and every listener's WriteRejection delivers the contract shape as-is. Do NOT route one of these through WriteRejectionForRequest on a path where the named refusal IS the answer: the MCP JSON-RPC 200 rewrite would hide it behind a protocol frame.
name is HTML-escaped into the body. Every name the contract defines — a host, a VM id — is drawn from a character set EscapeString never touches, so the conformance bytes are identical for every legitimate input; the escape only bites on a hostile "host" carrying HTML metacharacters, which no valid destination can. The body is client-visible reflection, so it gets the same neutralisation any reflected value owes (CodeQL's reflected- XSS query, the high-severity alert this keeps closed), and the refusal's header stays the raw code, which is a constant of the contract.
type ActionType ¶
type ActionType int
ActionType represents the result of a plugin's processing.
const ( // Continue the pipeline to the next plugin. Continue ActionType = iota // Reject the request; the listener synthesizes an HTTP response from // the accompanying Violation. Reject )
type AgentIdentity ¶
AgentIdentity carries the agent's own workload identity.
type Configurable ¶
type Configurable interface {
Configure(raw json.RawMessage) error
}
Configurable is an optional interface plugins implement when they need per-instance configuration. The pipeline builder calls Configure exactly once per instance, during pipeline construction, before Start. Plugins that don't need config simply omit this interface; the builder skips them.
The contract is deliberately narrow:
- The raw argument is the plugin's own config subtree from the runtime YAML, as json.RawMessage — the framework does not interpret it.
- Plugins decode with DisallowUnknownFields so stale or misspelled keys are rejected loudly at startup rather than silently ignored.
- Plugins apply their own defaults and run their own validation, then construct any internal state needed at request time.
- An error from Configure aborts pipeline construction and takes the process down; do not partial-initialize and return nil.
See docs/plugin-reference.md for the recommended shape of per-plugin config and a worked example.
type Context ¶
type Context struct {
Direction Direction
Method string
// Scheme is the URL scheme of the request, typically "http" or
// "https" — future transports ("ws" / "wss" / gRPC-specific
// schemes) pass through unchanged as free-form strings. Populated
// by the listener at pctx construction from the transport-native
// field: the :scheme pseudo-header in ext_proc,
// r.URL.Scheme in the forward and reverse proxies.
//
// Empty when the listener can't determine scheme (legacy test
// fixtures, an unrecognized transport, etc.). Plugins that need a
// concrete scheme should pick a default explicitly — treating ""
// as "assume http" would silently mask missing listener plumbing.
Scheme string
Host string
// Path is the URL path of the request, never including a query
// string: the proxy listeners populate it from r.URL.Path, and
// ext_proc runs the raw request target through the same
// URL parser (httpx.PathOnly → url.ParseRequestURI), so the value
// is identical across listener modes — modulo unparseable targets,
// which net/http rejects with 400 before any pipeline runs and the
// Envoy-fed listeners keep query-stripped but otherwise raw.
// Plugins may match, log, or feed Path into policy without
// stripping a query themselves.
Path string
Headers http.Header
Body []byte // nil unless at least one plugin declares BodyAccess: true
// UpgradeStripped names the protocol the client asked to switch to —
// "websocket" in every case seen so far — on a request whose Upgrade header
// the forward proxy then removed. Empty on every other request, which is
// almost all of them: a WebSocket the proxy FORWARDS (#1488) carries no
// marker, because nothing was stripped.
//
// Set by the listener, not a plugin, and purely diagnostic: nothing reads it
// to change behaviour. It exists because the stripping is CORRECT and its
// consequence was baffling. RFC 9110 makes Upgrade hop-by-hop, so a proxy
// must not forward it on an ordinary request; but a stripped upgrade request
// reaches the origin as a bare GET, and an origin whose endpoint takes a POST
// or an upgrade and nothing else answers 405. Codex did exactly this against
// chatgpt.com, retried about five times
// over roughly six seconds, falls back to HTTPS and works — leaving the user
// looking at `405 Method Not Allowed` in their agent's output with every
// reason to think Cortex broke, and an event saying only `backend_error/405`
// with nothing connecting the two. (Codex no longer reaches that 405 by default:
// the forward proxy carries a Responses API WebSocket and parses its turns, or
// answers it 426 itself, which Codex reads as "use HTTPS" at once — see
// listener.responses_websockets. A declined one keeps the marker, since its
// upgrade was not forwarded either; a carried one clears it as soon as the origin
// answers the forwarded upgrade, refusal or not, and a dial that failed keeps it.
// Every other WebSocket, and a Responses one under forward, is forwarded, and
// those rows carry no marker.)
//
// Recorded on the REQUEST row, where the fact is true, and paired with the
// response row's status by RequestID — the same split Tunnel/TunnelReason use.
// Independent of what came back on purpose: that an upgrade was stripped is
// true whether the origin answered 405, 200 or nothing at all, and a marker
// that only appeared alongside a failure would be useless for the case where
// an origin quietly serves the un-upgraded request instead.
UpgradeStripped string
// DialedAddr is the address the listener dialed for this request, "ip:port",
// set when the egress guard is enabled — the resolved address the guard
// checked, which may differ from Host whenever the destination was named.
// Read by the recorder onto SessionEvent.DialAddr; moca's egress conformance
// pins it as the audit trail against DNS rebinding. Listener-set: a plugin
// has no way to write it, for the same reason it has no way to write Host
// after the dial.
DialedAddr string
// StartedAt is the wall-clock time this context was constructed by the
// listener at the start of a request. Used on the response path to
// compute SessionEvent.Duration without walking the event history.
StartedAt time.Time
// ResponseHeadersAt is the wall-clock time the upstream's response HEADERS
// arrived — when client.Do returned (both proxy listeners) or Envoy delivered
// the response-headers callback (extproc). Set by the listener, once, on the
// arm that actually got a response; left zero on a failed exchange, so
// SessionEvent.Ttfb stays absent rather than reporting a figure for a call
// that never answered (#1251). Together with StartedAt it decomposes a
// response's Duration: ttfb is how long the origin took to answer, and the
// remainder is the body — for a streamed completion, how long it took to
// finish streaming. Duration alone cannot tell a slow-to-answer origin from
// a slow-to-finish stream, which is the distinction an operator sorting by
// duration is usually asking the timeline for.
ResponseHeadersAt time.Time
// UpstreamSentAt is the wall-clock time the listener handed the request to
// the upstream: just before the first client.Do (forward proxy, hop path
// included), just before the reverse proxy's ServeHTTP, or when ext_proc
// answered the last request-phase message and Envoy forwarded. Set by the
// listener, once, at the FIRST send: a resend (forward proxy resendIfAsked)
// comes after an upstream round trip, and counting from it would bill the
// origin's time to the proxy. StartedAt → UpstreamSentAt is the time the
// proxy's own request-side work added (SessionEvent.Added). Zero when the
// request never left (a denial, a refused destination).
UpstreamSentAt time.Time
Agent *AgentIdentity
Identity Identity // nil before an auth plugin runs
// Session is the session this request belongs to, and the identity a plugin
// should key any per-session state on (Redis counters, engine state,
// correlation). Read-only; see SessionView.
//
// Three things a plugin must know about it:
//
// - It may be nil, and nil means "no session identity is known" — not
// "sessions are off". A plugin that needs one must decide what to do
// without it rather than assume a fallback bucket; being handed a shared
// bucket instead would silently pool unrelated traffic under one key.
// - Events may be empty while ID is set. A session's first request is
// hydrated before its first event is recorded, so an empty view means
// "this session, nothing recorded yet". Key on the ID regardless (read
// SessionID); treating an empty view as absent skips the first request of
// every session.
// - ID may be CLIENT-ASSERTED. Listeners resolve it from a client-supplied
// header where one is configured (see session.IDFromHeaders), falling
// back to the most recently active session and then, for recording only,
// a shared default bucket. It is validated but not authenticated, so it
// is an observability and correlation key, not an authorization subject.
Session *SessionView
// SessionID is Session.ID: the id of the session handed to plugins. It is
// empty when there is no Session. A listener that sets Session must also set
// SessionID. Pipeline.Run fills it from Session when it is empty. A plugin
// that keys state on the session and reads no events reads this field,
// because it needs no nil check. The same rules as Session.ID apply to it.
SessionID string
// SessionSource says how the listener resolved Session, so a plugin that
// keys security state on it can tell a session the request named from one
// the listener guessed. Empty when the listener does not record it; treat
// that as a guess. SessionHeader is the header that named the session when
// SessionSource is SessionSourceHeader.
SessionSource SessionSource
SessionHeader string
// ChainSession is the session a process above the sender in its process
// chain named, when the listener can see the chain: the session of the
// agent that started the sender. It can differ from Session, which follows
// a session the sender named itself. A plugin keying security state on the
// session should prefer it, so a child process cannot name a fresh session
// to leave its parent's.
ChainSession string
// OutboundSessionID pins the session bucket the outbound REQUEST event was
// recorded under, so the paired RESPONSE event lands in the same session.
// recordOutboundResponseEvent reuses it instead of re-resolving
// Store.ActiveSession() at response time: ActiveSession() returns the global
// "most-recently-updated session", which interleaving traffic (e.g. a health
// probe bucketed under "default") can flip between a streaming request and
// its response, mis-filing the response into the wrong session. Empty when
// no request event was recorded (skip_hosts, sessions disabled), in which
// case the response recorder falls back to ActiveSession().
//
// Listeners MUST assign this only after the request pipeline has run, and
// must not read it back as the source of truth for recording. It is
// exported, so a plugin can write it; the listener's own resolution is held
// in a local for exactly that reason, and assigning last means a plugin
// write is overwritten rather than able to silently re-file this request and
// its response into a session of the plugin's choosing. Plugins wanting to
// influence attribution should say so through their own invocation records,
// where it is visible.
OutboundSessionID string
// TLS is the connection state of the inbound TLS handshake when
// the request arrived over TLS, nil otherwise. Populated by the
// reverse-proxy listener; nil for plaintext callers (UI, curl,
// healthchecks), outbound contexts, and any path that doesn't go
// through the proxy-sidecar reverse-proxy (envoy-sidecar mode
// terminates TLS in Envoy and never populates this field).
//
// Plugins that want per-caller policy use the convenience method
// PeerCertificate() to get the leaf cert and core/tlsconfig.PeerSPIFFEID
// to extract the URI SAN. Listeners use it to populate
// SessionEvent.TLS for the observability surface.
TLS *tls.ConnectionState
// when no store is wired; plugins that require it must fail closed.
Shared SharedStore
// Response-phase fields (populated by listener before RunResponse).
// ResponseBody may be nil even during response phase if no plugin declared BodyAccess.
StatusCode int
ResponseHeaders http.Header
ResponseBody []byte
// ResponseBytes is how many response-body bytes the listener observed on the
// wire, summed across every chunk. SessionEvent.BytesDown is recorded from it,
// and it is authoritative over len(ResponseBody) — which is a BUFFER, not a
// tally, and is wrong on three separate paths: extproc REPLACES it per chunk
// on the SSE arm (so it holds only the trailing chunk), extproc truncates it
// at the listener's cap, and neither proxy's streaming relay fills it at all.
// Reading the buffer's length at a record site would report a confident wrong
// number on exactly the streamed inference traffic the count is wanted for.
//
// ON THE WIRE is the part that makes the three listeners agree, and it is not
// the obvious reading: the proxies' SSE arms handle sseframe PAYLOADS, with
// the `data: ` prefixes and blank-line separators already stripped, while
// extproc counts the raw chunks Envoy hands it. Counting what each arm has in
// hand put the two 32 bytes apart on a four-event fixture. So the proxies
// count at one choke point per listener (see listener/internal/bodycount) and
// extproc sums its chunks, and all three report the body the destination sent.
//
// Zero means the listener counted nothing — no plugin asked for the body, so
// it was relayed without passing through a counted path — and NOT that the
// body was empty. Consumers render that as unknown rather than as 0 B; see
// SessionEvent.BytesDown.
//
// Another goroutine reads it while the body streams: the Timeline's live
// token estimate (#1861) reads forwardproxy's count through
// session.Store.StreamBytes, with atomic.LoadInt64. So every write must be
// atomic (atomic.AddInt64 or atomic.StoreInt64). Extproc's write is still
// plain, and is safe only because no live stream is tracked for it. Plugins
// do not write to it.
ResponseBytes int64
// ResponseCapture is the response body as the listener read it off the wire, for the
// session archive's lossless capture (#1494): up to MaxResponseCapture bytes, set by the
// listener and read when the response row is recorded. Plugins do not use it.
ResponseCapture *ResponseCapture
Extensions Extensions
// contains filtered or unexported fields
}
Context is the shared state passed through the plugin pipeline. Plugins read and mutate fields directly — there is no separate mutation API.
func (*Context) AccountingThread ¶
AccountingThread returns the thread SetAccountingThread named, with ok false when none did.
func (*Context) Allow ¶
Allow records an Invocation with Action=allow and the given Reason. Convenience for gate plugins on the approved branch.
func (*Context) AttributedClientProc ¶
AttributedClientProc is the pinned client process when it differs from AttributedProc (a worker under its launcher), "" otherwise. Recorded as SessionEvent.ClientProc.
func (*Context) AttributedProc ¶
AttributedProc is the pinned process, "" when the listener could not name it or pinned nothing. Recorded as SessionEvent.Proc.
func (*Context) BilledBody ¶
BilledBody returns forwarded as the provider bills it: forwarded itself when no plugin set SetBilledBody. See SetBilledBody.
func (*Context) BillingOverride ¶
func (c *Context) BillingOverride() (mode accountant.BillingMode, ok bool)
BillingOverride returns the mode SetBillingOverride pinned, with ok false when no plugin called it — the common case, where the client's own credential (BillingSnapshot) is the one that reaches the destination unchanged.
func (*Context) BillingSnapshot ¶
func (c *Context) BillingSnapshot() accountant.Billing
BillingSnapshot returns accountant.BillingFrom(c.Headers) as it stood the FIRST time this pctx was handed to a Pipeline.Run — before any plugin, inbound or outbound, can have rewritten the credential header BillingFrom reads. Computed and cached lazily, so a caller that reaches it before any Run (a test, or a listener that reads it itself) still gets a stable answer: once taken, the snapshot never changes, even if Headers does later.
Why it has to be this early: what BillingFrom must see is the CLIENT's credential, and the outbound chain's own plugins replace it before the request leaves — token-exchange, tokenbroker, inference-router's setKey and staticinject all rewrite Authorization. Read after them, the mode would be misclassified (often as "unknown", which drops every saving out of the dollar totals).
No shipped listener shares one pctx between chains: extproc builds a fresh one in each of handleInbound, handleInboundBody, handleOutbound and handleOutboundBody; reverseproxy runs only the inbound chain and forwardproxy only the outbound one. Pipeline.Run still calls this on every direction's Pipeline, so a listener that did run both chains on one pctx would get the snapshot from the first Run, before an inbound rewrite (jwt-validation's placeholder_mode) too.
func (*Context) BodyMutated ¶
BodyMutated reports whether some plugin's SetBody took effect during this request. Listeners check this after Run to decide whether to emit a body mutation on the wire. Stream-scoped — a new Context starts with false regardless of what a previous request did.
REQUEST-WIDE, not the caller's: with several writers it is true once any of them took effect, including for a later writer whose own call was a shadow under on_error: observe. A writer learns whether its own write applied from SetBody's result.
func (*Context) Classification ¶
Classification reports the request's protocol classification, aggregated across every populated protocol extension on Extensions:
- anyAction is true if at least one populated extension has IsAction=true (e.g. mcp-parser saw "tools/call"; inference-parser saw any inference call).
- anyBypass is true if at least one populated extension has IsAction=false (e.g. mcp-parser saw "tools/list" or a $transport/* synthetic event).
Both false means no parser populated anything and the request is unclassified — guardrails treating IBAC-style defense in depth (only fire on traffic a parser claimed) should pass through.
Parser-disjointness assumption. The current in-tree parsers fire on disjoint request shapes — mcp-parser on JSON-RPC bodies (or body- less MCP-shaped requests on configured paths), a2a-parser on A2A JSON-RPC bodies, inference-parser on /v1/{chat/,}completions paths — so a single request typically populates at most one extension. The aggregation above is defensive (handles the multi-extension case if a future hybrid transport ever does double-claim), but parser authors should not rely on the aggregation as a feature: a parser that populates an extension on a request another parser already classified breaks the contract that classification belongs to whichever parser owns the wire shape.
Conflict resolution. If anyAction && anyBypass both end up true, callers decide their own precedence:
- Defense-in-depth gates (IBAC, rate limiters): treat anyBypass as winning — skip first. Safer default when you can't tell who to trust.
- Audit-style guardrails: probably want to log the action even if some extension said bypass; flip the precedence.
Either choice is valid; the contract here just provides both signals. In practice the question rarely comes up because of the disjointness above.
func (*Context) ClearCurrentPlugin ¶
func (c *Context) ClearCurrentPlugin()
ClearCurrentPlugin resets the framework-owned attribution fields. Paired with SetCurrentPlugin.
func (*Context) ClientBody ¶
ClientBody is the request body as the client sent it, before the first plugin ran. Nil when the pipeline has no accountant: nothing is kept then.
It is the listener's own slice, not a copy. That is safe because SetBody replaces pctx.Body rather than writing into it, so a mutator's rewrite leaves the client's bytes as they were. A plugin must not write into pctx.Body in place; none does.
func (*Context) ClientCompaction ¶
func (c *Context) ClientCompaction() accountant.CompactionTrigger
ClientCompaction returns the verdict SetClientCompaction recorded, or "" when none did.
func (*Context) ClientInfo ¶
func (c *Context) ClientInfo() *EventClient
ClientInfo returns the calling coding agent, parsed from this request's User-Agent and memoized.
CLIENT-ASSERTED AND TRIVIALLY SPOOFABLE — an observability and cost-attribution key, never an authorization subject. See EventClient, and note that this is NOT Identity: that field is the authenticated principal, this one is a self-reported software label.
Nil means no User-Agent was sent. Callers do not nil-check: EventClient.Label() is nil-safe and answers "unknown".
Resolved HERE — once, on the context — rather than assigned by each listener or re-derived by each consumer. That follows the same doctrine Session states: the value is resolved in one place and never re-derived downstream, because two derivations of one fact are how the two drift apart. Session needs a listener to assign it since it comes from a store lookup; this one does not, because Context already carries the request headers, so an assignment would be a second source of a truth already present. It is also stronger than an assignment for the failure that actually happens: a listener-populated field can be forgotten at one of several context-construction sites and serialize a clean empty value, whereas an accessor over Headers cannot be.
"Once" is a claim about WHICH ANSWER, and on its own it is weaker than it sounds: the memo fills on the FIRST CALL, and the first call is at an event-construction site downstream of the pipeline. Headers is mutable and plugins write to it, so a plugin that rewrote User-Agent would change what an event is attributed to, and which recording site asked first would decide the answer. What makes "once" an ordering guarantee too is ResolveClient, which the listeners call at construction: see there for the guarantee in full, and for what holds on a Context that skips it.
NOT goroutine-safe, and that is correct: a Context belongs to one request and the pipeline runs its phases sequentially. Said explicitly because the surrounding type does have fields other goroutines read.
THE PIN IS WHAT MAKES THAT SAFE FOR RECORDING SITES, WHICH ARE NOT PIPELINE PHASES. The first call writes clientParsed and client, unsynchronised, and the callers are recorders — a response-path recorder, and on ext_proc a streaming-response append — so two of them reaching a FIRST ClientInfo() on one Context is a data race, not merely a wrong label. ResolveClient having already filled the memo is what rules that out: after it, every call here is a pure read.
A nil Headers map is fine and answers nil. A nil RECEIVER panics, unlike PeerCertificate above, and that difference is deliberate rather than an oversight: this mutates the memo, so it cannot be a no-op on nil, and every caller is an event-construction site that already dereferences pctx for Host and Method on adjacent lines. A guard here would convert a programming error into a silently unattributed event instead of a stack trace.
A COPY IS RETURNED, NOT THE MEMO. Every caller is an event-construction site that stores the result on a SessionEvent, so handing out the memoized pointer would make ten events share one mutable struct, and a single write through it would relabel events already appended to the store and already being served by the session API. See snapshotClient: the same rule every other extension on that event follows. The memo is what stops the header being parsed ten times; it does not escape.
THE COPY IS AN ALLOCATION PER CALL, roughly ten per request, and that is the price of the line above. SanitizeControlRunes's fast path is written not to allocate, which bounds what a hostile header costs; this one is unconditional and buys the integrity claim instead.
func (*Context) ContentSources ¶
func (c *Context) ContentSources() []capabilities.ContentSource
ContentSources returns every protocol extension on this Context that implements capabilities.ContentSource. Guardrail plugins call this to iterate inspectable text across whatever protocol a request happens to carry, without importing any specific parser package:
for _, src := range pctx.ContentSources() {
for _, f := range src.Fragments() {
if f.Role == capabilities.RoleUser { scan(f.Text) }
}
}
Order is A2A, MCP, Inference — but guardrails shouldn't rely on it; treat the result as an unordered set. Returns an empty slice when no parser produced an extension or when none of the populated extensions implement ContentSource.
func (*Context) CurrentPhase ¶
func (c *Context) CurrentPhase() InvocationPhase
CurrentPhase reports the phase of the plugin dispatch currently in flight — InvocationPhaseRequest while Pipeline.Run is iterating OnRequest, InvocationPhaseResponse while Pipeline.RunResponse is iterating OnResponse, and "" outside a dispatch. Plugins read it to distinguish request from response without inferring the phase from body presence (an empty-bodied 204 response would otherwise look like a request). Set by the framework via setCurrent before each dispatch; see SetCurrentPlugin.
func (*Context) DenyAndRecord ¶
DenyAndRecord records an Invocation with Action=deny AND returns a Reject Action. Bundles the two steps a gate plugin always does together on the deny path — emit the diagnostic record, then return the Action that changes control flow.
code/message become the pipeline.Violation that the listener serializes to an HTTP response. Reason becomes the Invocation's machine-stable reason code.
If the plugin has richer diagnostic data to attach to the Invocation (ExpectedIssuer, TokenScopes, etc.), use the two-step form: call pctx.Record(Invocation{...}) explicitly, then return pipeline.Deny.
func (*Context) InferenceHosts ¶
func (c *Context) InferenceHosts() (InferenceHosts, bool)
InferenceHosts is the InferenceHosts table of the request's session, and SessionFacts.HostsKnown: false means "do not use the table". The rules, in order:
- Session is nil: (nil, false), also when the listener set facts.
- The listener called SetSessionFacts: the table and HostsKnown it set.
- Else (nil, false). A view cannot vouch for a table: it can be a trimmed part of the session.
Do not change the returned slice: every plugin of the request gets the same one.
func (*Context) LastInference ¶
func (c *Context) LastInference() SessionFact
LastInference is the newest outbound inference request (model.IsInferenceRequest) of the request's session, by the same rules as LastIntent.
func (*Context) LastIntent ¶
func (c *Context) LastIntent() SessionFact
LastIntent is the newest user intent (model.IsIntent) of the request's session. The rules, in order:
- Session is nil: FactNoSession, also when the listener set facts.
- The listener called SetSessionFacts: the fact it set.
- Else from Session.Events: FactPresent with Event in Session.Events, or FactNone.
A plugin reads this, not Session.Events.
func (*Context) MarkRedirectable ¶
func (c *Context) MarkRedirectable()
MarkRedirectable says the listener builds the upstream request from this context itself, after the pipeline, so a Redirect can take effect. The forward proxy calls it for every request it re-originates, plain or TLS-bridged.
A listener must not call it for a context it cannot redirect. The outbound pipeline also runs once per CONNECT and once per transparently redirected connection, and both dial the address the client chose whatever a plugin does: a redirect accepted there would be recorded and never happen.
Listener-facing, like SetCurrentPlugin. Production plugins never call this.
func (*Context) MarkResend ¶
MarkResend names why a Resender that returns true wants the request sent again. A plugin that answers more than one kind of refusal reads ResendReasons to answer each kind at most once per request.
func (*Context) MarkResponseDelivered ¶
func (c *Context) MarkResponseDelivered()
MarkResponseDelivered records that the response has already gone downstream, so any refusal from here on cannot take effect.
A LISTENER'S STATEMENT OF FACT, and only a listener can make it: the pipeline has no idea whether bytes reached a client. ext_proc calls it before its teardown flush — Envoy has finished with the stream by then — and the proxies' finalization paths are the same shape.
WHAT IT CHANGES IS THE OUTCOME, NOT THE RECORD. Invocations appended afterwards are still recorded, and still say deny; they are marked Late so a reader can tell "a plugin refused this" from "this request was refused". What stops being true is the outcome: OutcomeFromContext no longer reports OutcomeDeny on the strength of a refusal that arrived after the response, because a request answered with a 200 was not denied — and every Finisher, every audit row and every dashboard that reads the outcome would otherwise say it was.
Idempotent, and one-way: a response cannot become undelivered.
func (*Context) Modify ¶
Modify records an Invocation with Action=modify. Convenience for plugins that mutated the message (token-exchange replacing the Authorization header, a header-rewriter).
func (*Context) NamedSession ¶
NamedSession is the pinned session id the request named, "" when none was pinned.
func (*Context) NamingHeader ¶
NamingHeader is the pinned session-id header that named the request's session, "" when none did. Recorded as SessionEvent.SessionHeader on the request's own row.
func (*Context) NoRecord ¶
NoRecord reports whether the request asked not to be recorded (#1923): it carried model.RecordHeader set to model.RecordOff. With an own session id (WithholdsSession), it is recorded as SessionEvent.NoRecord on the request's rows, and the archive keeps none of that session's events from then on; what it held before stays.
The first call also deletes model.RecordHeader from Headers. The header is for Cortex only: plugins never see it, and the listeners that send the request on from Headers (httpx.SyncRequestHeaders) do not forward it. ResolveClient makes that first call at construction, before any plugin runs, so a plugin cannot set or clear it either.
Memoized and pinned by ResolveClient on exactly the terms ClientInfo is; see there.
CLIENT-ASSERTED AND UNAUTHENTICATED, like Subagent. It can only withhold the sender's own session from the archive.
func (*Context) Observe ¶
Observe records an Invocation with Action=observe. Convenience for parsers that successfully extracted diagnostic data without modifying the message.
func (*Context) Observing ¶
Observing reports whether the plugin being dispatched runs under ErrorPolicyObserve: nothing it does this pass takes effect, so a plugin that would write state a later enforce pass applies — a pin recorded, an origin kept — must not. Redirect consults the same policy; this is for the paths that return before any redirect is attempted.
func (*Context) OpReporter ¶
func (c *Context) OpReporter() OpReporter
OpReporter captures the plugin being dispatched and its policy (Observing) now, on the request goroutine, so the returned OpReporter's Report method can be called later from any goroutine.
func (*Context) Outcome ¶
Outcome returns the terminal outcome of the request. Valid only during OnFinish — returns nil in OnRequest and OnResponse. Plugins implementing Finisher can rely on the return being non-nil; there is no path in the dispatcher that calls OnFinish with an unpopulated outcome.
func (*Context) ParentProject ¶
ParentProject is the pinned parent project label, "" when none was pinned. Recorded as SessionEvent.ParentProject.
func (*Context) ParentSession ¶
ParentSession is the pinned parent session, "" when none was pinned. Recorded as SessionEvent.ParentSession.
func (*Context) ParentSubagent ¶
ParentSubagent returns the agent that started this request's subagent: the value of X-Claude-Code-Parent-Agent-Id as the client sent it, or "" when there is none to record. Read with Subagent and pinned with it, under the same rules.
"" is the common answer and says the parent is the CONVERSATION, not that it is unknown: Claude Code sends the header only when the spawner was itself an agent, so on a subagent the main conversation started — every subagent there is, in a session that nests none — it is absent by design. The other three empty cases are Subagent's: a non-subagent request, a row with no headers, and a value model.SubagentHeader refused.
Recorded independently of Subagent rather than dropped when Subagent is empty. A parent with no child is not a shape the CLI produces, so if one ever appears it is evidence of a client this code was not written against, and keeping it is what lets someone see that.
func (*Context) PeerCertificate ¶
func (c *Context) PeerCertificate() *x509.Certificate
PeerCertificate returns the verified peer leaf certificate from the TLS connection state, or nil when the connection was plaintext or carried no peer cert. Convenience accessor so plugins don't have to bounds-check the slice.
func (*Context) Project ¶
Project is the pinned project label, "" when none was pinned. Recorded as SessionEvent.Project.
func (*Context) Record ¶
func (c *Context) Record(inv Invocation)
Record appends an Invocation to pctx under the current pipeline direction and framework-stamped plugin + phase. The author supplies only what's specific to this call (Action, Reason, plus any diagnostic fields like ExpectedIssuer, RouteHost, CacheHit); Plugin, Phase, and Path are populated automatically from pctx.
Authors may set Plugin, Phase, or Path on the argument explicitly to override the framework defaults — useful for test helpers or for a plugin synthesizing an invocation on behalf of a delegated sub-plugin. In normal plugin code, leave those fields zero.
For the bare (Action, Reason) case, prefer the convenience wrappers (Allow / Skip / Observe / Modify) below — one line each.
func (*Context) RecordHeaderSeen ¶
RecordHeaderSeen reports whether the client sent model.RecordHeader, with any value. NoRecord removed it from Headers, which is enough for a listener that forwards from Headers. One that forwards the wire headers and emits changes (ext_proc) must remove it explicitly.
func (*Context) RecordStrippedUpgrade ¶
RecordStrippedUpgrade notes that h carried an Upgrade header the caller is about to remove, so the session event can say so — see UpgradeStripped for why that is worth recording. A no-op when h has no Upgrade, which is almost every request. Call it BEFORE stripping, since it reads the value it records.
It lives here rather than in the listener so the value goes through the same sanitize-then-cap a User-Agent does: Upgrade is client-controlled and lands in a JSON event an operator reads in a terminal, so a "protocol name" made of escape sequences must not survive the trip. The bound is maxClientLen, shared with the User-Agent deliberately — a protocol token needs far less, and a second constant would be one more thing to keep in step for no gain. The ORDER of the two steps is load-bearing in the same direction as ParseUserAgent's: a substitution can grow the string, so capping first would let a short header become a long field.
Records the WHOLE header value, not the first token. RFC 9110 allows a list — "Upgrade: HTTP/2.0, websocket" — and which element the origin would have picked is not ours to guess, so this stays a statement about what the client asked for rather than a prediction about what it would have got.
func (*Context) Redirect ¶
Redirect sends the request to target instead of the host the client named.
target must be absolute — scheme http or https, a host, an optional port — and carry nothing else: no user info, no path beyond "/", no query, no fragment. A redirect changes where a request goes and nothing about what it says; the path, headers and body stay the plugin's to change through the existing APIs.
It sets Scheme and Host to the target's. Host following the redirect is the point: the session events, usage, the cost ledger and modelled pricing all key on it, and they must describe where the bytes went. Plugins that run after this one and key on Host see the new host for the same reason. The host the client named stays available as RequestedHost. The validated target is also kept privately, and that copy is what the listener applies (see RedirectTarget): Scheme and Host are any plugin's to write, so a later write to them cannot move the request.
The framework records the redirect as a modify/redirected Invocation with "from" and "to" in Details, as SetBody records a body rewrite: a redirect moves the request and its credentials to another host, so the timeline shows it even if the plugin records nothing of its own. Under on_error: observe nothing moves and the Invocation is marked Shadow, so plugin code looks the same under enforce and observe.
What a redirect does not do. The request's headers — credentials included — go to the new host unchanged. And it does not gate the plugin's own header writes: under observe nothing moves while those still apply, so a plugin that attaches credentials meant for the target must do so only when the request actually goes there — check Redirected after the call, which stays false under observe and on a refusal. Redirected is the only safe gate: pctx.Host names what the client asked for and, on a TLS-bridged request, is the client's own Host header, which need not match the address the proxy dials. A plugin that attaches credentials meant for a server should always Redirect to that server, even when pctx.Host already names it, so the request is dialed there. Plugins earlier in the chain made their decisions on the requested host and are not run again.
Refused, with nothing changed and nothing recorded, when the calling plugin does not declare WritesDestination, when the listener did not mark the context redirectable, when the target is malformed, and outside OnRequest.
func (*Context) RedirectPath ¶
RedirectPath is the path SetRedirectPath set, with ok only when one was set on a request a Redirect moved. Listeners apply it with RedirectTarget, never the exported Path, for the reason RedirectTarget gives.
func (*Context) RedirectTarget ¶
RedirectTarget is the scheme and host the last accepted Redirect validated, with ok exactly when Redirected. Listeners apply this, never the exported Scheme and Host: any plugin may write those, declared or not, so a listener that read them back would let a later plugin steer a redirected request somewhere no WritesDestination plugin chose, and the modify/redirected record would name a host the bytes never went to.
func (*Context) Redirectable ¶
Redirectable reports whether the listener will honor a Redirect on this request. A routing plugin checks it first, so that it acts only on requests it can move.
func (*Context) Redirected ¶
Redirected reports whether a Redirect took effect on this request, and is the ok RedirectTarget reports. The listener keys on that, not on RequestedHost: a redirect that changed only the scheme, or that pointed back at the host the client named, still has to be applied.
It is also the only safe gate for a plugin that attaches credentials meant for the target. The request's headers go wherever the request goes, and Redirect returns nil under on_error: observe without moving anything, so a key set on the strength of that nil alone would reach the host the client named. Redirected stays false under observe and after a refusal. Comparing pctx.Host with the target is unsafe: on a TLS-bridged request, pctx.Host is the client's own Host header, not necessarily the address the proxy will dial.
func (*Context) RejectingPlugin ¶
RejectingPlugin returns the name of the plugin whose Reject action stopped the pipeline, or "" if the pipeline allowed end-to-end. Populated by Pipeline.Run / RunResponse before they return; callable from OnFinish, listener code, or anywhere else that needs to know the denier without walking Invocations.
Shadow-mode denials (policy == observe, where the plugin's Reject was converted to a pass-through) do not set this field — the framework treats shadow rejections as "the pipeline effectively allowed," which matches how agentop and the session store classify them.
func (*Context) RenewRequestID ¶
func (c *Context) RenewRequestID()
RenewRequestID gives the context a new request id. Listener-facing: a listener that sends a request again calls it before recording the second attempt, which is a request of its own on the timeline and must not pair with the first one's answer.
func (*Context) ReportOps ¶
func (c *Context) ReportOps(ops ...accountant.Operation)
ReportOps records the context operations a plugin made on this request, for the accountant (accountant/docs/cortex-wiring.md W5.1). The ops are kept in call order, which is pipeline order.
The framework stamps two fields, so a plugin does not have to know its own name or policy: Operator is set to the plugin's name when the plugin left it empty, and DryRun is set when the plugin runs under on_error: observe, because its write was computed and not sent. A DryRun the plugin set itself is kept. A plugin whose write did not apply reports the op with DryRun set, or no op.
The stamp reads the plugin being dispatched, so ReportOps belongs on the request goroutine, inside OnRequest. A report from any other goroutine uses OpReporter.
func (*Context) ReportedOps ¶
func (c *Context) ReportedOps() []accountant.Operation
ReportedOps returns a copy of the ops reported so far, in the order they were reported.
func (*Context) RequestID ¶
RequestID returns a stable identifier for this request, generated on first use. Session events carry it so a consumer can pair a request event with its response event.
Without it, pairing is positional — a UI matches a request row to whatever response row follows it — which silently misattributes whenever a client has more than one request in flight. That produced a real misdiagnosis: a plugin was blamed for a 400 that belonged to a concurrent request it never touched.
Generated lazily rather than at Context construction so no listener can forget it; there are several construction sites and adding one more required field would be a standing trap. Contexts are single-goroutine by contract (plugins mutate Body, Headers and Extensions without locks), so the lazy write needs no synchronisation.
func (*Context) RequestModel ¶
RequestModel is the model the request body asks for: its top-level "model" string, exactly as SetRequestModel would find and replace it. ok is false where SetRequestModel would refuse the body — none, not valid JSON, no top-level string "model", an empty one, or "model" named more than once in any letter case.
A plugin that decides on the model reads it here rather than parsing the body itself, so the name it decides on is the name SetRequestModel replaces.
func (*Context) RequestedHost ¶
RequestedHost is the host the client named when a redirect sent the request somewhere else, and "" otherwise — including when the redirects ended back at that host. It is what a session event records beside Host. It compares against the target RedirectTarget reports, not the exported Host, so a later write to Host can neither hide a redirect nor invent one.
func (*Context) ResendReasons ¶
ResendReasons returns the reasons named so far for this request, oldest first.
func (*Context) Resendable ¶
Resendable reports whether this request's listener asks the Resenders after a refused answer. A Resender is still asked only under on_error: enforce (Resender).
func (*Context) ResolveClient ¶
func (c *Context) ResolveClient()
ResolveClient pins ClientInfo's answer to the User-Agent AS THE CLIENT SENT IT.
Listeners call it immediately after building a Context from the request, and that call is the whole of the ordering guarantee: the label is resolved before the pipeline runs, so no plugin can change what an event is attributed to, and no recording site can get a different answer by asking first or last. Attribution keys cost — see EventClient — and "which program spent this" must not depend on call order.
A named call rather than a bare `_ = pctx.ClientInfo()` at each site, so the line reads as the invariant it is and a later reader cannot mistake it for a leftover. Deleting it is a behaviour change, and the tests in forwardproxy's client_test.go say so.
It does NOT replace the memo, and the memo is deliberately still lazy. An accessor over Headers answers correctly at a construction site that forgets this call — one answer, for the life of the context, from the headers as they stood when something first asked — where a listener-assigned field would have serialized a clean empty value instead.
What a forgotten call costs is TWO things, not one. The ordering half: on such a Context the answer is pre-plugin by coincidence rather than by construction. And the concurrency half: this call is a pure read only AFTER the memo is filled, so without the pin whichever recording site asks first performs the write instead — see ClientInfo.
Call it AFTER Headers is populated. Called before, it pins nil and the request's own User-Agent is lost — which is why this is a listener's call to make at construction and not something a constructor could do earlier.
WHICH LISTENERS CALL IT, stated precisely because this is the authoritative answer to what "unknown" means on a given listener. In THIS change: the forward proxy, at three construction sites — serveOutbound, handleConnect and HandleTransparentConn. Arriving with the cost work later in this series: ext_proc, at its four, and the reverse proxy, at its one.
Until the second half lands, an inbound event records no client and Label() answers "unknown" for it — while that string is documented as "this request carried no User-Agent". For those events nil means "this listener is not wired yet", which an operator reading a per-agent breakdown cannot tell from absence. Read "unknown" on inbound traffic as unattributed rather than as absent until then.
It pins Subagent's and ParentSubagent's answers too, for the same two reasons: an X-Claude-Code-Agent-Id a plugin rewrote must not re-file a row under another subagent, and recorders reading the memo must not be the ones filling it.
It pins NoRecord too, which also removes model.RecordHeader from Headers, so no plugin sees it and the forwarded request does not carry it.
Idempotent: the second call is the memo's own no-op.
func (*Context) ResponseBodyMutated ¶
ResponseBodyMutated is the response-side analogue of BodyMutated, and answers for the response the same way.
func (*Context) ResponseDelivered ¶
ResponseDelivered reports whether the response has already gone downstream.
func (*Context) SetAccountingThread ¶
SetAccountingThread names the accountant thread for this request, overriding the default rule (core/accounting.ThreadOf: "main", or the subagent id). The context-guru plugin calls it with its own thread split, which it builds from prefix continuity. An empty id is ignored, so a plugin that could not name a thread leaves an earlier choice, or the default, in place.
func (*Context) SetAttribution ¶
SetAttribution pins the process and the naming header the listener's attribution gave this request, for every row recorded from it. FIRST CALL WINS, on ResolveClient's terms: the listener sets it before the pipeline runs, so no plugin can re-attribute a row, and a later re-resolution on a recording path cannot disagree with the first.
proc is attribution.Attribution.Proc, header the session-id header that named the session ("" when none did).
func (*Context) SetBilledBody ¶
SetBilledBody sets how the accountant host reads the forwarded body as the provider bills it (accountant R56). The host calls f once, in RequestEnd, with the body that goes upstream, and records the body f returns. unplaced true means the change cannot be described to the library: the host books no figure for the request (SkipInput.UnplacedDeferral).
context-guru's tool deferral needs it: a tool with defer_loading stays in the bytes sent, but the provider bills no definition for it. RequestEnd reads the hook before the first send, so a Resender does not need to clear it on a resend; the one nil call is OnRequest's own, for a write that SetBody did not apply. Under on_error: observe the call does nothing, because the change was not sent.
func (*Context) SetBillingOverride ¶
func (c *Context) SetBillingOverride(mode accountant.BillingMode)
SetBillingOverride tells the accountant to price this request on mode instead of the client's own credential (BillingSnapshot), because a plugin has replaced the outbound credential with one of its own. inference-router's setAuth calls it with the destination server's own key's mode on every request it routes: that key, not the client's, is what the server actually bills, and BillingSnapshot was taken before setAuth ran (rossoctl/cortex#2074). setAuth never passes an unclassifiable key through as mode == "" — BillingUnknown overrides on purpose there (review finding on #2074's PR) — so the guard below is only for a caller that passes the zero value, which leaves an earlier override, or the client's snapshot, in place. The LAST call before RequestEnd wins, so a request routed more than once is billed on the credential that actually went out.
token-exchange and tokenbroker rewrite Authorization too, but to a credential they hold on the CLIENT's behalf, not one of their own — the client still pays for it — so neither calls this.
func (*Context) SetBody ¶
SetBody replaces the request body with newBody. A plugin that calls it must declare WritesRequestBody: true in its Capabilities — the listener consults pctx.BodyMutated() after Run to decide whether to emit the new bytes on the wire.
It reports whether THIS write took effect. True means pctx.Body is now newBody. From OnRequest those are the bytes the listener sends, or the bytes a later writer starts from and may rewrite in turn; from OnResponse the request has already been sent, so they replace pctx.Body and go nowhere. False means pctx.Body is unchanged: the calling plugin runs under on_error: observe, so this was a shadow write, or the call was dropped in OnFinish. A writer that reports or counts its own outcome — applied or only measured — reads this result, never BodyMutated(): that one answers for the request, so after an earlier writer's bytes took effect it says true for a shadow write too. Callers that need neither may ignore the result.
NOTE — the capability is a contract, not an enforcement. SetBody sets bodyMutated unconditionally outside observe mode, and the listeners gate purely on pctx.BodyMutated(), so a plugin that calls SetBody WITHOUT declaring the capability still reaches the wire. This divergence is documented rather than closed: adding the enforcement silently would break any out-of-tree plugin relying on today's behaviour, so it needs its own compatibility review. Do not read it as licence to skip the declaration in order to keep response streaming — declaring WritesRequestBody costs no streaming (see PluginCapabilities).
Under ErrorPolicyObserve (shadow mode) SetBody is a NO-OP on bytes: the in-memory body is not replaced, this call does not set bodyMutated, and downstream plugins continue to see the body as it was. A modify Invocation is still recorded — with Shadow=true — so operators can count "would have redacted" on the rollout dashboard. Plugin code therefore looks identical under enforce and observe; only the result differs.
SetBody auto-emits a modify-action Invocation with Reason "body_rewritten" and publishes a plugin-public event under "body-mutation/event" carrying the before/after length and sha256 — never the body content. The session store has no auth, so raw bodies would be a privacy / credential leak.
Callers should NOT assign pctx.Body directly — the listener wouldn't know to propagate the change, and the Invocation wouldn't be emitted.
func (*Context) SetClientCompaction ¶
func (c *Context) SetClientCompaction(t accountant.CompactionTrigger)
SetClientCompaction records that this request is the first one after a client compaction (accountant R55). The context-guru plugin calls it from its thread tracker. The accounting host passes it to the accountant as RequestMeta.Compaction. An empty trigger is ignored, so a plugin that saw no compaction leaves an earlier verdict in place.
func (*Context) SetCurrentPlugin ¶
func (c *Context) SetCurrentPlugin(name string, phase InvocationPhase)
SetCurrentPlugin is called by Pipeline.Run / RunResponse immediately before dispatching into a plugin's OnRequest / OnResponse. It stamps the plugin name and phase onto pctx so the Record family of helpers can fill those fields without plugin-side ceremony. Reset with ClearCurrentPlugin after dispatch.
Exported (rather than framework-private) because listeners that embed pctx in their own dispatch loops (not strictly via Pipeline.Run) need to set the same fields to get consistent Invocation attribution. Production plugins should never call this directly.
Sets the policy to the default (enforce). Call setCurrent (unexported) to stamp a non-default policy — only Pipeline.Run/RunResponse should supply a non-default, and they use the unexported path.
func (*Context) SetNamedSession ¶
SetNamedSession pins the session id the request named with its session-id header (the one NamingHeader names), "" when none did. FIRST CALL WINS, with its own flag, as SetProject does: the listener sets it with SetAttribution, before any plugin runs, so a plugin that rewrites the session-id header cannot change which session the request named (#1923).
func (*Context) SetParent ¶
SetParent pins the parent session (the session that the topmost process above this request's agent named, when it is not this request's session) and the project label of the process that holds it, for every row recorded from this request. FIRST CALL WINS, as SetProject does, with its own flag: a path that pins "", "" keeps them, and no later call can write a parent.
func (*Context) SetProject ¶
SetProject pins the project label (project.Label of the agent process's repo root) for every row recorded from this request. FIRST CALL WINS, as SetAttribution does, with its own flag: a path that pins "" keeps "", and no later call can write a label.
func (*Context) SetRedirectPath ¶
SetRedirectPath sends a redirected request to path on its new host instead of the path the client named. A redirect alone changes only where a request goes, and that is enough between servers that take an API under the same path. A server that takes it under another — /v1/chat/completions where the client named /zen/v1/chat/completions — needs the path too, and this is how a routing plugin says so.
Accepted from OnRequest, from a plugin that declares WritesDestination, once a Redirect has taken effect; refused otherwise, with nothing changed. Under on_error: observe a Redirect moves nothing, so there is nothing to give a path to. path must be absolute, with no query or fragment and no ".." segment; the client's query string is kept. Errors quote no part of path.
It sets Path, as Redirect sets Host, so the request's row names the path the bytes went to, and the path the client named is kept in the modify/path_rewritten record. The listener applies the copy RedirectPath reports.
func (*Context) SetRequestModel ¶
SetRequestModel changes which model serves this request. It is the contract for every plugin that does — a router, a downgrader, an A/B test — and the only way such a plugin should do it: not by editing the body itself, and not by writing the inference extension, which belongs to the parser.
It replaces the body's top-level "model" value in place and changes no other byte. A prompt cache matches an exact prefix, so re-encoding the body would cost the client its cache. The new body goes through SetBody, which records modify/body_rewritten and the framework's body-mutation event as for any rewrite.
When the inference parser has built Extensions.Inference, Model becomes name — so settlement prices the model the request was sent for, and agentop shows it — and RequestedModel keeps the name the body carried before the first change, the client's. RequestedModel is cleared when a later change returns to that name. With no extension, none is created: the parser leaves it nil on purpose for a request it could not read.
The framework records modify/model_rewritten with "from" and "to" in Details. Under on_error: observe nothing changes, the body or the extension, and both records are shadows, so plugin code looks the same under enforce and observe.
A name equal to the current model changes nothing and records nothing.
Refused, with nothing changed and nothing recorded, from a plugin that does not declare WritesRequestBody, outside OnRequest, and for a body RequestModel would not read.
func (*Context) SetResendable ¶
func (c *Context) SetResendable()
SetResendable is listener-facing. A listener calls it before Run when it will ask the Resenders after a refused answer of this request. Only the forward proxy does. A plugin that changes a request in a way the provider may refuse, and that must then send the original instead (context-guru's tool deferral), reads Resendable first: on a listener that never resends, the client would see the refusal.
func (*Context) SetResponseBody ¶
SetResponseBody is the response-side analogue of SetBody. Used by plugins that redact or rewrite the upstream response (prompt-safety guardrails on LLM output, content filters, DLP). Same contract — Invocation + body-mutation/event emitted; never logs the body — and the same observe-mode suppression: under ErrorPolicyObserve the response body is untouched and the Invocation is marked Shadow=true.
It reports whether this write took effect, as SetBody does: true when pctx.ResponseBody is now newBody — which the client gets when the call comes from OnResponse, since the listener fills ResponseBody from the upstream only after the request pass — false for a shadow write under on_error: observe or a call dropped in OnFinish. ResponseBodyMutated() answers for the response, not for the caller.
A plugin that calls this must declare WritesResponseBody: true. That declaration is what makes listeners buffer the response instead of relaying SSE frames incrementally, so it must not be omitted.
func (*Context) SetSessionFacts ¶
func (c *Context) SetSessionFacts(f SessionFacts)
SetSessionFacts is for listeners: pass what session.Store.ViewFacts returned. A zero SessionFacts reads as FactNone.
func (*Context) SetUpstreamHeaders ¶
SetUpstreamHeaders gives headers that the listener sets on the upstream request after every plugin has run, each one replacing a header of the same name. A plugin cannot do this through Headers, because a later plugin can change those. Gates as SetRedirectPath, without the path. It keeps a clone of h, so a later change to h does not show. A second call replaces the first.
func (*Context) Skip ¶
Skip records an Invocation with Action=skip. Convenience for plugins that ran but didn't act on this message (path bypass, no route match, parser skipping a non-matching body).
func (*Context) Subagent ¶
Subagent returns the Claude Code subagent this request came from: the value of X-Claude-Code-Agent-Id as the client sent it, or "" when there is none to record.
"" MEANS NOTHING WAS STATED, and there are four ways to get it: a main-conversation request, a client that is not Claude Code, a row with no request headers (an opaque tunnel, a transparent connection), and a value model.SubagentHeader refused. A reader owes them the same treatment — this request names no subagent — and for "is this a subagent at all" should read Inference.AgentRole, which is stated independently of this header.
Memoized and pinned by ResolveClient on exactly the terms ClientInfo is; see there, including for why a nil receiver panics.
CLIENT-ASSERTED AND UNAUTHENTICATED: any caller of the proxy can send any id, so this is a display and grouping key, never a principal. session.IDFromHeaders' TRUST section applies unchanged.
func (*Context) SubagentKind ¶
SubagentKind returns the kind of a Bob child task: SubagentKindSubtask when the request's tool list has end_subtask (Bob gives that tool only to a subtask), else SubagentKindSubagent. It is "" on every request that is not a Bob child, Claude Code's subagents included.
Not memoized: the inference parser fills the tool list after ResolveClient pins Subagent, so the answer is read at each call. With no inference parser in the pipeline, a Bob child is SubagentKindSubagent.
func (*Context) Translate ¶
Translate asks the listener to convert this redirected request from the source protocol to the target protocol and send it to path, with no query string. It does not change Path: the request row keeps the path the client named.
Gates as SetRedirectPath: OnRequest only, a plugin that declares WritesDestination, a Redirect took effect, and path absolute with no query, fragment or ".." segment. Also source and target must be non-empty and different. It records nothing: only the listener knows what the conversion dropped, so the listener records modify/translated. A second call replaces the first.
func (*Context) TranslateTarget ¶
TranslateTarget is what the last accepted Translate set, with ok only when one was accepted on a request a Redirect moved. The listener applies it.
func (*Context) TypedPrompts ¶
TypedPrompts returns what the human typed in the session's main conversation, oldest first (intent.Prompts). The current request when it is a main-agent turn, else the session's LastMainTurn: from the listener's facts when set, else the newest such event in Session.Events. nil when there is none. shortcut: prompts before a compaction are lost; keep a per-session list if measurement shows the first prompt matters after one.
func (*Context) UpstreamHeaders ¶
UpstreamHeaders is what the last accepted SetUpstreamHeaders set, and nil unless a Redirect took effect.
func (*Context) WithholdsSession ¶
WithholdsSession reports whether this request's session is to be withheld from the archive: it asked not to be recorded (NoRecord) AND it names its own session with a session-id header (NamingHeader, pinned by SetAttribution). This is what listeners record as SessionEvent.NoRecord.
THE OWN-ID RULE IS THE SAFETY. A request that names no session is filed by fallback, to the active session or the shared default bucket (attribution.FiledSession), so honouring its flag would stop recording a session that is not the sender's. Such a request is recorded as if it had not asked; its header is still stripped. A request whose header names another session can still stop that session's recording from then on, but never erase what is already archived: the session-id header is client-asserted, with session.IDFromHeaders' TRUST caveat.
type DelegationExtension ¶
type DelegationExtension = model.DelegationExtension
extensions.go: see core/model for the docs.
type DelegationHop ¶
type DelegationHop = model.DelegationHop
extensions.go: see core/model for the docs.
type ErrorPolicy ¶
type ErrorPolicy string
ErrorPolicy controls how the pipeline reacts when a plugin returns a Reject action (i.e., decides to deny a request or response). The policy wraps the plugin — plugin authors do not consume it.
Default is ErrorPolicyEnforce: Reject becomes an HTTP error response and pipeline execution stops. Operators roll out a new guardrail in ErrorPolicyObserve first: the plugin still evaluates and may still return Reject, but the framework converts the Reject into a pass-through and records the would-have-denied Invocation as Shadow=true. ErrorPolicyOff is a kill-switch — the plugin is not dispatched at all.
Shadowing or disabling auth gates (jwt-validation, token-exchange) is an authentication bypass dressed as a feature — operators SHOULD leave those plugins on ErrorPolicyEnforce (the default).
The framework does NOT enforce this at startup: nothing prevents on_error: observe on jwt-validation today. A built-in-registry sealing pass is planned as a follow-up to reject a non-enforce policy on reserved gates at build time.
const ( // ErrorPolicyEnforce is the default. A Reject action becomes the // HTTP error the Violation describes, and the pipeline stops. ErrorPolicyEnforce ErrorPolicy = "enforce" // ErrorPolicyObserve (shadow mode) evaluates the plugin normally // but turns a Reject into a pass-through. Used to canary a new // guardrail: operators watch the shadow-deny counter before // flipping to enforce. Body mutations (SetBody / SetResponseBody) // also do not propagate to the wire under observe — the plugin's // decision logic runs identically, but its effect is muted. ErrorPolicyObserve ErrorPolicy = "observe" // ErrorPolicyOff disables the plugin. The plugin is not dispatched. // Off is an operator kill-switch without a redeploy. ErrorPolicyOff ErrorPolicy = "off" )
func (ErrorPolicy) Resolved ¶
func (p ErrorPolicy) Resolved() ErrorPolicy
Resolved returns the policy with "" normalized to ErrorPolicyEnforce. Callers that dispatch on policy value should use Resolved so they don't have to treat "" as a synonym for "enforce" themselves.
func (ErrorPolicy) Valid ¶
func (p ErrorPolicy) Valid() bool
Valid reports whether p is a recognized ErrorPolicy. The empty string is valid and means "use the default" (enforce); callers that need the defaulted value use the Resolved method instead.
type EventClient ¶
type EventClient = model.EventClient
client.go: see core/model for the docs.
func ParseUserAgent ¶
func ParseUserAgent(ua string) *EventClient
type EventError ¶
type EventError = model.EventError
session.go: see core/model for the docs.
func DeriveError ¶
func DeriveError(pctx *Context) *EventError
DeriveError constructs an EventError from response-side signals. Returns nil for 2xx / no guardrail block / no parser error.
func EventErrorOr ¶
func EventErrorOr(pctx *Context, fail *EventError) *EventError
EventErrorOr returns fail when the caller has an explicit failure to report, else what DeriveError can infer from the response. fail must win: it is set where the exchange failed — at the call, or while buffering the response — and DeriveError reads only the response. With no response it returns nil; with one it describes the upstream's status as though that had been delivered. A fail for a response the upstream did send carries that status in Code.
func ExchangeFailure ¶
func ExchangeFailure(ctx context.Context, err error) (int, *EventError)
func TransportError ¶
func TransportError(err error) *EventError
type EventIdentity ¶
type EventIdentity = model.EventIdentity
session.go: see core/model for the docs.
func SnapshotIdentity ¶
func SnapshotIdentity(pctx *Context) *EventIdentity
SnapshotIdentity copies the caller identity off pctx so the session event stays valid after pctx is discarded. Returns nil when no identity information is available (e.g., jwt-validation didn't run on this path and no agent identity was attached).
type EventTLS ¶
session.go: see core/model for the docs.
func NewEventTLS ¶
func NewEventTLS(state *tls.ConnectionState, peerSpiffeID string) *EventTLS
type FieldSchema ¶
type FieldSchema struct {
// Name is the JSON key (snake_case) — what operators type in YAML.
Name string `json:"name"`
// Type is a coarse-grained category sufficient to render templates
// and pick value placeholders. One of:
// "string", "int", "bool", "[]string", "object", "unknown".
// "object" indicates a nested struct whose fields populate Fields.
// "unknown" covers shapes the helper hasn't been taught (maps,
// slice-of-struct, etc.); the field still renders but without a
// type-specific placeholder.
Type string `json:"type"`
// Required reports the `required:"true"` tag. Boot semantics are
// the plugin's own concern — this field is just metadata.
Required bool `json:"required,omitempty"`
// Description is the `description:"..."` tag verbatim. Single-line.
Description string `json:"description,omitempty"`
// Default is the `default:"..."` tag verbatim. Cosmetic — the
// authoritative default is whatever applyDefaults sets at runtime.
Default string `json:"default,omitempty"`
// Enum is the `enum:"a,b,c"` tag split on commas. Empty when the
// field is not enum-shaped.
Enum []string `json:"enum,omitempty"`
// Fields is populated when Type is "object" (nested struct). The
// outer field's Description applies to the struct as a whole; the
// nested fields each carry their own metadata.
Fields []FieldSchema `json:"fields,omitempty"`
}
FieldSchema describes one config field's metadata for tooling.
func SchemaOf ¶
func SchemaOf(configType any) []FieldSchema
SchemaOf walks the given struct value and returns its field schemas. Pass a zero value (e.g. `SchemaOf(ibacConfig{})`) — the value is inspected for type only, not for runtime field values.
Returns nil if the argument isn't a struct (or pointer to struct). Fields without a `json:` tag are skipped (including untagged anonymous/embedded structs — unlike encoding/json, which promotes them). Explicit JSON tagging is the existing wire convention, and untagged fields don't appear in the operator-facing YAML, so they have nothing to surface in the schema either. No current plugin uses untagged embedding; if one ever needs that, this helper would need to grow flattening support.
type Finisher ¶
Finisher is an optional interface a plugin may implement when it reserves per-request state in OnRequest and needs a guaranteed release point — regardless of whether the request was allowed, denied by a later plugin, or errored at the upstream. The canonical shape is acquire-in-OnRequest / release-in-OnFinish:
func (p *RateLimiter) OnRequest(_ context.Context, pctx *pipeline.Context) pipeline.Action {
tenant := pctx.Identity.ClientID()
p.slots.Reserve(tenant)
pipeline.SetState(pctx, "rl", &rlState{tenant: tenant})
return pipeline.Action{Type: pipeline.Continue}
}
func (p *RateLimiter) OnFinish(ctx context.Context, pctx *pipeline.Context) {
s, ok := pipeline.GetState[*rlState](pctx, "rl")
if !ok { return }
p.slots.Release(s.tenant)
}
OnFinish runs once per request, after OnResponse has completed (if it ran), on every plugin whose OnRequest was dispatched — including the plugin that denied, if any. The dispatcher walks in LIFO order, symmetric with Shutdowner and OnResponse, so a plugin's cleanup can still rely on resources set up by earlier plugins.
The ctx passed to OnFinish is a FRESH context with a framework-set deadline (default 2s). It is NOT derived from the original request ctx, so a client disconnect during the request does not cancel OnFinish's I/O. Plugins that perform network work (flushing audits, releasing distributed leases) see a usable ctx by default.
pctx carries the full request + response state observed by OnResponse, plus pctx.Outcome() which returns a non-nil *Outcome describing the request's terminal outcome (allow / deny / error, status code, denying plugin, duration). pctx.Outcome() returns nil during OnRequest and OnResponse — the field is populated by the framework only before OnFinish dispatches.
OnFinish runs best-effort: panics are recovered and logged, errors in one plugin's OnFinish do not prevent later plugins in the LIFO chain from running. OnFinish must not call pctx.SetBody / SetResponseBody — the response is already on the wire; mutations are dropped with a WARN log.
OnFinish emits no automatic Invocation records. Plugins that want observability on cleanup publish through their own sink (Prometheus, external audit service) or via the pctx.Extensions.Custom escape-hatch map documented in plugin-reference.md.
type Holder ¶
type Holder struct {
// contains filtered or unexported fields
}
Holder is an atomic wrapper over *Pipeline.
Listeners hold a *Holder and call through it on every request; a reloader Store()s a newly-built pipeline under the hood, and the next Load returns it. atomic.Pointer guarantees a Load-then-use sequence sees a fully-initialized pipeline — a request that started before a swap finishes against the original *Pipeline, which the reloader Stops once no request holds it (Pipeline.Drained).
A Holder has exactly one long-lived value; its identity is the slot listeners reference, not the pipeline at any given moment.
func NewHolder ¶
NewHolder wraps p in a Holder. The Pipeline must already be non-nil — Holder.Load will return nil if it's unset, and the delegating helpers below will panic. Callers build the first pipeline at startup just like before and hand it to NewHolder.
func (*Holder) ForPctx ¶
ForPctx returns the pipeline a pctx-carrying phase should run on: the one pinned by Run when the request started, else the current one (a phase that runs without a preceding Run on this pctx — e.g. a response nobody dispatched a request for — or with no pctx at all has nothing to stay loyal to; a nil pctx is allowed).
Listeners must also ask this for every capability probe they make AFTER Run — the streaming and body-buffering decisions on the response path (HasStreamingResponders, WritesResponseBody, NeedsBody and friends). A probe on the current pipeline there picks the new pipeline's path while the phases still dispatch on the pinned old one: a StreamingResponder the reload removed never sees its frames, and a body reader never gets the body — the same silent skip the pin exists to prevent. Probes before Run (request-time buffering) have no pin to consult and keep reading the current pipeline.
func (*Holder) HasResenders ¶
HasResenders is equivalent to h.Load().HasResenders(). See Resender.
func (*Holder) HasStreamingResponders ¶
HasStreamingResponders is equivalent to h.Load().HasStreamingResponders(). Listeners read this to decide whether to take the streaming code path.
func (*Holder) Load ¶
Load returns the current pipeline. Safe for concurrent use. Returns nil only if no pipeline was ever stored (NewHolder requires non-nil, so this only happens if a caller zero-valued a Holder).
func (*Holder) NeedsBody ¶
NeedsBody is equivalent to h.Load().NeedsBody(). Hot path on listeners that decide whether to buffer the request/response body.
func (*Holder) NeedsRequestBody ¶
NeedsRequestBody is equivalent to h.Load().NeedsRequestBody().
func (*Holder) NeedsResponseBody ¶
NeedsResponseBody is equivalent to h.Load().NeedsResponseBody().
func (*Holder) NotReadyPlugin ¶
NotReadyPlugin is equivalent to h.Load().NotReadyPlugin(). Used by /readyz handlers to produce a helpful error body.
func (*Holder) Pin ¶
Pin pins pctx to the current pipeline and returns it. It re-checks the pipeline after holding it, so a reload that Stores in between is either seen here or sees the hold: the reloader counts holds only after its Store.
func (*Holder) Plugins ¶
Plugins is equivalent to h.Load().Plugins(). Used by the session events API to surface pipeline composition.
func (*Holder) Resend ¶
Resend is equivalent to h.Load().Resend(ctx, pctx, status, body). See Resender.
func (*Holder) Run ¶
Run is equivalent to h.Pin(pctx).Run(ctx, pctx). Offered as a one-liner so listeners can keep their Pipeline-era call sites unchanged when they migrate their field type from *Pipeline to *Holder.
Run also pins the loaded pipeline on pctx: every later phase on the same request (RunResponse, RunResponseFrame, RunFinish, Resend) dispatches against THAT pipeline, not whatever the Holder holds by then. A reload can Store a new pipeline while the request is open, and pctx.dispatched indexes the pipeline that ran OnRequest — without the pin, a shorter new chain panics in RunFinish and an equal-length one runs hooks on plugins that never saw the request.
func (*Holder) RunFinish ¶
RunFinish is equivalent to h.Load().RunFinish(ctx, pctx, outcome). Listeners call this in a defer at request entry to guarantee Finisher dispatch on every exit path. See Pipeline.RunFinish for the contract (LIFO over dispatched plugins, fresh ctx with timeout, pctx.Outcome() populated, silent phase).
func (*Holder) RunResponse ¶
RunResponse is equivalent to h.Load().RunResponse(ctx, pctx). See Run.
func (*Holder) RunResponseFrame ¶
func (h *Holder) RunResponseFrame(ctx context.Context, pctx *Context, frame []byte, last bool) Action
RunResponseFrame is equivalent to h.Load().RunResponseFrame(ctx, pctx, frame, last). See Pipeline.RunResponseFrame.
func (*Holder) Store ¶
Store replaces the current pipeline. Subsequent Loads return the new pipeline; in-flight requests that already Loaded the old one continue to run against it. The caller owns the lifecycle of the replaced pipeline — read the return value of the previous Load and call its Stop(ctx) once Drained is closed.
func (*Holder) WritesRequestBody ¶
WritesRequestBody is equivalent to h.Load().WritesRequestBody(). Listeners read this when deciding whether to propagate a rewritten request body to the wire.
func (*Holder) WritesResponseBody ¶
WritesResponseBody is equivalent to h.Load().WritesResponseBody(). Listeners read this when deciding whether streaming responses are safe — a pipeline with a response mutator can't stream, because the proxy can't rewrite a body it has already started forwarding. A request-only mutator does not disable streaming.
type Identity ¶
type Identity interface {
Subject() string // stable subject ID (sub claim / SPIFFE ID / email)
ClientID() string // registering-client ID, if applicable
Scopes() []string // granted scopes / roles
}
Identity carries the subject identity established by whichever auth plugin ran — jwt-validation, SAML, mTLS, custom. Populated by the auth plugin via pctx.Identity = <adapter>. Listener reads via these methods — not via concrete-type assertion — so plugins can contribute any identity shape without the framework caring.
Returning empty-string / nil from any method is valid (e.g., a SPIFFE-SVID authenticator may have no "ClientID" concept). Consumers that need plugin-specific fields type-assert to a richer interface or to the plugin's known concrete type.
func SubjectIdentity ¶
SubjectIdentity returns an Identity that carries only a subject: no client ID and no scopes. Listeners use it when a trusted header, not a validated token, names the requester.
type InferenceExtension ¶
type InferenceExtension = model.InferenceExtension
extensions.go: see core/model for the docs.
func SnapshotInference ¶
func SnapshotInference(ext *InferenceExtension) *InferenceExtension
type InferenceHostSeen ¶
type InferenceHostSeen = model.InferenceHostSeen
inferencehosts.go: see core/model for the docs.
type InferenceHosts ¶
type InferenceHosts = model.InferenceHosts
inferencehosts.go: see core/model for the docs.
type InferenceMessage ¶
type InferenceMessage = model.InferenceMessage
extensions.go: see core/model for the docs.
type InferenceThinking ¶
type InferenceThinking = model.InferenceThinking
extensions.go: see core/model for the docs.
type InferenceTool ¶
type InferenceTool = model.InferenceTool
extensions.go: see core/model for the docs.
type InferenceToolCall ¶
type InferenceToolCall = model.InferenceToolCall
extensions.go: see core/model for the docs.
type InferenceToolResult ¶
type InferenceToolResult = model.InferenceToolResult
extensions.go: see core/model for the docs.
type Initializer ¶
Initializer is an optional interface a plugin may implement when it needs to run work once before the pipeline starts serving traffic. Typical uses: load a model, warm a cache, open a database connection, register Prometheus metrics, spawn a background goroutine. Init is called by Pipeline.Start exactly once, in plugin declaration order. If any plugin's Init returns an error the pipeline fails fast — Pipeline.Start returns the error without calling Init on later plugins (nothing to unwind: earlier plugins succeeded).
Plugins that don't need initialization simply don't implement this interface; the pipeline skips them. Keeping it optional preserves backward compatibility with every existing plugin.
type InvocationAction ¶
type InvocationAction = model.InvocationAction
extensions.go: see core/model for the docs.
type InvocationPhase ¶
type InvocationPhase = model.InvocationPhase
extensions.go: see core/model for the docs.
type Invocations ¶
type Invocations = model.Invocations
extensions.go: see core/model for the docs.
func SnapshotInvocations ¶
func SnapshotInvocations(ext *Invocations, phase InvocationPhase) *Invocations
type LateOpsAccountant ¶
type LateOpsAccountant interface {
LateOps(pctx *Context) func(ops []accountant.Operation) (kept int)
}
LateOpsAccountant is an optional RequestAccountant capability: it books the context operations reported after the request's op list was sealed (Context.OpReporter). A model call that an engine detaches from its request, such as a background summarizer, finishes then, and its cost is real (cortex#2140).
Run calls LateOps on the request goroutine, right before it seals the list and calls RequestEnd, so the accountant can read pctx there and keep what it needs. pctx must not be read after LateOps returns. The handler it returns may be nil (nothing to book for this request). It is called from any goroutine, with no pipeline lock held, once for each late Report. It must not block, and it returns how many of the ops it kept; the pipeline counts the rest in LateOpsDropped.
type ListenerSupport ¶
type ListenerSupport struct {
// Listener names the listener in the build error, e.g. "forward proxy".
Listener string
// Destination: the listener re-originates requests from pctx after the pipeline
// and honors pctx.Redirect. Required by WritesDestination plugins.
Destination bool
}
ListenerSupport says which listener-dependent capabilities the listener a pipeline is built for can honor.
Some capabilities are promises only a listener can keep. A plugin may ask for a redirect, but only a listener that builds the upstream request itself can send it somewhere else; anywhere else the plugin would run, record its decision, and change nothing. plugins.BuildWithDeps refuses such a plugin at build time, on startup and on reload, so a configuration that cannot work fails before traffic arrives.
Each listener package says what it honors (forwardproxy.Support, reverseproxy.Support, extproc.Support) and each binary passes that into its builds. The zero value honors none of these capabilities, so a listener that has not considered one refuses the plugins that need it rather than silently ignoring them. Adding a capability of this kind means adding a field here and a case to Unsupported.
func (ListenerSupport) Name ¶
func (s ListenerSupport) Name() string
Name is Listener, or a description of the listener for a build that named none.
func (ListenerSupport) Unsupported ¶
func (s ListenerSupport) Unsupported(caps PluginCapabilities) string
Unsupported returns the name of the first capability caps declares that s cannot honor, or "" when it can honor every one.
type MCPExtension ¶
type MCPExtension = model.MCPExtension
extensions.go: see core/model for the docs.
func SnapshotMCP ¶
func SnapshotMCP(ext *MCPExtension) *MCPExtension
type Metric ¶
type Metric struct {
Name string `json:"name"`
Value float64 `json:"value"`
Unit string `json:"unit,omitempty"`
Note string `json:"note,omitempty"`
}
Metric is one operator-facing counter reported by a plugin. Values are float64 so a plugin can report a ratio or a per-request average without a second type; counts are whole numbers that happen to fit exactly.
Unit is advisory and drives display, not arithmetic: "count", "bytes", "tokens", "ratio". Note carries the caveat a number needs to be read honestly — most importantly the sample size behind an estimate, e.g. "estimate, n=1284". A derived figure with no Note is read as measured, so anything inferred must say so here.
type MetricsProvider ¶
type MetricsProvider interface {
Metrics() []Metric
}
MetricsProvider is implemented by plugins that expose counters for operator display. describePipeline calls it on demand while serving /v1/pipeline, so implementations must be safe for concurrent use with the request path and must not block — take a mutex, copy, release. Returning nil is fine and renders as "(none)".
CONTRACT ON Name AND Note: these are short operator-facing labels, surfaced on an endpoint with no authentication. They must never carry request or response content — no prompts, no completions, no header or credential values, nothing derived from a body. A caveat naming a sample size or a configuration key is fine; a caveat quoting the traffic is not. The framework caps their length but cannot inspect their meaning, so this is a producer obligation, the same one body-mutation events carry when they publish only lengths and hashes.
This is deliberately separate from plugins.StatsSource / auth.Stats, which are auth-shaped: they carry typed approval and denial enums and a custom MarshalJSON, so routing "bytes removed" through them would distort their meaning. Naming the interface here (rather than asserting an inline literal at the call site) gives callers a greppable contract and turns future signature drift into a compile error rather than a silently-failing type assertion — the same reasoning as RawConfigProvider.
type OpReporter ¶
type OpReporter struct {
// contains filtered or unexported fields
}
OpReporter is a goroutine-safe handle for reporting context operations under a fixed operator name and dry-run state, captured once on the request goroutine via Context.OpReporter. It is the form for a report that may come from a goroutine other than the request's: an engine's model call, which context-guru makes on goroutines of its own.
Keeping operator and dryRun inside OpReporter, rather than accepted as Report arguments, keeps the Operator stamp under the framework's control: a plugin gets a reporter for the plugin dispatching it, and cannot ask to report under another plugin's name (accountant/docs/ cortex-wiring.md W5.1: "The framework sets Operator. A plugin cannot report under another plugin's name.").
func (OpReporter) Report ¶
func (r OpReporter) Report(ops ...accountant.Operation) bool
Report records ops like Context.ReportOps, under the operator and dry-run state r was built with.
Pipeline.Run seals the request's op list right before it hands the list to the accountant. An op reported after the seal (a model call that finished after its request, such as a background summarizer) goes to the accountant's LateOpsAccountant handler, with Call.Detached set. Report returns false when an op was dropped: the accountant has no handler, or the handler refused it. Each dropped op is counted in LateOpsDropped. The zero OpReporter belongs to no request: it reports nothing and returns false.
type Option ¶
type Option func(*options)
Option configures pipeline construction.
func WithAccountant ¶
func WithAccountant(a RequestAccountant) Option
WithAccountant attaches the process's accountant host to the pipeline. With one set, Run keeps the client body (ClientBody) and calls the hooks, and NeedsRequestBody is true, so every listener buffers the request body. A nil a attaches nothing.
Only the outbound chain gets one: inference requests leave through it, and the host is process-scoped, so the pipelines a reload builds share it and its Tracker state.
func WithFinishTimeout ¶
WithFinishTimeout overrides the per-plugin OnFinish timeout. Each plugin's OnFinish runs under a fresh ctx derived from context.Background() with this timeout applied; a zero or negative value falls back to DefaultFinishTimeout. Listeners that know their deployment's OnFinish I/O patterns can tighten (fast local sinks) or relax (remote lease service) this knob.
func WithPolicies ¶
func WithPolicies(policies ...ErrorPolicy) Option
WithPolicies attaches per-plugin on_error policies in parallel with the plugin slice passed to New. policies[i] belongs to plugins[i]; an empty entry defaults to ErrorPolicyEnforce. If fewer policies are supplied than plugins, the remaining plugins use the default (enforce). Supplying more policies than plugins is a programmer error and New returns an error.
type Outcome ¶
type Outcome struct {
// FinalAction classifies the request as Allow / Deny / Error —
// three accounting buckets useful for per-outcome metrics and
// stateful-plugin cleanup.
FinalAction OutcomeAction
// StatusCode is the final HTTP status written to the downstream
// client. Zero for errors that never produced a response.
StatusCode int
// DenyingPlugin names the plugin whose Reject action stopped the
// pipeline. Empty when FinalAction != OutcomeDeny.
DenyingPlugin string
// Duration is wall-clock time between pctx.StartedAt and the
// moment OnFinish dispatches (after the response is on the wire).
// Useful for per-outcome latency accounting.
Duration time.Duration
}
Outcome carries the terminal state of a request — what final action the pipeline took, the resulting HTTP status, which plugin denied (if any), and how long the request took end-to-end. Populated by the framework exactly once per request, immediately before dispatching OnFinish on any Finisher-implementing plugins.
Read via pctx.Outcome(). The getter returns nil during OnRequest and OnResponse — plugins that accidentally inspect Outcome in those phases observe a nil pointer rather than a stale zero value, so the "this field is only meaningful in OnFinish" contract is enforced at read time rather than documented and forgotten.
Outcome is deliberately a small struct. If a future need demands more context (upstream response headers, body sha256, external request ID, etc.) add a field here rather than inventing a parallel mechanism — plugins already reach for pctx.Outcome().
func OutcomeFromContext ¶
OutcomeFromContext derives a best-effort Outcome from a pctx's final state, intended for listeners that want a one-liner finish call without threading outcome state through nested response / error callbacks. The derivation rules, checked in order:
- pctx.RejectingPlugin() is non-empty → OutcomeDeny, DenyingPlugin names the rejector. Populated by the framework (Pipeline.Run / RunResponse) whenever a plugin returned Action{Type: Reject} under the enforce policy. Independent of whether the plugin paired Reject with a pctx.Record call.
- Fallback: a deny Invocation on either phase → OutcomeDeny, DenyingPlugin = the most-recent deny's Plugin. Kept as defense-in-depth for bespoke dispatchers that populate Invocations directly.
- No deny AND StatusCode > 0 → OutcomeAllow. The HTTP status itself is not sufficient to classify error vs allow — a legitimate 500 from the upstream is still a pipeline Allow.
- No deny AND StatusCode == 0 → OutcomeError (no response was written: upstream transport failure, listener panic, etc.).
Listeners with no HTTP-status concept (check-only protocols) should construct Outcome explicitly using pctx.RejectingPlugin() — the "StatusCode == 0 means error" rule is HTTP-listener specific. StatusCode is taken from pctx.StatusCode verbatim. Duration is left zero; RunFinish auto-fills from pctx.StartedAt when left unset.
type OutcomeAction ¶
type OutcomeAction string
OutcomeAction classifies the terminal state of a request. Intentionally a small 3-value vocabulary distinct from the 5-value InvocationAction: Outcome describes the request as a whole (for OnFinish accounting), while InvocationAction describes what one plugin did in one phase.
A rate-limiter refunding a slot cares about "was this call successful" (OutcomeAllow) vs "did a plugin choose to deny" (OutcomeDeny) vs "did the upstream / framework fail" (OutcomeError) — three distinct accounting buckets. The 5-value InvocationAction (allow / deny / skip / modify / observe) doesn't answer that question because skip / modify / observe are mid-pipeline, not terminal states.
const ( // OutcomeAllow — every plugin returned Continue; response was // produced and sent to the client. OutcomeAllow OutcomeAction = "allow" // OutcomeDeny — a plugin (request-side or response-side) returned // Reject. Outcome.DenyingPlugin names it. OutcomeDeny OutcomeAction = "deny" // OutcomeError — the request terminated without a plugin denial: // upstream transport failure, context cancellation, a panic // recovered inside the dispatcher. DenyingPlugin is empty. OutcomeError OutcomeAction = "error" )
type Pipeline ¶
type Pipeline struct {
// contains filtered or unexported fields
}
Pipeline holds an ordered list of plugins and runs them sequentially. policies[i] holds the on_error ErrorPolicy that wraps plugins[i]; the slice is always the same length as plugins (guaranteed by New) so PolicyAt is a bounds-safe lookup. An empty ErrorPolicy resolves to ErrorPolicyEnforce via the Resolved() method.
func (*Pipeline) Drained ¶
func (p *Pipeline) Drained() <-chan struct{}
Drained returns a channel closed once no request holds p. The reloader calls it after Storing p's replacement, when no new request can pin p.
func (*Pipeline) HasResenders ¶
HasResenders reports whether any plugin in the pipeline may ask for a resend, so a listener reads a refused answer's body only when one might.
func (*Pipeline) HasStreamingResponders ¶
HasStreamingResponders reports whether any plugin in the pipeline implements StreamingResponder. Listeners use this to decide whether the streaming code path is worth taking — without any opt-in plugin the buffered path delivers the same result for less complexity.
func (*Pipeline) NeedsBody ¶
NeedsBody returns true if any plugin in the pipeline needs the body buffered — either to read it (ReadsBody) or to mutate it (WritesRequestBody).
func (*Pipeline) NeedsRequestBody ¶
NeedsRequestBody reports whether the request body must be buffered.
Split from NeedsBody because the undirected version made each write flag force the other direction's buffering: a response-only mutator had the request body buffered for nothing, and a request-only mutator had non-SSE responses buffered for nothing — the mirror image of the waste the directional capabilities exist to remove.
ReadsBody still counts toward both, and deliberately: it is itself undirected ("reads pctx.Body and/or pctx.ResponseBody").
func (*Pipeline) NeedsResponseBody ¶
NeedsResponseBody reports whether the response body must be buffered. See NeedsRequestBody for why ReadsBody counts toward both.
func (*Pipeline) NotReadyPlugin ¶
NotReadyPlugin returns the first plugin whose Ready() returned false, or "" when the pipeline is ready. Used by /readyz to produce a helpful error body.
func (*Pipeline) Plugins ¶
Plugins returns a copy of the pipeline's plugin list in execution order. The copy prevents callers from mutating the backing slice; individual Plugin values are interface types and can be inspected freely.
Used by the session events API to expose pipeline composition to off-process tools (agentop) and other observability surfaces.
func (*Pipeline) PolicyAt ¶
func (p *Pipeline) PolicyAt(i int) ErrorPolicy
PolicyAt returns the resolved policy for plugins[i] — Plugins()[i] — the one Run dispatches it under. The policies slice is always the same length as plugins (New guarantees this), but we check defensively so a zero-value Pipeline (constructed outside New, e.g. in a test) doesn't panic.
Exported for the session API, which serves it on /v1/pipeline: a plugin under observe runs and records, but its rejections, body writes and redirects are dropped — header writes still apply — and nothing else a reader can see says so. Read it from the same *Pipeline as Plugins(), not through a Holder twice, or a reload between the two calls pairs a plugin with another pipeline's policy.
func (*Pipeline) ReadsEveryResponseBody ¶
ReadsEveryResponseBody reports whether a plugin declares ReadsResponseBody itself. The forward proxy buffers a response no parser claimed only for such a plugin.
func (*Pipeline) Ready ¶
Ready reports whether every plugin implementing pipeline.Readier currently reports ready. Plugins without Readier are considered always-ready (no deferred state). Called per /readyz probe, so the implementation is one cheap type-assert + bool read per plugin.
func (*Pipeline) Resend ¶
Resend asks the pipeline's Resenders, in chain order, whether the request should be sent again, and the first that says yes decides. See Resender for the contract.
func (*Pipeline) Run ¶
Run executes the request phase of the pipeline sequentially. If any plugin returns Reject, the pipeline stops and returns that action with Violation.PluginName populated.
Plugins configured with ErrorPolicyOff are skipped entirely — they are not dispatched and contribute no Invocation. Plugins under ErrorPolicyObserve are dispatched normally, but a Reject return is converted into a pass-through: the Violation is recorded as a shadow Invocation and the pipeline continues to the next plugin. Body mutations under observe are also suppressed — see Context.SetBody / SetResponseBody.
Before dispatching into each plugin, Run stamps pctx with the plugin's name, the current phase, and the current policy so the plugin's Record / Allow / Skip / Observe / Modify / DenyAndRecord helpers can fill Invocation.Plugin and Invocation.Phase automatically. The stamp is cleared after each plugin returns so a plugin that spawns a goroutine capturing pctx won't mis-attribute a late-arriving Record to itself.
func (*Pipeline) RunFinish ¶
RunFinish dispatches the OnFinish hook on every Finisher-implementing plugin whose OnRequest was invoked during this request (Pipeline.Run tracks the dispatched set on pctx). Iteration is LIFO — reverse of OnRequest order — symmetric with Shutdowner and RunResponse.
Called by the listener after the response has been written to the wire (or after the terminal error has been recorded, for denied or errored requests). Before the first plugin's OnFinish runs, the framework populates pctx.outcome from the supplied Outcome so pctx.Outcome() returns non-nil for the duration of the finish chain and nil everywhere else.
Each plugin's OnFinish runs under a context derived from context.WithoutCancel(ctx) with p.finishTimeout applied. That means:
- Cancellation of the caller-supplied ctx (client disconnect, listener shutdown signal) does NOT abort OnFinish's I/O.
- Values carried on the caller-supplied ctx (slog fields, request ID, tracing span) ARE propagated into OnFinish.
- Deadlines from the caller-supplied ctx are NOT inherited; the per-plugin timeout is authoritative.
OnFinish is best-effort: a panicking plugin is recovered and logged, a returning plugin's errors (there is no error return on the interface by design — see Finisher godoc) are not observed by the framework. The LIFO chain continues regardless so one misbehaving plugin does not leak state in earlier plugins.
RunFinish is safe to call at most once per request. A second call on the same pctx is rejected with a WARN log rather than double- releasing Finisher state (defensive against a listener bug where two defers end up registered, or a handler refactor routes the finish call through two paths). Listeners MUST call it in a defer wrapping the response-produce block so a panic in response-writing still reaches cleanup.
func (*Pipeline) RunResponse ¶
RunResponse executes the response phase in reverse order. The last plugin in the chain sees the response first.
Plugins implementing StreamingResponder are skipped here — the framework picks one path per the StreamingResponder contract: streaming-aware plugins receive a final OnResponseFrame(last=true) from the listener (single dispatch on the buffered application/json path; per-frame + last=true on the SSE path) instead of OnResponse, so the same body is never delivered through both hooks.
See Run for the pctx attribution stamping, the off-policy skip, and the observe-policy shadow conversion. Same pattern, phase set to InvocationPhaseResponse.
func (*Pipeline) RunResponseFrame ¶
func (p *Pipeline) RunResponseFrame(ctx context.Context, pctx *Context, frame []byte, last bool) Action
RunResponseFrame dispatches a single response frame to every plugin implementing StreamingResponder, in reverse declaration order (symmetric with RunResponse). Plugins that don't implement the interface are skipped — they're handled by the buffered RunResponse path the listener still calls when the response is non-streaming.
The off-policy skip and observe-policy shadow conversion are applied identically to RunResponse — see Run for the contract.
Frames are dispatched in wire-arrival order: callers invoke this once per frame as they arrive off the upstream, then once with last=true (typically with an empty frame) at end-of-stream so aggregating plugins can finalize. Application/json responses are delivered as a single last=true frame so streaming-aware plugins have one code path.
A plugin that returns Reject mid-stream causes the listener to short-circuit. Today no in-tree plugin returns Reject here (the listeners forward+flush before invoking the hook for observability only); the contract leaves room for per-message enforcement later.
func (*Pipeline) Start ¶
Start invokes Init on every plugin that implements the Initializer interface, in declaration order. Returns the first error encountered; on error, later plugins are not initialized. Plugins without Init are silently skipped.
If Init fails on plugin N, Start invokes Shutdown on plugins [0..N-1] (those whose Init succeeded) in reverse order before returning the error. This cleans up any background goroutines the earlier plugins spawned, so the plugin chain doesn't leak when a downstream peer rejects its config at boot. Shutdown errors during unwind are logged but do not mask the original Init failure.
Callers should invoke Start after Pipeline construction (pipeline.New) and before the listener accepts traffic. Safe to call at most once per Pipeline — plugins may assume Init runs exactly once per process.
func (*Pipeline) Stop ¶
Stop invokes Shutdown on every plugin that implements the Shutdowner interface, in reverse declaration order (LIFO). Errors are logged but do not stop the sequence — every Shutdowner is given a chance to flush. The caller-supplied ctx carries the shutdown deadline; plugins are expected to respect it.
Callers should invoke Stop after the listener has drained / stopped accepting new requests so in-flight work is allowed to complete first. Safe to call at most once per Pipeline.
func (*Pipeline) WritesDestination ¶
WritesDestination returns true if any plugin in the pipeline declares WritesDestination: it may send a request somewhere other than where the client addressed it. A carried WebSocket is already connected to its origin, so the forward proxy declines one when this is true and the turns go over HTTPS instead.
func (*Pipeline) WritesRequestBody ¶
WritesRequestBody returns true if any plugin in the pipeline declares WritesRequestBody. Listeners use this to decide whether to diff-and-emit a body mutation on the wire. A pipeline with no WritesRequestBody plugins bypasses the mutation path entirely — zero overhead for the common read-only case.
func (*Pipeline) WritesResponseBody ¶
WritesResponseBody returns true if any plugin in the pipeline declares WritesResponseBody. This is the SSE streaming predicate: a response mutator needs the whole response to rewrite it, so listeners fall back from incremental relay to the buffered path only when this is true.
A request-only mutator (tool-prune, context-guru) keeps streaming: the request body is already complete before dispatch, so rewriting it has no bearing on how the response is relayed.
type Plugin ¶
type Plugin interface {
Name() string
Capabilities() PluginCapabilities
OnRequest(ctx context.Context, pctx *Context) Action
OnResponse(ctx context.Context, pctx *Context) Action
}
Plugin is the interface that all pipeline extensions implement.
func WrapConfigured ¶
func WrapConfigured(p Plugin, raw json.RawMessage) Plugin
WrapConfigured returns a Plugin whose dynamic type retains the raw config bytes the plugin was built from, so the session API can surface them on /v1/pipeline. Callers (plugins.Build) invoke this only after Configurable.Configure returns nil; non-Configurable plugins pass through unwrapped.
The raw bytes are defensively copied before being stored, so a caller that holds onto its reference and mutates it (or whose surrounding decoder reuses the underlying buffer) cannot perturb what RawConfig() later returns. The cost is one allocation per Configurable plugin per pipeline build — negligible at startup and on the rare hot-reload path.
type PluginCapabilities ¶
type PluginCapabilities struct {
// ReadsBody: the plugin reads pctx.Body in OnRequest and/or
// pctx.ResponseBody in OnResponse. The listener buffers the body
// when any plugin declares this; without it, pctx.Body is nil and
// a read silently sees "no body." On the forward proxy, the response
// of a request no parser claimed is buffered only for ReadsResponseBody.
ReadsBody bool
// ReadsResponseBody: the plugin reads pctx.ResponseBody and never pctx.Body.
// The listener buffers the response body, not the request body, including
// on the forward proxy for a request no parser claimed. Pipeline.New orders
// it against response mutators only: a request mutator before it changes
// nothing it reads.
ReadsResponseBody bool
// WritesRequestBody: the plugin may mutate pctx.Body (call
// pctx.SetBody or pctx.SetRequestModel). Implies ReadsBody —
// Normalize() auto-promotes. Listener propagates the mutation to the
// wire (ext_proc BodyMutation, or the outbound http.Request for proxy
// listeners).
//
// Any number of WritesRequestBody plugins may share a pipeline. They
// run in chain order, each seeing pctx.Body as the one before it left
// it, and the listener sends the last one's bytes. Pipeline.New rejects
// one placed before a ReadsBody-only plugin, which must see the bytes
// the client sent.
//
// A chained writer derives its edit from pctx.Body. The parser
// extensions (pctx.Extensions.Inference and the rest) are not re-parsed
// after a write: they describe the client's request — apart from the
// model, which SetRequestModel keeps current — so an edit built from
// them can undo an earlier writer's rewrite or land on the wrong element.
// A writer learns whether its own write applied from SetBody's result:
// BodyMutated() is true once any writer's bytes took effect, including
// for a later writer whose own call was a shadow under on_error: observe.
//
// Declaring this does NOT cost response streaming. Requests are
// never streamed — they arrive complete with a Content-Length and
// are read end to end before dispatch — so rewriting one says
// nothing about whether the response may be relayed incrementally.
WritesRequestBody bool
// WritesResponseBody: the plugin may mutate pctx.ResponseBody (call
// pctx.SetResponseBody). Implies ReadsBody — Normalize() auto-promotes.
//
// This is the streaming predicate. A plugin that rewrites a response
// needs the whole response to rewrite it, so listeners fall back from
// incremental SSE relay to the buffered path when — and only when —
// some plugin in the chain declares this. See
// Pipeline.WritesResponseBody.
//
// Any number of WritesResponseBody plugins may share a pipeline. The
// response pass runs in reverse, so each sees pctx.ResponseBody as the
// writer after it in the chain left it, and the listener sends what the
// last to run left. Pipeline.New rejects one placed before a
// ReadsBody-only plugin, so readers — the parsers included — see the
// response the client receives. A writer therefore cannot use what the
// parsers found in this response; it parses pctx.ResponseBody itself.
WritesResponseBody bool
// WritesDestination: the plugin may call pctx.Redirect to send the request to a
// different host than the one the client named.
//
// Only a listener that builds the upstream request itself can honor that, so
// plugins.BuildWithDeps refuses a plugin declaring it for a listener whose
// ListenerSupport says otherwise — on startup and on reload — rather than let
// it run, record a redirect, and change nothing. Pipeline.New admits at most
// one per pipeline: with two, the destination would be whichever ran last.
WritesDestination bool
// Requires names plugins that MUST be present in the same chain
// AND appear earlier (lower index). Matches are case-sensitive
// plugin Name() strings. A missing or misordered name causes
// plugins.Build to fail at startup.
//
// Use Requires when the plugin hardcodes access to a specific
// other plugin's extension fields — e.g., a tool-allowlist plugin
// that reads pctx.Extensions.MCP.Params["name"] declares
// Requires: []string{"mcp-parser"}.
Requires []string
// RequiresAny names plugins of which AT LEAST ONE must be present
// in the same chain, and each named plugin that IS present must
// appear earlier. Missing-all-of-them or misordered-any-of-them
// causes plugins.Build to fail at startup.
//
// Use RequiresAny for protocol-agnostic plugins that read through
// pctx.ContentSources(). Example: a guardrail that works against any
// parser declares RequiresAny: []string{"a2a-parser", "mcp-parser",
// "inference-parser"} so a chain with no parsers fails loud instead
// of running the guardrail as silent dead code.
RequiresAny []string
// RequiresLater names plugins that MUST be present in the same chain and
// positioned AFTER this plugin — the mirror of Requires.
//
// This exists because the request and response passes run in opposite
// directions: RunResponse and RunResponseFrame walk the chain in reverse, so a
// plugin that needs another's RESPONSE-phase output needs that plugin at a
// HIGHER index, not a lower one. Declaring Requires there would enforce exactly
// the wrong order.
//
// litellm-budget-track is the case: it prices the token counts inference-parser
// publishes while folding response frames, so the parser has to fold each frame
// BEFORE budget-track settles the cost — which means later in the chain.
//
// Without this, a plausible ordering silently unprices every streamed response:
// the counts simply are not there yet when the terminal frame arrives, and
// nothing reports that they were missed.
RequiresLater []string
// Description is operator-facing prose, one line, ≤80 chars,
// describing what this plugin does. Surfaces in `agentop`'s
// plugin-detail and catalog panes, and in /v1/plugins.
//
// The capabilities an UNCONFIGURED instance reports are the ceiling for
// every instance its factory produces: plugins.Catalog() reads them from
// such an instance, once, so they are what /v1/plugins and agentop's
// catalog show. A CONFIGURED instance may report less — WithinCeiling
// says how much less — when its config means it will not use some of
// them, and the pipeline it is built into reads the narrower set. That
// is the point: a plugin whose config turns off its response rewriting
// stops costing every response its streaming. Anything WithinCeiling
// does not admit, plugins.BuildWithDeps logs a WARN naming.
Description string
}
PluginCapabilities declares whether a plugin accesses the request / response body and which other plugins it depends on.
Body-access fields drive the listener's body-buffering handshake (ext_proc ProcessingMode, net/http read-body). Dependency fields are checked at startup by plugins.Build so misconfigured chains fail before traffic arrives.
func (PluginCapabilities) Normalize ¶
func (c PluginCapabilities) Normalize() PluginCapabilities
Normalize applies the promotions: either write implies ReadsBody, and ReadsBody implies ReadsResponseBody. Called by Pipeline.New for every plugin's declared capabilities so the rest of the framework reads a normalized form. Plugins never need to call this themselves.
func (PluginCapabilities) WithinCeiling ¶
func (c PluginCapabilities) WithinCeiling(ceiling PluginCapabilities) string
WithinCeiling reports whether the catalog, which shows ceiling, describes c: whether c declares nothing ceiling does not, and fits every chain ceiling fits. That holds when no flag ceiling leaves false is set; ReadsBody is not kept alone when ceiling writes a body, since a pure reader may not follow a mutator; no Requires or RequiresLater name is added; and RequiresAny is either ceiling's set or empty, since dropping a name and adding one each refuse chains ceiling fits. Both sides are normalized first, so a configured instance that keeps WritesRequestBody need not repeat the ReadsBody it implies. Description is not compared. It names the first difference, or "" when there is none.
type PromptContext ¶
type PromptContext = model.PromptContext
promptcontext.go: see core/model for the docs.
func MergePromptContext ¶
func MergePromptContext(a, b *PromptContext) *PromptContext
type PromptContextFold ¶
type PromptContextFold = model.PromptContextFold
promptcontext.go: see core/model for the docs.
type RawConfigProvider ¶
type RawConfigProvider interface {
RawConfig() json.RawMessage
}
RawConfigProvider is implemented by plugins (or wrappers around them) that can surface the raw runtime config bytes the plugin was built from. The session API uses this interface in describePipeline to populate /v1/pipeline's Config field. Naming it explicitly (rather than asserting an inline interface literal at the call site) gives callers a greppable contract and turns any future signature drift into a compile-time error rather than a silently-failing type-assertion.
type Readier ¶
type Readier interface {
Ready() bool
}
Readier is an optional interface a plugin may implement when it has deferred initialization that matters to a /readyz probe. The host ANDs Ready() across all implementers to decide whether the pipeline is ready to serve traffic. A plugin whose Configure succeeded but whose Init is still waiting (e.g. for a credential file to be mounted by the operator from a Secret) returns false — the kubelet keeps traffic off the pod until Init completes.
Plugins without deferred state don't implement this interface and are treated as always-ready. Pipeline.Ready() returns true when every Readier-implementing plugin returns true.
Ready is expected to be cheap (pointer read / atomic load). The /readyz handler calls it on every probe (~10s cadence from kubelet).
type RequestAccountant ¶
RequestAccountant is the per-request hook the accountant host (core/accounting.Host) implements. Pipeline.Run calls RequestStart before the first plugin and RequestEnd after the last one, on a request the pipeline let through.
The hook lives in Run, not in each listener (the design put it in the listeners, §5.3a): Run is the one place every listener passes that sees the body before the first plugin and after the last, so the three listeners need no change of their own.
RequestEnd is not called on a Reject or a cancel. A refused request never went upstream, so there is nothing to account for, and no work may start for it (Review Focus 1). Both calls run on the request goroutine and must return at once: the host does its hashing on a goroutine of its own.
type RequestCapture ¶
type RequestCapture = model.RequestCapture
capture.go: see core/model for the docs.
type Resender ¶
type Resender interface {
Resend(ctx context.Context, pctx *Context, status int, body []byte) bool
}
Resender is an optional interface for a plugin that may have the listener send a request again after its upstream refused it. A router is the case it was made for: its server refused the model the client asked for, and the router has one of the server's own models to send instead, before the client sees the refusal.
Resend is called after an attempt the upstream answered with a status outside 2xx, before any byte of that answer reached the client, and at most MaxResends times per request. status is the answer's status, and body is its first ResendPeekLimit bytes. A plugin that wants the request sent again changes it through the usual APIs — SetRequestModel, SetBody, Headers — names why with MarkResend, and returns true. The listener then records the refused answer, sends the request as it now stands to the same destination, and asks again only if that attempt is refused too and fewer than MaxResends resends were made. A plugin must not answer the same kind of refusal twice for one request; ResendReasons says what it already answered. Returning false lets the refused answer through unchanged.
It is dispatched like OnRequest, in the request phase and under the plugin's WritesRequestBody declaration, so SetRequestModel is accepted. Redirect and SetRedirectPath are not: the destination was fixed by the first send. Only a plugin under on_error: enforce is asked, because a resend changes the request, and a plugin under observe must not. Only the forward proxy asks today.
type ResponseCapture ¶
type ResponseCapture = model.ResponseCapture
capture.go: see core/model for the docs.
type SchemaProvider ¶
type SchemaProvider interface {
ConfigSchema() []FieldSchema
}
SchemaProvider is implemented by plugins whose config field metadata should appear in the catalog and downstream tooling (agentop edit templates, future rossoctl-UI forms, JSON Schema generators). Plugins without configs (a2a-parser, inference-parser today) can omit this interface.
The convention is a one-line method that delegates to SchemaOf:
func (p *MyPlugin) ConfigSchema() []FieldSchema {
return SchemaOf(myPluginConfig{})
}
The framework's catalog adapter type-asserts against this interface; absence is silently treated as "no field metadata."
type SecurityExtension ¶
type SecurityExtension = model.SecurityExtension
extensions.go: see core/model for the docs.
type SessionEraser ¶
type SessionEraser interface {
EraseSession(ctx context.Context, sessionID string) error
EraseAllSessions(ctx context.Context) error
}
SessionEraser is an optional interface a plugin implements when it keeps per-session data outside the session store: in memory, or in a file of its own. The session API calls it when the user erases sessions (DELETE /v1/sessions/{id} calls EraseSession, DELETE /v1/sessions calls EraseAllSessions), after the session store and the archive are cleared.
The id is the Cortex session id (Context.SessionID). The plugin removes what it holds for that session, including what it has not yet written to disk, so a later write cannot bring it back. An unknown id is not an error. An error is reported in the response; it does not undo the rest of the erase.
type SessionSource ¶
type SessionSource = model.SessionSource
session.go: see core/model for the docs.
type SharedStore ¶
type SharedStore interface {
}
SharedStore is a process-scoped key→value store with TTL, injected by the listener so plugins can share state across the inbound→outbound request boundary (e.g. credential placeholders). Implemented by core/memstore.Store.
type Shutdowner ¶
Shutdowner is an optional interface a plugin may implement when it needs to release resources on graceful shutdown. Typical uses: flush in-flight audit events, close a DB connection, cancel a background goroutine it spawned in Init. Shutdown is called by Pipeline.Stop exactly once, in reverse declaration order (LIFO — symmetric with OnResponse dispatch) so a plugin that depends on an earlier plugin's resources can still use them while shutting down.
Shutdown is best-effort: errors are logged but do not prevent other plugins from shutting down. The caller-supplied ctx carries a shutdown deadline; plugins must respect it and return rather than block indefinitely.
type StreamingResponder ¶
type StreamingResponder interface {
OnResponseFrame(ctx context.Context, pctx *Context, frame []byte, last bool) Action
}
StreamingResponder is an optional interface a plugin may implement when its response handling is naturally per-message rather than over a fully-buffered body. Listeners that detect a streaming response (today: text/event-stream) deliver each complete protocol message to the pipeline as a frame; plugins that opted in see one OnResponseFrame call per frame and a final empty-frame call with last=true so aggregating plugins (inference-parser, a2a-parser) can finalize their running state.
Plugins without streaming awareness are unaffected: the listener either falls back to the buffered path (Content-Type: application/json or any non-streaming response) and runs OnResponse as today, or — for streaming responses — skips OnResponse entirely. Aggregating plugins that want to support both shapes implement OnResponseFrame and treat the buffered application/json case as a single last=true frame; the listener delivers it that way for them so one code path covers both shapes.
Contract:
- Per-frame ordering matches the wire: frames are dispatched to plugins in the order the listener parsed them off the upstream response, in pipeline reverse order (symmetric with RunResponse).
- The frame slice is owned by the listener and is valid only for the duration of the call. Plugins that need to retain bytes must copy.
- A non-Continue Action returned mid-stream stops further dispatch for that frame and rejects the response. Both proxies dispatch a frame's payload before writing its bytes, so a Reject keeps the rejected frame off the wire; but previously-emitted frames cannot be un-sent, so a mid-stream Reject results in a truncated stream rather than a 4xx/5xx response. Today no in-tree plugin returns Reject from this hook; the contract leaves the door open for per-message enforcement to be added later (a listener doing enforcement would inspect-before-forward at that point).
- last=true is always called exactly once at end-of-stream, even for an empty/zero-frame stream. Plugins finalize on last=true.
- For application/json responses the listener calls OnResponseFrame once with the full body and last=true. pipeline.RunResponse skips plugins implementing this interface so OnResponse is not called for them — the framework picks one path so a single response body is never delivered through both hooks.
type Violation ¶
type Violation struct {
// Structured fields — the authoritative description of the denial.
// Plugins that only care about semantics (not wire shape) set just
// Code and Reason; listeners and clients can inspect the rest.
Code string // machine-readable error code, e.g. "auth.missing-token"
Reason string // short human-readable message
Description string // longer explanation; optional
Details map[string]any // structured context; optional
// HTTP rendering hints — all optional. When empty, Render() picks
// defaults. Plugins set these only when they need to override.
Status int // HTTP status; if 0, StatusFromCode(Code) is used
Body []byte // response body; if nil, synthesized JSON
BodyType string // Content-Type for Body; defaults to application/json
Headers http.Header // merged into response headers
// RPCCode is the JSON-RPC error code when the rejection is rendered
// as an MCP error frame; 0 means the generic -32000. Set it only for
// a code a client acts on, such as a retry signal.
RPCCode int
// PluginName is populated by the pipeline framework from Plugin.Name()
// when the Reject is returned. Plugins should leave this empty.
PluginName string
}
Violation is the structured denial a plugin returns when it rejects a request or response. The shape is intentionally close to CPEX's PluginViolation so bridges and cross-framework tooling can reason about authbridge and CPEX denials uniformly: Code is machine-readable, Reason is a short human message, Description is a longer explanation, Details is plugin-arbitrary structured context.
HTTP-rendering hints (Status, Body, BodyType, Headers) are optional overrides — when empty, Render() synthesizes sensible defaults from Code, Reason, Description, Details, and PluginName.
func (*Violation) Render ¶
Render produces the HTTP response triple (status, headers, body) for a Violation. Called by each listener's reject path so the translation from structured Violation to wire bytes lives in one place.
Defaults when fields are unset:
- Status: StatusFromCode(Code), or 500 for unknown codes
- Body: JSON {"error":Code,"message":Reason, plus description/plugin/details when non-empty}
- BodyType: application/json
- Content-Type header: set from BodyType if not already present in Headers
Render does not mutate the receiver — it's safe to call multiple times. When Headers is nil, a fresh map is allocated.