session

package
v8.0.13 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: MIT Imports: 18 Imported by: 4

Documentation

Overview

Package session derives stable conversation identities from protocol request roots.

Package session derives stable conversation identities and extracts hierarchical session relationships.

Index

Constants

This section is empty.

Variables

View Source
var CandidateSessionPrefixes = []string{
	"lcp:v1:", "lcp:",
	"codex:", "claude:", "header:", "session:",
	"affinity:", "slot:", "task:", "conv:",
	"thread:", "clientreq:", "geminicache:",
	"pck:", "user:", "execution:", "agy:", "derived:",
}

CandidateSessionPrefixes lists recognized protocol-specific session prefixes used in affinity lookup and routing.

Functions

func BoundSessionIdentity

func BoundSessionIdentity(id string) string

BoundSessionIdentity bounds an identifier to <= 256 bytes safely, preserving uniqueness via SHA256 and guarding against splitting multibyte UTF-8 characters.

func CallerScope

func CallerScope(value string) string

CallerScope returns an irreversible namespace for a downstream caller credential.

func ClaudeMetadataIdentities

func ClaudeMetadataIdentities(payload []byte) (sessionID, parentSessionID, agentID string)

ClaudeMetadataIdentities extracts session_id, parent_session_id, and agent_id from Claude user_id metadata.

func ClaudeMetadataParentSessionID

func ClaudeMetadataParentSessionID(payload []byte) string

ClaudeMetadataParentSessionID extracts parent_session_id from Claude user_id metadata if present.

func ClaudeMetadataSessionID

func ClaudeMetadataSessionID(payload []byte) string

ClaudeMetadataSessionID extracts the explicit Claude Code session from current JSON metadata or the legacy user_id suffix before bounding the surrounding metadata container.

func DeriveID

func DeriveID(format sdktranslator.Format, payload []byte, callerScope string) string

DeriveID builds a stable identity from leading instructions and the first complete user input.

func DerivedID

func DerivedID(metadata map[string]any) string

DerivedID returns a derived session identity stored in execution metadata.

func Enrich

Enrich derives a session identity once and places it in both request and option metadata. When opts.OriginalRequest is unset, it shares req.Payload as the read-only original request baseline to avoid multi-megabyte allocations on large payloads. Callers that mutate req.Payload in-place after Enrich must explicitly provide an independent opts.OriginalRequest.

func EnvironmentDigest

func EnvironmentDigest(turns []CanonicalTurn) string

EnvironmentDigest computes a deterministic SHA-256 digest across all system and developer turns in a conversation.

func FastTurnFingerprint

func FastTurnFingerprint(turn CanonicalTurn) string

FastTurnFingerprint returns a deterministic, bounded fingerprint for one turn. Values larger than 16 KiB are represented by a 12 KiB head/middle/tail sample and full digest.

func NormalizeExplicitID

func NormalizeExplicitID(raw string) string

NormalizeExplicitID validates an explicit client-provided session identifier. It preserves opaque printable values while rejecting oversized or control-bearing IDs.

func NormalizeToCanonicalUUID

func NormalizeToCanonicalUUID(rawID string) string

NormalizeToCanonicalUUID deterministically normalizes any session identifier to a canonical 36-character lowercase UUID (RFC 4122 / RFC 9562 compliant):

  1. If rawID (or rawID without known protocol prefix) is already a standard UUID (e.g. Codex UUIDv7, Claude UUIDv4, Header UUID), it strips the prefix and returns the lowercase UUID.
  2. If rawID has known protocol prefixes, they are stripped iteratively (supporting chained wrappers such as "derived:ctx:v1:"). If no identifier remains after stripping, it returns empty.
  3. If rawID is not a standard UUID (e.g. LCP 64-hex hash, subagent hierarchy, or custom string), it deterministically projects it to an RFC 9562 UUIDv8 using SHA-256 with domain separation.
  4. Idempotent: NormalizeToCanonicalUUID(NormalizeToCanonicalUUID(x)) == NormalizeToCanonicalUUID(x).

Types

type CanonicalPart

type CanonicalPart struct {
	Kind         string `json:"kind"`
	MIME         string `json:"mime,omitempty"`
	Value        string `json:"value"`
	Digest       string `json:"digest,omitempty"`
	OriginalSize int    `json:"original_size,omitempty"`
	Sampled      bool   `json:"sampled,omitempty"`
}

CanonicalPart is a normalized logical part of a conversation turn. Large values are represented by a bounded sparse sample and retain their original size.

type CanonicalTurn

type CanonicalTurn struct {
	Role  string          `json:"role"`
	Parts []CanonicalPart `json:"parts"`
}

CanonicalTurn is a protocol-independent conversation turn.

