model

package
v0.0.0-...-53bd38a Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: Apache-2.0 Imports: 21 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	SubagentKindSubagent = "subagent"
	SubagentKindSubtask  = "subtask"
)

The values of SessionEvent.SubagentKind, for a Bob child task.

View Source
const BobParentTaskIDHeader = "X-Parent-Task-Id"

BobParentTaskIDHeader is the request header Bob sets on a child task's requests. Every child names the ROOT task, also a child that a subtask started, so the wire gives no deeper tree. It is the only signal that a request is a child's.

Client-asserted and unauthenticated: a grouping key, never a principal. NOT a session id header: it must not be added to session.id_headers.

View Source
const BobTaskIDHeader = "X-Task-Id"

BobTaskIDHeader is the request header Bob sets on every chat request, naming the task that made it. It is session.BobSessionHeader's value. It is here because both session and pipeline read it, and session must not import pipeline (#1502). On a Bob child task (a subagent or a subtask) it names the child, and pipeline.Context.Subagent reads it when BobParentTaskIDHeader is also present (issue #1803, rule 2).

View Source
const ErrorKindDestinationPrivate = "destination_private"

ErrorKindDestinationPrivate is the egress guard refusing a destination that resolved into loopback, link-local, private or this host's own address space (listener.egress_guard), rendered as 403 destination_private. Like upgrade_declined it rides on an EventError to say whose answer a 4xx is, and usage does not count it as an error: the guard did what it was configured to. The string is the MOCA egress contract's identifier, used verbatim so the shared conformance suite matches without a translation table.

View Source
const ErrorKindGatewayUnavailable = "gateway_unavailable"

