thread

package
v0.7.9 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: Apache-2.0 Imports: 11 Imported by: ? modules, 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 thread tells apart the THREADS of one session: the main agent, each subagent, each fork. Every thread has its own prompt and its own provider cache entry, so the two places that reason about one cache entry — the dashboard's miss attribution and the idle keep-alive — must key on session + thread, not on the session alone (issue #423).

A thread id is found in this order:

  1. The agent's own header. Claude Code sends `x-claude-code-agent-id` on every subagent request and omits it on the main thread (seen on the wire with 2.1.294). The proxy reads the header and passes it in as the hint.
  2. Prefix continuity, for every request without that header and for every agent and provider that never sends it. A request continues thread T when T's last message list is a prefix of the new request's message list — the same rule the provider cache applies, so requests are grouped exactly as the cache groups them.
  3. The session itself (thread id ""), when neither gives an answer. That is the behaviour before this package existed, so a wrong guess can never be worse than no guess.

The first thread of a session without a header also gets the id "". A single-thread session — every Codex or Bob Shell session, and every Claude Code session that never starts a subagent — therefore keys exactly as it did before.

"" goes to the main agent, told apart by metadata: the first header-less thread that declares tools. An auxiliary request (Claude Code's security monitor, a title) declares none, so if one speaks first it holds "" only until the main agent's first request, and then moves to its own "p:" id (see newID). Turn count or order would not do: order is wrong when an auxiliary request comes first, and choosing by turn count would re-key a live thread. One case is still open: after a proxy restart mid-session, a header-less SUBAGENT that speaks before the main agent declares tools too and takes "".

Index

Constants

View Source
const AgentHeader = claudecode.AgentHeader

AgentHeader is the request header Claude Code names a subagent's thread with. The rule lives in agent/claudecode (its AgentID function); the name stays here for existing callers.

View Source
const Primary = ""

Primary is the id of a session's first thread, and of every request whose thread cannot be told. Key(session, Primary) is the session itself.

Variables

This section is empty.

Functions

func AgentThread

func AgentThread(agentID string) string

AgentThread is the thread id of a request whose agent named itself with agentID (the `x-claude-code-agent-id` header, checked with ValidHeaderID). Resolve gives this id to such a request. A host that keys its own state per thread before or without Resolve uses it too, so the rule has one home.

func Fingerprint

func Fingerprint(body []byte) ([]uint64, bool)

Fingerprint returns the cumulative fingerprint of a request's message list: element i is the hash of messages[0..i]. ok is false when the body carries no message list to match on — no `messages` or `input` array, or a Responses request that continues server-held history (`schema.ServerHeldHistory`: previous_response_id, conversation, item_reference), whose `input` is only the newest turn.

The fingerprint covers what decides whether the agent CONTINUED a conversation, and leaves out what the agent rewrites in place without starting a new one:

  • `cache_control` markers: an agent moves its breakpoint to the newest message every turn.
  • thinking and reasoning blocks: their signatures and encrypted payloads carry no thread identity, and a client may drop them from earlier turns.
  • the CONTENT of a tool result, kept by its call id only: Claude Code clears old tool results ("microcompact") without starting a new thread.
  • a message's own `output_config` (the effort setting): Claude Code 2.1.309 adds it to the system-role message it sends second, where 2.1.303 sent none. A session resumed after an upgrade then sends it on a message the old requests sent without it (#708). The provider's cache still read the whole old prefix, so it is not part of what the cache matches on. Left out on the message object only, never inside one.
  • a message's `content` sent as a plain string versus as a one-element `[{"type":"text","text":...}]` array: Claude Code sends the newest turn in the array form (to carry a cache_control breakpoint) and the SAME message as a plain string once a later turn displaces it. The provider normalizes both to one text block and its cache still hits, so this package hashes them the same way too (see canon).

The system prompt and the tools are left out on purpose. A thread whose system prompt changes is still the same thread — that change is a prefix change, and it must be labelled as one.

func HeaderAgentID

func HeaderAgentID(v string) (id string, ok bool)

HeaderAgentID is the one parser of an agent id's form. agent.Identify calls it with the Claude Code header value (claudecode.AgentID), so the Client's AgentID is already checked. It turns a raw AgentHeader value into the agentID that Resolve and ResolveSession take. It trims the value. It gives "" when the header is absent, and also when ValidHeaderID refuses it: a header that is present but unusable falls back to prefix continuity. It must not become a key, and it must not merge the request into another thread. ok is false only for that refused value, so a host can log it.

func IsAgentCompaction

func IsAgentCompaction(body []byte) bool

IsAgentCompaction reports whether body is the agent asking the model to summarize the conversation so far (its own context compaction). Pass the result to Resolve as agentCompaction, with the same body: the request as the agent sent it.

The match is scoped to the last TURN's raw JSON (the phrases contain no characters JSON escapes, so string and content-block shapes both work) and to user-role messages, which is where every known agent puts it. See agentCompactionPhrases and lastTurn.

func IsAgentCompactionHint added in v0.7.8

func IsAgentCompactionHint(markedByClient bool, body []byte) bool

IsAgentCompactionHint is IsAgentCompaction plus a hint from the host. markedByClient is true when the client marked the request as its own compaction: the host reads that from headers it owns (see agent.MarkedCompaction). A marked request is a compaction whatever its text says. A host with no headers passes false, and the phrase match is the fallback. Pass the result to Resolve as agentCompaction.

func IsAgentThread

func IsAgentThread(threadID string) bool

IsAgentThread reports whether a thread id was named by the agent's header (see AgentThread): a subagent or an agent-team teammate. The primary thread and every prefix thread are not.

func Key

func Key(session, thread string) string

Key is the map key the recorder and the keeper use for one thread: the session itself for the primary thread, so single-thread traffic keys exactly as it did before threads existed.

func ValidHeaderID

func ValidHeaderID(v string) bool

ValidHeaderID reports whether an agent-id header value is usable. Empty, over-long, or containing anything outside [A-Za-z0-9_.:@-] is not: such a value falls back to prefix continuity rather than becoming a key. `@` is in the set because an agent-team teammate's id is `<name>@<team>` (Claude Code 2.1.296); without it every teammate fell back to prefix continuity.

Types

type Result

type Result struct {
	ID     string
	Source Source
	// Disagree is set when the agent's header named a KNOWN thread but prefix continuity matched
	// a different one. The header wins; the caller logs this so a drift between the two paths is
	// visible rather than silent.
	Disagree bool
	// Inherits is set on the FIRST request of a new thread whose message content is mostly an
	// existing thread's: it names that thread. Such a request is not a cold start. It is the
	// existing conversation with a changed prefix — a user rewind, an edited earlier message, a
	// fork. Attribution then treats it as that thread's next turn, so its miss reads
	// prefix_change (or ttl_expiry), never cold_start. See inheritMass. "" otherwise.
	Inherits string

	// AfterCompaction is set on the first request after the main agent's own compaction: the request
	// that matched no prefix and took over the compacting thread's id (newID), when that thread
	// declares tools or is the primary. It is the request
	// whose body holds the summary in place of the old transcript. The host reports it to the
	// accountant (RequestMeta.Compaction) and on the dashboard row (#947).
	AfterCompaction bool
	// contains filtered or unexported fields
}

Result is one request's thread.

func (Result) InheritsFrom

func (r Result) InheritsFrom() (string, bool)

InheritsFrom reports the existing thread a new thread continues by content, if any.

type Source

type Source string

Source says which rule produced a thread id.

const (
	SourceHeader  Source = "header"  // the agent named the thread
	SourcePrefix  Source = "prefix"  // matched, or started, by prefix continuity
	SourceSession Source = "session" // last resort: no usable message list
)

type Tracker

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

Tracker holds each live session's threads. Safe for concurrent use. The zero value is not usable; call New.

func New

func New() *Tracker

New returns an empty tracker.

func (*Tracker) Resolve

func (t *Tracker) Resolve(scope, agentID string, body []byte, agentCompaction bool) Result

Resolve finds the thread of one request.

scope is the tenant + session the thread belongs to. agentID is the agent's own thread header ("" when absent; the caller validates it with ValidHeaderID). body is the request AS THE AGENT SENT IT — before any compaction, which would otherwise break the very prefix this matches on. agentCompaction marks the agent's own compaction request (see the compacting field).

A nil tracker, and an empty scope, give the session itself.

Each call records the request as its thread's newest turn, so call it once per request. A host calls ResolveSession, which adds the empty-session rule and fails open.

func (*Tracker) ResolveSession

func (t *Tracker) ResolveSession(tenant, session, agentID string, body []byte, agentCompaction bool) (res Result, err error)

ResolveSession is Resolve for a host: the one rule the proxy and every embedding host share (#1247). Use it to build apply.Opts.ThreadOf.

  • The scope is tenant + "\x00" + session, as the proxy keys it.
  • An empty session gives the session itself (Primary, SourceSession), whatever the header says. apply leaves Trace.Session empty when it returns before it resolves the session, so a host that calls this again with Trace.Session gets the primary thread, as the proxy does.
  • It fails open. A panic gives the session itself, and err describes the panic, so the host can log it. The result is always usable; err never means "drop the request".

agentID is HeaderAgentID's result. body and agentCompaction are as for Resolve: pass the request as the agent sent it, and agent.IsClientCompaction of that same Client and body (the mark, then the prompt match).

Jump to

Keyboard shortcuts

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