func ExtractCanonicalTurns

func ExtractCanonicalTurns(format sdktranslator.Format, payload []byte) []CanonicalTurn

ExtractCanonicalTurns extracts all logical turns from the five supported inbound protocols. Invalid or empty payloads return an empty slice.

type InMemorySessionTreeStore

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

InMemorySessionTreeStore is a backward-compatible in-memory session tree stub. Deprecated: Standalone CPA nodes use flat KV session cache (SessionCache). Full hierarchical session tree management and global aggregation are handled by Home.

func NewInMemorySessionTreeStore

func NewInMemorySessionTreeStore(maxNodes int, ttl time.Duration) *InMemorySessionTreeStore

NewInMemorySessionTreeStore creates a new in-memory session tree store stub. Deprecated: Standalone CPA nodes use flat KV session cache.

func (*InMemorySessionTreeStore) Ancestors

func (s *InMemorySessionTreeStore) Ancestors(sessionID string) []string

Ancestors returns ancestor session IDs. Deprecated: Session tree management has moved to Home.

func (*InMemorySessionTreeStore) Clear

func (s *InMemorySessionTreeStore) Clear()

Clear flushes all nodes. Deprecated: Session tree management has moved to Home.

func (*InMemorySessionTreeStore) GetNode

func (s *InMemorySessionTreeStore) GetNode(sessionID string) (*SessionTreeNode, bool)

GetNode returns a recorded node. Deprecated: Session tree management has moved to Home.

func (*InMemorySessionTreeStore) GetSubtree

func (s *InMemorySessionTreeStore) GetSubtree(sessionID string) []*SessionTreeNode

GetSubtree returns subtree rooted at sessionID. Deprecated: Session tree management has moved to Home.

func (*InMemorySessionTreeStore) GetTree

func (s *InMemorySessionTreeStore) GetTree(rootSessionID string) []*SessionTreeNode

GetTree returns nodes under rootSessionID. Deprecated: Session tree management has moved to Home.

func (*InMemorySessionTreeStore) Len

func (s *InMemorySessionTreeStore) Len() int

Len returns the number of nodes. Deprecated: Session tree management has moved to Home.

func (*InMemorySessionTreeStore) RecordNode

RecordNode records a session tree node stub. Deprecated: Session tree management has moved to Home.

func (*InMemorySessionTreeStore) UpdateAffinity

func (s *InMemorySessionTreeStore) UpdateAffinity(sessionID, authID, provider, model string) bool

UpdateAffinity updates the latest successful upstream binding. Deprecated: Session tree management has moved to Home.

type MerklePrefixBindResult

type MerklePrefixBindResult struct {
	SessionID       string
	ParentSessionID string
	IsFork          bool
	IsCompaction    bool
	NodeKind        string
	AccessNumber    uint64
}

MerklePrefixBindResult describes the session identities produced by binding an LCP sequence.

type MerklePrefixMatch

type MerklePrefixMatch struct {
	AuthID          string
	SessionID       string
	ParentSessionID string
	PrefixLength    int
	IsFork          bool
	IsCompaction    bool
	NodeKind        string
	AccessNumber    uint64
}

MerklePrefixMatch describes the best known affinity match for a request.

type MerklePrefixMatcher

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

MerklePrefixMatcher stores rolling Merkle prefixes and their selected auth bindings. It ignores prefixes that contain only system instructions, because a shared system prompt is not enough evidence that two requests belong to the same conversation. It is safe for concurrent use and has no background goroutine.

func NewMerklePrefixMatcher

func NewMerklePrefixMatcher(ttl time.Duration) *MerklePrefixMatcher

NewMerklePrefixMatcher creates a bounded matcher with a one-hour default TTL.

func NewMerklePrefixMatcherWithConfig

func NewMerklePrefixMatcherWithConfig(cfg MerklePrefixMatcherConfig) *MerklePrefixMatcher

NewMerklePrefixMatcherWithConfig creates a matcher with explicit resource bounds.

func (*MerklePrefixMatcher) Bind

func (m *MerklePrefixMatcher) Bind(namespace string, turns []CanonicalTurn, authID string) string

Bind records a request sequence for an auth and returns its stable LCP session identity.

func (*MerklePrefixMatcher) BindFingerprints

func (m *MerklePrefixMatcher) BindFingerprints(namespace string, fingerprints []string, minPrefixLength int, authID string) string

BindFingerprints records a precomputed request sequence for an auth.

func (*MerklePrefixMatcher) BindFingerprintsWithContext

func (m *MerklePrefixMatcher) BindFingerprintsWithContext(namespace string, fingerprints, tailFingerprints []string, envDigest string, minPrefixLength int, authID string) MerklePrefixBindResult