ErrorKindGatewayUnavailable is the praxis hop answering 503 itself because cortex-gateway is not ready or does not accept the dial (#1721). Cortex records the request row and this row, because the gateway never saw the request.

View Source
const ErrorKindMisdirectedRequest = "misdirected_request"

ErrorKindMisdirectedRequest is a 421 for traffic naming a host other than its tunnel's: a bridged request's Host, or under tls_bridge.fail_closed a ClientHello's SNI. The MOCA egress contract's identifier, used verbatim.

View Source
const ErrorKindNotTLS = "not_tls"

ErrorKindNotTLS is the TLS bridge closing a connection to a host it intercepts whose first bytes are not a TLS handshake, under tls_bridge.fail_closed.

View Source
const ErrorKindTurnInterrupted = "turn_interrupted"

ErrorKindTurnInterrupted is a carried WebSocket turn the client ended before its last event: Codex's Esc, which drops the socket. The row keeps the 200 the origin was answering with, as an HTTPS stream the client leaves part way does, and /v1/usage does not count it as an error. The kind says what happened; it is not a failure.

View Source
const ErrorKindUpgradeDeclined = "upgrade_declined"

ErrorKindUpgradeDeclined is the forward proxy answering a Responses API WebSocket upgrade with 426 itself (listener.responses_websockets). It rides on an EventError because the status is a 4xx and the row should say whose answer it is, but it is not a failure: the client is expected to switch to HTTPS, and does. usage does not count it as an error, and the Finisher sees an allow.

View Source
const ErrorKindUpstreamUnverified = "upstream_unverified"

ErrorKindUpstreamUnverified is the TLS bridge refusing a connection whose origin certificate did not verify, under tls_bridge.fail_closed: a CONNECT is answered 502 upstream_unverified instead of being tunnelled. The MOCA egress contract's identifier, used verbatim.

View Source
const ImportedSourcePrefix = "imported:"

ImportedSourcePrefix starts the Source of every event that an import wrote.

View Source
const MaxResponseCapture = 10 << 20

MaxResponseCapture is the most of a response body a capture keeps: the forward proxy's buffered-response cap.

View Source
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.

View Source
const RecordHeader = "X-Cortex-Record"

RecordHeader is the request header a client sends to keep its session out of the session archive (#1923). RecordOff is the one value that does so.

For Cortex only: a listener reads it before any plugin runs and removes it from the request it forwards, so the upstream never sees it. Named like the other X-Cortex-* headers. It is not a session-id header and is never in session.id_headers.

Claude Code sends it from ANTHROPIC_CUSTOM_HEADERS, e.g. ANTHROPIC_CUSTOM_HEADERS="X-Cortex-Record: off".

View Source
const RecordOff = "off"

RecordOff is the value of RecordHeader that withholds a session from the archive.

View Source
const StatusClientClosedRequest = 499

StatusClientClosedRequest is nginx's 499, for a request the client abandoned before it was answered. No client ever receives it — it has gone — which is what makes it useful in a record: it keeps a hangup out of the 5xx series that an upstream outage shows up in.

View Source
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 ledger.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 AgentName

func AgentName(label string) string

AgentName is the agent a Label names, with its version dropped: "claude-code/2.1.285" is "claude-code". It is the key every per-agent figure is filed under — the usage ring's agent axis, the ledger's on read, a session's agent, and /v1/usage?agent= — so an agent's releases are one row rather than one row each. The ledger stores the full Label; only reads fold.

ONLY A WHOLE-LABEL name/version TOKEN FOLDS. An unrecognised agent's label is its raw User-Agent, and cutting "Claude-User (claude-code/2.1.284; …)" at its first slash would name a row after half a comment, so anything with a space or a second slash is returned unchanged. A single-token one does fold — "curl/8.4.0" is "curl" — which is the same rule, not an exception to it.

RETIRED SPELLINGS FOLD TOO, through CanonicalAgent: a label recorded under a name this package no longer produces answers that name's replacement, so a rename does not split history. "bob-shell/2.2.1" and "ibm-bob/2.2.1" are both "bob".

func AgentSpellings

func AgentSpellings(name string) []string

AgentSpellings is name and every retired spelling that folds to it, sorted: for "bob", ["bob", "bob-shell", "ibm-bob"]. For every other name, just the name.

FOR WRITERS THAT MUST CLEAR EVERY WAY A CONFIG MIGHT NAME THE AGENT: agentop's server commands remove each of an agent's spellings from a router config's agents: map, so a retired spelling cannot sit beside the canonical key and fold back into routing once the key is gone. Read-side callers want FoldAgentNames or CanonicalAgent instead.

func BobChildTask

func BobChildTask(h http.Header) (own, root string)

BobChildTask returns a Bob child task's own id and its root's, from BobTaskIDHeader and BobParentTaskIDHeader, or "", "" when the request is not a child: both ids must pass SubagentHeader and differ. A parent equal to the task id is a client that names itself, so the row stays a root's. Session rule 1 and pipeline rule 2 (#1803) both ask this, so a row filed in its root's session is always a child row.

func CanonicalAgent

func CanonicalAgent(name string) string

CanonicalAgent is the canonical agent name for name, folding the spellings a previous release produced to the name this one does. It is the identity function on every current name, which is what lets callers apply it to values they stored earlier without first having to know whether a rename ever happened.

Takes a NAME, not a label: fold a label with AgentName first, or hand it a name a config file named (the inference router's `agents:` keys and stored pins are both canonicalized through this), never a raw User-Agent.

func DurationBetween

func DurationBetween(from, to time.Time) time.Duration

DurationBetween returns to − from, or 0 when either endpoint is zero. For the optional response-side timestamp (ResponseHeadersAt), whose absence means "no headers ever arrived", the zero guard keeps an unset endpoint from publishing a nonsense figure — a negative span against time.Now() would read as a real duration on the row. The inverse of DurationSince: that one spans start-to-now for a figure read at record time, this one spans two recorded moments, which is what SessionEvent.Ttfb is (StartedAt → ResponseHeadersAt, measured when the row is written long after both).

func DurationSince

func DurationSince(start time.Time) time.Duration

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 FoldAgentNames

func FoldAgentNames(agents map[string]string) map[string]string

FoldAgentNames is agents keyed by canonical agent name: every key folded through CanonicalAgent, so a map written before an agent-name rename — a router config's `agents:`, pinned under "bob-shell" before it converged into "bob" — names the agent requests report today.

THE ONE IMPLEMENTATION OF THE MAP-LEVEL FOLD, shared by every reader and writer of such a map: the inference router keys its routing table with it, and agentop reads and writes the same `agents:` map through it, so the two cannot disagree about which spelling a config names — a disagreement that made `server reset` report "not routed" for an agent the proxy was routing.

Sorted order with set-if-absent, so a config naming both a retired spelling and its replacement resolves deterministically whichever way the map iterates: whichever key sorts first wins. Deliberately the same rule on both sides rather than a "current beats retired" preference, because agreeing is the property that matters and this rule needs no second list of which spelling is which.

func HasControlRunes

func HasControlRunes(s string) bool

HasControlRunes reports whether s carries anything SanitizeControlRunes would replace.

A RUNE scan rather than a byte scan, because the C1 block cannot be seen from the bytes alone: 0xC2 0x9B is U+009B, and 0x9B on its own is a continuation byte of nothing. Allocation-free either way, and the strings are header-length.

An INVALID byte reports true (RuneError at size 1 is the decoder saying "this is not UTF-8"); a legitimately encoded U+FFFD does not, because it decodes at size 3.

func ImportedSource

func ImportedSource(agent string) string

ImportedSource returns the Source value for an event that an import of agent wrote.

func IsControlRune

func IsControlRune(r rune) bool

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 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 cost/ledger 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 IsInferenceRequest

func IsInferenceRequest(e *SessionEvent) bool

IsInferenceRequest reports an outbound inference request. SessionView.InferenceRequests uses the same rule.

func IsIntent

func IsIntent(e *SessionEvent) bool

IsIntent reports an inbound A2A request: a user intent. SessionView.LastIntent uses the same rule.

func IsKnownAgent

func IsKnownAgent(name string) bool

IsKnownAgent reports whether name is the canonical name of a coding agent ParseUserAgent recognises — every canonical name in knownClients — as AgentName folds a Label to it.

FOR A CONSUMER THAT HAS TO TELL AN AGENT FROM A RAW User-Agent, which a label alone cannot say: "curl" is what AgentName answers for curl/8.4.0, and nothing in that string marks it as unrecognised. agentop's AGENTS pane pools every label this rejects under one row.

False for UnknownClientLabel and for any label carrying a version: fold with AgentName first.

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: core/parse/inference.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 agentop'S OWN CACHE and not from the session summary: the summary carries no per-request field, so there is nothing to read. agentop 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. agentop 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 RecordsOff

func RecordsOff(h http.Header) bool

RecordsOff reports whether h asks not to be recorded: RecordHeader is present with the value RecordOff, compared without case and padding. Any other value, or none, records as today, so a typo can never hide a session by accident. Several values: any one "off" counts, because the header can only withhold.

func RoutedKeyOf

func RoutedKeyOf(in *Invocations) string

RoutedKeyOf is the name of the server whose key the request sent: the "key_of" detail of the last outbound request-phase inference-router invocation that has one, of any action. It is "" for a nil in or no such invocation. It never holds a key.

func RoutedServer

func RoutedServer(in *Invocations) string

RoutedServer is the server name that the inference-router recorded for a request: the "server" detail of the last outbound request-phase modify/routed invocation. It is "" for a nil in or no such invocation. Other invocations that carry a server detail (would_route, pinned_server_removed and others) do not count: they did not send the request to that server.

func SanitizeControlRunes

func SanitizeControlRunes(s string) string

SanitizeControlRunes replaces every control character in s with U+FFFD. It is the rule that lived under sanitizeUA's name until #1539's CodeQL finding made the honest name necessary: it applies to any client-controlled string headed for a surface a terminal or a file renders, not only a User-Agent. Exported for the listeners — the forward proxy logs the destination Host on its egress-guard refusal paths, and a newline forged into that header would forge a log entry, the same CWE-150 shape the UA path guards against.

THE PRIMARY CHOKE POINT FOR THIS STRING. ParseUserAgent is the one place a header becomes an EventClient, and Label() is what both consumers of the result read — the live usage aggregator and, later in this series, the durable cost ledger. Sanitising per consumer is strictly worse: whichever one does it neutralises the bytes on its own surface while the other serves them intact, and the next consumer added starts out unguarded too.

THE HEADER IS NOT ALREADY CLEAN, and the reason it looked clean is worth stating because it is not a property of this package. On the forward proxy net/http rejects control bytes in a header value, so a hostile UA never reaches here through that listener — protection by accident, and only there. THE EXT_PROC PATH HAS NO SUCH PARSER: header values arrive from Envoy as protobuf bytes (HeaderValue.RawValue) and are handed over as-is, so on that path this function is the only bound on what a client can put in a string that ends up on a terminal and in a 30-day file. CWE-150.

C0, DEL AND C1 — all three, because a C0-only filter is the version of this that looks right and is not. U+009B is the single-character CSI: a terminal decoding UTF-8 treats it exactly as it treats ESC [, so "\u009b2J" clears the screen with no ESC byte anywhere in the string. The C1 block is U+0080–U+009F and encodes as 0xC2 0x80–0xC2 0x9F, so nothing below 0x20 appears in it and a byte scan for control bytes steps straight past it.

A BYTE THAT IS NOT VALID UTF-8 is replaced too. It is the same character in a pane that is not in UTF-8 mode (a lone 0x9B is CSI in Latin-1), and encoding/json would substitute U+FFFD for it on the way to disk regardless — doing it here means the label held in memory, the label served from /v1/usage and the label on disk are one string rather than three.

REPLACED, NOT DROPPED, so tampering stays visible: "claude-cli/1\x1b[31m" reads as "claude-cli/1�[31m" rather than as "claude-cli/1[31m", which nobody would question.

SHARED WITH cost/ledger AND cost/usage, which call it for Endpoint, Model and Provenance — labels that never pass through here — and as defence in depth for this one, and with agentop, which calls it at render time. One rule, so a label is spelled the same in memory, on disk and on screen.

func SanitizeLogValue

func SanitizeLogValue(s string) string

SanitizeLogValue is SanitizeControlRunes plus the two strings.ReplaceAll calls CodeQL's go/log-injection query recognizes as sanitizers: the calls are markers the scanner reads, and the bytes they target are already gone by the time they run. For any client-controlled value headed into slog, this rather than SanitizeControlRunes directly.

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 SubagentHeader

func SubagentHeader(v string) string

SubagentHeader is a header value with its padding trimmed and checked by validSubagentID, or "" when it fails the check.

PADDING IS SP AND HTAB ONLY — RFC 9110's optional whitespace around a field value — and not strings.TrimSpace, which also strips \n, \r, \v, \f and U+0085 from either end. Those are control characters, not padding: trimming them would hand validSubagentID a clean id and record "a1a2…\n" as "a1a2…", which is sanitising by another route. Left in place, they reach the check and refuse the value, which is the rule validSubagentID states.

func ToolArgumentsJSON

func ToolArgumentsJSON(s string) (any, bool)

ToolArgumentsJSON decodes s, a tool call's Arguments, when it is exactly one JSON object. A detail view shows that value, not the string. Numbers decode as json.Number.

func ToolOutputJSON

func ToolOutputJSON(s string) (any, bool)

ToolOutputJSON decodes s, a tool result's Content, when it is one line and exactly one JSON object or array. Output with line breaks already reads well as a string.

func TruncateLabel

func TruncateLabel(s string, n int) string

TruncateLabel cuts s to at most n BYTES, on a rune boundary.

The cap stays in bytes because that is what it bounds — retained memory, and through cost/ledger the length of an appended line. Cutting on a rune boundary only changes WHERE the byte cap lands (by up to three bytes), never that there is one. A plain s[:n] can split a multi-byte sequence, and encoding/json then expands each invalid byte into a 3-byte U+FFFD, so the serialized label would exceed the cap it was cut to.

func TruncateLabelTail

func TruncateLabelTail(s string, n int) string

TruncateLabelTail cuts s to at most n BYTES, on a rune boundary, and keeps the END. For a path label: the end names the repo, and two repos with one long prefix must stay apart.

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"`  // last task state in the response, e.g. "completed"
	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() []capabilities.Fragment

Fragments implements capabilities.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 A2APart

type A2APart struct {
	Kind    string `json:"kind"`
	Content string `json:"content,omitempty"`
}

A2APart represents a message part in an A2A request.

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.

const (
	AgentRoleMain     AgentRole = "main"
	AgentRoleSubagent AgentRole = "subagent"
)

type ArchiveUsage

type ArchiveUsage struct {
	Bytes         int64 `json:"bytes"`
	MaxBytes      int64 `json:"maxBytes"`
	RetentionDays int   `json:"retentionDays"`
	// DroppedEvents, WriteErrors and DroppedRenames are what never reached disk, process-wide.
	// Nonzero means the history shown has gaps; see core/session/archive.Stats.
	DroppedEvents  uint64 `json:"droppedEvents,omitempty"`
	WriteErrors    uint64 `json:"writeErrors,omitempty"`
	DroppedRenames uint64 `json:"droppedRenames,omitempty"`
	// DroppedCaptures counts request captures not archived because too many bytes waited for
	// the writer. Their events were archived without them.
	DroppedCaptures uint64 `json:"droppedCaptures,omitempty"`
	// Paused is true after the disk filled, until the archive's next retention pass.
	Paused bool `json:"paused,omitempty"`
	// FailedClosed is true once more sessions asked not to be recorded, while the archive's
	// writer was behind, than it keeps track of (#1923): until a restart it records no
	// conversation.
	FailedClosed bool `json:"failedClosed,omitempty"`
}

ArchiveUsage is the session archive's size, bounds and losses, as `GET /v1/sessions?archived=true` reports them beside the sessions it lists.

HERE RATHER THAN IN core/session/archive so a client decodes it without linking the archive's zstd encoder: agentop reads this and nothing else of the archive.

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).

const (
	Inbound Direction = iota
	Outbound
)

func (Direction) MarshalJSON

func (d Direction) MarshalJSON() ([]byte, error)

MarshalJSON emits the string form ("inbound"/"outbound") so the wire format is human-readable without an enum→int lookup.

func (Direction) String

func (d Direction) String() string

String returns "inbound" / "outbound". Used for structured logs and the wire format of SessionEvent.

func (*Direction) UnmarshalJSON

func (d *Direction) UnmarshalJSON(data []byte) error

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 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
	// SanitizeControlRunes) 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) AffinityName

func (c *EventClient) AffinityName() string

AffinityName is the coding agent a request belongs to for SESSION ATTRIBUTION: Name when the User-Agent was recognised, else a known agent's canonical name found in any token — comments included — else "". See session.Store.SessionForClient for what it decides.

WIDER THAN Name, AND ONLY HERE. Claude Code's WebFetch sends "Claude-User (claude-code/2.1.284; …)", naming its agent only inside the comment the parser deliberately skips. Reading comments into Name would move those rows to a different agent in the ledger and the AGENTS pane than the history beside them; for attribution the only question is which agent's session a header-less call joins, and there the comment is right.

Canonical names, not knownClients' keys: the comment says "claude-code", while the key is the product token "claude-cli". Nil-safe, like Label.

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 cost/ledger 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 ExchangeFailure

func ExchangeFailure(ctx context.Context, err error) (int, *EventError)

ExchangeFailure is what a listener records for an exchange with the upstream that ended in err instead of a response it could deliver: the status for the event, and why. err must be non-nil.

ctx is the CLIENT's request context, and it is asked first. A client that hangs up cancels the upstream call under it, so err is then context.Canceled — and since neither proxy bounds how long the upstream may take to answer (forwardproxy.NewServer says why), that is how a hung upstream usually ends: the client gives up first. Recording a 502 upstream failure there would count a 502 nobody received, once per abandoned request, and leave upstream_timeout unreachable for the case it names. So it is client_canceled with a 499, which /v1/usage still counts as an error but keeps out of the 5xx series.

Otherwise the client got a 502, and TransportError says why.

func TransportError

func TransportError(err error) *EventError

TransportError classifies a failed exchange with the upstream: a call that produced no response, or a response body that broke off while being read. Each surfaces to the client as the same synthetic 502, so Kind is what tells an operator whether to look at the network, the upstream, DNS, or a trust store.

Matched on types with errors.Is/errors.As, unlike handshakeFailureReason, which cannot. TestTransportError verifies every branch against a real failed request.

ORDER MATTERS for the forward proxy, whose client.Do wraps every error in a *url.Error. That implements net.Error, so each of its errors satisfies errors.As(&netErr) and only Timeout() discriminates — hence timeout first, and a bare net.Error is never a classifier. The reverse proxy hands over raw RoundTrip errors, with no *url.Error around them; the checks hold either way.

Message is the cause without the request URL — see causeOf.

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.

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 a core/tlsconfig 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 generics pipeline.SetState / pipeline.GetState. 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 core modification. See 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 FactState

type FactState uint8

FactState tells if a session fact is present and, if it is not, if the request has a session. The zero value is FactNone. FactNoSession comes only from Context.Session being nil, so no stored or zero SessionFacts reads as "no session".

const (
	// FactNone: the request has a session, and the store has no event of this kind for it.
	// The reasons are:
	//   - the store has no entry for the session yet, or it dropped the entry (max_sessions,
	//     ttl, Delete, Clear, a restart);
	//   - no event of this kind was appended to the session;
	//   - a session.max_events trim removed the event.
	FactNone FactState = iota
	// FactNoSession: the request has no session. Context.Session is nil.
	FactNoSession
	// FactPresent: Event is set.
	FactPresent
)

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}}

	// RequestedModel is the model the client asked for when a plugin changed it with
	// Context.SetRequestModel, and empty otherwise. Model is then the model the
	// request was sent for: what settlement prices and agentop's model column shows.
	// Set only by SetRequestModel, never by a parser.
	RequestedModel string `json:"requestedModel,omitempty"`

	// ServedModel is the model the upstream says answered, when that is not Model:
	// a gateway's x-litellm-model-name header first, else the response body's own
	// "model" field. Empty when the upstream named no model or named Model itself,
	// which is every response from a server that answers under the requested name.
	// Display only: settlement prices Model, and a gateway that resolved an alias
	// already reports its cost from the model it ran. Set by inference-parser.
	ServedModel string `json:"servedModel,omitempty"`

	// ToolResults are the tool_result blocks of an Anthropic request and the
	// function_call_output and custom_tool_call_output items of a Responses API request —
	// what each earlier tool call returned, as the client sent it back. Message Content
	// keeps only text blocks, so without this a tool result left nothing behind but its
	// size in ContentBytes.
	//
	// KEPT OUT OF MESSAGES ON PURPOSE. Plugins read Messages — IBAC as the user's intent,
	// OPA/SPARC/CPEX as policy input, lineage as an exported span — and tool output reaches
	// none of them unless a plugin opts in to this field. It is for the session store and its
	// readers. OpenAI Chat Completions clients already carry tool output as role "tool"
	// messages, so their requests leave this empty; the wire format puts it in Content
	// where this parser cannot keep it out. core/intent reads the results of ask-user tools, by
	// tool name only.
	ToolResults []InferenceToolResult `json:"toolResults,omitempty"`

	// HistoryToolCalls are the tool calls an earlier assistant turn made, as the client sends
	// them back in this request: Anthropic tool_use blocks and chat-completions tool_calls,
	// with their ids and arguments. InferenceMessage.ToolUseIDs says which message made each.
	//
	// NOT ToolCalls, which is the response side: the calls the model asks for NOW. OPA, SPARC,
	// CPEX and lineage read ToolCalls that way, so history in it would be judged as a new call.
	// For the session store and its readers only, under the same rule as ToolResults: no
	// plugin reads it. Without it the arguments are only on an earlier response, which
	// view=summary strips, so a request's detail could name a call but not show it.
	// core/intent reads the calls of ask-user tools, by tool name only.
	HistoryToolCalls []InferenceToolCall `json:"historyToolCalls,omitempty"`

	// ThinkingType and ThinkingDisplay are the request's thinking.type and thinking.display:
	// "adaptive" and "summarized", for example. Effort is the effort level the request asked
	// for, from whichever field its dialect uses: output_config.effort (Anthropic),
	// reasoning_effort (chat completions), reasoning.effort (Responses). AnthropicBeta is the
	// request's anthropic-beta header, every value joined with a comma. Each is empty when
	// the request did not state it, and when it stated it with a value of another JSON type.
	// Record only: no plugin reads them.
	ThinkingType    string `json:"thinkingType,omitempty"`
	ThinkingDisplay string `json:"thinkingDisplay,omitempty"`
	Effort          string `json:"effort,omitempty"`
	AnthropicBeta   string `json:"anthropicBeta,omitempty"`

	// HistoryThinking counts the thinking blocks the client sent back in this request, and
	// ResponseThinking the ones the model returned. Nil when there were none. Counts, not the
	// blocks: what a reader needs is whether they were there, and a block sent back with a
	// signature and no text is one a gateway may drop before the model sees it.
	HistoryThinking  *InferenceThinking `json:"historyThinking,omitempty"`
	ResponseThinking *InferenceThinking `json:"responseThinking,omitempty"`

	// 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". agentop'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
	// agentop's CONTEXT column and these fields projects without setting them, and then neither
	// answers — which is one reason agentop remembers its own figure rather than recomputing it
	// from whatever it happens to hold.
	MessageCount int `json:"messageCount,omitempty"`
	ToolCount    int `json:"toolCount,omitempty"`

	// ToolCallCount is how many ToolCalls this event HAD, on the same terms as the two counts
	// above: set only by sessionapi.summarizeEvent immediately before it nils the slice, zero
	// everywhere else, and ZERO MEANS "NOT STATED", NOT "NONE" — so a reader prefers the slice
	// when it is present, as in the snippet above.
	//
	// NOT THE SAME QUESTION AS ToolCount, which is the manifest the REQUEST offered; this is
	// how many calls the RESPONSE actually made of it. A request can carry 40 tools and the
	// model call none.
	//
	// It exists because a consumer of a projected copy could otherwise not distinguish "the
	// model called no tools" from "the projection dropped them": core/sessionexport.Record
	// exports a tool-call figure, and reading len(ToolCalls) alone made every view=summary
	// row report absence. ToolResults deliberately has no equivalent — it is re-sent whole on
	// every request, so a count of it sums to nonsense over a session (rossoctl/cortex#1740).
	ToolCallCount int `json:"toolCallCount,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. agentop'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
	// every response path this parser reads: both non-streaming dialects,
	// Anthropic streaming (assembled from content_block_start plus
	// input_json_delta fragments), and OpenAI Chat Completions streaming
	// (assembled from index-keyed delta.tool_calls fragments). Empty on a
	// parsed response means the model requested no tools.
	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
	// CacheWrite1hTokens is the part of CacheWriteTokens written with a 1-hour TTL
	// (Anthropic's usage.cache_creation.ephemeral_1h_input_tokens), never an addition
	// to it. Zero means either no 1h writes or a provider that does not report the
	// split; CacheWriteTokens still carries the true total either way. Pricing uses it
	// to price that subset at the 1h rate (pricing.CostWith1h).
	CacheWrite1hTokens int `json:"cacheWrite1hTokens,omitempty"`
	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.

EVERY RECORDER MUST CALL THIS, IN EITHER DIRECTION. It is the only route by which token counts reach a SessionEvent, and cost/usage reads every figure it reports off SessionEvent.Inference (usage.go's foldInto) — so a recorder that omits it publishes a turn whose counts reach nothing. The omission does not present as one: the cost record travels independently, published into Extensions.Custom and collected by SnapshotPlugins, so a consumer sees a whole, correctly priced cost beside zero tokens with nothing to say a measurement is missing rather than small. The inbound recorders omitted it until inbound inference traffic existed — a reverse proxy in front of a model endpoint — and then it read as free traffic.

The leak described above is, on today's paths, defended a second time downstream — session.Interner.InternEvent clones the extension inside Store.Append, so the store holds its own copy whether or not the recorder took one. Measured, not assumed: the parity suite stays green against a recorder that keeps the live pointer. That is a reason to keep calling this at every site rather than a reason to stop — the alternative makes each recorder's correctness depend on the internals of another package, and on that package continuing to clone. The counts claim above is unaffected either way: a recorder that passes nil here reports nothing, and no downstream copy can restore a figure that was never attached.

Five recorders in this tree are exempt, and the exemptions are listed here rather than left to be rediscovered: the four SessionDenied recorders and forwardproxy.recordTunnelOpened. A denied request was never forwarded, so it has no counts and no listener records protocol extensions on a deny; a CONNECT tunnel's bytes are opaque, so there is nothing to parse. Anything else that builds a SessionEvent and skips this call is the bug above, not a sixth exemption.

func (*InferenceExtension) Fragments

func (e *InferenceExtension) Fragments() []capabilities.Fragment

Fragments implements capabilities.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 InferenceHostSeen

type InferenceHostSeen struct {
	Agent        string `json:"agent"`                  // model.AgentName(e.Client.Label()), as serverOf compares it
	Host         string `json:"host"`                   // e.Host as recorded: where the bytes went. Raw, not routerconfig.Key
	Server       string `json:"server,omitempty"`       // RoutedServer of the request: the router's server name, "" when not routed
	Last         uint64 `json:"last"`                   // Seq of the newest eligible request
	LastUnrouted uint64 `json:"lastUnrouted,omitempty"` // Seq of the newest one CapturePath takes with RequestedHost == ""
}

InferenceHostSeen is where one agent's eligible inference requests in a session went.

type InferenceHosts

type InferenceHosts []InferenceHostSeen

InferenceHosts is one session's table: one InferenceHostSeen for each (agent, host, server).

func (InferenceHosts) LastNamedServer

func (h InferenceHosts) LastNamedServer(agent string, exists func(server string) bool, serverAt func(host string) (server string, known bool)) (string, bool)

LastNamedServer is LastServer for a config where servers can share a host. exists tells if a server name is in the config. serverAt gives the host's server: known is true when the host has at least one server, and server is "" when it has more than one. An entry with a server name that exists counts at Last with that name. Else an entry on a host with one server counts at Last with that server. Else an entry on a host with several servers is no evidence. Else the entry counts at LastUnrouted, and answers "". The newest evidence wins. On a tie the first entry wins, as in LastServer.

func (InferenceHosts) LastServer

func (h InferenceHosts) LastServer(agent string, serverAt func(host string) (string, bool)) (string, bool)

LastServer is serverOf's answer over the table: the newest evidence for agent. serverAt is the reader's host→server map. A routed host counts at Last. Any other host counts at LastUnrouted, and answers ("", true). Each seq must be in one entry only, as one event has one agent and one host: on a tie the first entry wins.

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"`

	// ToolUseID is the tool_call_id of a chat-completions "role":"tool" result message:
	// the id of the assistant tool_calls entry it answers. The parser also records the
	// result in InferenceExtension.ToolResults, so a consumer walking both must skip the
	// message half of a pair this id names — the result would otherwise count twice.
	// Empty on every other message.
	ToolUseID string `json:"toolUseId,omitempty"`

	// ToolCallNames names the tools an assistant message called, joined by ", " in call
	// order: Anthropic tool_use blocks, chat-completions tool_calls. Content keeps only text,
	// so without this a turn that only called tools read as empty. The join is unambiguous
	// because both APIs restrict a tool name to letters, digits, "_" and "-". A string rather
	// than a slice keeps this struct comparable, which core/session's interner relies on.
	// Names only: the ids are ToolUseIDs and the arguments InferenceExtension.HistoryToolCalls.
	ToolCallNames string `json:"toolCallNames,omitempty"`

	// ToolUseIDs are the ids of the tool blocks this message carries, joined by ", " in
	// block order: an assistant message's tool calls (Anthropic tool_use, chat-completions
	// tool_calls) and a user message's tool results (Anthropic tool_result). They key into
	// InferenceExtension.HistoryToolCalls and ToolResults, which hold the calls and results
	// themselves, so a reader can show each one under the message that sent it. A string for
	// the reason ToolCallNames is one. Anthropic restricts an id to letters, digits, "_" and
	// "-"; a chat-completions id that contains ", " splits wrongly, which costs only the
	// display. Empty on a message with no tool block, and on a
	// chat-completions "role":"tool" message, whose one id is ToolUseID.
	ToolUseIDs string `json:"toolUseIds,omitempty"`
}

