obs

package
v1.0.6 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: Apache-2.0 Imports: 15 Imported by: 0 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 obs holds the observability surface of the proxy (spec §20): the Prometheus metrics, the status report of a session and the trace export that feeds the replay (spec §17.2 item 4). Everything is built per Metrics value with a private registry, so several proxies can live in one process.

Index

Constants

View Source
const (
	OutcomeAccepted = "accepted"
	OutcomeRejected = "rejected"
	OutcomeRefused  = "refused"
	OutcomeFailOpen = "failopen"
	OutcomeCompact  = "compacted"
	// OutcomeClientCompaction counts the client's own compaction call, which is
	// forwarded unchanged. It is not a fail-open.
	OutcomeClientCompaction = "client_compaction"
	// OutcomeSideRequest counts a client's side request (for example Claude
	// Code's auto-mode classifier), forwarded unchanged with no session.
	OutcomeSideRequest = "side_request"

	TierNone = "none"
)

Label values. They are a closed set, so cardinality stays bounded: no label carries a session, project or message identifier.

View Source
const (
	TagSession = "session"
	TagMessage = "msg"
	TagIntent  = "intent"
	TagBlock   = "block"
	TagEvent   = "event"
)

Line type tags, the "t" field of each JSON line.

View Source
const DefaultDecisions = 20

DefaultDecisions is how many recent events the status report lists.

View Source
const TraceVersion = 1

TraceVersion is the format version written in the session line.

Variables

This section is empty.

Functions

func Bool

func Bool(b bool) string

Bool renders a boolean as the accepted label value.

func WriteTrace

func WriteTrace(w io.Writer, t Trace) error

WriteTrace writes t as JSON lines.

Types

type BlockLine

type BlockLine struct {
	T         string   `json:"t"`
	ID        string   `json:"id"`
	Tier      int      `json:"tier"`
	Topic     Body     `json:"topic"`
	Summary   Body     `json:"summary"`
	StartSeq  int64    `json:"start_seq"`
	EndSeq    int64    `json:"end_seq"`
	SrcTokens int      `json:"src_tokens"`
	SumTokens int      `json:"sum_tokens"`
	Active    bool     `json:"active"`
	Sources   []string `json:"sources,omitempty"`
}

BlockLine is one compression block (spec §5.2). Sources lists the consumed blocks of a T2/T3 block, in ledger order.

type Body

type Body struct {
	Value  *string `json:"value,omitempty"`
	SHA256 string  `json:"sha256"`
	Len    int     `json:"len"`
}

Body is a text kept verbatim (Value set) or anonymized (Value nil).

type CacheInfo

type CacheInfo struct {
	Calls         int64   `json:"calls"`
	InputTokens   int64   `json:"input_tokens"`
	CachedTokens  int64   `json:"cached_tokens"`
	ReadRatio     float64 `json:"read_ratio"`
	AfterCompress int64   `json:"after_compress"`
}

CacheInfo is the measured cache cost of the upstream calls (spec §9.4).

type DecisionInfo

type DecisionInfo struct {
	Seq     int64          `json:"seq"`
	At      int64          `json:"at"`
	Type    string         `json:"type"`
	Payload map[string]any `json:"payload,omitempty"`
}

DecisionInfo is one recent event. Payload holds the decision keys of its type (see decisionKeys).

type EventLine

type EventLine struct {
	T       string          `json:"t"`
	Seq     int64           `json:"seq"`
	At      int64           `json:"at"`
	Type    string          `json:"type"`
	Payload json.RawMessage `json:"payload"`
}

EventLine is one row of the events log. Payload is the stored JSON.

type IntentInfo

type IntentInfo struct {
	Open      []OpenIntent `json:"open"`
	OpenCount int          `json:"open_count"`
	DoneCount int          `json:"done_count"`
}

IntentInfo lists the open intents (spec §11.3). Intent text is left out.

type IntentLine

type IntentLine struct {
	T         string `json:"t"`
	ID        int64  `json:"id"`
	OriginSeq int64  `json:"origin_seq"`
	Status    string `json:"status"`
	Text      Body   `json:"text"`
}

IntentLine is one user intent (spec §11.3).

type KernelSettings

