session

package
v7.3.9 Latest Latest
Warning

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

Go to latest
Published: Sep 19, 2026 License: MIT Imports: 19 Imported by: 0

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 added in v7.2.152

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 added in v7.2.147

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 added in v7.2.147

func ClaudeMetadataParentSessionID(payload []byte) string

ClaudeMetadataParentSessionID extracts parent_session_id from Claude user_id metadata if present.

func ClaudeMetadataSessionID added in v7.2.103

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.

func FastTurnFingerprint added in v7.2.147

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 added in v7.2.103

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 added in v7.2.155

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 added in v7.2.147

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 added in v7.2.147

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

CanonicalTurn is a protocol-independent conversation turn.

func ExtractCanonicalTurns added in v7.2.147

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 added in v7.2.147

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 added in v7.2.147

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 added in v7.2.147

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

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

func (*InMemorySessionTreeStore) Clear added in v7.2.147

func (s *InMemorySessionTreeStore) Clear()

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

func (*InMemorySessionTreeStore) GetNode added in v7.2.147

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

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

func (*InMemorySessionTreeStore) GetSubtree added in v7.2.147

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

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

func (*InMemorySessionTreeStore) GetTree added in v7.2.147

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

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

func (*InMemorySessionTreeStore) Len added in v7.2.147

func (s *InMemorySessionTreeStore) Len() int

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

func (*InMemorySessionTreeStore) RecordNode added in v7.2.147

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

func (*InMemorySessionTreeStore) UpdateAffinity added in v7.2.147

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 added in v7.2.149

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

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

type MerklePrefixMatch added in v7.2.147

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

MerklePrefixMatch describes the best known affinity match for a request.

type MerklePrefixMatcher added in v7.2.147

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 added in v7.2.147

func NewMerklePrefixMatcher(ttl time.Duration) *MerklePrefixMatcher

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

func NewMerklePrefixMatcherWithConfig added in v7.2.147

func NewMerklePrefixMatcherWithConfig(cfg MerklePrefixMatcherConfig) *MerklePrefixMatcher

NewMerklePrefixMatcherWithConfig creates a matcher with explicit resource bounds.

func (*MerklePrefixMatcher) Bind added in v7.2.147

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 added in v7.2.147

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

BindFingerprints records a precomputed request sequence for an auth.

func (*MerklePrefixMatcher) BindFingerprintsWithResult added in v7.2.149

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 added in v7.2.149

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 added in v7.2.147

func (m *MerklePrefixMatcher) Clear()

Clear removes all remembered prefix bindings.

func (*MerklePrefixMatcher) InvalidateAuth added in v7.2.147

func (m *MerklePrefixMatcher) InvalidateAuth(authID string)

InvalidateAuth removes every LCP binding owned by authID.

func (*MerklePrefixMatcher) LookupSession added in v7.2.156

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 added in v7.2.147

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

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

func (*MerklePrefixMatcher) MatchFingerprints added in v7.2.147

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

MatchFingerprints returns the longest known prefix match without reparsing turns.

func (*MerklePrefixMatcher) Prepare added in v7.2.147

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) Remove added in v7.2.147

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 added in v7.2.147

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

RemoveFingerprints removes an exact precomputed request sequence.

func (*MerklePrefixMatcher) RemoveFingerprintsBefore added in v7.2.149

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 added in v7.2.147

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 added in v7.2.147

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

TouchFingerprints refreshes or binds a precomputed request sequence.

type MerklePrefixMatcherConfig added in v7.2.147

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 added in v7.2.147

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"`
	IsFork          bool           `json:"is_fork,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 added in v7.2.147

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 added in v7.2.147

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

ExtractTreeInfo is an alias for ExtractSessionInfo for backward compatibility.

type SessionTreeInfo added in v7.2.147

type SessionTreeInfo = SessionInfo

SessionTreeInfo is an alias for SessionInfo for backward compatibility.

type SessionTreeNode added in v7.2.147

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"`
	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 added in v7.2.147

func (n *SessionTreeNode) Clone() *SessionTreeNode

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

type SessionTreeStore added in v7.2.147

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