InferenceMessage represents a single message in the conversation.

type InferenceThinking

type InferenceThinking struct {
	Blocks         int `json:"blocks"`
	Redacted       int `json:"redacted,omitempty"`
	TextBytes      int `json:"textBytes,omitempty"`
	SignatureBytes int `json:"signatureBytes,omitempty"`
	RedactedBytes  int `json:"redactedBytes,omitempty"`

	// Opaques are the opaque strings of a RESPONSE's thinking blocks, in block order: each
	// "thinking" block's signature and each "redacted_thinking" block's data, as JSON decodes
	// them. The accounting host records them with the response's reasoning tokens, so the
	// accountant can price a block at its own token count when the client sends it back
	// (accountant design D16, rossoctl/cortex#2280 item 4).
	//
	// json:"-", deliberately: a signature is a few KB, and keeping it would bloat every session
	// row and the session API with a value no reader wants. It is a transient carrier from the
	// response parser to the accounting host, held only for the life of the request. Empty on a
	// request's HistoryThinking, which the library prices from the request bytes directly.
	Opaques []string `json:"-"`
}

InferenceThinking counts the thinking blocks of one request or response. Blocks counts both kinds and Redacted the redacted_thinking ones among them. TextBytes and SignatureBytes are the bytes of the thinking blocks' text and signatures, RedactedBytes of the redacted blocks' data. A field of another JSON type counts as zero bytes.

