Documentation
¶
Index ¶
- Constants
- func DurationSince(start time.Time) time.Duration
- func GetState[T any](pctx *Context, key string) *T
- func IsControlRune(r rune) bool
- func PromptContextOf(events []SessionEvent) int
- func PromptTokensOf(resp *InferenceExtension) int
- 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
- type A2AExtension
- type A2APart
- type Action
- type ActionType
- type AgentIdentity
- type AgentRole
- type Configurable
- type Context
- func (c *Context) Allow(reason string)
- func (c *Context) BodyMutated() bool
- func (c *Context) Classification() (anyAction, anyBypass bool)
- func (c *Context) ClearCurrentPlugin()
- func (c *Context) ClientInfo() *EventClient
- func (c *Context) ContentSources() []contracts.ContentSource
- func (c *Context) CurrentPhase() InvocationPhase
- func (c *Context) DenyAndRecord(reason, code, message string) Action
- func (c *Context) MarkResponseDelivered()
- func (c *Context) Modify(reason string)
- func (c *Context) Observe(reason string)
- func (c *Context) Outcome() *Outcome
- func (c *Context) PeerCertificate() *x509.Certificate
- func (c *Context) Record(inv Invocation)
- func (c *Context) RejectingPlugin() string
- func (c *Context) RequestID() string
- func (c *Context) ResolveClient()
- func (c *Context) ResponseBodyMutated() bool
- func (c *Context) ResponseDelivered() bool
- func (c *Context) SetBody(newBody []byte)
- func (c *Context) SetCurrentPlugin(name string, phase InvocationPhase)
- func (c *Context) SetResponseBody(newBody []byte)
- func (c *Context) Skip(reason string)
- type DelegationExtension
- type DelegationHop
- type Direction
- type ErrorPolicy
- type EventClient
- type EventError
- type EventIdentity
- type EventTLS
- type Extensions
- type FieldSchema
- type Finisher
- type Holder
- 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) Plugins() []Plugin
- func (h *Holder) Ready() 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 InferenceMessage
- type InferenceTool
- type InferenceToolCall
- type Initializer
- type Invocation
- type InvocationAction
- type InvocationPhase
- type Invocations
- type MCPError
- type MCPExtension
- type Metric
- type MetricsProvider
- type Option
- type Outcome
- type OutcomeAction
- type Pipeline
- func (p *Pipeline) HasStreamingResponders() bool
- 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) Ready() 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) WritesRequestBody() bool
- func (p *Pipeline) WritesResponseBody() bool
- type Plugin
- type PluginCapabilities
- type PromptContext
- type PromptContextFold
- func (f *PromptContextFold) Add(e *SessionEvent)
- func (f *PromptContextFold) AddAll(events []SessionEvent)
- func (f PromptContextFold) Folded() int
- func (f PromptContextFold) Publish() *PromptContext
- func (f *PromptContextFold) ResetFolded()
- func (f PromptContextFold) Tokens() int
- func (f PromptContextFold) TokensMergedWith(p *PromptContext) int
- type RawConfigProvider
- type RawJSON
- type Readier
- type SchemaProvider
- type SecurityExtension
- type SessionEvent
- type SessionPhase
- type SessionView
- func (v *SessionView) FailedEvents() []SessionEvent
- func (v *SessionView) InferenceRequests() []SessionEvent
- func (v *SessionView) Intents() []SessionEvent
- func (v *SessionView) LastError() *SessionEvent
- func (v *SessionView) LastIntent() *SessionEvent
- func (v *SessionView) Len() int
- func (v *SessionView) ToolCalls() []SessionEvent
- func (v *SessionView) ToolResponses() []SessionEvent
- type SharedStore
- type Shutdowner
- type StreamingResponder
- type TunnelReason
- type Violation
Constants ¶
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 PluginEventSuffix = "/event"
PluginEventSuffix is the key suffix that marks a Custom entry as plugin-public observability data destined for SessionEvent.Plugins. Plugin authors opt into serialization by writing:
pctx.Extensions.Custom["rate-limiter"+pipeline.PluginEventSuffix] = ...
The listener strips the suffix when populating SessionEvent.Plugins, so consumers see the plugin name as the map key.
const UnknownClientLabel = "unknown"
UnknownClientLabel is the reserved key for traffic that carried no User-Agent.
EXPORTED so there is exactly one definition of it. Both surfaces that serve group=agent have to agree on this string: the live aggregator keys its series on Label() directly, while the cost ledger stores absence losslessly as "" and maps it back at the query boundary (see costledger.labelFor). Those are two different code paths reaching the same bucket, so two spellings would surface as two rows in any client that merged a ring answer with a ledger answer — and each row would hold half the unattributed spend, which is worse than either alone. A matching literal in both packages would agree only by the comment saying it must; this makes it the compiler's to keep.
NOT an agent name. See Label for what it means and why a consumer must not present it as one.
Variables ¶
This section is empty.
Functions ¶
func DurationSince ¶
DurationSince returns the elapsed time since start, or 0 when start is zero (pctx constructed without wall-clock stamping, e.g. in unit tests).
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 IsControlRune ¶
isControlRune reports whether r is a C0 control, DEL, a C1 control, or a rune that rewrites or hides the text around it without being a control character at all.
The one predicate both the scan and the rewrite read, so they cannot disagree about what a control character is. The ledger's copy will carry the same clauses in the same order.
THE FOURTH CLAUSE IS THE SAME ARGUMENT AS THE THIRD, applied to runes that need no escape sequence at all. C1 is here because U+009B opens one in a terminal, so a User-Agent could paint over a chart; a bidi override does the same job in any renderer, with no terminal involved — U+202E makes a label display right-to-left, so "claude-code/2.1.14" can be made to read as another agent's name in the column beside real spend, and a zero-width joiner or space hides the difference between two keys a reader is comparing. Display-spoofing runes reaching a 30-day file and a chart through a self-reported header are the same class.
NOT A GENERAL UNICODE POLICY, and deliberately narrow: the members named are the ones with no legitimate use in a product token, and non-compliant clients are the interesting ones.
ONE MEMBER IS REACHABLE BY A COMPLIANT CLIENT, and it is worth naming rather than implying otherwise: RFC 9110's User-Agent separator is RWS = 1*( SP / HTAB ), so a tab is legal there. It is still replaced here like any other C0 control — ParseUserAgent normalises tabs to spaces before this runs, so the legal-whitespace reading is honoured.
EXPORTED, AND NOW THE ONLY COPY. usage and costledger each held a byte-identical duplicate under a comment asserting "THE THREE COPIES MOVE TOGETHER" — which nothing enforced, and only this one had test coverage for the bidi marks. Both import this package, so there was never a reason for the other two to exist; a shared predicate is what makes the identical-rule rule true instead of aspirational.
func PromptContextOf ¶
func PromptContextOf(events []SessionEvent) int
PromptContextOf is how full the session's context is, in prompt tokens: the MAIN AGENT's latest request, ignoring the subagents and one-shot calls interleaved with it.
Zero when nothing can be said, which the gauge renders as an em dash rather than as an empty track — "not known" and "barely used" are different answers and the column has to keep them apart.
A SESSION IS THREE KINDS OF CALLER, not one thread: Claude Code puts all of them under the same X-Claude-Code-Session-Id. One session's own events, in order, show what that does to a column that follows whoever spoke last — prompt tokens per response:
msgs 1491 3 3 1494 3 3 1497 2 1500 1503 1506 2 1509 context 830k 282k 282k 835k 282k 282k 837k 6k 840k 844k 848k 7k 851k
It swung 83% to 0.7% between adjacent turns. So the column classifies, and two facts do it — neither of them sufficient alone:
tool manifest agentRole main agent present main <- the conversation, which is what this file wants subagent present subagent <- Task-spawned, and carries its own manifest one-shot ABSENT main <- monitor / classifier / title call
THE MANIFEST EXCLUDES THE ONE-SHOTS. A request carrying no tools is a single completion rather than an agentic turn, and across 115 responses in three live sessions the split was total:
carries tools 73 responses 63-1572 messages 94k-897k context no tools 42 responses 2-3 messages 6.5k-295k context
Note the second row's ceiling, because it rules out the two cheaper filters. One of those calls carried 295k and another 421,220 against a true context of 998,334, so no size threshold separates them — and they declare themselves MAIN, since the CLI issues them rather than a subagent, so the role does not exclude them either.
THE ROLE EXCLUDES THE SUBAGENTS, which the message count only approximated. Claude Code states the role outright (see InferenceExtension.AgentRole) and a compaction cannot change it, whereas subagent turns reached 177 and 186 messages against main threads at 188 and 288, with their contexts overlapping too — 198,899 against 217,121. The count separates the populations it happens to be ordered on, and only while it is.
AMONG WHAT IS LEFT, THE LATEST WINS, by timestamp. That is safe only because both filters are exact rather than statistical: there is no window, so a main thread that goes SILENT while a subagent runs is never aged out, and no amount of subagent traffic is a candidate to fill one. Measured across 555 main-agent turns in six sessions the series steps upward and drops exactly once — at the compaction — so the column tracks the conversation, and follows it when it restarts on the next turn rather than on the next five hundred.
WITH NO ROLE STATED the rule falls back to the most messages, ties to the latest, and then to the larger context: what this column did before, plus a final tie-break for the one pair the sequential form left to arrival order (see better). It pays the cost the role was added to remove. A compaction restarts the conversation at a low message count while the pre-compaction request stays retained with 2,468 of them, so the gauge keeps showing the old context, for the rest of the session if that request is never evicted. A stale figure still beats one that flips to a subagent's, and a window would not fix it — it would reintroduce the silence problem.
AND THAT FALLBACK IS PERMANENT, not a version-skew relic to be deleted. An earlier version of this comment said the fallback, PromptContextFold.msgs and messageCount could all go "once the supported proxy floor publishes agentRole" — which reads the field as a proxy capability. It is not one: inferenceparser.agentRole returns "" for a request with no system message at all (/v1/completions), for one whose first system line lacks the required billing-header prefix, and on an unparseable body, so the answer depends on the CLIENT. Its own doc puts it plainly — "every client that is not Claude Code". So there is no proxy version at which the unstated arm stops being reachable, and anything resting on the assumption that there is should stop.
A SESSION IS EITHER STATED OR IT IS NOT, and any stated turn outranks every unstated one, however much longer the unstated one was: a figure chosen by a rule that cannot see subagents is not evidence about the conversation. So the first stated turn takes the column on the event it arrives on, and an unstated row after it never takes it back — a session already producing stated turns has no reason to produce an unstated one, and trusting it would hand the column to whatever sent it.
A PROPERTY OF THE SESSION, NOT OF ITS PROXY, which is this clause's own correction to make: an earlier version read "a session whose proxy states roles", the framing the paragraph above dismantles. A proxy only PUBLISHES the field; what fills it is the client's billing-header line, so no proxy version makes a session stated, and both an upgrade and a client change can be the reason the first stated turn arrives mid-session.
Expressed as the top rank of a total order rather than as a one-way latch, so that which of the two arrived first cannot matter (see better).
THE PROMPT SIDE ONLY. PromptTokensOf is input + cache-read + cache-write; output is left out. Measured on the same sessions it is 0.003%-2.2% of the prompt, and 0.2% on the conversations near the limit — a fifth of one eighth-block at 1M, so counting it would change no pixel.
Read off the RESPONSE because the provider is the only party that tokenizes — the same reason tokensCell looks forward from a request row to its pair.
WHY THIS COMES FROM abctl'S OWN CACHE and not from the session summary: the summary carries no per-request field, so there is nothing to read. abctl subscribes to /v1/events unfiltered and appends every event under its session id, so any session with traffic since it attached has a conversation here.
THE TIMELINE ANSWERS THROUGH THE COUNTS AND THE ROLE. abctl asks for `view=summary` on every timeline fetch, tail and page alike, and that projection drops the two SLICES this rule used to read — so summarizeEvent records their lengths first and toolCount/messageCount read either shape. Without them a delivered row cannot be read at all: measured on one live session's 200-event window, 41 of 62 inference responses carry a manifest unprojected and 0 of 62 do projected. agentRole needs none of that machinery: it is a scalar, and summarizeEvent copies the extension struct whole before nilling the slices, so it arrives on a projected row as-is.
AND THE FIGURE OUTLIVES THE EVENTS IT WAS READ FROM, deliberately — see rebaseSessionContext. Two cases need that: a proxy built between this column and the counts projects without stating them, and the picker releases a live session's events for memory (keys.go) without learning anything about the session.
A whole-slice fold, for callers with no running state to keep — the tests, and any future one-shot reader. The sessions pane goes through sessionContextFor instead.
func PromptTokensOf ¶
func PromptTokensOf(resp *InferenceExtension) int
PromptTokensOf is the request's own billed token count: what the provider counted for everything we sent. It lives on the response because the provider is the only party that tokenizes, but it is a request-side quantity — which is what lets a request row show a total at all.
NAMED ...Of BECAUSE THE BARE NAME IS ALSO A FIELD, and they do not agree: this function is Input+CacheRead+CacheWrite, while InferenceExtension.PromptTokens is an aggregate nothing in tree writes. `x.PromptTokens` against `PromptTokens(x)` was one character from a silent zero, with the compiler content either way. PromptContextOf in this package already reads as the house style for "the figure for this thing".
OUTPUT IS DELIBERATELY EXCLUDED, which the prompt-context rule measured on the same sessions: output is 0.003%-2.2% of the prompt and 0.2% on conversations near the context limit, so folding it in would change no rendered pixel while making the figure mean something else.
The aggregate fallback cannot currently fire: parsercommon.TokenUsage.Fill is the sole production writer of these fields and sets PromptTokens to Input+CacheRead+CacheWrite — the same sum computed here — so when the split is zero the aggregate is zero too. It costs nothing and would start earning its keep if a parser ever published the aggregate directly. An earlier version of this paragraph said the fallback was "kept only to mirror savedTokensAndCost", an identifier that exists nowhere at this branch or upstream; it was already dangling in the cost_event.go this branch deletes.
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
SnapshotPlugins collects plugin-public observability events from pctx.Extensions.Custom entries whose keys end in PluginEventSuffix. Each matching value is json.Marshaled into the wire-form map under the plugin name (suffix stripped). Marshal errors downgrade to slog Debug and skip the entry rather than aborting recording — that keeps a misbehaving plugin from taking out the whole session stream.
func StatusFromCode ¶
StatusFromCode returns the HTTP status a Violation maps to when its Status field is unset. Falls back to 500 for unknown codes.
Types ¶
type A2AExtension ¶
type A2AExtension struct {
// Request fields
Method string `json:"method,omitempty"`
RPCID any `json:"rpcId,omitempty"`
SessionID string `json:"sessionId,omitempty"`
MessageID string `json:"messageId,omitempty"`
TaskID string `json:"taskId,omitempty"`
Role string `json:"role,omitempty"`
Parts []A2APart `json:"parts,omitempty"`
// Response fields (populated by a2a-parser OnResponse)
FinalStatus string `json:"finalStatus,omitempty"` // "completed", "failed", "canceled"
Artifact string `json:"artifact,omitempty"` // final artifact text
ErrorMessage string `json:"errorMessage,omitempty"` // failure reason if status is "failed"
// Classification — see MCPExtension.IsAction.
IsAction bool `json:"isAction,omitempty"`
}
A2AExtension carries parsed A2A protocol metadata from inbound requests and response summaries for debugging.
IsAction is the parser's classification verdict; see MCPExtension.IsAction for the contract. Set true for user-meaningful methods (message/send, message/stream); zero value covers protocol/discovery methods.
func SnapshotA2A ¶
func SnapshotA2A(ext *A2AExtension) *A2AExtension
SnapshotA2A returns a shallow copy of ext. The record helpers attach the snapshot to the SessionEvent rather than the live pointer so response-phase mutations on pctx.Extensions.A2A (e.g. the parser stamping the server-assigned contextId onto SessionID during OnResponse) don't retroactively rewrite request-phase events that were already appended. Slice fields are reused intentionally — they are only assigned, never mutated in place, after the parser completes.
func (*A2AExtension) Fragments ¶
func (e *A2AExtension) Fragments() []contracts.Fragment
Fragments implements contracts.ContentSource for A2A messages.
Request-phase: iterates message Parts, emitting text and data parts tagged with the message role (normalized: A2A's native "agent" role is rewritten to "assistant" so guardrails match a single vocabulary across A2A and Inference). File parts carry URIs or base64 blobs, not prose; they're skipped.
Response-phase: the final artifact is assistant-authored text.
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.
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 AgentRole ¶
type AgentRole string
AgentRole is the closed vocabulary for InferenceExtension.AgentRole.
THE EMPTY VALUE HAS NO CONSTANT, deliberately. It means "the parser could not tell", and naming it would invite a reader to compare against it as though it were a third kind of caller; the two constants below are the only claims this type ever makes.
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 authbridge/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
// 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
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 ID regardless; 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
// 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 authlib/tls.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
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) Allow ¶
Allow records an Invocation with Action=allow and the given Reason. Convenience for gate plugins on the approved branch.
func (*Context) BodyMutated ¶
BodyMutated reports whether a plugin called SetBody 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.
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) 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. sanitizeUA'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() []contracts.ContentSource
ContentSources returns every protocol extension on this Context that implements contracts.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 == contracts.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) 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) Observe ¶
Observe records an Invocation with Action=observe. Convenience for parsers that successfully extracted diagnostic data without modifying the message.
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) 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) 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) 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 abctl and the session store classify them.
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) 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.
Idempotent: the second call is the memo's own no-op.
func (*Context) ResponseBodyMutated ¶
ResponseBodyMutated is the response-side analogue of BodyMutated.
func (*Context) ResponseDelivered ¶
ResponseDelivered reports whether the response has already gone downstream.
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.
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, bodyMutated stays false, and downstream plugins continue to see the original. 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.
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) 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) 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.
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.
type DelegationExtension ¶
type DelegationExtension struct {
Origin string // original caller's subject ID
Actor string // current actor's subject ID
// contains filtered or unexported fields
}
DelegationExtension tracks the token delegation chain across hops. The chain is append-only and unexported to prevent forgery or truncation.
func (*DelegationExtension) AppendHop ¶
func (d *DelegationExtension) AppendHop(hop DelegationHop)
AppendHop adds a hop to the delegation chain. This is the only way to extend the chain — direct mutation is prevented by the unexported slice.
AppendHop is not safe for concurrent use. The pipeline guarantees sequential invocation.
func (*DelegationExtension) Chain ¶
func (d *DelegationExtension) Chain() []DelegationHop
Chain returns a copy of the delegation chain. The copy prevents callers from mutating the backing slice (truncation, reordering, forgery).
func (*DelegationExtension) Depth ¶
func (d *DelegationExtension) Depth() int
Depth returns the number of hops in the delegation chain.
type DelegationHop ¶
type DelegationHop struct {
SubjectID string
Scopes []string
Timestamp time.Time
// Audience is the target audience the hop's token was minted for
// (RFC 8693 `audience`). Empty when the hop isn't an exchange.
Audience string
// Strategy names how the hop was produced — e.g. "token-exchange"
// for an RFC 8693 exchange. Empty when unclassified.
Strategy string
// FromCache reports the hop's token was served from the exchange
// cache rather than freshly minted at the IdP.
FromCache bool
}
DelegationHop represents one hop in the delegation chain.
Audience, Strategy, and FromCache enrich a hop produced by an AuthBridge auth plugin (today: token-exchange) so downstream policy can reason about WHAT a token was minted for and HOW. They map onto the corresponding CPEX DelegationHop fields. All three are optional — a producer that only knows the subject leaves them zero.
type Direction ¶
type Direction int
Direction indicates whether a request is inbound (caller → this agent) or outbound (this agent → target service).
func (Direction) MarshalJSON ¶
MarshalJSON emits the string form ("inbound"/"outbound") so the wire format is human-readable without an enum→int lookup.
func (Direction) String ¶
String returns "inbound" / "outbound". Used for structured logs and the wire format of SessionEvent.
func (*Direction) UnmarshalJSON ¶
UnmarshalJSON decodes a Direction from the string form emitted by MarshalJSON. Unknown strings decode to Inbound (zero value) without error so downstream consumers stay tolerant of forward-compatible additions. A Debug-level log fires on unknown input so wire-format drift is at least observable in a verbose test run.
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 struct {
// Name is the canonical agent name — "claude-code" — or empty when the
// User-Agent matched nothing in knownClients. Empty is not a failure; see Raw.
Name string `json:"name,omitempty"`
// Version is the version string that followed the product token, or empty when
// the agent was not recognised or sent no version.
Version string `json:"version,omitempty"`
// Raw is the User-Agent as it was sent, with tabs normalised to spaces, sanitised (see
// sanitizeUA) and capped at maxClientLen.
//
// "Verbatim" up to those three rules, which is as verbatim as a string that reaches a
// terminal and a durable file can be. Worth knowing before comparing this against a
// header captured somewhere else: a tab in the original is a space here, because RFC
// 9110 allows HTAB as the separator and ParseUserAgent normalises it rather than letting
// the sanitiser turn it into U+FFFD.
//
// Kept ALONGSIDE Name rather than only when parsing fails, so a new coding
// agent appears in the breakdown the day someone runs it instead of after a
// parser update ships — and so the detection work for the other agents can see
// what strings to expect rather than guessing them.
Raw string `json:"raw,omitempty"`
}
EventClient identifies the coding agent that made a request, parsed from its User-Agent header.
A DISPLAY AXIS, NOT A SECURITY BOUNDARY. The User-Agent is a request header, so this value is CLIENT-ASSERTED AND TRIVIALLY SPOOFABLE: it is an observability and cost-attribution key, never an authorization subject. Any client can claim to be any agent at any version. Nothing here may ever be used for an authorization decision, a rate-limit exemption, a pricing tier, or any other choice whose wrong answer costs something. What this is for is attribution in a cost breakdown, where a caller lying about itself mis-attributes that caller's own spend and nothing else.
That is the same caveat Context.Session carries about client-asserted session ids, deliberately in the same words: the same property of a different field.
NOT TO BE CONFUSED WITH Identity / EventIdentity, which sit beside it on the same context and the same event. Those are the AUTHENTICATED auth principal, established by an auth plugin and nil until one runs. This is a self-reported software label. The two answer different questions — "who is calling" versus "what program is calling" — and the proximity of the fields is the reason this paragraph exists: a reader who treats one as the other has built authorization on a request header.
Nil means NO User-Agent was sent. That is distinct from a User-Agent that was sent but matched no known agent, which produces a non-nil value carrying only Raw. The distinction is load-bearing for #952, which has to tell an honest zero from missing data: an unrecognised agent we can still NAME is data, one we cannot is not.
func ParseUserAgent ¶
func ParseUserAgent(ua string) *EventClient
ParseUserAgent derives an EventClient from a User-Agent header value.
Returns nil when the header is absent or blank — absence, not a client named "unknown". Callers must not substitute a placeholder here: EventClient.Label() is where absence becomes the display string "unknown", and doing it at parse time would make a missing header indistinguishable from an agent that really called itself that.
A value that IS present but matches no known agent returns non-nil with an empty Name and the (capped) header in Raw. That is an unrecognised agent, not an absent one, and Label() reports it under its raw value rather than folding it into "unknown" — otherwise every new coding agent would land in the same bucket as untagged traffic and the breakdown could not distinguish them.
func (*EventClient) Label ¶
func (c *EventClient) Label() string
Label returns the display key for this client: "claude-code/2.1.14" for a recognised agent, the raw User-Agent for an unrecognised one, and UnknownClientLabel ("unknown") when there is no client at all.
NIL-SAFE ON PURPOSE. Every consumer — the usage aggregator, the cost ledger — calls this on events that may carry no client, and a nil check at each call site is how one of them eventually gets forgotten. A forgotten one is not a panic caught in review either: it is a blank key in a breakdown table, which reads as a rendering bug rather than as unattributed traffic.
"unknown" means THIS EVENT CARRIED NO USER-AGENT. It is a RESERVED BUCKET, not an agent name, and a consumer must not present it as one: a row labelled "unknown" in a cost breakdown is unattributed traffic, not a program that spent money. It is never the answer for a User-Agent that WAS sent and could not be recognised — that case answers with the raw value, so it stays nameable and does not pool with untagged traffic. The empty struct answers "unknown" for the same reason: it can name nothing, and inventing a name for it would put a value in a cost table that no request ever sent.
CARRIES NO CONTROL CHARACTERS when the EventClient came from ParseUserAgent, which is the only path a request takes — a property of the parser, not of this method. A hand-built EventClient (a test, a future producer) can hold anything its author put there and this method will join it to a name and hand it on, which is the second reason costledger sanitises again before writing a row: the guarantee here covers one code path, and the file is forever.
A caller that sends literally "User-Agent: unknown" does land in that reserved bucket, and that collision is not defended against. Reserving the word would buy nothing: the axis is spoofable by construction, so the same caller could just as well claim "claude-cli/2.1.14" and land in a real agent's row instead. Anything that must not be spoofable belongs on Identity. Recorded here so the collision is a known property rather than a surprise to whoever first sees the row.
type EventError ¶
type EventError struct {
Kind string `json:"kind"`
Code string `json:"code,omitempty"`
Message string `json:"message,omitempty"` // human-readable reason; safe to surface in logs/metrics
}
EventError describes why a response event represents a failure.
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.
type EventIdentity ¶
type EventIdentity struct {
Subject string `json:"subject,omitempty"`
Scopes []string `json:"scopes,omitempty"`
ClientID string `json:"clientId,omitempty"`
AgentID string `json:"agentId,omitempty"`
}
EventIdentity carries the "who" for a session event.
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 ¶
type EventTLS struct {
// Version is the negotiated TLS version, e.g. "TLS 1.3".
Version string `json:"version,omitempty"`
// CipherSuite is the negotiated cipher suite name, e.g.
// "TLS_AES_128_GCM_SHA256".
CipherSuite string `json:"cipherSuite,omitempty"`
// PeerSPIFFEID is the URI SAN of the verified peer cert when it
// is a SPIFFE URI; otherwise empty. Empty means either the peer
// cert had no SPIFFE URI (workload outside SPIRE) or had multiple
// (non-conformant cert).
PeerSPIFFEID string `json:"peerSpiffeId,omitempty"`
}
EventTLS describes the TLS state of a connection that produced a session event. Populated by the reverse-proxy listener when mTLS is enabled and the inbound connection completed a TLS handshake; otherwise nil.
func NewEventTLS ¶
func NewEventTLS(state *tls.ConnectionState, peerSpiffeID string) *EventTLS
NewEventTLS builds an EventTLS from a *tls.ConnectionState (the shape http.Request.TLS exposes). peerSpiffeID is the caller's pre-extracted SPIFFE URI — passed in rather than re-extracted here to keep this package free of an authlib/tls dependency. Returns nil when state is nil so callers can pass r.TLS unconditionally.
type Extensions ¶
type Extensions struct {
MCP *MCPExtension
A2A *A2AExtension
Security *SecurityExtension
Delegation *DelegationExtension
Inference *InferenceExtension
Invocations *Invocations
Custom map[string]any
}
Extensions holds typed extension slots for plugin-to-plugin communication. Each slot is populated by a specific plugin and consumed by downstream plugins.
The named slots (MCP, A2A, Security, Delegation, Inference, Auth) are reserved for telemetry-worthy extensions — data that flows into SessionEvent, is serialized on the wire API, and has a published schema that unrelated plugins can rely on. Adding a new named slot is a core-library change.
For data that shouldn't drive a core-library change, use Custom. Two access patterns share the same map:
Plugin-PRIVATE state (cross-phase continuity inside one plugin). Use the typed SetState / GetState generics. Key is plugin.Name(). Value is typically *T for a plugin-internal struct (may contain sync primitives, unexported fields, channels). Never flows to session events.
Plugin-PUBLIC observability. Use a key suffixed with "/event" (e.g., "rate-limiter/event"). Value must be JSON-marshalable. The listener serializes matching entries into SessionEvent.Plugins at record time — keyed by the plugin name (suffix stripped). A new plugin can surface events to /v1/sessions without any authlib modification. See authbridge/docs/plugin-reference.md for the convention + promotion criteria for named-slot graduation.
The suffix convention keeps the two intents unambiguous at write time: a plugin author has to deliberately type "/event" to opt into serialization, so private state can never leak by accident.
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, and the reloader is responsible for not Stop()ing the old pipeline until a drain window expires.
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) 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) Plugins ¶
Plugins is equivalent to h.Load().Plugins(). Used by the session events API to surface pipeline composition.
func (*Holder) Run ¶
Run is equivalent to h.Load().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. One atomic Load per call.
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) after the intended drain window.
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.
type InferenceExtension ¶
type InferenceExtension struct {
Model string `json:"model,omitempty"`
Messages []InferenceMessage `json:"messages,omitempty"`
Temperature *float64 `json:"temperature,omitempty"`
MaxTokens *int `json:"maxTokens,omitempty"`
TopP *float64 `json:"topP,omitempty"`
Stream bool `json:"stream,omitempty"`
Tools []InferenceTool `json:"tools,omitempty"`
ToolChoice any `json:"toolChoice,omitempty"` // "auto" | "none" | {type,function:{name}}
// MessageCount and ToolCount are how many Messages and Tools this event HAD, for readers of
// a copy that no longer carries them. Set only by sessionapi.summarizeEvent, immediately
// before it nils both slices; zero everywhere else, including on every event the store keeps.
//
// WHY A COUNT AND NOT THE SLICE: the two useful facts about a conversation that have nothing
// to do with its content are "did this request carry a tool manifest" and "how long is the
// conversation". abctl's CONTEXT gauge asks exactly those — a manifest separates an agentic
// turn from a one-shot completion, and the message count was how it guessed which of the
// threads sharing a session id was the conversation — and it asked them of len(Tools) and
// len(Messages), which `view=summary` strips. Measured on one live session, 41 of 62 inference
// responses carry a manifest unprojected and 0 of 62 do projected, so the gauge showed a dash
// for every row the timeline delivered. Two ints answer both against a payload that is 99.5%
// of the event.
//
// THE MESSAGE COUNT IS NOW THE FALLBACK for that second question and AgentRole below is the
// answer: the count separates a conversation from its subagents only while it is the longer of
// the two, and it cannot see a compaction, which restarts the conversation at a low count. It
// stays because a consumer may be reading a proxy that states no role. ToolCount is not
// affected — nothing else distinguishes a one-shot.
//
// ZERO MEANS "NOT STATED", NOT "NONE", so a reader must prefer the slice when it is present:
//
// if n := len(inf.Tools); n > 0 { use n } else { use inf.ToolCount }
//
// Both version-skew directions land on that rule. An OLD proxy ignores `view` and returns
// full events (sessionapi.eventProjection), so the slices answer there. A proxy built between
// abctl's CONTEXT column and these fields projects without setting them, and then neither
// answers — which is one reason abctl remembers its own figure rather than recomputing it
// from whatever it happens to hold.
MessageCount int `json:"messageCount,omitempty"`
ToolCount int `json:"toolCount,omitempty"`
// AgentRole says WHICH CALLER under one session id made this request — the interactive
// conversation, or a subagent it spawned. Claude Code declares it: every request's system
// prompt opens with a pseudo-header line, and a subagent's carries cc_is_subagent=true.
//
// main: x-anthropic-billing-header: cc_version=2.1.270.119; cc_entrypoint=cli;
// subagent: x-anthropic-billing-header: cc_version=2.1.270.658; cc_entrypoint=cli; cc_is_subagent=true;
//
// Measured on 19 probed requests across three live sessions: present on every restricted
// manifest (11 tools), absent on every full one (27 and 31), and — the property that makes
// it worth publishing — UNCHANGED ACROSS A COMPACTION, which rewrites the messages and
// leaves the system prompt alone. The message count cannot say this: subagent turns reached
// 177 and 186 messages against main threads at 188 and 288, so the two populations overlap.
//
// WHY THERE IS NO THIRD VALUE FOR A ONE-SHOT. The completions Claude Code interleaves with
// a conversation — its permission security monitor, the auto-mode state classifier — are
// issued by the same CLI rather than by a subagent, so they declare no marker and are
// "main" here. What separates them is that they carry no tool manifest, which is ToolCount
// above; this field does not restate it, and a reader needs both.
//
// EMPTY MEANS "NOT STATED", NOT "MAIN" — the same rule as the counts, and the reason this
// is a string rather than a bool. abctl's CONTEXT gauge takes the main agent's LATEST turn
// where the role is stated and falls back to the message count where it is not; a bool's
// false cannot tell a proxy that says "main" from one that says nothing, and the difference
// decides which rule runs. Set only when the billing-header line is there, so a client that
// is not Claude Code states nothing and gets the fallback.
//
// Read off the REQUEST. It reaches the response event the same way the manifest does —
// SnapshotInference copies the struct whole — and survives `view=summary` because
// summarizeEvent copies it too.
AgentRole AgentRole `json:"agentRole,omitempty"`
// StreamedResponse says the RESPONSE arrived as a stream, which is a different fact from Stream
// above — that one is what the request ASKED for, read off the request body.
//
// They come apart in both directions and the difference decides whether a token tally is FINAL: a
// gateway may answer a non-streaming request with SSE, and a client asking for a stream may get a
// buffered body. A parser reading the request flag then calls a running tally final (a floor
// labelled exact) or calls a final one running (a caveat on correct money). Set by whoever
// observed the frames — inferenceparser's per-frame arm — and read by pricing.IncompleteReason,
// both of which are in this PR.
StreamedResponse bool `json:"streamedResponse,omitempty"`
// Response fields (populated after OnResponse runs).
Completion string `json:"completion,omitempty"`
FinishReason string `json:"finishReason,omitempty"`
// ToolCalls are the tool invocations the model requested. Populated on
// three of the four response paths — both non-streaming dialects and
// Anthropic streaming. An OpenAI *stream* leaves it empty: that dialect
// splits each call across `choices[].delta.tool_calls[]` fragments keyed
// by their own index, a shape the streaming chunk decoder does not read.
//
// So empty means "the model requested no tools" only for a non-streaming
// response or an Anthropic stream. A consumer that spans dialects — cost
// accounting, per-tool attribution — must not read absence as a negative
// on a streamed OpenAI turn, where it is indistinguishable from a turn
// whose calls were never captured.
ToolCalls []InferenceToolCall `json:"toolCalls,omitempty"`
// Legacy aggregates, derived from the split fields below via
// parsercommon.TokenUsage.Fill.
PromptTokens int `json:"promptTokens,omitempty"`
CompletionTokens int `json:"completionTokens,omitempty"`
TotalTokens int `json:"totalTokens,omitempty"`
// Split token counters — provider-neutral shape published by every
// inference parser via parsercommon.TokenUsage.Fill.
InputTokens int `json:"inputTokens,omitempty"` // uncached prompt tokens
CacheReadTokens int `json:"cacheReadTokens,omitempty"` // served from cache
CacheWriteTokens int `json:"cacheWriteTokens,omitempty"` // written to cache
OutputTokens int `json:"outputTokens,omitempty"` // generated tokens
ReasoningTokens int `json:"reasoningTokens,omitempty"` // reasoning-only output
// PresentKinds names which split sub-kinds the provider populated.
// Zero on a set bit means "reported zero"; zero on an unset bit
// means "not exposed." Bit layout matches parsercommon.Kind
// (Input=1, CacheRead=2, CacheWrite=4, Output=8, Reasoning=16);
// typed as uint8 to avoid importing parsercommon here.
PresentKinds uint8 `json:"presentKinds,omitempty"`
// Classification — see MCPExtension.IsAction.
IsAction bool `json:"isAction,omitempty"`
}
InferenceExtension carries parsed LLM inference request and response metadata. Request fields are populated by OnRequest; response fields by OnResponse.
IsAction is the parser's classification verdict; see MCPExtension.IsAction for the contract. Inference calls are always actions when populated, so inference-parser sets this true unconditionally.
func SnapshotInference ¶
func SnapshotInference(ext *InferenceExtension) *InferenceExtension
SnapshotInference returns a shallow copy of ext. Scalar response fields (Completion, FinishReason, *Tokens) get assigned on the live extension during OnResponse; without snapshotting, the request event's view would contain the eventual response's token counts and completion.
func (*InferenceExtension) Fragments ¶
func (e *InferenceExtension) Fragments() []contracts.Fragment
Fragments implements contracts.ContentSource for Inference messages.
Request-phase: walks the Messages slice. OpenAI's role vocabulary maps to our standard values directly, except that OpenAI's "tool" role marks a tool RESULT in the conversation history — remapped to "tool_result" so it lines up with MCP's tool result semantics.
Response-phase: the model's completion (assistant) plus any tool calls the model emitted (tool name + arguments as separate fragments).
type InferenceMessage ¶
type InferenceMessage struct {
Role string `json:"role"`
Content string `json:"content,omitempty"`
// ContentBytes is the wire size of this message's content value as the
// client sent it, before the parser reduced it to text. Content keeps
// only text blocks, so a message whose payload is a tool result, an
// image, or any other non-text block flattens to "" and looks free —
// while the model was billed for all of it. ContentBytes is what those
// messages contribute, without recording their contents: it is a byte
// count of the raw JSON (syntax and escapes included), not a token
// count, and is a size signal rather than an exact one.
//
// Whitespace counts too, because the measure is of what was sent, not of
// a normalized form of it. A client that pretty-prints its request bodies
// therefore reports a higher count than one sending compact JSON for the
// same content — tens of percent apart on a deeply nested tool result.
// Comparable across messages from one client; not across clients.
ContentBytes int `json:"contentBytes,omitempty"`
}
InferenceMessage represents a single message in the conversation.
type InferenceTool ¶
type InferenceTool struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Parameters RawJSON `json:"parameters,omitempty"`
}
InferenceTool is a function/tool the client declared the model may call. Parameters is the OpenAI-style JSON Schema object describing valid args, kept as received — see RawJSON for why it is not decoded.
type InferenceToolCall ¶
type InferenceToolCall struct {
ID string `json:"id,omitempty"`
Name string `json:"name"`
Arguments string `json:"arguments,omitempty"`
}
InferenceToolCall is a tool invocation the model emitted in its response. Arguments is the raw JSON string as returned by the LLM (often needs json.Unmarshal by the caller) — kept as a string so malformed output from the model doesn't prevent capture.
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 Invocation ¶
type Invocation struct {
Plugin string `json:"plugin"`
Action InvocationAction `json:"action"`
// Phase is the pass (request or response) that appended this
// record. The listener uses it to filter invocations per event at
// record time — the request event carries only request-phase
// entries, the response event only response-phase entries, even
// though pctx carries the union.
Phase InvocationPhase `json:"phase,omitempty"`
Reason string `json:"reason,omitempty"`
// Path is the request path the invocation ran on. Populated so
// operators can disambiguate invocations on the same plugin (e.g.
// a jwt-validation skip on /healthz vs /.well-known/agent.json;
// a mcp-parser observe on tools/call vs tools/list). Left empty
// when the plugin has no path context.
//
// Back-filled from Context.Path by Record when a plugin leaves it
// unset, so it holds the same value as SessionEvent.HTTPPath on the
// enclosing event. Read HTTPPath for "the path of this request" — it
// is present on every recorded HTTP event, while this field exists
// only where a plugin recorded an invocation.
Path string `json:"path,omitempty"`
// Details carries plugin-specific context as a flat string→string
// map. Opaque to the framework; abctl renders it as key=value rows
// in the invocation detail pane. Suggested convention: snake_case
// keys scoped to the plugin's semantic domain. Built-in plugins
// use keys like expected_issuer, token_subject, route_host,
// target_audience, cache_hit. Third-party plugins define their own.
//
// Stringify booleans as "true"/"false" and []string as space-
// joined (matching OAuth scope conventions). Keep values short
// enough for a detail pane — bulky diagnostics belong in the
// Extensions.Custom escape-hatch event.
//
// NEVER put raw tokens, signatures, or client credentials here.
// The session API has no auth on it — only safe-to-log data
// belongs in Invocation.Details.
Details map[string]string `json:"details,omitempty"`
// Shadow reports that the plugin ran under on_error: observe and
// its decision (deny or modify) was NOT applied to the request.
// An operator reading a would-have-blocked timeline filters on
// Shadow=true to count rollout-candidate events; a dashboard that
// aggregates "effective denies" filters Shadow=false. The
// framework, not the plugin, sets this — plugin code looks
// identical under enforce and observe.
Shadow bool `json:"shadow,omitempty"`
// Late reports that this Invocation was appended AFTER the response had already gone
// downstream — a teardown flush, a finalization pass — so a deny recorded here could not
// have taken effect whatever it says. Kept rather than dropped: a plugin that would have
// refused a response that already shipped is exactly what a rollout wants to see, and it
// is the same distinction Shadow draws for on_error: observe.
//
// Read by OutcomeFromContext, which does not let a late deny make the request a denial.
// The framework sets it, from Context.MarkResponseDelivered.
Late bool `json:"late,omitempty"`
}
type InvocationAction ¶
type InvocationAction string
InvocationAction is the universal 5-value vocabulary every plugin uses to describe what it did on a single pipeline pass. Every plugin — gate, parser, rate-limiter, guardrail, whatever we add next — MUST emit exactly one of these per Invocation so abctl and /v1/sessions can render a consistent per-plugin timeline.
allow — a gate plugin permitted the request. jwt-validation
returns this on successful signature + issuer + audience.
deny — a gate plugin rejected the request. Terminal for the
pipeline pass. jwt-validation on bad token,
token-exchange on upstream IdP failure.
skip — the plugin ran but didn't act. jwt-validation on a
bypass path, token-exchange on a host with no matching
route, a parser whose body didn't match its format.
modify — the plugin mutated the message. token-exchange replaced
the Authorization header with a freshly-issued token.
observe — the plugin attached diagnostic data without altering
flow. All parsers use this when they successfully parse.
Reason (the stable machine code alongside Action) can discriminate within a value — e.g. skip/path_bypass vs skip/no_matching_route tell different stories at the detail-pane level, but both read "skip" in the at-a-glance timeline.
Named InvocationAction rather than Action because pipeline.Action is already the pipeline-directive struct (Continue / Reject); keeping the names distinct avoids a shadowing foot-gun.
const ( ActionAllow InvocationAction = "allow" ActionDeny InvocationAction = "deny" ActionSkip InvocationAction = "skip" ActionModify InvocationAction = "modify" ActionObserve InvocationAction = "observe" )
type InvocationPhase ¶
type InvocationPhase string
Invocation records one plugin's action on one pipeline pass. Plugin is the plugin's Name() for traceability. Action is the universal 5-value verb (see Action). Reason is a stable machine-readable label paired with the counters plugins already feed into /stats — use Reason for filtering / indexing rather than Action alone when you need to distinguish skip/path_bypass from skip/no_matching_route.
Diagnostic fields are populated selectively per plugin. Auth gates populate ExpectedIssuer/Audience/Token*; outbound routers populate Route* and CacheHit; parsers typically populate only Plugin/Action/ Reason because their semantic payload lives on the typed extension slots (A2A / MCP / Inference).
NEVER contains the raw bearer token, token signature, or client credentials. The session API has no auth on it; only safe-to-log data belongs here. InvocationPhase identifies whether an Invocation was appended during the request pass or the response pass. Without this tag the full list on pctx — which is cumulative across both phases — can't be correctly partitioned by the listener when it records the request event and the response event separately. Keeping the full list on pctx is deliberate (plugins may need cross-phase context); the phase tag lets consumers filter by pass.
const ( InvocationPhaseRequest InvocationPhase = "request" InvocationPhaseResponse InvocationPhase = "response" )
type Invocations ¶
type Invocations struct {
Inbound []Invocation `json:"inbound,omitempty"`
Outbound []Invocation `json:"outbound,omitempty"`
}
Invocations carries one record per plugin that ran on a pipeline pass, split by direction so a single event's inbound and outbound plugin activity stays distinguishable. Multiple plugins can contribute — each appends an entry — so chained plugins cooperate without schema churn. Directions are disjoint per request: a single listener pass populates at most one of Inbound / Outbound.
Replaces the earlier AuthExtension; parsers and any other plugin class share the list now. abctl renders one row per Invocation, so operators get a per-plugin timeline without guessing which plugins touched each event.
func SnapshotInvocations ¶
func SnapshotInvocations(ext *Invocations, phase InvocationPhase) *Invocations
SnapshotInvocations is an alias for FilteredByPhase that participates in the Snapshot* family for symmetry with the other shallow-copy helpers. The underlying call already returns a fresh slice.
func (*Invocations) FilteredByPhase ¶
func (in *Invocations) FilteredByPhase(phase InvocationPhase) *Invocations
FilteredByPhase returns a new *Invocations containing only entries whose Phase matches the argument. Strict match — untagged entries (Phase == "") are dropped because the framework always populates Phase via Context.Record; an untagged entry is a plugin bug and including it in the wrong phase would double-report in one event and be missing from the other.
The underlying Invocation values are copied shallowly; mutating a returned entry's Details map mutates the source. Acceptable for the per-request flow where the original lives only on pctx and is discarded after recording.
Returns nil when no entries match so callers can drop the field from the SessionEvent without a null check.
Intended for reject-event recording in listeners and for the accept-path phase split (one SessionEvent per phase). Listeners that need full independence from pctx's lifecycle layer their own snapshot on top.
type MCPError ¶
type MCPError struct {
Code int `json:"code"`
Message string `json:"message"`
Data any `json:"data,omitempty"`
}
MCPError mirrors a JSON-RPC 2.0 error object.
type MCPExtension ¶
type MCPExtension struct {
Method string `json:"method,omitempty"`
RPCID any `json:"rpcId,omitempty"`
Params map[string]any `json:"params,omitempty"`
Result map[string]any `json:"result,omitempty"`
Err *MCPError `json:"error,omitempty"`
IsAction bool `json:"isAction,omitempty"`
}
MCPExtension carries parsed MCP JSON-RPC metadata. Result and Err are mutually exclusive: a response sets exactly one.
IsAction is the parser's classification verdict (see pipeline.Context.Classification). The parser explicitly sets it true for user-meaningful action methods (tools/call, prompts/get, resources/read); the zero value false means "protocol mechanics or unclassified." Default-false reflects defense-in-depth: if the parser can't confidently classify a method as an action, guardrails err toward letting traffic through rather than judging it.
func SnapshotMCP ¶
func SnapshotMCP(ext *MCPExtension) *MCPExtension
SnapshotMCP returns a shallow copy of ext. Important for outbound request events: the same pctx.Extensions.MCP pointer receives Result or Err on the response side, so without snapshotting, the already-recorded request event would display the future response's result map.
func (*MCPExtension) Fragments ¶
func (e *MCPExtension) Fragments() []contracts.Fragment
Fragments implements contracts.ContentSource for MCP messages.
Request-phase: only tools/call is modeled — it's the one MCP method carrying user-intent content. Control-plane calls (initialize, ping, tools/list, resources/list, etc.) return nil. The tool name is emitted as role=tool; each argument value is emitted as role=tool_args, JSON-stringified if non-string. On JSON-RPC errors, the error message is emitted as role=tool_result so guardrails see content that could leak through the error channel (credentials, stack traces, PII) the same as they see normal tool output.
Response-phase: MCP tool results are conventionally shaped as {"content": [{"type":"text","text":"..."}, {"type":"image",...}, ...]}. Text items are emitted with role=tool_result; non-text items are skipped as not inspectable.
Type-assertion misses on Params["arguments"] / Result["content"] / content-items get a DEBUG log. These shapes are what the MCP parser produced from a JSON-validated body, so misses typically indicate a malformed or protocol-non-conforming payload worth surfacing to operators debugging an odd client — rather than a silent skip.
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 Option ¶
type Option func(*options)
Option configures pipeline construction.
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) 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"), so a plugin that only reads responses cannot be distinguished from one that only reads requests. Closing that needs direction-specific READ capabilities — the same prerequisite as the reverse-order reader gap noted in validateCapabilities.
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 (abctl) and other observability surfaces.
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) 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) 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."
ReadsBody bool
// WritesRequestBody: the plugin may mutate pctx.Body (call
// pctx.SetBody). Implies ReadsBody — Normalize() auto-promotes.
// Listener propagates the mutation to the wire (ext_proc
// BodyMutation, or the outbound http.Request for proxy listeners).
//
// Pipeline.New rejects a pipeline that has more than one
// WritesRequestBody plugin per direction — mutation ordering would
// be ambiguous.
//
// 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.
//
// Pipeline.New rejects more than one WritesResponseBody plugin per
// direction, for the same ordering reason as the request side.
WritesResponseBody 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 `abctl`'s
// plugin-detail and catalog panes, and in /v1/plugins.
//
// Capabilities are static type-level metadata: Capabilities() must
// return the same value for any instance produced by a given
// factory. If a plugin's behavior varies enough that its capabilities
// differ, register it under multiple names.
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 WritesRequestBody-implies-ReadsBody promotion. 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.
type PromptContext ¶
type PromptContext struct {
Tokens int `json:"tokens"`
Stated bool `json:"stated"` // which rule ranked it; stated always beats unstated
At time.Time `json:"at"` // the winning turn's arrival, for latest-wins
Msgs int `json:"msgs"` // the unstated rule's LEADING comparator; see better
}
PromptContext is the fold's PUBLISHABLE state: enough to merge two of them, which a client holding its own figure must do, and which a future restore-then-continue would do.
LOSSLESS WITH RESPECT TO THE ORDERING, carrying every field better() compares — so the published order IS the fold's order rather than a coarsening of it, and MergePromptContext is the same max over the same comparator. Because those four fields are now the WHOLE struct, better() is a total order on this type, which it was not while a comparator was missing from it.
NOT A WHOLE FOLD, and this is not a claim that a restore path exists: n is deliberately unpublished (it is a cursor into a caller's slice, not part of the answer) and there is no PromptContext-to-fold constructor. What losslessness buys is that two published figures can be COMPARED exactly, which is what a restore would need of them — not that one can be resumed from.
MSGS IS PUBLISHED, AND THE REASON IT WAS NOT IS FALSE. An earlier draft dropped it as the FALLBACK rule's comparator, "slated for deletion once the supported proxy floor publishes agentRole". Stated depends on the CLIENT, not on the proxy version: inferenceparser.agentRole returns "" for a request with no system message at all (/v1/completions), for one whose first system line lacks the required billing-header prefix, and on an unparseable body — "every client that is not Claude Code", as its own doc says. So an unstated figure is a live state on a CURRENT proxy rather than a version-skew relic, the unstated-versus-unstated arm is a real path, and msgs is permanent.
Omitting it therefore bought nothing and cost exactness. It left two combining operations over two DIFFERENT total orders which had to be kept in agreement by hand — the drift risk this design rejects everywhere else, and one that had already produced two reasoning errors here. The cost of carrying it is one int on the wire.
func MergePromptContext ¶
func MergePromptContext(a, b *PromptContext) *PromptContext
MergePromptContext combines two published figures, nil — or any figure carrying no tokens — meaning "nothing known"; see nothingKnown.
THE SAME ORDER AS THE FOLD'S, and it DEFERS to better() rather than restating it. PromptContext is lossless (see there), so there is exactly one total order here, not two that have to be kept in agreement by hand:
stated ≻ unstated a figure from a rule that cannot see subagents is not
evidence, at any size
within stated: (At, Tokens, Msgs)
within unstated: (Msgs, At, Tokens)
A HAND-WRITTEN SECOND COPY WAS THE EARLIER SHAPE, and it is worth recording why it went. With Msgs unpublished this function had a single arm serving both classes, documented as "(At, Tokens) either way" — true only because the comparator that distinguishes the two arms had been dropped from the wire. Publishing Msgs makes the orders genuinely differ, which would mean maintaining better()'s two arms twice; deferring instead makes disagreement impossible by construction.
A max over a total order, so MergePromptContext is commutative, associative, and has nil — or any other operand nothingKnown accepts — as its identity. That is what lets a client merge the server's figure with its own and need no version detection: an old proxy sends nothing, and nothing is a valid operand.
AND CLOSED OVER "NOTHING KNOWN", which is a separate claim from accepting it: two operands that both say nothing merge to NIL rather than to whichever of them was passed. Without that arm, MergePromptContext(nil, &PromptContext{Stated: true}) returned a non-nil figure carrying no tokens — an empty value wearing the one representation this package treats as real, which the next merge or the next marshal would then carry forward. No caller outside a test can build that operand and the gauge could not see the difference (it reads Tokens and draws an em dash either way), so this closes a half-truth rather than fixing a symptom: the identity holds of the RESULT as well as of the inputs, by construction instead of by what nothing happens to construct.
FULLY-TIED OPERANDS KEEP a, exactly as the fold keeps its incumbent: better() is false both ways for two figures equal on every field it compares, and two such figures are interchangeable for every purpose this package has.
SPELLED OUT IN FULL, and a free function rather than a method. Bare `Merge` was rejected: this package also owns pipelines, extensions, sessions, events and snapshots, and `pipeline.Merge(a, b)` reads at the call site as "merge two pipelines". A method — `server.Merge(local)` — was rejected too, and for a sharper reason than symmetry: nil is the identity of this monoid, so a method would have to be callable on a NIL RECEIVER to accept the operand an old proxy actually sends. That works in Go and it is a footgun, because nothing at the call site warns the next reader that the receiver may be nil; two plainly nilable arguments say so in the signature.
type PromptContextFold ¶
type PromptContextFold struct {
// contains filtered or unexported fields
}
PromptContextFold is the running answer over the events folded so far: the winning figure and the message count that won it, plus how many events have been folded in.
A RUNNING answer rather than a rescan, because the caller's shape demands it: the sessions row loop asks for every session, rebuildSessionsTable runs on every streamed event, and retention is unbounded, so a full scan per call is O(events) per session per event on the DEFAULT pane. A rescan measured 6.1ms and 3.49MB per call at 100k events — 60ms and 35MB for ten such sessions on one arriving event. TestSessionContextFor_DoesNotRescanTheFoldedPrefix pins that it does not happen; BenchmarkSessionContextPerEvent says what it costs.
A REMEMBERED EXTREMUM, not a cache of a pure function over m.events — and the difference is load-bearing, not a convenience. The events abctl holds for a session can stop carrying the evidence the figure was read from, and a cache would be invalidated by that and come back empty. Three ways it happens: a proxy that projects without stating the counts (the version window between abctl's CONTEXT column and InferenceExtension.MessageCount), the picker releasing a live session's events for memory, and server-side FIFO eviction dropping the turn the figure came from. What it costs is stated with the compaction trade-off above — a figure this holds was read from whichever turn abctl has SEEN ranks highest under better(), and that turn may be one it no longer holds. Highest-ranking is not largest, and the fold is no high-water mark: within the stated arm the latest turn wins, so a compaction lowers the figure.
func (*PromptContextFold) Add ¶
func (f *PromptContextFold) Add(e *SessionEvent)
Add folds one event into f, keeping the MAXIMUM under better's total order.
A max rather than a sequential scan with a latch, and that is the whole of this function's claim: arrival order says nothing once a rebase folds new events onto a winner that is no longer in the slice, and a restore from disk has no order to offer at all.
func (*PromptContextFold) AddAll ¶
func (f *PromptContextFold) AddAll(events []SessionEvent)
AddAll is the existing loop body, folding a slice of events into f, in order.
AddAll advances n; Add does not: n is a cursor into a caller's slice, and a per-event caller has no slice. The store leaves n at zero forever.
func (PromptContextFold) Folded ¶
func (f PromptContextFold) Folded() int
Folded is how many events have been folded in — abctl's slice-length check reads this to decide whether a caller's slice has grown, shrunk, or is a wholesale replacement.
func (PromptContextFold) Publish ¶
func (f PromptContextFold) Publish() *PromptContext
Publish projects the fold for the wire, or nil when nothing can be said.
NIL RATHER THAN A ZERO STRUCT, so the field is absent under omitempty. A session with only one-shot calls has no conversation to measure and is indistinguishable from one nobody has observed; both must render as an em dash rather than as a figure. Same standing rule SessionSummary.CostMicros states for its own omitempty.
func (*PromptContextFold) ResetFolded ¶
func (f *PromptContextFold) ResetFolded()
ResetFolded zeroes the slice cursor while KEEPING the figure, for a caller whose slice was replaced rather than appended to. See abctl's rebaseSessionContext: dropping the figure there blanks a live session's gauge, because a view=summary timeline may carry no candidate at all.
func (PromptContextFold) Tokens ¶
func (f PromptContextFold) Tokens() int
Tokens is the winning figure folded so far.
func (PromptContextFold) TokensMergedWith ¶
func (f PromptContextFold) TokensMergedWith(p *PromptContext) int
TokensMergedWith is f's figure merged with a PUBLISHED one: the same figure MergePromptContext(p, f.Publish()) carries, or zero where that is nil, without publishing f.
IT EXISTS FOR THE ALLOCATION, and the measurement is the whole justification — this file does not add a second entry point for tidiness. abctl's sessions row loop asks EVERY visible session for its gauge on every rebuild, and a rebuild is one streamed event or one poll, so anything per-row here is on the same hot path the fold itself exists to protect. Going through Publish() put a 48-byte *PromptContext on the heap per row per rebuild. On BenchmarkSessionContextPerEvent/folded/10000, ten sessions per iteration and one of them with a turn to fold:
184 ns/op 0 allocs/op the int-returning path, before a server figure existed 356 ns/op 10 allocs/op merged by publishing f — exactly one allocation per row 253 ns/op 0 allocs/op as shipped, through this method
Those first two were taken before the benchmark grew its second case, whose slice index costs the baseline about a nanosecond. That second case, folded+server/10000, is where every row carries a figure as a current proxy sends it: 342 ns/op and 0 allocs/op, so the comparison itself costs about 9ns a row and allocates nothing.
THE LITERAL DID NOT STAY ON THE STACK IN THE SHAPE THIS REPLACED, which is why the fix is a signature change rather than a compiler hint. Publish() inlines, but MergePromptContext does not — cost 110 against a budget of 80 — and the caller returned the PUBLISHED POINTER out of localContextFor, so the struct crossed a function boundary and had to go on the heap: one per row per rebuild, the 10 allocs/op above.
NOT "WHATEVER THE CALLER LOOKS LIKE", which an earlier version of this paragraph claimed. Written in a SINGLE frame — Publish() inlined at the call site and the merged pointer read and dropped there — escape analysis does keep it on the stack; measured at 0 allocs. What this method buys is that the row loop no longer DEPENDS on that: a fold is a VALUE, so comparing out of one allocates nothing and no caller shape can put the struct back on the heap. TestSessionContextFor_MergesWithoutAllocating asserts the zero rather than reporting it.
STILL ONE ORDERING. This defers to better() exactly as MergePromptContext does, so the two are views of the same total order rather than two implementations of it — the property this file protects everywhere, and the reason Msgs is on the wire at all. Only the identity handling is restated, two lines of it, and TestPromptContextFold_TokensMergedWithAgreesWithMergePromptContext pins the agreement over every combination of stated, unstated and absent.
THE COMPARISON IS INVERTED relative to MergePromptContext, and saying so is cheaper than leaving the next reader to derive it: that function asks better(b, a) and keeps a — the SERVER figure, at abctl's call site — where this asks better(p, f.current()) and keeps the FOLD. Both return the same int, for a reason narrow enough to state outright: better() is false in both directions only for candidates equal on every field it compares, and it compares all four of PromptContext's, so a tie means the two token counts are equal as well and which operand is kept cannot show.
SO THE EQUIVALENCE RESTS ON PromptContext STAYING LOSSLESS — the same invariant MergePromptContext's own doc asserts, load-bearing here for a second reason. A comparator added to better() and NOT published would make a tie with UNEQUAL tokens reachable, and these two would then disagree. The sweep test cannot catch that: it builds its folds one-to-one from PromptContext values, so an unpublished fold field is unconstructible in that fixture. Anything adding a field to better() owes this method a look.
RETURNS THE FIGURE, not the winner, and that is not a shortcut: the only caller draws a gauge from an int, and handing back a *PromptContext would put the allocation straight back.
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 RawJSON ¶
type RawJSON string
RawJSON is a JSON value held exactly as it arrived, rather than decoded into Go values. What it preserves is KEY ORDER, which is what decoding into a map destroys — marshaling a map sorts keys, so a schema came back reordered from the one the client sent.
It does not preserve the bytes exactly through a re-marshal, and claiming so would be wrong: encoding/json compacts a Marshaler's output and HTML-escapes it, so insignificant whitespace is dropped and the characters less-than, greater-than and ampersand come back as their six-byte unicode escapes. The value this type HOLDS is untouched; only a copy that has been through json.Marshal is compacted. TestRawJSON_ReMarshalCompactsAndEscapes pins both.
WHY A NAMED STRING, and not the two obvious alternatives — this type exists to be deduplicated by authlib/session's interner, and both of them defeat that:
- map[string]any (what InferenceTool.Parameters used to be) cannot be interned at all without a recursive walk that rewrites map values, and a walk cannot lean on immutability the way sharing a string can. It is also expensive to hold: a tool manifest's schemas measured 4.1x their JSON text as maps, per event, on a live session.
- json.RawMessage fails twice. Converting an interned string to []byte COPIES, so every event would get its own copy and the interning would buy nothing; and []byte is mutable, so genuinely sharing one across events would let any holder rewrite bytes another event has already published.
A string is immutable, and both string(RawJSON) and RawJSON(string) are free conversions, so an interned value is shared rather than copied. That is the entire reason for the type.
The MarshalJSON method is load bearing beyond serialization: OPA's ast.InterfaceToValue switches on the concrete Go type and treats anything it sees as a plain string as a JSON string. Reaching rego as an object depends on landing in that switch's default arm, which round-trips through encoding/json — so this must stay a NAMED type (never `= string`, which the switch would catch) and must keep the method. See plugins/opa/tool_parameters_rego_test.go, which drives that exact conversion.
func (RawJSON) MarshalJSON ¶
MarshalJSON emits the value verbatim.
Empty becomes null rather than nothing, because empty bytes are not valid JSON and would fail the enclosing marshal. Not hypothetical: plugins/sparc/collect.go inserts this value into a map unconditionally, without checking for absence first.
func (*RawJSON) UnmarshalJSON ¶
UnmarshalJSON keeps the raw bytes without validating or reformatting them. The decoder has already established that they are a well-formed JSON value.
JSON null is the exception, and it decodes to EMPTY rather than to the four bytes "null". Keeping them would make `"parameters": null` four bytes long, which passes every `len(...) > 0` guard a consumer writes — plugins/opa/plugin.go tests exactly that before putting the schema in its policy input — and would hand rego a null where the map-typed field left the key absent. Empty also round-trips: MarshalJSON writes null back.
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 SchemaProvider ¶
type SchemaProvider interface {
ConfigSchema() []FieldSchema
}
SchemaProvider is implemented by plugins whose config field metadata should appear in the catalog and downstream tooling (abctl 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 struct {
Labels []string `json:"labels,omitempty"`
Blocked bool `json:"blocked,omitempty"`
BlockReason string `json:"blockReason,omitempty"`
}
SecurityExtension carries guardrail output. Caller identity is already in ctx.Agent and ctx.Claims — this slot is only for downstream signals from content-inspection plugins.
type SessionEvent ¶
type SessionEvent struct {
// SessionID is the session bucket the event was appended to. Populated by
// Store.Append so downstream consumers (particularly the SSE stream
// filter) can attribute any event — including outbound MCP/Inference
// events that have no protocol-native session concept — to a session
// without needing a side-channel lookup.
SessionID string
// Seq orders the events within one session, counting from 1. Assigned by
// Store.Append; zero on an event that never went through a store.
//
// It exists because nothing else here can order a session reliably. At ties —
// two events recorded in the same instant are common on a fast local proxy —
// and RequestID pairs a request with its response without saying which pair
// came first. That made a stable pagination cursor impossible: an offset into
// the slice shifts under eviction, and a timestamp cannot break its own ties.
//
// Seq is per session, not global, so it says nothing about ordering across
// sessions. Gaps are expected and are not lost events in the paging sense:
// FIFO eviction drops a prefix, and trimEventsPinIntent can leave one much
// older event pinned ahead of the retained tail. What is guaranteed is that
// the events a session holds are ascending in Seq, which is what lets both
// the store and a client binary-search them.
//
// The numbering is unique within one INCARNATION of a session, not forever:
// the counter lives on the store's entry, so whole-session eviction followed
// by traffic under the same id starts again at 1. A client holding a cursor
// across that boundary cannot detect it from Seq and must order pages by At —
// see session.entry.nextSeq and abctl's applyOlderPage.
//
// Serialized via sessionEventWire like every other field here, not by a tag on
// this struct — SessionEvent has a custom MarshalJSON.
Seq uint64
At time.Time
Direction Direction
Phase SessionPhase
// RequestID pairs a request event with its response event. Without it a
// consumer can only pair positionally, which misattributes whenever a
// client has concurrent requests in flight.
RequestID string
A2A *A2AExtension
MCP *MCPExtension
Inference *InferenceExtension
// Invocations carries records of every plugin that ran on the
// pipeline pass — gate, parser, rate-limiter, etc. Nil when no
// plugin appended a record, non-nil with at least one Inbound or
// Outbound entry otherwise. See Invocations godoc for the per-
// plugin shape.
Invocations *Invocations
// Plugins carries plugin-public observability events in JSON form.
// Populated by the listener from Extensions.Custom entries whose keys
// end in PluginEventSuffix ("/event"); the suffix is stripped, so
// consumers see the plugin name as the map key. Value is the plugin-
// provided struct marshaled to JSON — opaque from the listener's
// perspective. Consumers decode each key into their own type. See
// authbridge/docs/plugin-reference.md for the producer contract.
Plugins map[string]json.RawMessage
// Identity snapshot at record time. Lets downstream plugins attribute an
// event to the caller (Subject) and the handling sidecar (AgentID)
// without re-parsing the original request. Nil for events recorded
// before jwt-validation ran or when session tracking is disabled.
Identity *EventIdentity
// StatusCode is the HTTP status of the response. Zero on request events
// and on response events that were recorded before the status was known
// (e.g., connection reset). A non-zero value >= 400 also populates Error.
StatusCode int
// Error captures a terminal error condition for this event. Nil on
// successful requests and 2xx responses. Populated for non-2xx responses,
// guardrail blocks, and parse failures.
Error *EventError
// Host is the HTTP :authority (or Host header) of the event. For inbound
// events it's the agent's own address; for outbound events it's the
// target service, which is the useful case — a session with many
// outbound calls can be attributed to the tool / LLM / target each
// landed on. Empty when the listener didn't populate pctx.Host.
Host string
// Duration is the wall-clock time from request entry into the listener
// to response recording. Zero on request-phase events. On response
// events it's computed as now - matching-request.At.
Duration time.Duration
// TLS, when non-nil, carries connection-level identity for events
// that arrived over TLS: negotiated version, cipher, and the peer's
// SPIFFE ID extracted from the URI SAN. Nil for plaintext events
// and for events recorded before the TLS handshake completed.
// Populated by the listener layer; plugins do not write to it.
TLS *EventTLS
// Tunnel marks an opaque CONNECT / transparent-redirect tunnel-open: the
// bytes are not HTTP, so there's no protocol parse. Set only by
// recordTunnelOpened. Consumers (abctl) use it to fold the tunnel into the
// decrypted inner request a TLS bridge produces — an explicit producer
// signal rather than inferring "tunnel" from host/extension shape, which
// an ordinary unparsed request could otherwise mimic.
Tunnel bool
// TunnelReason says WHY the bytes were left opaque. Empty when Tunnel is
// false, and empty on a bridged CONNECT (abctl folds that row into the
// decrypted inner request, whose own action is the interesting one).
//
// It exists because "tunnel" with no reason is indistinguishable from a
// routine egress passthrough, and the two demand opposite responses: a
// configured passthrough is working as intended, while a client that
// rejected the bridge certificate means every plugin is blind to that
// traffic and someone has to restart something. Diagnosing the latter
// previously required the proxy log, the CA's NotBefore and a process
// listing — none of which the timeline hinted at.
TunnelReason TunnelReason
// HTTPMethod and HTTPPath are the request's HTTP verb and its
// query-stripped path, copied from the pipeline context at record
// time.
//
// They exist because an event Cortex could not parse as A2A, MCP or
// inference previously reached the timeline carrying only a host: the
// operator saw that *something* went to an address, with no way to tell
// a token refresh from an object download. The verb and path are the
// cheapest thing that distinguishes them, and both were already on the
// context — they simply never made it onto the event.
//
// Distinct from the Method on A2AExtension and MCPExtension, which is a
// protocol-level method name ("message/stream", "tools/call") and not an
// HTTP verb; hence the prefix on these two.
//
// HTTPPath is empty on an opaque tunnel, where the bytes are never parsed
// as HTTP and there is no request line to read: recordTunnelOpened pairs
// that empty path with a synthetic CONNECT. A blank path on a tunnel row
// is therefore correct rather than missing plumbing. Both are empty when
// the listener left the context fields unset.
//
// A query string is always stripped before the path gets here (see
// pipeline.Context.Path), so query-borne credentials never reach the
// timeline. What is recorded is the DECODED path, not the raw request
// target: every listener mode runs the target through net/url, so
// "/x/..%2f..%2fetc/passwd" is stored as "/x/../../etc/passwd". That is
// deliberate cross-mode parity (net/http decodes identically for the proxy
// listeners), but it means the timeline does not preserve how a caller
// encoded a path — read it as the resolved path, and do not infer from it
// that no encoded-traversal attempt was made. A secret embedded in a path SEGMENT does survive, because
// nothing can tell it from a resource id — a bot token or a webhook path
// lands here verbatim. That is the same exposure Host already carried on
// this unauthenticated surface, which serves request bodies besides; it is
// worth knowing before these events are exported off-box.
//
// HTTPPath duplicates the per-invocation Invocation.Path (serialized as
// "path"), deliberately: both are copies of the same Context.Path, so the
// two keys cannot disagree. They differ in when they are THERE, which is
// why this one exists. HTTPPath is on every event the listener recorded
// from a parsed HTTP request, whether or not a plugin ran; Invocation.Path
// appears only where some plugin recorded an invocation. An event can
// carry invocations and no HTTPPath (an opaque tunnel that ran a gate), so
// a consumer that wants "the path of this request" should read HTTPPath
// and treat Invocation.Path as per-invocation context.
HTTPMethod string
HTTPPath string
// Client is the coding agent that made the request, parsed from the request's
// User-Agent by Context.ClientInfo. Nil when the request carried none —
// ABSENCE, not an agent named "unknown"; EventClient.Label() is the only place
// absence becomes a display string, so a consumer that aggregates on Label
// gets a reserved bucket rather than a fabricated agent name.
//
// CLIENT-ASSERTED AND TRIVIALLY SPOOFABLE: an observability and
// cost-attribution key, never an authorization subject. Deliberately the same
// caveat, in the same words, that Context.Session carries about client-asserted
// session ids. Distinct from Identity above, which is the AUTHENTICATED
// principal — the two sit on the same event and answer different questions
// ("what program is calling" versus "who is calling"), and treating this one as
// the other means building authorization on a request header.
Client *EventClient
}
SessionEvent represents a single pipeline event captured by the session store. At most one of A2A, MCP, or Inference is non-nil on any given event, but the event may also carry Invocations (records from any plugin that ran on the pass) and/or Plugins (the escape-hatch map from Extensions.Custom) regardless of which protocol extension is present. An event with Phase=SessionDenied typically carries only Invocations (+ Identity, Host, Error) because the request never reached a protocol parser before the pipeline rejected it.
func (SessionEvent) MarshalJSON ¶
func (e SessionEvent) MarshalJSON() ([]byte, error)
func (*SessionEvent) UnmarshalJSON ¶
func (e *SessionEvent) UnmarshalJSON(data []byte) error
UnmarshalJSON accepts the on-the-wire form written by MarshalJSON. This makes SessionEvent round-trippable through JSON so off-process clients (e.g. abctl) can decode straight into the canonical type.
type SessionPhase ¶
type SessionPhase int
SessionPhase distinguishes request, response, and terminal-denial events.
const ( SessionRequest SessionPhase = iota SessionResponse // SessionDenied is a terminal event for inbound requests a pipeline // plugin rejected (e.g., jwt-validation failing a token check). The // listener records this instead of a Request/Response pair so abctl // and other session consumers can distinguish denials from normal // request/response flow without scanning StatusCode. SessionDenied )
func (SessionPhase) MarshalJSON ¶
func (p SessionPhase) MarshalJSON() ([]byte, error)
MarshalJSON emits the string form ("request"/"response"/"denied") so the wire format stays human-readable.
func (SessionPhase) String ¶
func (p SessionPhase) String() string
func (*SessionPhase) UnmarshalJSON ¶
func (p *SessionPhase) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes a SessionPhase from the string form emitted by MarshalJSON. Unknown strings decode to SessionRequest (zero value) without error — tolerant forward-compat behavior. A Debug-level log fires on unknown input so wire-format drift (e.g., a server emitting a typo) is at least observable in a verbose test run rather than silent.
type SessionView ¶
type SessionView struct {
ID string `json:"id"`
Events []SessionEvent `json:"events"`
// TotalEvents is how many events the session holds, which is more than
// len(Events) when the view is a tail of a longer session.
//
// Absent means Events IS the session: every caller that builds a whole view
// leaves this zero, so a consumer that ignores the field sees exactly what it
// saw before the field existed. A consumer that reads it can tell "the timeline
// starts here" from "the timeline starts where I can see", which is otherwise
// indistinguishable — and was, for a 5000-event session whose snapshot request
// simply timed out with nothing to show for it.
TotalEvents int `json:"totalEvents,omitempty"`
// OldestSeq is the Seq of the oldest event the session still HOLDS — not the
// oldest in this response. It is what lets a paging client know when to stop:
// having received an event with this Seq, there is nothing older to ask for.
//
// A count cannot answer that question. TotalEvents says how many events exist,
// but eviction and the pinned intent make "how many" a poor guide to "how far
// back can I go", and a client comparing counts would keep asking for pages the
// store cannot produce. Comparing two Seq values is exact and survives events
// being evicted between one page and the next.
//
// Absent when the view already starts at the oldest held event, so the common
// whole-session response is unchanged — same reasoning as TotalEvents above.
OldestSeq uint64 `json:"oldestSeq,omitempty"`
// View names the projection the server applied, and is set only when one was:
// "summary" means the message bodies were omitted (see sessionapi.summarizeEvent).
//
// An ECHO, not a request. It exists because abctl and the proxy install
// separately, so a client asking for a summary cannot assume it got one — an
// older proxy ignores the parameter and returns full events. Absence therefore
// has a precise meaning to a client that asked: "this server does not project",
// which is the difference between telling the operator their proxy predates the
// feature and leaving them to wonder why opening a session is slow.
//
// Inferring it from the response instead would be wrong: a session with no
// inference traffic has no message bodies to omit, so "no bodies present" does
// not distinguish a projected response from a naturally empty one.
View string `json:"view,omitempty"`
}
SessionView is a read-only snapshot of a session, safe to pass to plugins. It contains a copy of events — plugins cannot mutate the store.
ID is the session identity: stable for the life of one session, and what a plugin should key per-session state on. The listener resolves it (see Context.Session for the order, and for why it may be client-asserted), so a plugin must not re-derive it from headers or bodies of its own accord — two plugins deriving it differently is how per-session state drifts apart.
Events is a snapshot and may be EMPTY for a session that genuinely exists: a view is available as soon as the id is known, which is before that session's first event is recorded. The accessors below therefore return nothing on a fresh session, which is a truthful answer rather than a missing one. None of them distinguishes "this session has no such events" from "this session is new", so a plugin that needs to tell those apart must key on ID and track it, not infer it from an empty result.
func (*SessionView) FailedEvents ¶
func (v *SessionView) FailedEvents() []SessionEvent
FailedEvents returns response-phase events that carry an Error.
func (*SessionView) InferenceRequests ¶
func (v *SessionView) InferenceRequests() []SessionEvent
InferenceRequests returns only outbound inference request events.
func (*SessionView) Intents ¶
func (v *SessionView) Intents() []SessionEvent
Intents returns only inbound A2A request events (user messages).
func (*SessionView) LastError ¶
func (v *SessionView) LastError() *SessionEvent
LastError returns the most recent response event with an Error, or nil.
func (*SessionView) LastIntent ¶
func (v *SessionView) LastIntent() *SessionEvent
LastIntent returns the most recent inbound A2A user message, or nil.
func (*SessionView) ToolCalls ¶
func (v *SessionView) ToolCalls() []SessionEvent
ToolCalls returns only outbound MCP request events.
func (*SessionView) ToolResponses ¶
func (v *SessionView) ToolResponses() []SessionEvent
ToolResponses returns only outbound MCP response events.
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 authlib/shared.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. Listener ordering varies: forwardproxy invokes OnResponseFrame before emitting frame bytes, while reverseproxy emits frame bytes first (FlushInterval=-1 ferries each Read straight to the client) and then dispatches. Either way 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 TunnelReason ¶
type TunnelReason string
TunnelReason is why an opaque tunnel stayed opaque.
A named type rather than a bare string so the compiler catches a typo on the producer side and on every consumer: these values are decoded from the wire, enumerated in the operator docs and pinned by tests, and a misspelling in any of those places would otherwise be a value that renders as itself and means nothing. It marshals as a plain JSON string, so the wire contract is unchanged.
const ( // TunnelClientRejectedCA — the client sent a TLS alert rejecting our leaf, so it // does not trust the bridge CA. Claimed ONLY on a "remote error: tls: // bad certificate" / "unknown certificate authority", which is the peer actively // refusing us. Usually a process that started before the CA was minted, since CA // files are read once at startup. TunnelClientRejectedCA TunnelReason = "client-rejected-ca" // TunnelClientHungUp — the client disappeared mid-handshake without sending an // alert. CA distrust is one cause, but so is a cancelled request or a dead // socket, so this deliberately does NOT tell anyone to restart anything. TunnelClientHungUp TunnelReason = "client-hung-up" // TunnelHandshakeFailed — the handshake failed for some other reason: a version, // cipher or ALPN mismatch, or our own certificate minting failing. Not the // client's fault as far as we can tell, so it gets no client-side advice. The // logged error= field carries the specific cause. TunnelHandshakeFailed TunnelReason = "handshake-failed" // TunnelOriginUnverified — WE could not verify the origin, so bridging would have // meant vouching for a certificate we could not check. TunnelOriginUnverified TunnelReason = "origin-unverified" // TunnelSkipCached — an earlier handshake FAILURE for this host is still inside the // skip window, so no interception was attempted at all. // // Deliberately does not say why that earlier attempt failed. The skip is seeded by // any failed forge — a rejection, a hang-up, a cipher mismatch — because in every // one of those the connection died mid-handshake and the client's retry needs a // tunnel to work at all. Claiming "another client rejected the CA" here would be // right only some of the time. The seeding failure logged its own specific reason // when it happened; that is where the why lives. // // Distinct from client-rejected-ca either way: THIS client may well trust the CA // and is being tunnelled because an earlier one had trouble. TunnelSkipCached TunnelReason = "skip-cached" // TunnelBridgeDisabled — no TLS bridge is configured. TunnelBridgeDisabled TunnelReason = "bridge-disabled" // TunnelPassthroughPort, TunnelPassthroughNonTLS and TunnelPassthroughHost mirror // Decision.Classify's own reasons for declining to intercept. All three are // working as intended. TunnelPassthroughPort TunnelReason = "passthrough-port" TunnelPassthroughNonTLS TunnelReason = "passthrough-nontls" TunnelPassthroughHost TunnelReason = "passthrough-host" // TunnelPassthroughUnknown is the fallback when a lower layer declines to // intercept for a reason this vocabulary does not yet name. It exists so that // case can never produce the EMPTY string, which a consumer reads as "bridged" — // the exact opposite of what happened, and invisible in a timeline. TunnelPassthroughUnknown TunnelReason = "passthrough-unknown" )
Tunnel reasons. Stable strings: abctl renders them and operators grep them.
Each is at most 18 characters, which is the width of abctl's PLUGIN column (events_columns.go). A longer value truncates in the cell, which would break the one property that makes these useful — that the token in the timeline is the same token you grep for in the proxy log.
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
// 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.