type KernelSettings struct {
	StepBase       int    `json:"step_base"`
	StepMin        int    `json:"step_min"`
	StepMax        int    `json:"step_max"`
	StepReadGain   string `json:"step_read_gain"`
	MinGrowthFloor int    `json:"min_growth_floor"`
	UFloor         string `json:"u_floor"`
	UHigh          string `json:"u_high"`
	UEmerg         string `json:"u_emerg"`
	TiersEnabled   bool   `json:"tiers_enabled"`
}

KernelSettings is kernel.Config with its decimals written as strings, so they survive a JSON round trip exactly.

func (KernelSettings) Config

func (k KernelSettings) Config() (kernel.Config, error)

Config rebuilds the kernel configuration. It fails when a decimal is malformed.

type MessageLine

type MessageLine struct {
	T          string `json:"t"`
	Seq        int64  `json:"seq"`
	Ref        string `json:"ref"`
	Role       string `json:"role"`
	Kind       string `json:"kind"`
	ToolName   string `json:"tool_name,omitempty"`
	ToolCallID string `json:"tool_call_id,omitempty"`
	Tokens     int    `json:"tokens"`
	Text       Body   `json:"text"`
}

MessageLine is one ledger message (spec §5.2).

type Metrics

type Metrics struct {
	Registry *prometheus.Registry

	// ContextTokens is the calibrated size of each request's window, per protocol.
	ContextTokens *prometheus.HistogramVec // acd_ctx_context_tokens{protocol}
	// CompressTotal counts compress calls by the highest tier they produced
	// (none for refusals) and by outcome.
	CompressTotal *prometheus.CounterVec // acd_ctx_compress_total{tier,outcome}
	// CompressRatio is src/sum of each accepted block.
	CompressRatio prometheus.Histogram // acd_ctx_compress_ratio
	// CacheReadRatio is cached/input of each upstream call that reported usage.
	CacheReadRatio prometheus.Histogram // acd_ctx_cache_read_ratio
	// FoldCacheCost is the estimated cache cost (kind=cost) and benefit
	// (kind=benefit) of the best candidate fold, in tokens (spec §9.1).
	FoldCacheCost *prometheus.HistogramVec // acd_ctx_fold_cache_cost_tokens{kind}
	// RecallHints counts recall hints by signal, and whether the model acted on
	// them (a decompress of the hinted block before the next turn).
	RecallHints *prometheus.CounterVec // acd_ctx_recall_hint_total{signal,accepted}
	// CalibFactor is the last token calibration factor (spec §15).
	CalibFactor prometheus.Gauge // acd_ctx_token_calib_factor
	// Requests counts compaction requests by protocol and outcome.
	Requests *prometheus.CounterVec // acd_ctx_requests_total{protocol,outcome}
	// ClientCompactions counts the client's own compaction calls, forwarded
	// unchanged, by protocol and by the signal that recognised them. The signals are a
	// closed set in the proxy, so the cardinality stays bounded.
	ClientCompactions *prometheus.CounterVec // acd_ctx_client_compactions_total{protocol,signal}
	// RequestSeconds is the time of a whole compaction request, tool loop included.
	RequestSeconds *prometheus.HistogramVec // acd_ctx_request_duration_seconds{protocol}
	// UpstreamSeconds is the latency of each upstream call.
	UpstreamSeconds prometheus.Histogram // acd_ctx_upstream_duration_seconds
	// ToolCalls counts the internal tool calls the proxy ran, by tool and outcome.
	ToolCalls *prometheus.CounterVec // acd_ctx_tool_calls_total{tool,outcome}
}

Metrics is one set of collectors and the registry that holds them.

func NewMetrics

func NewMetrics() *Metrics

NewMetrics builds the collectors and registers them in a new private registry.

func (*Metrics) Handler

func (m *Metrics) Handler() http.Handler

Handler serves the registry in the Prometheus text format.

type OpenIntent

type OpenIntent struct {
	ID        int64 `json:"id"`
	OriginSeq int64 `json:"origin_seq"`
}

OpenIntent identifies an open intent by its id and origin.

type SessionLine