func (*InferenceThinking) Add

func (t *InferenceThinking) Add(typ string, text, signature, data int)

Add counts one block of type typ, either kind; a type that is neither counts nothing.

func (*InferenceThinking) AddOpaque

func (t *InferenceThinking) AddOpaque(opaque string)

AddOpaque records one RESPONSE thinking block's opaque string for pricing when the client returns it: a "thinking" block's signature or a "redacted_thinking" block's data. An empty string is not recorded. Call it only for a response; a request's blocks are priced by the library from the request bytes.

func (*InferenceThinking) Merge

Merge adds the counts of o to t.

func (*InferenceThinking) OrNil

OrNil returns t, or nil when it counted no block, so an extension states nothing rather than a zero count.

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 InferenceToolResult

type InferenceToolResult struct {
	ToolUseID string `json:"toolUseId,omitempty"`
	Content   string `json:"content,omitempty"`
	IsError   bool   `json:"isError,omitempty"`
}

InferenceToolResult is one tool_result block from an Anthropic request. ToolUseID is the id of the call it answers — InferenceToolCall.ID on an earlier response. Content is the result's text: a string as sent, or its text blocks joined by newlines. Non-text blocks (an image a Read returned) are not recorded.

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; agentop 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 agentop 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. agentop 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 LenientBool

