waitcause

package
v0.7.14 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2026 License: Apache-2.0 Imports: 10 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 waitcause records WHY a thread's conversation went idle and WHY it woke up again — the signal issue #424 asks for so a later change can choose a keep-alive ping budget from real data, instead of today's fixed 2 pings per thread (see package thread and #426).

This package does NOT choose a ping budget and does NOT change keep-alive or compaction behaviour. It only reads the request body the agent already sent (and the stop reason / tool calls of the response the proxy already parsed) and classifies two things:

  • WaitingFor: what the thread is about to wait on, known the moment the response that ENDS a turn finishes.
  • WakeCause: what ended a wait, known the moment the NEXT request arrives.

Every signal is a string match or a structural read of a tool_use/tool_result block — no LLM, no guessing. Where a marker Claude Code uses does not apply (another agent, another provider, a shape this package does not recognise), the fields read "unknown" rather than a guess. Every exported method recovers internally from a panic and returns the zero value (every field "unknown", every count 0): a bug here can degrade the data this package produces, and must never touch the request or its timing. See issue #424 and the scripts/analysis/wait_causes.py script (#425) this package's marker shapes come from, verified there against real Claude Code transcripts.

Index

Constants

View Source
const (
	MaxScanBytes    = 8 << 20
	MaxScanMessages = 20000
)

The work bounds of ScanBody. They bound the WORK, not the time: the byte bound refuses a body before any read; the message bound refuses a list after it is normalized (the byte bound is what limits that work). Either way the caller falls back to the counts the tracker holds. 8 MiB is above any body the dashboard writer scanned in measurements (783 KB was the largest in #424's benchmark, ~11 ms).

View Source
const (
	WaitingOwnTool    = "own_tool"
	WaitingHuman      = "human"
	WaitingBackground = "background"
	WaitingTeammate   = "teammate"
	WaitingRetry      = "retry"
	// WaitingDone: the response's LAST tool_use is a terminal tool (the shipped list). The
	// thread has finished and no tool result will come back (#857).
	WaitingDone    = "done"
	WaitingUnknown = "unknown"
)

WaitingFor values: what a thread is about to wait on, set on the row whose response ENDS a turn with nothing more for the agent to do right now.

View Source
const (
	WakeToolResult = "tool_result"
	WakeBackground = "background"
	WakeTeammate   = "teammate"
	WakeHuman      = "human"
	WakeSystem     = "system"
	WakeRetry      = "retry"
	WakeUnknown    = "unknown"
)

WakeCause values: what ended a wait, read off the request that ends it.

View Source
const (
	PromptNone       = "none"
	PromptPermission = "permission"
	PromptQuestion   = "question"
	PromptOther      = "other"
)

WaitPrompt values: whether the turn ends on a prompt that a person must answer (#1198).

Variables

This section is empty.

Functions

func ClassifyWaitingFor

func ClassifyWaitingFor(toolUseNames []string, stopReason string, failed, usageOK bool, openBackground, openTeammate int) (waitingFor, lastTool string)

ClassifyWaitingFor turns one response's own facts into a WaitingFor value, applying the shipped terminal-tool list (#857), and, for WaitingOwnTool, the LAST tool_use block's name (issue #424: "also store the last tool_use's tool name"). toolUseNames is every tool_use/function-call name the response carried, in the order they appeared.

failed means the call itself did not complete (a non-2xx upstream status, or a transport error) — the proxy's own, more precise analogue of the transcript's isApiErrorMessage. usageOK is responseUsageWhy's own success flag: when neither a stop reason nor any tool use nor a parsed usage block came back, there is nothing to classify from, so the answer is WaitingUnknown rather than a guess at WaitingHuman.

func ClassifyWaitingForClient

func ClassifyWaitingForClient(cl agent.Client, terminal []string, toolUseNames []string, stopReason string, failed, usageOK bool, openBackground, openTeammate int) (waitingFor, lastTool string)

ClassifyWaitingForClient is ClassifyWaitingForTerminal for the client that sent the request (see agent.Identify): the only difference is the end_turn-with-nothing-open fallback (see HumanFallback).

func ClassifyWaitingForTerminal

func ClassifyWaitingForTerminal(terminal []string, toolUseNames []string, stopReason string, failed, usageOK bool, openBackground, openTeammate int) (waitingFor, lastTool string)

ClassifyWaitingForTerminal is ClassifyWaitingFor with the terminal-tool list (#857). nil is the shipped list; a list with no usable name switches the #857 rules off. When the LAST tool_use is terminal the answer is WaitingDone. When it is a handback tool the answer is the one for an end_turn with nothing else open.

func DefaultTerminalTools

func DefaultTerminalTools() []string

DefaultTerminalTools returns a copy of the shipped terminal-tool list.

func HumanFallback

func HumanFallback(cl agent.Client) bool

HumanFallback reports whether an end_turn with nothing open reads "human" for this client. It does for Claude Code, whose own signals (the agent header, the question tools, the task markers) rule out the other causes, and for Bob, whose behavior stays as it was. For any other client the proxy cannot tell a person from a subagent hand-back, a background terminal or a tool it does not know, so the cause reads "unknown". A request with no User-Agent (agent.Identify of no headers, Label "unknown", or a zero Client from a host that passes none) names no client and keeps "human", as before.

func IsDone

func IsDone(toolUseNames []string, terminal []string) bool

IsDone reports whether the LAST tool_use name is in the terminal list (nil list: the shipped list; a list with no usable name: never). Only the last name counts: a terminal tool earlier in the response is followed by another call, so the thread is not finished. Metadata only: tool names. A host that knows the name list may be incomplete (a spliced sniff window) must pass an empty non-nil list, so the answer is false.

func Key

func Key(tenant, session, threadID string) string

Key names one thread for Observe/RecordOutcome, matching thread.Key's shape (tenant is folded in here because waitcause is tenant-scoped the same way thread identification is).

func PromptOfClient added in v0.7.11

func PromptOfClient(cl agent.Client, toolUseNames []string) string

PromptOfClient reads the prompt a response ends on from its tool names alone. It uses the same set of tools as ClassifyWaitingForClient (agent.Client.AsksHuman): any call to one of them means a person must answer, as in a WaitingHuman response. A question tool is "question" and wins over the others; any other tool of the set (a plan approval) is "other"; with none, "none". A permission prompt is not in the response (the client raises it after the response ends), so the client's Notification signal sets that value later. A name list that missed a call (a spliced window) can only under-report. A zero cl takes both clients' tool lists. Question tools are read with agent.Client.IsQuestionTool.

Types

type Observation

type Observation struct {
	// WakeCause is "" (callers should treat as WakeUnknown) only when the body carried no
	// usable message list; otherwise always one of the WakeXxx constants.
	WakeCause string
	// OpenBackground / OpenTeammate are the open-task and open-teammate counts AS OF this
	// request's own body — the "waiting_on" detail issue #424 asks for, and the input
	// ClassifyWaitingFor needs for the NEXT response that ends a turn.
	OpenBackground int
	OpenTeammate   int
	// MonitorExpiryMs is the latest known absolute expiry (epoch ms) among this thread's
	// currently open Monitor tasks that stated one; 0 when none is open or none stated an
	// expiry (a persistent Monitor, or a backgrounded Bash/agent/skill, has none).
	MonitorExpiryMs int64
	// MsgCount is the number of entries in the body's message/input list, carried back so the
	// caller can hand it to RecordOutcome once this request's own HTTP status is known.
	MsgCount int
}

Observation is what Tracker.Observe reports for one request.

type Option

type Option func(*scanCfg)

Option tells a scan which client sent the body. Without one, a scan applies only the rules that hold for every client (the Claude Code markers).

func ForClient

func ForClient(cl agent.Client) Option

ForClient turns on the markers that only one client writes. The Codex terminal markers ("Process running with session ID N", "Process exited with code C") are read only for the Codex client: a Claude Code tool result that echoes the same text must not open a background task.

type Scan

type Scan struct {
	// OpenBackground and OpenTeammate count the tasks this body alone shows as open, with every task's
	// start marker still in the body. A task whose start fell out of a compacted body is not counted here;
	// the Tracker's persistent counts cover it (the keeper takes the larger of the two).
	OpenBackground int
	OpenTeammate   int
	// contains filtered or unexported fields
}

Scan is the open-task facts of ONE request body, read without the Tracker (#1225, #1227).

ScanBody is a pure function of the body: it writes no shared state, so it can run while the request is upstream, on any goroutine, in any order. The Tracker keeps its own, ordered reading of the same body (the dashboard writer); the keeper plans from the Scan at response time instead of from the Tracker's counts, which lag by one request. A Scan carries the normalized messages so the writer can reuse them and read the body once.

func ScanBody

func ScanBody(stop func() bool, provider bschemas.ModelProvider, body []byte, opts ...Option) (res *Scan)

ScanBody reads the open background tasks and teammate waits of one request body. It returns nil when it cannot say, and the caller then uses today's path:

  • the body is over MaxScanBytes, or its message list over MaxScanMessages (the work bound);
  • the body is empty, has no message list, or continues server-held history (schema.ServerHeldHistory);
  • stop reports true (the request ended, so the answer is no longer needed);
  • anything panics.

stop is polled before and after the normalization and once per message, so the work in progress when it turns true is at most one message. nil never stops. No timer decides anything.

func (*Scan) Messages

func (s *Scan) Messages() []bschemas.ChatMessage

Messages returns the normalized message list the scan read. The caller must not change it.

type Tracker

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

Tracker holds, per thread, the small amount of state a body alone cannot supply: how long ago an open item was first seen (the body carries no timestamps at all), and the previous request's status and message count (for the retry rule). Safe for concurrent use. The zero value is not usable; call New.

func New

func New() *Tracker

New returns an empty tracker.

func (*Tracker) Observe

func (t *Tracker) Observe(tenant, session, threadID string, provider bschemas.ModelProvider, body []byte, opts ...Option) (obs Observation)

Observe reads one request's body and returns its wake cause and the open-task/open-teammate state as of that body. provider picks the dialect apply.NormalizeMessages reads — the SAME normalization the compaction pipeline itself uses, so this package carries no second per-provider body parser (see the package doc). Fails open: any panic (a malformed body, an unexpected shape) yields the zero Observation (WakeCause "", read by callers as unknown) rather than escaping.

func (*Tracker) ObserveWith

func (t *Tracker) ObserveWith(tenant, session, threadID string, body []byte, norm func() []bschemas.ChatMessage, opts ...Option) (obs Observation)

ObserveWith is Observe with the normalized messages supplied by the caller (norm is called at most once, and not at all for a server-held-history body, see schema.ServerHeldHistory), so a caller that also needs the normalization can share one pass over the body.

func (*Tracker) OpenCounts

func (t *Tracker) OpenCounts(tenant, session, threadID string) (background, teammate int)

OpenCounts reports the open background-task and open-teammate counts for a thread as of the last request Observe saw, with the same expiry rules Observe applies. It reads state and changes none except dropping an expired item, which Observe would drop on its next call anyway.

It exists for the keep-alive, which needs the thread's wait cause at the moment a ping falls due, between requests, when no body is at hand to observe. A thread Observe has never seen reports 0, 0.

func (*Tracker) RecordOutcome

func (t *Tracker) RecordOutcome(tenant, session, threadID string, msgCount, status int)

RecordOutcome stores this request's own status and message count, for the NEXT request on the same thread's retry check. Call once this request's upstream status is known (status 0 means "never reached an upstream" and is never read back as a retry predecessor).

Jump to

Keyboard shortcuts

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