BindFingerprintsWithContext records a precomputed request sequence for an auth with explicit tail and environment context.

func (*MerklePrefixMatcher) BindFingerprintsWithResult

func (m *MerklePrefixMatcher) BindFingerprintsWithResult(namespace string, fingerprints []string, minPrefixLength int, authID string) MerklePrefixBindResult

BindFingerprintsWithResult records a precomputed request sequence for an auth and returns detailed session identities.

func (*MerklePrefixMatcher) BindWithResult

func (m *MerklePrefixMatcher) BindWithResult(namespace string, turns []CanonicalTurn, authID string) MerklePrefixBindResult

BindWithResult records a request sequence for an auth and returns detailed session identities.

func (*MerklePrefixMatcher) Clear

func (m *MerklePrefixMatcher) Clear()

Clear removes all remembered prefix bindings.

func (*MerklePrefixMatcher) InvalidateAuth

func (m *MerklePrefixMatcher) InvalidateAuth(authID string)

InvalidateAuth removes every LCP binding owned by authID.

func (*MerklePrefixMatcher) LookupSession

func (m *MerklePrefixMatcher) LookupSession(sessionID string) (authIDs []string, namespace string, ok bool)

LookupSession observes the bound authIDs for an LCP sessionID without side effects or TTL refresh. It skips expired groups and cleans them up, returning all distinct active authIDs.

func (*MerklePrefixMatcher) Match

func (m *MerklePrefixMatcher) Match(namespace string, turns []CanonicalTurn) (MerklePrefixMatch, bool)

Match returns the longest known prefix match for a request namespace.

func (*MerklePrefixMatcher) MatchFingerprints

func (m *MerklePrefixMatcher) MatchFingerprints(namespace string, fingerprints []string, minPrefixLength int) (MerklePrefixMatch, bool)

MatchFingerprints returns the longest known prefix match without reparsing turns.

func (*MerklePrefixMatcher) MatchFingerprintsWithContext

func (m *MerklePrefixMatcher) MatchFingerprintsWithContext(namespace string, fingerprints, tailFingerprints []string, envDigest string, minPrefixLength int) (MerklePrefixMatch, bool)

MatchFingerprintsWithContext returns the longest known prefix match or compaction continuation with explicit tail and environment context.

func (*MerklePrefixMatcher) Prepare

func (m *MerklePrefixMatcher) Prepare(turns []CanonicalTurn) ([]string, int)

Prepare returns bounded turn fingerprints and the first eligible prefix boundary. The returned fingerprints can be retained in request-scoped metadata.

func (*MerklePrefixMatcher) PrepareExt

func (m *MerklePrefixMatcher) PrepareExt(turns []CanonicalTurn) (fingerprints []string, minPrefixLength int, tailFingerprints []string, envDigest string)

PrepareExt returns bounded turn fingerprints, the first eligible prefix boundary, actual trailing turn fingerprints, and the environment digest across all system turns.

func (*MerklePrefixMatcher) Remove

func (m *MerklePrefixMatcher) Remove(namespace string, turns []CanonicalTurn, authID string) bool

Remove removes the exact request sequence when it is still bound to authID.

func (*MerklePrefixMatcher) RemoveFingerprints

func (m *MerklePrefixMatcher) RemoveFingerprints(namespace string, fingerprints []string, authID string) bool

RemoveFingerprints removes an exact precomputed request sequence.

func (*MerklePrefixMatcher) RemoveFingerprintsBefore

func (m *MerklePrefixMatcher) RemoveFingerprintsBefore(namespace string, fingerprints []string, authID string, maxGeneration uint64) bool

RemoveFingerprintsBefore removes an exact precomputed request sequence only if it has not been refreshed after maxGeneration. If maxGeneration is 0, it removes the sequence unconditionally.

func (*MerklePrefixMatcher) Touch

func (m *MerklePrefixMatcher) Touch(namespace string, turns []CanonicalTurn, authID string) bool

Touch refreshes an existing sequence or binds it to authID when it is a new extension.

func (*MerklePrefixMatcher) TouchFingerprints

func (m *MerklePrefixMatcher) TouchFingerprints(namespace string, fingerprints []string, minPrefixLength int, authID string) bool

TouchFingerprints refreshes or binds a precomputed request sequence.

func (*MerklePrefixMatcher) TouchFingerprintsWithContext

func (m *MerklePrefixMatcher) TouchFingerprintsWithContext(namespace string, fingerprints, tailFingerprints []string, envDigest string, minPrefixLength int, authID string) bool

TouchFingerprintsWithContext refreshes or binds a precomputed request sequence with explicit tail and environment context.