type LenientBool bool

LenientBool decodes JSON true as true and any other JSON value as false, for the reason LenientString gives. Used where false is the safe default: noRecord can only withhold.

func (*LenientBool) UnmarshalJSON

func (b *LenientBool) UnmarshalJSON(raw []byte) error

type LenientInt64

type LenientInt64 int64

LenientInt64 decodes a JSON integer as itself, a JSON float with no fractional part (3.0, the form a non-Go producer's float-typed millisecond figure takes) as the same integer, and any other JSON value (a fractional float, a string, a bool, an object) as 0 — for the reason LenientString gives: one bad-typed key must not cost the whole line. Used for a field another writer can set, where 0 is already the "not measured" value (an omitempty wire field).

func (*LenientInt64) UnmarshalJSON

func (n *LenientInt64) UnmarshalJSON(raw []byte) error

type LenientString

type LenientString string

LenientString decodes a JSON string as itself and any other JSON value as "". A field that another writer can set uses it, so that one key of the wrong type does not refuse the whole line.

func (*LenientString) UnmarshalJSON

func (s *LenientString) UnmarshalJSON(b []byte) error

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() []capabilities.Fragment

Fragments implements capabilities.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 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: core/parse/inference.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 function was written in core/pipeline, which also owns pipelines, and `pipeline.Merge(a, b)` reads at the call site as "merge two pipelines". In core/model, a bare `Merge` is not clear either: this package owns extensions, sessions and events. 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 agentop 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 agentop'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 agentop 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 — agentop'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 agentop'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. agentop'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 agentop'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 RawBody

type RawBody struct {
	Status     int         `json:"status"`
	Headers    http.Header `json:"headers,omitempty"`
	Body       string      `json:"body,omitempty"`
	BodyBase64 []byte      `json:"bodyBase64,omitempty"`
	Decoded    bool        `json:"decoded,omitempty"`
	Truncated  bool        `json:"truncated,omitempty"`
	Incomplete bool        `json:"incomplete,omitempty"`
	// Upstream is the server's reply before Cortex converted it to the agent's protocol.
	Upstream          *string `json:"upstream,omitempty"`
	UpstreamBase64    []byte  `json:"upstreamBase64,omitempty"`
	UpstreamTruncated bool    `json:"upstreamTruncated,omitempty"`
}

RawBody is a captured response. Body is in its Content-Encoding unless Decoded is set, so a compressed body is in BodyBase64.

type RawCapture

type RawCapture struct {
	Request         string  `json:"request,omitempty"`
	RequestBase64   []byte  `json:"requestBase64,omitempty"`
	Forwarded       *string `json:"forwarded,omitempty"`
	ForwardedBase64 []byte  `json:"forwardedBase64,omitempty"`
	// Translated is the body after Cortex converted it to the server's protocol.
	Translated       *string     `json:"translated,omitempty"`
	TranslatedBase64 []byte      `json:"translatedBase64,omitempty"`
	RequestHeaders   http.Header `json:"requestHeaders,omitempty"`
	Query            string      `json:"query,omitempty"`
	Response         *RawBody    `json:"response,omitempty"`
}

RawCapture is an event's exact capture as GET /v1/sessions/{id}/events/{seq}?raw=1 serves it (#1494). A request event's has the request fields, a response event's has Response. A body is text when it is valid UTF-8, which every JSON API body is, and base64 in the matching *Base64 field otherwise, so any body survives the trip.

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 core/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

func (r RawJSON) MarshalJSON() ([]byte, error)

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

func (r *RawJSON) UnmarshalJSON(b []byte) error

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 RequestCapture

type RequestCapture struct {
	// Original is the body as the agent sent it.
	Original []byte
	// Forwarded is the body as Cortex sent it upstream, nil when no plugin rewrote it.
	Forwarded []byte
	// Translated is the body as Cortex sent it upstream after it converted it to the
	// server's protocol, nil when it did not convert it. Forwarded, or Original when
	// Forwarded is nil, is the input of the conversion.
	Translated []byte
	// Header is the request's headers. The producer removes credential headers before it
	// hands the capture over: the archive stores what it is given.
	Header http.Header
	// Query is the request URL's raw query, without the '?'. The producer removes
	// query-borne credentials too (Gemini's key=, any api_key=): the archive stores the
	// query as given.
	Query string

	// Response is the response, on a response event's capture.
	Response *ResponseCapture
}

RequestCapture is one exchange exactly as it crossed the proxy, for the session archive's lossless capture (#1494). On a request event it holds the body the agent sent, the body Cortex forwarded, and the request's headers and query. On a response event it holds Response alone. The archive stores it beside its event and rebuilds it byte for byte. It never enters the in-memory session store.

type ResponseCapture

type ResponseCapture struct {
	Status int
	// Header is the response's headers, without credentials.
	Header http.Header
	// Body is the body as the proxy read it, up to MaxResponseCapture bytes: as it came off
	// the wire, in its Content-Encoding, unless Decoded is set.
	Body []byte
	// Decoded is set when the proxy's transport decompressed the body: it asked for the
	// encoding itself, to read the body for a plugin, so the wire bytes never reached the proxy.
	Decoded bool
	// Truncated is set when the body was longer than MaxResponseCapture.
	Truncated bool
	// Upstream is the server's reply before Cortex converted it to the agent's protocol, up
	// to MaxResponseCapture bytes, nil when Cortex did not convert the reply. Body is then the
	// converted reply, as the agent got it.
	Upstream []byte
	// UpstreamTruncated is set when Upstream was longer than MaxResponseCapture.
	UpstreamTruncated bool
	// Incomplete is set when the body did not arrive whole: the stream broke, or the client
	// went away first.
	Incomplete bool
	// Ended is set by the listener when it read the body to its end. Not stored: it decides
	// Incomplete.
	Ended bool
}

ResponseCapture is a response as the origin sent it.

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, then Seq —
	// see session.entry.nextSeq and agentop'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
	// 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

	// RequestedHost is the host the client asked for, present only when a plugin
	// redirected the request (pctx.Redirect) and Host is therefore somewhere else.
	// Host stays the host the bytes went to, because usage, the cost ledger and
	// pricing key on it.
	RequestedHost 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. On denied events
	// it's DurationSince(pctx.StartedAt) — a denial ends the request, so
	// it has a duration even though no response was ever recorded.
	Duration time.Duration

	// Ttfb is the wall-clock time from request entry into the listener
	// (pctx.StartedAt) to the upstream's response HEADERS arriving — not to
	// the first body byte, which no listener measures. Zero when the exchange
	// failed before headers (and on every request-phase event), so Duration −
	// Ttfb on a delivered response is how long the body took: for a streamed
	// completion, the stream time. Duration alone cannot separate an origin
	// that was slow to answer from one that answered and then streamed slowly
	// (#1251) — an 11-minute response with a small ttfb says "the origin
	// answered, then trickled", which is a different problem than a large one.
	// Tunnel rows carry none: an opaque tunnel has no headers to time.
	Ttfb time.Duration

	// Added is the wall-clock time from request entry into the listener
	// (pctx.StartedAt) to the request being handed to the upstream
	// (pctx.UpstreamSentAt): the time the proxy's own request-side work — the
	// inbound pipeline, body rewrites, header sync — added before the origin saw
	// anything. It is the figure llm.inference.added_seconds reports, and what
	// tells an operator whether Cortex or the origin is slow. Zero when the
	// request never left, and on request-phase and tunnel rows.
	Added 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 both rows of an opaque CONNECT / transparent-redirect tunnel:
	// the bytes are not HTTP, so there's no protocol parse. Set only by
	// recordTunnelOpened (the request-phase open) and recordTunnelClosed (the
	// response-phase close, which shares the open's RequestID). Consumers (agentop)
	// use it to fold the OPEN 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. Only the request-phase row folds; a close row never does.
	//
	// A bridged tunnel whose decrypted requests carry their own responses records
	// no close: its open folds into the first of them. Every other tunnel does —
	// opaque ones when they end, a failed dial at once, and a bridged one that
	// carried no request at all.
	Tunnel bool

	// BytesUp and BytesDown are how many bytes went each way: up is client to
	// destination, down is destination to client. A row carries whichever side it
	// is in a position to know, so the two never collide on one row:
	//
	//   request row        BytesUp   — the request body as FORWARDED, which is
	//                                  len(pctx.Body) at record time and so
	//                                  reflects any plugin that rewrote it
	//   response row       BytesDown — the response body the listener observed
	//                                  FROM THE DESTINATION, read from
	//                                  pctx.ResponseBytes
	//   tunnel close row   both      — the opaque bytes the tunnel carried
	//
	// The two sides differ on where the pipeline sits, and not by preference: the
	// request figure is read at record time, after any rewrite, because that is
	// when pctx.Body is what will be forwarded; the response figure is summed as
	// the bytes arrive, because on a streamed response there is no later moment
	// at which the whole body exists. A response mutator's rewrite is therefore
	// not reflected — extproc records the row before it even emits the
	// replacement — so BytesDown is what the destination sent.
	//
	// ZERO MEANS NOT COUNTED, NOT ZERO BYTES, and the field is absent from the
	// wire when zero. Body buffering is gated on a pipeline capability in all
	// three listeners, so a request no plugin wanted the body of is relayed
	// without ever being measured — and a body-less GET is indistinguishable from
	// it, which is why neither may render as a real 0 B. A bridged tunnel's close
	// reports zero for the same reason: its bytes were TLS the bridge terminated
	// rather than counted, and its decrypted inner requests carry their own
	// figures. Consumers render zero as blank (agentop's bytesCell).
	//
	// Headers are deliberately not counted. The question these answer is how big
	// a payload was — a prompt that overran a model's context window is the case
	// they exist for — and a kilobyte of constant header noise on every row
	// obscures it. They are therefore NOT a wire-cost figure.
	BytesUp   int64
	BytesDown int64

	// TunnelReason says WHY the bytes were left opaque. Empty when Tunnel is
	// false, and empty on a bridged CONNECT (agentop 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

	// DialAddr is the address the proxy actually dialed for this event's
	// destination, "ip:port", set by the listener when the egress guard is
	// enabled (listener.egress_guard). It differs from Host whenever the
	// destination was named: Host is what the request said, DialAddr is the
	// resolved address the guard checked and the only address the connection
	// can reach. On a DNS-rebindable name the two together are the audit trail
	// — "asked for example.com, dialed 203.0.113.7" — and moca's egress
	// conformance reads this field (its dial_addr) off the tunnel open row.
	//
	// Present only on a tunnel's open row: a plain or bridged request dials
	// through the guarded transport too, but nothing threads the checked
	// address back to its pctx, so its rows carry Host alone. Absent when the
	// guard is off. Set only by the listener, never by a plugin.
	DialAddr string

	// UpgradeStripped names the protocol a client asked to switch to on a request
	// whose Upgrade header the forward proxy removed — see
	// pipeline.Context.UpgradeStripped for why that is both correct and
	// confusing. Empty on every other request.
	//
	// On the REQUEST row; pair it with the response row's StatusCode by RequestID.
	// A 405 next to this is the origin rejecting the un-upgraded request, which is
	// the sequence worth being able to read off the timeline rather than out of an
	// agent's stderr. A 426 with error.kind "upgrade_declined" is the proxy answering
	// a Responses API WebSocket itself, before any origin is contacted
	// (listener.responses_websockets).
	UpgradeStripped string

	// 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

	// Subagent is the Claude Code agent that made the request — a subagent or an
	// agent-team teammate — read from the request's X-Claude-Code-Agent-Id header by
	// Context.Subagent. Empty on the main conversation's requests, on every client that is
	// not Claude Code, and on a value Context.Subagent refused — see there for what each
	// case means and why a refused value is not cleaned up instead.
	//
	// It names WHICH agent, which Inference.AgentRole cannot, so two subagents running at
	// once no longer file the same. It does NOT say the row is a subagent's: a teammate
	// sends this header without the cc_is_subagent marker, so its rows carry an id here
	// and AgentRole "main". Read AgentRole for that question. For a subagent the same id
	// names its files under ~/.claude/projects/<dir>/<session>/subagents/, so a consumer
	// can join a row to its agent-<id>.meta.json for the subagent's type and description.
	//
	// Client-asserted, with the same caveat as Client above.
	Subagent string

	// ParentSubagent is the agent that started Subagent, read from
	// X-Claude-Code-Parent-Agent-Id by Context.ParentSubagent. Together the two give a
	// row's place in the session's tree of agents: Subagent is the node, this is its
	// parent, and EMPTY HERE ON A SUBAGENT'S ROW MEANS THE PARENT IS THE CONVERSATION —
	// Claude Code sends the header only when the spawner was itself an agent. See
	// Context.ParentSubagent for the other empty cases.
	//
	// Client-asserted, with the same caveat as Client above.
	ParentSubagent string

	// Source is "" on a live event, "imported:<agent>" on an event an import wrote.
	// Use ImportedSource to make the value and Imported to test it.
	Source string

	// NoRecord is true when the request withholds its own session from the archive: it
	// carried RecordHeader with the value RecordOff and named its session with a session-id
	// header (#1923; Context.WithholdsSession, pinned before any plugin runs). The proxy
	// still forwards the request and runs its plugins. The archive keeps none of the
	// session's events from then on; what it held before the opt-out stays.
	//
	// Client-asserted, with the same caveat as Client above. It can stop a session's
	// recording, never put one there or erase what is recorded.
	NoRecord bool

	// SubagentKind is the kind of a Bob child task, from Context.SubagentKind:
	// SubagentKindSubtask or SubagentKindSubagent. Set only on a Bob child's rows, and
	// empty everywhere else, Claude Code rows included (read Inference.AgentRole there).
	SubagentKind string

	// Proc is the agent process the request belongs to, "<pid>.<start>", as process
	// attribution named it (attribution.Attribution.Proc): the agent root of the client's
	// chain, so a launcher and its worker are one. Empty where the listener could not name
	// the process, which is everywhere but a loopback-bound install. It is what links a
	// process's calls from before it named a session to that session when the list is read
	// (session.Link), so it is recorded on rows in a session as well as on pending ones.
	Proc string

	// ClientProc is the client process itself when it differs from Proc: a worker naming the
	// session its launcher (Proc) is attributed with. Only on a request that named its
	// session. The fold records a span for it too, so the worker's own pending bucket links.
	ClientProc string

	// Project is the project label (project.Label of the git repo root of the agent process's
	// cwd), "" where the listener could not name the process or the row came on the trusted path.
	Project string

	// ParentSession is the session that the topmost process above this row's agent named, when
	// it is not this row's session (pipeline.Context.ParentSession). For A → B → C it is A on
	// C's rows. "" everywhere else.
	ParentSession string
	// ParentProject is the project label of the process that holds ParentSession, "" with it.
	ParentProject string

	// SessionHeader is the session-id header that named this row's session, "" when the
	// session was not named by the request (process, affinity, ActiveSession). Recorded so
	// the fold can tell which processes NAMED a session from those merely filed into it,
	// which Link needs and the session's agent is decided by.
	SessionHeader string
	// Stamped is true on an ext_proc row whose session X-Cortex-Session named: a claim of the
	// Cortex before the recorder. A row without it, where that Cortex stamps, was not stamped.
	Stamped bool
}

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) Imported

