session

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: 19 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

Overview

Package session provides an in-memory session store for correlating inbound user intents with outbound tool calls across request boundaries. The store is per-pod (AuthBridge sidecar) and does not persist across restarts; where a session archive runs, ListSessions continues each session from it (see PriorKeeper).

Index

Constants

View Source
const (
	TurnContinuation = "continuation" // a conversation the router did not see begin
	TurnAside        = "aside"        // a one-shot or a subagent's request, which decides nothing
)

TurnOf's answers. The inference-router records them as the turn detail on a not-routed record, where the request's own turn decided an unpinned Claude Code session.

View Source
const BobSessionHeader = model.BobTaskIDHeader

BobSessionHeader is the request header the Bob coding agent sets to name the task a request belongs to. Two differences from ClaudeCodeSessionHeader are worth knowing before reading a bucket keyed on it: it is not verified against a released client, and the value is a task id rather than a session uuid — so it is stable for as long as Bob reuses that task, which may span what a user would call several sessions, or none.

UNNAMESPACED, and in the default list, which is the one property here worth a second thought. X-Task-Id is a name any client might plausibly send for its own reasons, and nothing ties it to Bob — so unrelated traffic that happens to use it captures a bucket named after its value, rather than falling through to ActiveSession() as it did before this header was consulted. That is a mis-grouping, not an escalation: IDFromHeaders already treats every id as client-asserted and untrusted (see its TRUST section), and a caller able to send this header could equally send the Claude Code one. Accepted because the alternative — Bob traffic silently pooling in the shared bucket — is the problem this solves, and session.id_headers is the per-deployment override either way.

Canonical HTTP casing is required here even though IDFromHeaders reads via http.Header.Get, which canonicalizes: tests construct http.Header map literals directly from these constants, and a raw map literal does not.