type MerklePrefixMatcherConfig

type MerklePrefixMatcherConfig struct {
	TTL       time.Duration
	MaxTurns  int
	MaxGroups int
	// MaxPrefixes bounds group-to-prefix index entries, not just groups.
	MaxPrefixes int
	// NowFunc provides a mockable clock for deterministic TTL/expiration tests.
	NowFunc func() time.Time
}

MerklePrefixMatcherConfig controls the bounded in-memory LCP index.

type SessionInfo

type SessionInfo struct {
	SessionID       string         `json:"session_id"`
	ParentSessionID string         `json:"parent_session_id,omitempty"`
	AgentName       string         `json:"agent_name,omitempty"`
	ClientType      string         `json:"client_type,omitempty"`
	CallerScope     string         `json:"caller_scope,omitempty"`
	AuthID          string         `json:"auth_id,omitempty"`
	Provider        string         `json:"provider,omitempty"`
	Model           string         `json:"model,omitempty"`
	NodeKind        string         `json:"node_kind,omitempty"`
	IsFork          bool           `json:"is_fork,omitempty"`
	IsCompaction    bool           `json:"is_compaction,omitempty"`
	IsSubagent      bool           `json:"is_subagent,omitempty"`
	Metadata        map[string]any `json:"metadata,omitempty"`
}

SessionInfo encapsulates incoming request details needed for session affinity and upstream reporting.

func ExtractSessionInfo

func ExtractSessionInfo(headers http.Header, payload []byte, metadata map[string]any) (SessionInfo, bool)

ExtractSessionInfo extracts session hierarchy and client identification from request attributes. Priority matches selector.go:

  1. X-Claude-Code-Session-Id
  2. Claude Code metadata.user_id session
  3. Session-Id / Session_id (Codex and compatible clients)
  4. X-Http-Session-Id (Antigravity CLI)
  5. X-Session-ID / X-Session-Affinity / X-Slot-Session-Id
  6. X-Conversation-Id / X-Thread-Id / X-Client-Request-Id
  7. Gemini cachedContent
  8. OpenAI thread_id
  9. session_id / sessionId
  10. prompt_cache_key (pck:), conversation.id (conv:), metadata.user_id (user:)
  11. conversation_id / chat_id
  12. execution_session_id metadata

func ExtractTreeInfo

func ExtractTreeInfo(headers http.Header, payload []byte, metadata map[string]any) (SessionInfo, bool)

ExtractTreeInfo is an alias for ExtractSessionInfo for backward compatibility.

type SessionTreeInfo

type SessionTreeInfo = SessionInfo

SessionTreeInfo is an alias for SessionInfo for backward compatibility.

type SessionTreeNode

type SessionTreeNode struct {
	SessionID       string         `json:"session_id"`
	ParentSessionID string         `json:"parent_session_id,omitempty"`
	TreePath        string         `json:"tree_path"`
	TreeDepth       int            `json:"tree_depth"`
	AgentName       string         `json:"agent_name,omitempty"`
	ClientType      string         `json:"client_type,omitempty"`
	CallerScope     string         `json:"caller_scope,omitempty"`
	LastAuthID      string         `json:"last_auth_id,omitempty"`
	LastProvider    string         `json:"last_provider,omitempty"`
	LastModel       string         `json:"last_model,omitempty"`
	NodeKind        string         `json:"node_kind,omitempty"`
	IsFork          bool           `json:"is_fork,omitempty"`
	IsCompaction    bool           `json:"is_compaction,omitempty"`
	CreatedAt       time.Time      `json:"created_at"`
	UpdatedAt       time.Time      `json:"updated_at"`
	Metadata        map[string]any `json:"metadata,omitempty"`
}

SessionTreeNode represents a node in the session hierarchy. Deprecated: Session tree management and multi-node lineage have moved to Home. This struct is maintained as a migration stub for SDK backward compatibility.

func (*SessionTreeNode) Clone

func (n *SessionTreeNode) Clone() *SessionTreeNode

Clone returns a deep copy of the node. Deprecated: Session tree management has moved to Home.

type SessionTreeStore

type SessionTreeStore interface {
	RecordNode(info SessionTreeInfo) *SessionTreeNode
	GetNode(sessionID string) (*SessionTreeNode, bool)
	GetTree(rootSessionID string) []*SessionTreeNode
	GetSubtree(sessionID string) []*SessionTreeNode
	Ancestors(sessionID string) []string
	UpdateAffinity(sessionID, authID, provider, model string) bool
	Len() int
	Clear()
}

SessionTreeStore defines the interface for recording and querying session trees. Deprecated: Session tree management has moved to Home.

Jump to

Keyboard shortcuts

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