func (e *SessionEvent) Imported() bool

Imported tells if an import wrote e. A live event gives false.

func (SessionEvent) MarshalJSON

func (e SessionEvent) MarshalJSON() ([]byte, error)

func (*SessionEvent) RollupProject

func (e *SessionEvent) RollupProject() string

RollupProject is the project this row's cost and session count are filed under: the parent's project when the row has one, else Project.

func (*SessionEvent) SplicedUpgrade

func (e *SessionEvent) SplicedUpgrade() bool

SplicedUpgrade tells if e is the forward proxy's 101 row for a WebSocket it relayed (forwardproxy/upgrade.go). That row is written after both splice directions end, so its Duration is the socket's lifetime and its bytes are the relay's opaque frames, not a request's latency or a response's body. Aggregations that read Duration or bytes as a request's skip it, as they skip a Tunnel row; the session timeline keeps it.

Scoped to Outbound: the reverse proxy records its own 101 (Direction Inbound) at handshake time, so that row's Duration is an ordinary handshake latency.

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. agentop) can decode straight into the canonical type.

type SessionFact

type SessionFact struct {
	Event *SessionEvent
	State FactState
}

SessionFact is one session fact. Event is not nil only when State is FactPresent.

type SessionFacts

type SessionFacts struct {
	LastIntent    SessionFact // the newest event that IsIntent accepts
	LastInference SessionFact // the newest event that IsInferenceRequest accepts
	LastMainTurn  SessionFact // the newest event that intent.IsMainTurnEvent accepts

	// InferenceHosts is the session's table: the store entry's events and the archive's history.
	InferenceHosts InferenceHosts
	// HostsKnown is false when no store answered, or when the archive holds history that it has
	// no table for. So the zero value is "unknown", and a reader must not use the table.
	HostsKnown bool
}