A CHILD TASK FILES IN ITS PARENT (#1803, rule 1). A Bob subagent or subtask sends its own X-Task-Id and also model.BobParentTaskIDHeader, which names the root task (every child names the root, not its direct parent). When this header gave the id and the parent value is valid, IDHeaderFrom returns the parent id. The parent header is never in session.id_headers: it is read only beside this one.

View Source
const ClaudeCodeSessionHeader = "X-Claude-Code-Session-Id"

ClaudeCodeSessionHeader is the request header the Claude Code CLI sets on every inference request, carrying a UUID that is stable for the life of one session and reused when a session is resumed (`claude --resume <id>`). It is the same id the CLI names its transcript after (~/.claude/projects/<slug>/<uuid>.jsonl), so a bucket keyed on it lines up with what the user sees in their own client.

Verified against claude-cli/2.1.266. The value is also duplicated inside the request body as metadata.user_id, which is why losing the header is not silently fatal — see IDFromHeaders for why we read the header only.

View Source
const CodexSessionHeader = "Session-Id"

CodexSessionHeader is the request header Codex sets on its inference requests to name the session they belong to. Verified on codex_exec/0.160.1 by logging every header name Codex sends: the value is a UUID, constant across all nine inference requests of one multi-turn session and different in the next, which is the property a bucket keyed on it needs.

NOT X-Session-Id, which is the one letter-prefix this nearly was: Codex sends the BARE name, so the header Cortex already read for OpenCode missed it and Codex's traffic grouped by process instead of by conversation.

Codex sends two other headers carrying the same value — Thread-Id and X-Client-Request-Id. This one is read because its NAME matches the intent: if Codex later makes X-Client-Request-Id per-request as its name implies, a bucket keyed on that would split one session into one session per request, and nothing would announce the change.

UNNAMESPACED, and the least namespaced of the four — a bare Session-Id is a name any client might send for its own reasons. So it is read by default only on a loopback-only install, exactly as SessionIDHeader is and for the same reason given there: on a laptop the only clients are the user's own agents, while in a cluster an agent sending this for its own purposes would have its calls filed away from the session holding its user's intent. It also sits LAST in that list, so any client sending one of the three dedicated headers still wins. Canonical casing, for the reason the others give.

WHICH REQUESTS CARRY IT DIFFERS BY FRONT-END, measured on both. Under `codex exec` only the inference requests do, so a run also leaves a small pending:codex@<pid> bucket for the chatter that preceded them. The TUI sends it on its chatter too — a TUI session was named with zero inference requests in it — so a TUI run leaves one row rather than two. Both confirmed by driving the real clients through the proxy; the TUI needed `-c check_for_update_on_startup=false -c features.api_key_model_discovery=false` to suppress the two modal dialogs that otherwise block its composer.

View Source
const DefaultSessionID = "default"

DefaultSessionID is used when no explicit A2A SessionID is present and no active session exists. This collapses all such requests into one shared session, which is correct for single-agent pods but may cause cross-user correlation in multi-tenant deployments. Future work: derive session ID from JWT claims.

View Source
const (
	// InternMinLen is the shortest string worth a map lookup.
	//
	// A role ("user"), a finish reason ("end_turn") and an empty completion all repeat
	// constantly and all cost less to duplicate than to hash. The savings live in
	// message bodies, which are orders of magnitude past this.
	//
	// Exported for the session archive, which deduplicates the same seven fields on disk
	// and must agree with the store on what is worth sharing — one threshold, not two
	// numbers kept equal by hand.
	InternMinLen = 64
)

Repeated message content is stored once per session, not once per event.

WHY: an LLM request carries the whole conversation, so every turn re-sends every earlier message. The store keeps one event per request, each holding its own copy of that array, which makes retention quadratic in turns while the conversation itself grows linearly. Measured on a real 96-turn session: 27.7MB of message text held, 7.0MB distinct — 3.9x, and the factor rises with turn count because the duplicated prefix gets longer. The proxy reached 3.37GB resident on a laptop in 18 hours, against ~833MB for every Claude Code transcript on the same disk. The transcripts are the same conversations, appended once each; the difference was all duplication.

The fix costs nothing at read time and changes nothing observable: Go strings are immutable, so two events sharing one backing array cannot tell, and a consumer sees the same bytes it always did.

SCOPE: string fields only — inference messages and completions, tool results (content by the threshold, ToolUseID below it via internID), the history tool calls' arguments (ids and names via internID), A2A part content, and the tool manifest's descriptions AND schemas. Tool results repeat exactly as the conversation does: a client re-sends every earlier one on every request. The manifest earns its place: a client re-sends it on every request, so it duplicates harder than the conversation does. Measured on a live 272-event session, 10.3MB of tool JSON held against 0.1MB distinct — 154x, where the conversation itself was 6.5x. Interning the descriptions took that session's tool retention from 7.12MB to 0.37MB.

The schemas (InferenceTool.Parameters) were the last big duplicate and are interned too. They used to be map[string]any, which is what put them out of reach: a walk that rewrites map values cannot lean on string immutability the way this does, so it needs its own reasoning about aliasing. Rather than write that walk, the FIELD changed — it is a model.RawJSON, a named string type, so it interns here like any other string and the aliasing question never arises. Two measurements motivated it: the schemas were 34.7% of that 10.3MB, and as maps they cost 4.1x their JSON text to hold — 84KB per event on a live session, ~172MB across one 2050-event session.

What is still duplicated: MCP Params/Result, which remain map[string]any and would need the recursive walk. Left alone deliberately — they are unmeasured on this workload (zero MCP events across every live session inspected), so there is no evidence yet about what they cost, and the same field-type change is available to them if there ever is.

View Source
const MaxSessionIDLen = 256

MaxSessionIDLen is the longest session ID the store keeps intact; longer ids are truncated on Append. Exported so callers that validate an id before reaching the store — the session API's query parameters, for one — bound it at the same length instead of duplicating the number.

View Source
const PendingPrefix = "pending:"

PendingPrefix marks a pending bucket: the calls an agent process makes before it names a session, recorded under PendingID. Nothing renames one; see Link.

View Source
const SessionIDHeader = "X-Session-Id"

SessionIDHeader is the generic request header OpenCode, Pi (pi.dev, through the extension `agentop configure pi` installs; it does not send one by default) and similar frameworks set to name the session a request belongs to. OpenCode (verified on 2.0.21) sends its session's AFFINITY id here — the parent session's id for a subagent, the source session's for a fork, else its own — so a subagent's and a fork's requests join the conversation they belong to, the way Claude Code's subagents share their parent's session id. OpenCode also sends X-Opencode-Session-Id, the session's own id; that one is not read, so a subagent does not get a row of its own.

UNNAMESPACED, like BobSessionHeader: any client that sends it captures a bucket named after its value. Unlike BobSessionHeader it is read by default only on a loopback-only install (config.SessionConfig.SessionIDHeadersFor): in a cluster an agent may send it for its own reasons, as the IBAC demo's does, and filing its calls by it would take them away from the session that holds its user's intent. Canonical casing, for the same reason as the others.

Variables

This section is empty.

Functions

func CapturePath

func CapturePath(method, path string) (string, bool)

CapturePath is the server path an inference request addressed to a host that is no server is sent to, and whether the inference-router captures it at all: a POST, with a path ending in one of capturedPaths. The parse is checked by the caller; see the router's capture.

func IDFromHeaders

func IDFromHeaders(h http.Header, names []string) string

IDFromHeaders returns the first usable session id found in h among names, in order, or "" when none is present. Callers treat "" as "fall back to whatever bucketing you did before" — never as an error, so a client that stops sending the header degrades to the old shared bucket instead of dropping telemetry.

The header is read rather than the equivalent body field (Claude Code duplicates the id in metadata.user_id) because a header costs nothing to reach: bucketing must work for every request, including ones no parser matched and ones whose body was never buffered.

TRUST: the returned id is CLIENT-ASSERTED AND UNAUTHENTICATED. validity checks below stop a value from corrupting a log line or a terminal; nothing establishes that the client owns the session it names. Two distinct effects follow, and the second is the cheaper one:

  • Targeting. A client may name another session's id and write into that bucket, or name "default" and become indistinguishable from unattributed traffic. Since these buckets now feed cost attribution, a poisoned key mis-attributes spend, not just a TUI row.
  • Cardinality. Store.Append evicts the oldest bucket once the store exceeds session.max_sessions (default 100), so a client that sends distinct random ids evicts every real bucket without needing to know a single one of them. Memory stays bounded; the telemetry does not survive. That destroys history rather than mis-filing it, and it reaches the buckets this comment calls trustworthy below — an agent can evict the A2A-correlated buckets, not only redirect its own. session.max_sessions is the only knob that bounds it, and raising it trades eviction for memory rather than removing the effect.

The blast radius is set by one property only: the session store is in-process, so the bucket namespace is shared by exactly those clients that can reach this proxy. Nothing here narrows that further — the listener role says which pipeline runs, not how many workloads a process serves, and in-cluster the forward proxy binds a wildcard address by default (ListenerConfig.BindLoopbackOnly is off), so "only my own pod reaches it" is a property of the deployment — network namespace, NetworkPolicy, who sets HTTP_PROXY — and not of this code.

So: a laptop with bind_loopback_only is a single trust domain and the user owns every session. A sidecar serving one workload confines mis-filing to that workload's own telemetry. A shared or standalone forward proxy serving several workloads shares one bucket namespace, and there a poisoned id does cross workloads. Even within a single pod there is a residual worth naming: an agent serving several users can redirect telemetry away from the inbound A2A turn that caused it, and that A2A correlation is the trustworthy signal in-cluster.

Set session.id_headers to an empty list wherever attribution is a trust boundary rather than a convenience. Compare DefaultSessionID, which carries the mirror-image caveat for the shared bucket.

func IDHeaderFrom

func IDHeaderFrom(h http.Header, names []string) (id, header string)

IDHeaderFrom is IDFromHeaders that also returns the name of the header the id came from, "" when none did.

func IsConversation

func IsConversation(id string) bool

IsConversation reports whether id is one conversation's session: false for "", the default bucket, and any pending bucket, each of which holds many conversations' calls or none. Plugins that key state on a session (the inference-router's pins, cpex's taint) skip the others.

func LinkedEvents

func LinkedEvents(events []model.SessionEvent, links []PendingLink, session string) []model.SessionEvent

LinkedEvents is the part of a linked bucket's events that belongs to session: the requests OwnerAt gives it, each with its response, wherever the response landed in time.

func OwnerAt

func OwnerAt(links []PendingLink, t time.Time) string

OwnerAt is the session a call its process made at t belongs to, "" for none: the first session the process named at or after t. Concretely, among the links whose span has not ended by t (Last >= t), the one whose naming resumed soonest — a span already covering t resumed "at t", so it beats one that begins later, and between two that both cover t the one begun more recently is the one the process had just named.

LAST DECIDES ELIGIBILITY, FIRST DECIDES ORDER. Ordering by Last instead sent an OpenCode service's start-up calls into a session it began naming minutes after them, because that session's span happened to end before the first one's. Eligibility by Last is what keeps the restart case: a session named yesterday and again today, after a restart lost the claim, still takes the calls made today before it was named again.

func ParsePending

func ParsePending(id string) (agent, proc string, ok bool)

ParsePending splits a pending bucket's id into its agent and process ("<pid>.<start>", "" for the agent-wide bucket), and reports false for any other id.

func PendingID

func PendingID(agent, proc string) string

PendingID is the pending bucket for agent's calls from one process, proc being that process as "<pid>.<start>", or the agent-wide bucket when proc is "" — the process could not be looked up. It is a recording id only: nothing renames a pending bucket, and its calls are linked to the session the process names when the list is read (see Link).

func PendingSessionID

func PendingSessionID(client string) string

PendingSessionID is the agent-wide pending bucket for client, used when the client's process could not be looked up.

func TurnOf

func TurnOf(ext *model.InferenceExtension) string

TurnOf is a Claude Code request's place in its session's conversation, read from inference-parser's parse: TurnContinuation for the main conversation with earlier assistant turns, TurnAside for any other request, and "" for the main conversation's opening turn or a request that states no role.

The role is stated only by Claude Code's system prompt (see model.InferenceExtension.AgentRole), and only Claude Code is read this way: another agent's earlier turns may have gone to another provider — OpenCode starts on Zen and addresses a server later — so its turns say nothing about whether its use of the servers began before this request. The main conversation carries its tool manifest; the one-shots Claude Code interleaves with it, its title request, auto mode's classifier and the permission monitor, carry none, and neither they nor a subagent's requests say whether the session began now.

func ValidSessionID

func ValidSessionID(id string) bool

ValidSessionID reports whether id is one a client's session-id header can name: no longer than MaxSessionIDLen, valid UTF-8, no control character. A longer id is filed under a cut one, so stopping its recording would mark an id no call is filed under.

Types

type Bucket

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

Bucket is the session an event was appended to. It follows that session through a Rekey or an Adopt, which rename a session rather than replace it, and names nothing once the store has evicted or expired it.

type CaptureRecorder

type CaptureRecorder interface {
	RecordCapture(sessionID string, e *model.SessionEvent, c *model.RequestCapture)
}

CaptureRecorder is optionally implemented by a Recorder that takes the request captures AppendCapture hands over (#1494). RecordCapture is called in place of Record, under the store's write lock, with c nil for an event that has none. The store never keeps c: raw bodies are megabytes, and the store keeps every event in memory.

type Clearer

type Clearer interface {
	Cleared()
}

Clearer is optionally implemented by a Recorder that keeps state keyed by session id: the usage aggregator's per-session figures, the archive's numbering and files. Clear tells each one, under the store's write lock and after the store has dropped every session, so no append can land between the two halves and be kept by one side only.

Cleared runs in front of live traffic, like Record: it must not block. Work that takes time — the archive's file deletion — is queued for the Clearer's own goroutine.

type Deleter

type Deleter interface {
	Deleted(sessionID string)
}

Deleter is optionally implemented by a Recorder that keeps state keyed by session id: the usage aggregator's per-session figures, the archive's numbering and files. Delete tells each one, under the store's write lock and after the store has dropped the session, so no append can land between the two halves and be kept by one side only.

Deleted runs in front of live traffic, like Record: it must not block. Work that takes time — the archive's file deletion — is queued for the Deleter's own goroutine.

type EntryStarter

type EntryStarter interface {
	EntryStarted(sessionID string, after uint64)
}

EntryStarter is optionally implemented by a SeqSeeder. The store calls EntryStarted under its write lock each time it creates an entry for sessionID, with the seq it numbers that entry's events after. A rename of the entry carries the events numbered after it; those at or below it were recorded under sessionID before this entry existed, and stay there. Like LastSeq, it must be a memory update.

type Evicter

type Evicter interface {
	Evicted(sessionID string)
}

Evicter is optionally implemented by a Recorder that keeps per-session state: the store calls Evicted under its write lock when it drops a session for max_sessions or ttl, as it calls Deleted for an explicit delete. The attributor forgets the session, so a tool bound to it is rebound to its agent's live one.

type History

type History interface {
	// Earlier calls fn, newest first, for the events recorded under sessionID numbered below
	// before, every one when before is 0, until fn returns false or none are left. It reads
	// from disk.
	Earlier(sessionID string, before uint64, fn func(*model.SessionEvent) bool) error
}

History is the events a session recorded on disk, the session archive's, for a plugin that needs the events from before this process: a store entry starts empty after a restart.

type HistoryConsumer

type HistoryConsumer interface {
	SetHistory(History)
}

HistoryConsumer is implemented by plugins that read a session's archived events. plugins.BuildWithDeps injects the process's History before Configure runs; a process with no session archive passes nothing.

type HostsKeeper

type HostsKeeper interface {
	// InferenceHosts is the table over every event the keeper wrote under sessionID. ok is false
	// when it holds history that it has no table for. An id it does not hold gives (nil, true).
	InferenceHosts(sessionID string) (model.InferenceHosts, bool)
}

HostsKeeper is optionally implemented by a Recorder that keeps a session's history for longer than the store does — the session archive. ViewFacts asks it for a session's InferenceHosts table when the entry is numbered after earlier history, and when there is no entry.

It is called under the store's lock, like LastSeq: it must be a memory lookup, and must not block or call back into the store.

type Interner

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

Interner maps a string to the one copy the session keeps of it, and one conversation's growing message arrays to the events that re-send them.

CONVERSATIONS, NOT EVENTS. The table holds the strings of the last event of EACH conversation in the session, keyed by conversationKey (model + the first two messages — the system prompt, which differs between a subagent and its parent), LRU-capped at maxConversations. A single rolling table served single-conversation sessions: turn N's array is turn N-1's plus a message or two, so interning N against N-1 makes them share. But a session that runs subagents carries several conversations taking turns, and every switch threw the table away: one live session switched between its 14 conversations 1,307 times in 2,436 requests, re-retaining a full copy of the conversation on every switch back (#1541 — 60.5x the distinct content on a two-conversation fixture, against 1.9x for one).

PREFIX-SHARED ARRAYS. Beyond the strings, each conversation state holds the growing []InferenceMessage / []InferenceTool / []InferenceToolResult backing arrays, appended the way a transcript is: a turn that extends the conversation appends its tail to the shared array, and every event's slice points into it — so the per-event message HEADERS (48 bytes each, 15.4 million of them across one measured 30-day archive = 738MB) are shared the same way the strings are, instead of cloned per event. A turn whose prefix stops matching (a compaction that rewrote history) shares only the verified prefix and copies the rest — graceful degradation, the same trade the string table already makes.

Sharing an ARRAY needs a stronger invariant than sharing a string: strings are immutable, slices are not. The pipeline's snapshot contract supplies it — "Slice fields are reused intentionally — they are only assigned, never mutated in place, after the parser completes" — and nothing in this package or its readers writes an event's slice elements after Append. The interner itself only ever APPENDS to the shared arrays; it never writes an index below the length a published event already references.

The table pins no content of its own: every key is a string some event still references, and every array element belongs to some event's slice. Eviction (whole-session or LRU) therefore needs no pruning — the state is garbage with its events. The tradeoff is deliberate: content that disappears and comes back (compaction, an evicted conversation) misses the table and gets a second copy. Best-effort dedup with a bounded table beats exact dedup with a table that outlives what it describes.

Exported for readers outside this package, because the store is not the only place these events pile up: agentop decodes the same events off the session API and held more memory than the proxy it was watching. Feed events through one Interner in the order they were recorded — the tables depend on consecutive events of a conversation being neighbours, so shuffled input still returns correct strings but shares almost nothing. The zero value is ready to use, and one Interner is for one goroutine.

func (*Interner) InternEvent

func (in *Interner) InternEvent(e *model.SessionEvent)

InternEvent gives the event its own extension, with content pointing at the session's existing copies and message slices prefix-shared into the conversation's growing arrays, then rolls the string table forward.

It CLONES or prefix-shares rather than rewriting in place, and that is not defensive habit — writing in place is unsound here for three separate reasons:

  • pipeline.SnapshotInference and SnapshotA2A are shallow copies, and their contract says so: "Slice fields are reused intentionally — they are only assigned, never mutated in place, after the parser completes." Interning in place breaks the invariant the rest of the pipeline is written against.
  • the request-phase and response-phase events of one request alias the same backing array, because both snapshot the same live pctx.Extensions.Inference (forwardproxy/server.go:377 and :880). So the second Append would rewrite an array the first event already published.
  • publishLocked hands the event — extension pointers included — to subscriber channels, and the SSE goroutine encodes it outside the store's mutex. Mutating those arrays is a straight data race against an in-flight encode.

"Every replacement is a string equal to the one it replaced" does not rescue it either. With two requests interleaved in one session bucket, the second Append rolls prev forward before the first request's response-phase event is interned, so that pass writes a genuinely different pointer over memory the store has already handed out.

Cloning costs one slice copy per event and nothing in steady state: the original array becomes garbage when the request completes, and the store then owns everything it mutates.

type MarkKeeper

type MarkKeeper interface {
	Withheld(sessionID string) bool
}

MarkKeeper is optionally implemented by a Recorder that keeps a session's opt-out mark across restarts (the session archive, #1923). Withheld reports whether sessionID is marked, so a store entry created after a restart, by a session that sends no header any more (claude --continue), is still listed as not recorded. Called under the store's READ lock, on agentop's poll: a memory lookup that never blocks and never calls back into the store.

type Option

type Option func(*Store)

Option configures a Store at construction time.

func WithClock

func WithClock(fn func() time.Time) Option

WithClock replaces the clock sessions are stamped and expired by. No production caller: the README demo runs its whole stack on one shifted clock, and a store left on the real one stamps UpdatedAt weeks away from the clock the TUI measures it against.

type PendingLink struct {
	Session string    `json:"session"`
	First   time.Time `json:"first"`
	Last    time.Time `json:"last"`
}

PendingLink is one session a pending bucket's process named, with the span of its naming requests: the first and the last. Which of a bucket's calls are whose is OwnerAt's answer.

type Prior

type Prior struct {
	// Fold is the earlier history's figures. SHARED AND IMMUTABLE: the keeper hands out the copy it
	// published, so a caller reads it and never Adds to it.
	Fold *SummaryFold
	// CreatedAt is when the keeper first saw the session; zero when it does not know.
	CreatedAt time.Time
}

Prior is a session's history from before a store entry began: what the session archive folded under the id up to the seq the entry numbers after.

type PriorKeeper

type PriorKeeper interface {
	Prior(sessionID string, after uint64) (Prior, bool)
}

PriorKeeper is optionally implemented by a Recorder that keeps a session's history across the store's restarts and evictions — the session archive. For every entry numbered after earlier history (a SeqSeeder answered above zero when the entry was created), ListSessions asks for that history and reports the session's row as the two together, so that — with session.max_events unset, the default — a restart, a ttl or max_sessions changes nothing a list shows. With a cap the entry's own figures shed what a trim drops while the archive's fold keeps it, so a restart can raise them.

ok is false when the keeper cannot say EXACTLY what came before, and the row then shows the entry's own figures. That undercount is the safe side: the keeper records every event the store appends, so anything but the history from before the entry would count the entry twice.

Prior is called under the store's READ lock, on agentop's two-second poll: it must be a memory lookup, must not block, and must not call back into the store.

type ProcSpan

type ProcSpan struct {
	First time.Time `json:"first"`
	Last  time.Time `json:"last"`
}

ProcSpan is when one process named a session through its own header: its first such request and its last. Link reads it; the fold keeps one per process per session.

type Recorder

type Recorder interface {
	Record(sessionID string, e *model.SessionEvent)
}

Recorder receives every event the store appends, for side-channel aggregation. Declared here as a narrow interface rather than importing the usage package so the dependency points one way: usage knows about events, the store knows nothing about usage.

Implementations are called while the store holds its write lock, so they must not block or call back into the store.

type Rekeyer

type Rekeyer interface {
	Rekeyed(oldID, newID string)
}

Rekeyer is optionally implemented by a Recorder that keeps per-session state, so that state follows a rename. Called under the store's write lock, once for every rename Rekey — the in-cluster A2A default → contextId merge — makes, and never for one it refused.

type SeqSeeder

type SeqSeeder interface {
	LastSeq(sessionID string) uint64
}

SeqSeeder is optionally implemented by a Recorder that keeps a session's events for longer than the store does — the session archive. When the store creates an entry it asks every SeqSeeder, under its write lock, for the last seq it holds under that id, and numbers the entry's events after the highest answer.

Without it a session re-created under the same id — after max_sessions evicted it, a ttl expired it, or the proxy restarted — numbers its events from 1 again, so one session would carry two events numbered 1: one on disk, one in memory. A pager walking ?before= across that point would loop.

LastSeq is called under the store's write lock, in front of live traffic: it must be a memory lookup, and must not block or call back into the store.

type SessionSummary

type SessionSummary struct {
	ID         string    `json:"id"`
	CreatedAt  time.Time `json:"createdAt"`
	UpdatedAt  time.Time `json:"updatedAt"`
	EventCount int       `json:"eventCount"`
	// Title names this session from its own events, absent when nothing in them named it.
	// Folded by Append; see entry.Title for the rule and titleFrom for the ranks.
	//
	// A SUGGESTION, NOT AN IDENTIFIER: derived from the events and nothing addresses a
	// session by it.
	//
	// FIRST-WINS, EXCEPT THAT A /rename ALWAYS OVERRIDES. Two consequences a client may rely
	// on, both the opposite of what this field promised while it was recomputed per call:
	// ordinary conversation does NOT re-title the session on every turn, and a /rename is not
	// lost when the event carrying it is evicted.
	//
	// omitempty on the standing rule CostMicros states below: an unknown value must not
	// render as a real one, so an absent key is what a client should expect for a session the
	// events never named.
	//
	// ABSENT IS A DISPLAYED STATE NOW, not just an unread one. agentop renders this in its TITLE
	// column as a FALLBACK: it prefers a title harvested from Claude Code's transcripts and
	// reaches for this one only when that harvest named nothing. So the sessions where this
	// field decides what an operator sees are exactly those with no transcript on the machine
	// running agentop — an agent that routes through the proxy without writing Claude Code
	// transcripts is the case that motivated it. Do not assume a change here is invisible.
	Title string `json:"title,omitempty"`
	// Agent is the client this session belongs to, as event.AgentLabel names it, which is the
	// label agent= matches: the affinity owner's when one claimed the session, else the first
	// recognised agent's, else — #1214 — the first UNRECOGNISED client's, which is its raw
	// User-Agent folded by model.AgentName. Absent for the default and pending buckets, which
	// are no one agent's, for a claimed session its owner has sent nothing into, and for a session
	// whose every event carried no User-Agent at all, since "unknown" is a reserved bucket rather
	// than a name (see model.EventClient.Label).
	//
	// NOT A STATEMENT THAT THE AGENT IS RECOGNISED, and a consumer that reads it as one is the
	// one thing this field's widening can surprise. model.IsKnownAgent(agent) still answers
	// correctly — that is what it exists for, and agentop's AGENTS pane uses it to pool every
	// label it rejects under one row — but presence alone no longer implies it. The alternative
	// was a session that nothing in the list could attribute to any program, which is what #1214
	// was filed about; a spoofable label is the same axis the usage ring and the ledger already
	// key on, never an identity.
	Agent       string `json:"agent,omitempty"`
	TotalTokens int    `json:"totalTokens,omitempty"` // sum of Inference.TotalTokens across response events
	// CostMicros is what this session's events cost, in millionths of a dollar, summed from
	// the records the session itself holds — where a session archive runs, including those from
	// before this entry.
	//
	// FROM THE EVENTS, not from the ledger, and that is the only honest source available: the
	// ledger's row key is (endpoint, model, agent, provenance) with no session dimension by
	// design, so it cannot answer "what did this session cost" at all. The live ring can, but
	// only over its rolling window, which would put a partial figure beside the LIFETIME
	// TotalTokens above and understate the row by whatever fell off the ring.
	//
	// SCOPED TO WHAT THE STORE STILL HOLDS, PLUS — WHERE A SESSION ARCHIVE RUNS — THE SESSION'S
	// HISTORY FROM BEFORE THIS ENTRY (see PriorKeeper). So with an archive it continues across a
	// restart, and without one it resets; a ledger window always continues. Both are correct:
	// this is "the cost of the events in this session", the ledger is "the cost of the day". A
	// client showing them together must not present one as a check on the other.
	//
	// Omitted when zero rather than sent as 0, on this codebase's standing rule that an
	// unknown cost must never render as $0.00: a session whose traffic nothing could price is
	// indistinguishable here from one that was free, so the field's absence lets a client show
	// "—" instead of asserting either.
	CostMicros int64 `json:"costMicros,omitempty"`
	// AvoidedMicros is cost this session did NOT incur, same unit, APPLIED savings only.
	//
	// NOT SPEND, and never to be added to CostMicros — see usage.Counts.AvoidedMicros and the
	// invariant on event.Event.Avoided. Reported beside it because the two answer
	// different questions about the same session.
	AvoidedMicros int64 `json:"avoidedMicros,omitempty"`
	// PenaltyMicros is what the operators behind AvoidedMicros caused on this session's
	// requests, same unit, basis "usd" only: usage.Counts.PenaltyMicros. Net saved is
	// AvoidedMicros minus PenaltyMicros, and may be negative.
	PenaltyMicros int64 `json:"penaltyMicros,omitempty"`
	// AvoidedUnits, PenaltyUnits, AvoidedAPIEquivalentMicros, AvoidedUnknownMicros,
	// PluginSpendMicros, PluginSpendUnits and PluginSpendUnknownMicros are the usage.Counts
	// fields of the same names, summed over this session's records (event.Event.Figures). Only
	// PluginSpendMicros is money; see usage.Counts. Absent rather than zero, like every figure.
	AvoidedUnits               int64 `json:"avoidedUnits,omitempty"`
	PenaltyUnits               int64 `json:"penaltyUnits,omitempty"`
	AvoidedAPIEquivalentMicros int64 `json:"avoidedApiEquivalentMicros,omitempty"`
	AvoidedUnknownMicros       int64 `json:"avoidedUnknownMicros,omitempty"`
	PluginSpendMicros          int64 `json:"pluginSpendMicros,omitempty"`
	PluginSpendUnits           int64 `json:"pluginSpendUnits,omitempty"`
	PluginSpendUnknownMicros   int64 `json:"pluginSpendUnknownMicros,omitempty"`
	// KeepAliveMicros, KeepAliveUnits, KeepAliveAPIEquivalentMicros and KeepAliveUnknownMicros
	// are the usage.Counts fields of the same names: what the context-guru keep-alive pings on
	// this session's threads cost, by basis. Only KeepAliveMicros is money. KeepAlivePings is how
	// many pings there were. A ping is not an event of the session (it is not agent activity, so
	// it is in no EventCount, TotalTokens or CostMicros, and does not refresh UpdatedAt): the
	// store adds these from core/accounting.Host's ping listener (Store.AddKeepAlive). They are
	// the resident entry's own: the session archive keeps events, and a ping is none, so a
	// session's pings from before a restart are not here.
	KeepAliveMicros              int64 `json:"keepAliveMicros,omitempty"`
	KeepAliveUnits               int64 `json:"keepAliveUnits,omitempty"`
	KeepAliveAPIEquivalentMicros int64 `json:"keepAliveApiEquivalentMicros,omitempty"`
	KeepAliveUnknownMicros       int64 `json:"keepAliveUnknownMicros,omitempty"`
	KeepAlivePings               int64 `json:"keepAlivePings,omitempty"`
	// InteractionMicros is usage.Counts.InteractionMicros summed over this session's records: the
	// value of the tokens no operator owns on its rescued requests. Money, basis "usd", signed.
	// In no operator's figure and not in AvoidedMicros; the session's net saving adds it.
	InteractionMicros int64 `json:"interactionMicros,omitempty"`
	// CostAPIEquivalentMicros and CostUnknownMicros are the usage.Counts fields of the same names:
	// what this session's requests on a subscription login cost at API rates, and what its
	// requests of unknown billing cost. Neither is money, and neither is in CostMicros.
	CostAPIEquivalentMicros int64 `json:"costApiEquivalentMicros,omitempty"`
	CostUnknownMicros       int64 `json:"costUnknownMicros,omitempty"`
	// Currencies names the units CostMicros and AvoidedMicros are in, sorted, dollars spelled
	// "USD" — and is ABSENT when every priced event was in dollars, which is every deployment
	// with no pricing unit configured, so those serve the bytes they always have.
	//
	// MORE THAN ONE ENTRY MEANS THE FIGURES ARE A CROSS-UNIT SUM and must not be rendered as a
	// single amount. They are still summed here rather than split, because the running totals
	// predate units and a client that ignores this field must keep reading what it always read;
	// splitting is the job of a surface that can show two figures. Follows the events through a
	// trim, like the totals themselves; see entry.units.
	Currencies []string `json:"currencies,omitempty"`
	// Saturated says the two figures above are FLOORS: an addition into one of them reached
	// the int64 ceiling and was clamped rather than allowed to wrap.
	//
	// It exists because the clamp on its own is not honest. MaxInt64 micros is about
	// $9.2 trillion, which renders as a perfectly well-formed dollar amount and is
	// indistinguishable from a measured one — "a clamped figure is a wrong number wearing a
	// right label", which is why pricing.MicrosFromUSD refuses an out-of-range figure
	// instead of clamping it. Here the sum cannot be refused (the money was really spent),
	// so the figure is clamped and this field is what makes that admissible.
	//
	// ONE FLAG FOR BOTH, on usage.Counts.Saturated's reasoning: it means "read every money
	// figure here as a bound", and a second flag for the same fact would let a client
	// believe one while the other contradicted it.
	//
	// Practically unreachable — it takes over a thousand maximal per-request figures in one
	// session — and carried anyway, because the alternative is a number no consumer can
	// tell apart from a real one.
	Saturated bool `json:"saturated,omitempty"`
	Active    bool `json:"active"` // true if this is the most recently updated session
	// PromptContext is how full this session's conversation got, by the rule in
	// model.PromptContextFold: the main-agent turn that RANKS HIGHEST under that rule's total
	// order, in prompt tokens. Where the client states its role that is the LATEST such turn;
	// where it does not it is the one with the MOST MESSAGES. See model.PromptContext, which is
	// this field's type and carries the order.
	//
	// NO MONOTONICITY IS PROMISED, and a client must not build on one: this figure can DECREASE
	// between two polls. A compaction is the ordinary case, not a corner — the stated arm leads
	// with arrival time, so a session reporting 830,000 before one reports 12,000 on the turn
	// after it. WHERE THE ROLE IS STATED that is what the column is for: an operator needs how full
	// the conversation is NOW rather than how full it has ever been. The unstated arm claims no such
	// thing — it ranks by message count, so it can legitimately hold a pre-compaction turn for the
	// rest of a session, which is the documented cost of having no role to read rather than a defect
	// (see model.PromptContextOf). So the figure decreases on one arm and goes stale on the
	// other, and neither is a guarantee to build on.
	//
	// RETENTION-INDEPENDENT ALL THE SAME — unlike TotalTokens and CostMicros above, and the
	// asymmetry is deliberate rather than an inconsistency. Those are sums over the events the
	// store still holds (plus, where a session archive runs, the session's history from before
	// this entry), so a trim sheds exactly what left the slice, which is why CostMicros can
	// honestly call itself the cost of the events in this session. This is an extremum under a
	// total order: nothing about it is accumulated, so a trim has nothing to subtract from it and
	// it outlives the events it was read from. Recomputing it over the survivors would not
	// understate by a known amount the way that sum does — it would report a small conversation
	// for a session whose conversation is large and merely aged out of the store. A client showing
	// the three on one row must not present any of them as a check on another.
	//
	// A POINTER SO ABSENT AND ZERO STAY APART, which is the same standing rule CostMicros states
	// for its omitempty: an unknown figure must never render as a real one. A session with only
	// one-shot completions has no conversation to measure and is indistinguishable here from one
	// nobody observed; both must reach a client as an absent field so it can draw an em dash.
	//
	// CONTINUES ACROSS A RESTART WHERE A SESSION ARCHIVE RUNS, like CostMicros, and resets where
	// none does, because the store is in-memory per-pod. A client that has been watching longer
	// than this proxy has been up may hold a larger figure legitimately — see
	// model.MergePromptContext, which is how the two combine.
	PromptContext *model.PromptContext `json:"promptContext,omitempty"`

	// InferenceHost is where this session's inference traffic goes: the host of its most recent
	// request that carried an inference parse, as the event recorded it. After a redirect that is
	// the server it was sent to, whether or not that server answered, and not the host the client
	// named (see SessionEvent.RequestedHost).
	// Absent for a session with no inference traffic — and for one resumed from an archive written
	// before this field existed, until its next inference request, where absent means unknown:
	// that history was folded without it (see foldJSON.InferenceHost).
	//
	// LATEST WINS, AND ONLY AN INFERENCE REQUEST MOVES IT. A CONNECT tunnel row, an MCP call, any
	// response or a denial leaves it where it was: live traffic interleaves those between turns,
	// and a field they cleared would read "no inference traffic" on a session that has plenty. A
	// denial carries its request's parse but went nowhere, so its host is not where anything goes.
	//
	// GENERIC, NOT THE ROUTER'S: it says where a session's inference goes with or without the
	// inference-router. agentop names a session's server from it, which is why the router refuses
	// two servers on one host. A host[:port] as the request carried it.
	//
	// CONTINUES ACROSS A RESTART WHERE A SESSION ARCHIVE RUNS, like Title: the archive's fold
	// persists it, and a resumed session reports it until its own next inference request.
	InferenceHost string `json:"inferenceHost,omitempty"`

	// InferenceServer is the server name from the routed invocation of the request that set
	// InferenceHost (model.RoutedServer), and "" when that request was not routed. It moves with
	// InferenceHost, and InferenceHostFromHistory covers it too.
	InferenceServer model.LenientString `json:"inferenceServer,omitempty"`

	// InferenceKeyOf is the name of the server whose key the request that set InferenceHost
	// sent (model.RoutedKeyOf), and "" when that key matched no server. It moves with
	// InferenceHost, and InferenceHostFromHistory covers it too. It never holds a key.
	InferenceKeyOf model.LenientString `json:"inferenceKeyOf,omitempty"`

	// InferenceHostFromHistory is true when InferenceHost came from the session's history before
	// this store entry — the archive's fold — because no request the entry holds has set it: a
	// session resumed after a restart, or re-created after an eviction, that has sent no inference
	// request since. Absent otherwise, and on a row only the archive holds (Resident false), all of
	// whose figures are history.
	//
	// WHAT IT TELLS A CLIENT: the host is the archive's word, from before this process, and not a
	// request this process saw. Whether something still holds the session there is the router's
	// business: on a local install it keeps its pins in the plugin store, which a restart keeps, and
	// agentop counts such a session as staying; a process with no plugin store keeps them in memory
	// and forgets them on restart. InferenceHost itself is unchanged by this: it still says where
	// the session's inference last went.
	InferenceHostFromHistory bool `json:"inferenceHostFromHistory,omitempty"`

	// Resident is false on a row the session archive served because the store no longer holds
	// the session (GET /v1/sessions?archived=true), and absent otherwise. A POINTER because
	// omitempty on a bool drops exactly the false the wire needs; absent then means "resident",
	// so a client reading a proxy that predates the archive sees every row as it always did.
	Resident *bool `json:"resident,omitempty"`

	// Procs are the processes that named this session through their own session header,
	// "<pid>.<start>", sorted. Absent when none did, and on a summary from before the field.
	Procs []string `json:"procs,omitempty"`
	// Projects are the distinct project labels of this session's events (model.SessionEvent.RollupProject),
	// most recent first, at most maxSessionProjects. Absent when none had one, and on the default
	// and pending buckets.
	Projects []string `json:"projects,omitempty"`
	// ParentSession is the topmost session above this session's agent: the first
	// non-empty model.SessionEvent.ParentSession. Absent on default and on pending buckets.
	ParentSession model.LenientString `json:"parentSession,omitempty"`
	// LastRequestAt is the time of the newest request this session holds, zero when it holds
	// none. On a pending bucket it is what Link compares with a process's claims.
	LastRequestAt time.Time `json:"lastRequestAt,omitzero"`
	// Source is "imported:<agent>" while every event of the session is imported, and ""
	// otherwise. Only the archive's fold sets it: store entries are live.
	Source string `json:"source,omitempty"`
	// NoRecord is true when the session asked not to be recorded (#1923): the archive keeps none
	// of its events from then on, and what it held before stays. A session with nothing before
	// is only a marker that it opted out. A live session shows it from its first flagged request,
	// and after a restart from the archive's mark.
	NoRecord bool `json:"noRecord,omitempty"`
	// LinkedTo, on a pending bucket, is the sessions its process named that OwnerAt gives a
	// call of the bucket, each with the span of its naming requests (Link says how close that
	// is); LinkedAll says every request in the bucket falls before one of them. Set by Link when
	// the list is read, never stored. agentop folds a fully linked bucket that links to one
	// session into it and lists any other as its own row.
	LinkedTo  []PendingLink `json:"linkedTo,omitempty"`
	LinkedAll bool          `json:"linkedAll,omitempty"`
	// contains filtered or unexported fields
}

SessionSummary is a per-session view for list endpoints: counters, money figures and timestamps rather than the event backlog.

"METADATA-ONLY" WOULD NOW BE WRONG, and the phrase used to be here: Title carries up to maxTitleLen runes of VERBATIM USER PROMPT. This is not a new exposure — /v1/sessions/{id} returns whole request and response bodies on the same unauthenticated listener, which the session API documents as its trust model — but a reader deciding how this endpoint may be exposed should not be told by this comment that no content reaches it. Note in particular core/config/config.go's tls_bridge guard, which forces the session API to loopback on the rationale that it "may carry decrypted request/response bodies": that guard keys off the bridge, not off this field, and nothing here should be read as having considered whether it wants widening.

func Link(list []SessionSummary) []SessionSummary

Link marks every pending bucket in list whose calls a process made before naming a session: LinkedTo is the sessions OwnerAt gives some instant between the bucket's first and last request, ordered by First, and LinkedAll says every request in the bucket has an owner (OwnerAt), which holds when the newest request is no later than some link's Last. It is how a process's pre-session calls reach their session now that nothing renames a bucket into one: computed from what is recorded, each time the list is read, so it survives a restart and needs no merge. A response goes where its request went, which is why the bucket's figure is its newest REQUEST (LastRequestAt).

Only a per-process bucket links. The agent-wide pending:<agent> — a client the lookup could not name — and the default bucket carry no process, and linking them would be a guess.

list is modified in place and returned. O(sessions × procs); called once per list request.

func (SessionSummary) ProcSpans

func (s SessionSummary) ProcSpans() map[string]ProcSpan

ProcSpans is a copy of the span of each process in Procs, nil when none named the session.

type Store

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

Store is an in-memory, per-pod session store. It is safe for concurrent use.

func New

func New(ttl time.Duration, maxEvents int, maxSessions int, opts ...Option) *Store

New creates a Store with the given TTL, per-session event limit, and max concurrent sessions. maxEvents <= 0 keeps every event a session produces, which is what the binaries pass unless session.max_events is configured; maxSessions <= 0 likewise keeps every session. A background goroutine runs cleanup every TTL/2. Call Close() during graceful shutdown to stop the background goroutine.

func (*Store) ActiveSession

func (s *Store) ActiveSession() string

ActiveSession returns the most recently updated session ID. Used for outbound correlation when no explicit session ID is available.

func (*Store) AddDetachedSpend

func (s *Store) AddDetachedSpend(sessionID string, f event.Figures)

AddDetachedSpend adds a detached model call's spend to sessionID's totals: only the PluginSpend* fields of f, which is the call's event.Figures. A detached call finished after the request it served was accounted (core/accounting.Host.LateOps), so it is not an event and is not agent activity: it neither creates a session nor makes one active. An unknown sessionID is ignored.

func (*Store) AddKeepAlive

func (s *Store) AddKeepAlive(sessionID string, f event.Figures)

AddKeepAlive adds one context-guru keep-alive ping's spend to sessionID's totals: SessionSummary.KeepAlive*. Only the KeepAlive* fields of f are read. A ping is NOT AN EVENT OF THE SESSION: it is not agent activity, so this appends nothing, publishes nothing, reaches no Recorder (core/accounting.Host writes the ping to the cost recorders itself) and leaves UpdatedAt and the active session alone — refreshing them would keep an idle session alive on its own pings, the idle the keeper measures. A session the store does not hold (expired, evicted, never seen) is not created for a ping: the spend is dropped here and stays in the ledger and /v1/usage.

func (*Store) AddRecorder

func (s *Store) AddRecorder(r Recorder)

AddRecorder registers a Recorder. Safe at any time: every reader of the list holds the store's lock, and so does this. A recorder added late misses the events before it.

func (*Store) Append

func (s *Store) Append(sessionID string, event model.SessionEvent)

Append adds an event to the named session. Creates the session if it doesn't exist. Updates activeID to this session. Evicts the oldest event if the session exceeds maxEvents — which by default it cannot, maxEvents being unset.

func (*Store) AppendBucket

func (s *Store) AppendBucket(sessionID string, event model.SessionEvent) *Bucket

AppendBucket is Append, returning the bucket the event went into.

func (*Store) AppendCapture

func (s *Store) AppendCapture(sessionID string, event model.SessionEvent, c *model.RequestCapture)

AppendCapture is Append for a request event with its capture c, which only a CaptureRecorder receives.

func (*Store) AppendPair

func (s *Store) AppendPair(sessionID string, first, second model.SessionEvent) *Bucket

AppendPair appends first and then second to the named session under one lock acquisition, so no concurrent append can land between them, and returns the bucket both went into. agentop folds a bridged tunnel's open row into the event directly after it in the session, and two separate appends could be split by any traffic in between.

func (*Store) AppendPairCapture

func (s *Store) AppendPairCapture(sessionID string, first, second model.SessionEvent, c *model.RequestCapture) *Bucket

AppendPairCapture is AppendPair with second's capture c; see AppendCapture.

func (*Store) AppendTrailing

func (s *Store) AppendTrailing(b *Bucket, event model.SessionEvent) bool

AppendTrailing appends an event that ends something b's session started earlier — a tunnel's close, recorded when the tunnel ends. It is not that session speaking now, so it neither makes the session active nor refreshes its UpdatedAt. It reports false, and records nothing, when b's session has been evicted or has expired: the event would pair with nothing, and re-creating the session to hold it could evict another.

func (*Store) Cleanup

func (s *Store) Cleanup()

Cleanup removes expired sessions. Safe for concurrent use.

func (*Store) Clear

func (s *Store) Clear() int

Clear removes every session and the active-session mark, tells every Clearer, and reports how many sessions it removed. The next append to any id starts a new session, numbered from 1 once the archive has reset.

Subscribers stay attached: a clear erases history, it does not end the stream.

func (*Store) Close

func (s *Store) Close()

Close stops the background cleanup goroutine and closes every subscriber's channel so consumers unblock cleanly on shutdown. Safe to call multiple times.

func (*Store) Delete

func (s *Store) Delete(sessionID string) bool

Delete removes one session — its entry, owner and adoption records, and the active-session mark if it holds it — tells every Deleter, and reports whether memory held it.

THE DELETERS ARE TOLD EVEN WHEN MEMORY DID NOT HOLD THE ID. The archive keeps sessions the store has evicted, and startup replays the archive into the usage ring, so either can hold a session alone; a delete that skipped them would leave it listed.

Memory is touched only when it holds the id. An adopted pending id has no entry but still has its adoption, which redirects the response in flight at adoption time (followAdoptedLocked); dropping it would let that response re-create the pending bucket as a stray row.

Process claims stay, as eviction leaves them: resolution ignores a claim on an id that is not live (see newestClaimLocked). The next append to the id starts a new session.

func (*Store) DeleteAndWithhold

func (s *Store) DeleteAndWithhold(sessionID string) bool

DeleteAndWithhold erases one session as Delete does, and keeps it out of the archive from then on (#1923, mid-session): the person at the machine asked to stop recording it and to erase what it holds. It reports whether memory held it.

ONE STEP UNDER THE STORE'S WRITE LOCK. Every Deleter is told, then every Withholder (the archive). A delete removes the archive's opt-out mark, so the withhold must come after it, and nothing in between: an append takes the same lock, so no row of the session can reach the archive between the erase and the mark. The archive queues the two in that order (a withhold that finds the queue full is kept at its place, after the delete: optOutLocked).

No own-session check, unlike the X-Cortex-Record header: that header is client-asserted, so a request may only withhold its own session from then on. This is the erase's own route, behind its guards (sessionapi.clearRefusal), for the local user who may already erase any session.

A conversation's id only, as MarkNoRecord: the default and pending buckets hold other clients' calls. For any other id it is Delete.

func (*Store) ListSessions

func (s *Store) ListSessions() []SessionSummary

ListSessions returns summaries for every non-expired session. Order is UpdatedAt descending (most recent first). Safe for concurrent use.

func (*Store) MarkNoRecord

func (s *Store) MarkNoRecord(sessionID string)

MarkNoRecord withholds sessionID from the archive from now on (#1923), for a request whose rows the listener does not build itself: in praxis mode the gateway records a hopped request, and its rows come back through /v1/ingest without the flag, the header having been stripped before the hop. It tells every Withholder (the archive), whose mark is the opt-out's only state, and marks the live entry's summary when there is one. Call it before the request is hopped: the archive's op then precedes every row that comes back.

The caller must have checked pipeline.Context.WithholdsSession: the request named sessionID with its own session-id header. Never for a fallback bucket.

func (*Store) Rekey

func (s *Store) Rekey(oldID, newID string)

Rekey renames a session from oldID to newID, preserving all events. Used to merge the bootstrap "default" session into the server-assigned contextId after the backend response reveals it, so events recorded during the request phase (under "default") and subsequent turns (under the real contextId) land in the same bucket.

Safe to call when oldID does not exist (no-op) or newID already exists (no-op — preserves the existing newID entry). If oldID was the active session, activeID is updated to newID.

Assumes single-tenant, no concurrent conversations per pod. In a multi-tenant deployment two in-flight first-turn requests could both land under "default"; rekeying the first to arrive would strand the second's events. Call sites are expected to guard against that.

func (*Store) StreamBytes

func (s *Store) StreamBytes(requestID string) (int64, bool)

StreamBytes returns the live byte count of the open response with requestID. It returns false when no open response has that ID.

func (*Store) Subscribe

func (s *Store) Subscribe() (*Subscription, func())

Subscribe registers a listener for session events written after the call. The returned channel is buffered (64). Events are sent non-blockingly; if the consumer falls behind, events are dropped — the caller can observe the drop count via the returned Subscription's Drops method. Always call the cancel func to remove the subscriber and close the channel.

func (*Store) TakesCaptures

func (s *Store) TakesCaptures() bool

TakesCaptures reports whether some recorder is a CaptureRecorder, so a listener can skip copying bodies nobody keeps. False on a nil store.

func (*Store) TrackStream

func (s *Store) TrackStream(requestID string, n *int64) (untrack func())

TrackStream records n as the live byte counter of the open response with requestID. The writer of n must use atomic operations. Call untrack when the response ends. untrack removes the entry only if it still holds n, so a newer TrackStream with the same requestID stays.

func (*Store) View

func (s *Store) View(sessionID string) *model.SessionView

View returns a read-only snapshot of the session's events. Returns nil if the session doesn't exist or is expired.

func (*Store) ViewFacts

func (s *Store) ViewFacts(sessionID string) (*model.SessionView, model.SessionFacts)

ViewFacts is View and the session's facts, read under one lock, so the two agree. Each present fact's Event points into the returned view, as SessionView.LastIntent does. When View returns nil (no entry, or an expired one), the view is nil and both facts are FactNone.

The InferenceHosts table is a copy:

  • With an entry numbered after earlier history: the HostsKeeper's table now, merged with the entry's own. HostsKnown is the keeper's.
  • With an entry and no earlier history: the entry's own table. HostsKnown is true.
  • With no entry: the keeper's table over every event it holds under the id.
  • With no keeper: the entry's own table, or none. HostsKnown is false when a SeqSeeder holds history for the id.

THE KEEPER IS READ NOW, NOT WHEN THE ENTRY WAS CREATED. The history's last events can still be in the archive's queue when the entry is created (an eviction, then the next request), and a read now has them once the writer writes them. Prior is not used: it answers only after the writer takes the entry's first event.

func (*Store) ViewPage

func (s *Store) ViewPage(sessionID string, before uint64, limit int) *model.SessionView

ViewPage returns up to limit events ending just BEFORE the given Seq — the page older than a cursor the caller already holds.

It is what makes the whole store readable. ViewTail can only ever return the most recent events, capped by what one response is willing to carry, so on a long session every event before that window was unreachable through any API: a laptop session held 2119 events where nothing could read past the most recent 2000, while the oldest events still cost memory. Paging backward from the tail reaches all of them without any single response growing.

The cursor is a Seq rather than an offset because offsets do not survive eviction: a FIFO trim between two requests shifts every index, so a client would silently skip or repeat a page. Seq survives that trim, and the events a session holds are ascending in Seq (see trimEventsPinIntent), so the boundary is a binary search.

What Seq does NOT survive is the session itself being evicted and re-created under the same id, which restarts the numbering — see entry.nextSeq. A cursor from the previous incarnation is then above everything held, and this function answers with the tail, because from here every event held does precede that cursor. That is deliberate rather than defensive: the store cannot distinguish the two cases, so the client compares timestamps instead of trusting the ordering it gets back.

before == 0 means "from the newest", making ViewPage(id, 0, n) equivalent to ViewTail(id, n) — a client can then page with one code path rather than special-casing its first request. limit <= 0 is treated as 1, as in ViewTail.

TotalEvents and OldestSeq are set on the same terms as ViewTail: only when this page is not the whole session, so a caller can tell "this is the beginning" from "there is more behind me" without a second request.

func (*Store) ViewTail

func (s *Store) ViewTail(sessionID string, limit int) *model.SessionView

ViewTail returns the most recent limit events of a session, and reports how many the session holds in total.

It exists because View copies every event a session has, and with max_events unset that is unbounded: one session reached 5078 events, whose JSON encoding is 1.1GB and takes 17s to write on loopback. The only consumer of that response is a TUI with a 10s client timeout, so the whole of it was spent producing bytes nobody received.

limit <= 0 is treated as 1, not as "unlimited": an accidental zero from a caller that forgot to set it should return a small answer, not the largest one the store can produce. Callers that genuinely want everything call View.

TotalEvents and OldestSeq on the returned view are set only when events were left out, so a tail that happens to cover the whole session is byte-identical to what View produces. Use ViewPage to reach the events a tail leaves behind. The tail IS the newest page, so this delegates rather than repeating the slicing and the two-field bookkeeping — which were identical in both, and are the part a later change would update in one place and not the other.

type Subscription

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

Subscription is the consumer-facing handle returned by Store.Subscribe.

func (*Subscription) Drops

func (s *Subscription) Drops() uint64

Drops returns the cumulative event drops due to a full channel.

func (*Subscription) Events

func (s *Subscription) Events() <-chan model.SessionEvent

Events returns the receive-only channel of session events.

type SummaryFold

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

SummaryFold is ListSessions' per-session figures folded one event at a time and never shed: the session archive's running summary for a session the store may no longer hold.

It uses the store's own rules — moneyOf through prepareAppend, sumTokens' response-only token rule, applyTitle, applyAgent, and entry.context's CTX fold — so a fold over an untrimmed session's events reports what ListSessions does. TestSummaryFold_AgreesWithListSessions holds that.

ONE DIFFERENCE IS INHERENT: Agent is the first recognised agent's label (else the first unrecognised client's), while the store prefers the label of the agent that CLAIMED the session, which only the store knows. A resident session's row therefore always comes from the store, which adds the archive's fold of the history before its entry (PriorKeeper).

The zero value is not ready — rankRename is 0, so a zero titleRank would claim the session had been renamed. Use NewSummaryFold. Not safe for concurrent use.

func NewSummaryFold

func NewSummaryFold() *SummaryFold

NewSummaryFold returns an empty fold.

func (*SummaryFold) Add

func (f *SummaryFold) Add(sessionID string, e *model.SessionEvent)

Add folds one event recorded under sessionID. It does the work appendLocked hoists above the store's lock — a plugin-map decode and a scan of message content — so call it from a goroutine of your own, never from Record.

func (*SummaryFold) Clone

func (f *SummaryFold) Clone() *SummaryFold

Clone returns a copy of f that later Adds to either do not reach.

func (*SummaryFold) ForgetInferenceHosts

func (f *SummaryFold) ForgetInferenceHosts()

ForgetInferenceHosts marks the fold's InferenceHosts table unknown, for a fold that holds events of more than one session entry: the archive moves such a fold to a new id when it cannot tell the entry's events from the history's. Unknown is sticky, as after a decode.

func (*SummaryFold) InferenceHosts

func (f *SummaryFold) InferenceHosts() (model.InferenceHosts, bool)

InferenceHosts is a copy of the fold's table, and false when the fold holds history it has no table for.

func (*SummaryFold) MarkNoRecord

func (f *SummaryFold) MarkNoRecord()

MarkNoRecord marks the session as not recorded without folding an event, for the archive's content-free marker of an opted-out session (#1923).

func (*SummaryFold) MarshalJSON

func (f *SummaryFold) MarshalJSON() ([]byte, error)

MarshalJSON persists the fold's whole state, not just its Summary: resuming needs the title rank and each currency's count, which a summary does not carry.

func (*SummaryFold) NoRecord

func (f *SummaryFold) NoRecord() bool

NoRecord reports whether the session asked not to be recorded; see SummaryFold.noRecord.

func (*SummaryFold) Summary

func (f *SummaryFold) Summary(sessionID string) SessionSummary

Summary sets EventCount, Title, Agent, TotalTokens, CostMicros, AvoidedMicros, Currencies, Saturated, PromptContext and InferenceHost on a SessionSummary for sessionID, and nothing else: the timestamps and the live-only fields (Active, Adopted) are the caller's.

func (*SummaryFold) UnmarshalJSON

func (f *SummaryFold) UnmarshalJSON(b []byte) error

UnmarshalJSON restores a fold MarshalJSON wrote; a missing titleRank is rankNone.

type Withholder

type Withholder interface {
	Withhold(sessionID string)
}

Withholder is optionally implemented by a Recorder that keeps a session's events (the session archive): Withhold tells it, from now on, to keep none of sessionID's (#1923). Called under the store's write lock. It may wait for its own writer, never for the store.

Directories

Path Synopsis
Package archive persists sessions to disk so they survive a restart and the store's own eviction, and so agentop can browse them afterwards.
Package archive persists sessions to disk so they survive a restart and the store's own eviction, and so agentop can browse them afterwards.
Package importer writes sessions from an agent's own transcripts on disk into the session archive and the cost ledger, as sessions with the imported mark.
Package importer writes sessions from an agent's own transcripts on disk into the session archive and the cost ledger, as sessions with the imported mark.
bob
Package bob is the importer source for Bob (Bob Shell and Bob IDE).
Package bob is the importer source for Bob (Bob Shell and Bob IDE).
claude
Package claude is the importer source for Claude Code.
Package claude is the importer source for Claude Code.
codex
Package codex is the importer source for Codex.
Package codex is the importer source for Codex.
opencode
Package opencode is the importer source for OpenCode.
Package opencode is the importer source for OpenCode.
pi
Package pi is the importer source for Pi (pi.dev).
Package pi is the importer source for Pi (pi.dev).
sqlitecli
Package sqlitecli reads a SQLite database through the sqlite3 program, so that no module links a SQLite driver.
Package sqlitecli reads a SQLite database through the sqlite3 program, so that no module links a SQLite driver.
Package timeline turns one session's events into spans on a time axis: which Claude Code agent was generating, which tool it was running, when a subagent was spawned and when its result came back, and which hosts the session talked to.
Package timeline turns one session's events into spans on a time axis: which Claude Code agent was generating, which tool it was running, when a subagent was spawned and when its result came back, and which hosts the session talked to.
Package toolpair pairs a session's tool calls with their results.
Package toolpair pairs a session's tool calls with their results.

Jump to

Keyboard shortcuts

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