type SessionLine struct {
	T            string `json:"t"`
	Version      int    `json:"version"`
	ID           string `json:"id"`
	ProjectID    string `json:"project_id"`
	Model        string `json:"model"`
	ContextLimit int    `json:"context_limit"`
	Mode         string `json:"mode"`
	Integration  string `json:"integration"`
	Anonymized   bool   `json:"anonymized"`
}

SessionLine describes the session the trace comes from.

type Settings

type Settings struct {
	RecentKeep       int            `json:"recent_keep"`
	MinCompressRange int            `json:"min_compress_range"`
	MinSummaryChars  int            `json:"min_summary_chars"`
	Kernel           KernelSettings `json:"kernel"`
}

Settings are the per-session options that decide a Plan (spec §8, §10.2).

func SettingsOf

func SettingsOf(k kernel.Config, recentKeep, minCompressRange, minSummaryChars int) Settings

SettingsOf captures the options of a session.

type Status

type Status struct {
	Session         store.SessionRow `json:"session"`
	Trigger         TriggerInfo      `json:"trigger"`
	Window          WindowInfo       `json:"window"`
	Blocks          []TierInfo       `json:"blocks"`
	Intents         IntentInfo       `json:"intents"`
	RecentDecisions []DecisionInfo   `json:"recent_decisions"`
	Cache           CacheInfo        `json:"cache"`
}

Status is the report of GET /__acd-ctx/sessions/{id}/status (spec §20). It carries counts, identifiers and decision payloads, never message or block text.

func BuildStatus

func BuildStatus(ctx context.Context, st *store.Store, sid string, decisions int) (Status, error)

BuildStatus reads the status of session sid. decisions bounds the recent events (DefaultDecisions when <= 0).

type TierInfo

type TierInfo struct {
	Tier      int `json:"tier"`
	Active    int `json:"active"`
	SrcTokens int `json:"src_tokens"`
	SumTokens int `json:"sum_tokens"`
}

TierInfo counts the active blocks of one tier.

type Trace

type Trace struct {
	Session  SessionLine
	Messages []MessageLine
	Intents  []IntentLine
	Blocks   []BlockLine
	Events   []EventLine
}

Trace is the replayable record of one session (spec §17.2 item 4). It is written as JSON lines: one session line, then the messages, intents, blocks and events in ledger order. A trace with anonymized text keeps each text's length and sha256 and drops the text itself.

func ExportTrace

func ExportTrace(ctx context.Context, st *store.Store, sid string, anonymize bool) (Trace, error)

ExportTrace reads session sid from st into a Trace. With anonymize set, texts are replaced by their length and sha256, and the location keys of event payloads (see pathKeys) are dropped.

func ReadTrace

func ReadTrace(r io.Reader) (Trace, error)

ReadTrace parses the JSON lines written by WriteTrace. The session line must come first and be the only one of its kind; unknown tags are an error, so a truncated or edited file fails loudly.

type TriggerInfo

type TriggerInfo struct {
	LowWaterTokens int  `json:"low_water_tokens"`
	NudgePending   bool `json:"nudge_pending"`
	NudgeShownAt   int  `json:"nudge_shown_at"`
	LastShownT2    int  `json:"last_shown_t2"`
	LastShownT3    int  `json:"last_shown_t3"`
	Refusals       int  `json:"refusals"`
}

TriggerInfo is the trigger state (spec §8.2, §8.3).

type TurnEvent

type TurnEvent struct {
	Tokens       int      `json:"tokens"`
	Messages     int      `json:"messages"`
	ContextLimit int      `json:"context_limit"`
	Settings     Settings `json:"settings"`
}

TurnEvent is the payload of a "turn" event: the inputs of one Plan, which replay repeats. Tokens is the calibrated window size the Plan saw, Messages the ledger length it ran on, ContextLimit the window in force and Settings the session options in force. A replay that restores all four makes the same decisions.

type WindowInfo

type WindowInfo struct {
	Tokens        int            `json:"tokens"`
	Messages      int            `json:"messages"`
	MessagesTotal int            `json:"messages_total"`
	ByKind        map[string]int `json:"by_kind"`
}

WindowInfo describes the rendered window: what the next request would carry.

Jump to

Keyboard shortcuts

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