SessionFacts are the facts that the session store keeps for one session.

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 agentop
	// 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 SessionSource

type SessionSource string

SessionSource is how a listener resolved Context.Session.

const (
	// SessionSourceHeader: a configured session id header on the request
	// named the session (Context.SessionHeader says which).
	SessionSourceHeader SessionSource = "header"
	// SessionSourceProcess: the session of the process that sent the request,
	// or of an ancestor, named by its own session header earlier.
	SessionSourceProcess SessionSource = "process"
	// SessionSourcePending: a coding agent's pending bucket, held until its
	// first session header names a session.
	SessionSourcePending SessionSource = "pending"
	// SessionSourceAffinity: the newest session of the coding agent the
	// User-Agent names.
	SessionSourceAffinity SessionSource = "affinity"
	// SessionSourceActive: the most recently active session.
	SessionSourceActive SessionSource = "active"
	// SessionSourceConnection: the listener's own trusted answer, resolved
	// from how the connection arrived rather than anything the client sent
	// (which per-VM socket accepted it, vmcontrol). Client-asserted headers
	// cannot override it.
	SessionSourceConnection SessionSource = "connection"
)

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 agentop 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"`

	// SchemaVersion is the session API's sessionapi.SchemaVersion. The server sets it
	// on the response, so a view that the store builds has zero, and omits it.
	SchemaVersion int `json:"schemaVersion,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) Len

func (v *SessionView) Len() int

Len returns total event count.

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 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"
	// TunnelProgramRefused — an earlier handshake by the program that opened this
	// connection failed, so no interception was attempted. Usually that failure was a CA
	// rejection, but, as with skip-cached, any failed handshake seeds it: the connection
	// died mid-handshake either way, and the program's retry needs a tunnel. The earlier
	// failure's proxy.log line names the program (program=, and agent= when it runs
	// under one) and gives its own reason.
	//
	// Recorded against the client's program (tlsbridge.Program), not the host, so
	// another program talking to the same host is still bridged. The window starts at
	// 30s and doubles only on rejections, and a rejection counts only once the window
	// before it has ended; after three rejections in a row the program is not retried
	// until Cortex restarts. A hang-up or a cipher mismatch never adds to the count or
	// lengthens the window, but when it is the program's first failure it starts the
	// count at one, so a hang-up followed by two spaced rejections stops the program. A
	// process that started before the bridge CA is recorded on its own instead
	// (Program.ProcessKey): it cannot have loaded that CA, so its refusal says nothing
	// about the program, and restarting that process is enough.
	TunnelProgramRefused TunnelReason = "program-refused"
	// TunnelOSTrustOnly — the program trusts only the operating system's certificate
	// store, and the store does not trust the bridge CA, so no leaf was shown: it could
	// only have been refused. Today that is a Go program on macOS (tlsbridge.ClientTrust),
	// which reads no CA file there. The connection works from its first try; adding the
	// CA to the keychain is what has Cortex read it.
	TunnelOSTrustOnly TunnelReason = "os-trust-only"
	// 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"
	// TunnelDialFailed — the proxy could not reach the destination at all, so no
	// tunnel ever opened. Recorded with a 502 close row carrying the dial error, so
	// an unreachable destination shows in the timeline instead of leaving no trace —
	// except where the TLS bridge is enabled for the connection's port: there the
	// CONNECT is answered 200 first (a redirect can still send the request to a
	// live server, #1595), and a bridge that then declines or falls open closes
	// with that 200 and the dial error.
	TunnelDialFailed TunnelReason = "dial-failed"
	// 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"
	// TunnelWebSocket — not opaque at all: a Responses API WebSocket the forward
	// proxy carries and reads. The open row is its handshake and the close row its
	// end, with the bytes and duration of the whole socket; every turn on it records
	// its own request and response rows between the two, parsed like an HTTPS turn.
	TunnelWebSocket TunnelReason = "websocket"
	// TunnelDestPrivate — the egress guard refused the destination before any
	// dial: it resolved to loopback, link-local (cloud metadata), RFC 1918 /
	// unique-local space, or one of this host's own addresses, and no permit
	// covered it (link-local is never permit-able). Recorded with a 403 close
	// row carrying error.kind "destination_private" — the MOCA egress contract's
	// identifier, used verbatim. Never confused with dial-failed: a refused
	// destination was never attempted.
	TunnelDestPrivate TunnelReason = "dest-private"
	// TunnelSNIMismatch — under tls_bridge.fail_closed, the client's TLS SNI named a
	// host other than the CONNECT target, so the bridge refused the handshake. Recorded
	// with a 421 close row carrying error.kind "misdirected_request".
	TunnelSNIMismatch TunnelReason = "sni-mismatch"
	// TunnelRefusedNonTLS — under tls_bridge.fail_closed, a connection to a host the
	// bridge intercepts sent bytes that are not a TLS handshake, so it was closed
	// rather than tunnelled.
	TunnelRefusedNonTLS TunnelReason = "refused-non-tls"
)

Tunnel reasons. Stable strings: agentop renders them and operators grep them.

Each is at most 18 characters, which is the width of agentop'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.

Jump to

Keyboard shortcuts

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