otel

package
v0.13.0 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2026 License: MIT Imports: 30 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultPollInterval = 5 * time.Second

DefaultPollInterval is the time between successive polls to the remote OTel Collector.

Variables

This section is empty.

Functions

func EnrichTurnsWithReplies added in v0.13.0

func EnrichTurnsWithReplies(turns []trace.Turn, replies map[string]string)

EnrichTurnsWithReplies fills in OutputLines on turns that have a matching promptId in the replies map. The converter produces turns with promptId stored as the first UserLine's source — we match by scanning the OTEL span's prompt.id attribute via the turn's PromptID field.

func ExportTrace

func ExportTrace(cfg ExportConfig, turns []trace.Turn, store *evaluation.Store) error

ExportTrace sends trace turns and annotations as OTLP/HTTP spans to the configured endpoint. Each turn becomes a child span under a session root span. Tool calls become grandchild spans. Annotations become span attributes.

func FetchSessionReplies added in v0.13.0

func FetchSessionReplies(sandboxName, sessionID string) map[string]string

FetchSessionReplies reads the Claude Code session JSONL from inside a remote sandbox and returns assistant reply text keyed by promptId. Returns nil (not an error) if the file doesn't exist yet or the exec fails — this is called on every trace-pane refresh and transient failures are expected.

func FetchSessionTurns added in v0.13.0

func FetchSessionTurns(sandboxName, sessionID string) []trace.Turn

FetchSessionTurns reads the session JSONL from inside a sandbox and builds trace.Turn entries directly from it, without needing OTEL data. This is the fallback for the preview/trace pane when the OTEL store is empty (e.g., after an aimux restart).

func FlushTracker added in v0.13.0

func FlushTracker(store *SpanStore, dataDir string) error

FlushTracker walks all sessions in the SpanStore and writes a tracker JSON file per session to dataDir. Existing files are overwritten.

func ParseSessionReplies added in v0.13.0

func ParseSessionReplies(data []byte) map[string]string

ParseSessionReplies extracts assistant reply text from a Claude Code session JSONL file, keyed by the promptId of the preceding user message. Claude Code puts promptId on user entries but NOT on assistant entries, so we track the last-seen user promptId and assign the next assistant's text to it.

This is the primary source for model reply text in aimux's trace pane: Claude Code's OTEL telemetry does not emit assistant responses, but the session JSONL file (written to disk inside the sandbox) contains the full conversation transcript.

func ParseSessionTurns added in v0.13.0

func ParseSessionTurns(data []byte) []trace.Turn

ParseSessionTurns builds complete trace.Turn entries directly from a Claude Code session JSONL file, without needing any OTEL data. This is the fallback for the preview/trace pane when the OTEL store has no spans (e.g., after an aimux restart — the in-memory OTEL store is empty but the session file on the sandbox's disk is persistent).

func SpansToTurns

func SpansToTurns(root *Span) []trace.Turn

SpansToTurns converts a span tree (from the OTEL receiver) into trace.Turn slices that the current TUI can render.

Handles two data formats:

  1. Claude Code log events: flat events with prompt.id, grouped into turns
  2. Codex trace spans: hierarchical spans where each child is a turn

Auto-detects the format by checking for prompt.id attributes.

Types

type ExportConfig

type ExportConfig struct {
	Endpoint     string            // e.g., "localhost:5001" (MLflow) or "localhost:4318" (collector)
	Insecure     bool              // true for HTTP (no TLS)
	SessionID    string            // session identifier
	Provider     string            // "claude", "codex"
	ExperimentID string            // MLflow experiment ID (required by MLflow OTLP endpoint)
	Headers      map[string]string // extra HTTP headers

	// Session-level evaluation metadata (from .meta.json sidecar)
	Annotation   string   // achieved/partial/failed/abandoned
	FailureModes []string // failure-mode tags
	Note         string   // free-text rationale
}

ExportConfig holds the configuration for OTEL export.

type K8sReader added in v0.7.0

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

K8sReader connects to a remote OTel Collector and imports spans into the local SpanStore. It periodically fetches new spans and merges them with locally-collected data. Only instantiated when config.Kubernetes.OTELEndpoint is set.

func NewK8sReader added in v0.7.0

func NewK8sReader(endpoint string, store *SpanStore) *K8sReader

NewK8sReader creates a new K8sReader that will poll the given endpoint for remote agent traces and merge them into store.

func (*K8sReader) Endpoint added in v0.7.0

func (r *K8sReader) Endpoint() string

Endpoint returns the configured remote endpoint.

func (*K8sReader) Start added in v0.7.0

func (r *K8sReader) Start() error

Start begins polling the remote OTel Collector in a background goroutine. Non-blocking. Returns an error if the reader is already running.

func (*K8sReader) Stats added in v0.7.0

func (r *K8sReader) Stats() (polls, spans int, lastPoll time.Time, lastErr error)

Stats returns reader statistics. Thread-safe.

func (*K8sReader) Stop added in v0.7.0

func (r *K8sReader) Stop()

Stop stops the background polling goroutine and waits for it to exit.

type Receiver

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

Receiver is an OTLP/HTTP trace receiver that listens for incoming spans from Claude Code, Codex CLI, or any OTEL-instrumented agent. It stores spans in a SpanStore for the TUI to display.

func NewReceiver

func NewReceiver(store *SpanStore, port int) *Receiver

NewReceiver creates a new OTLP/HTTP receiver.

func NewReceiverWithKeys added in v0.5.0

func NewReceiverWithKeys(store *SpanStore, port int, keys map[string]subagent.AttrKeys) *Receiver

NewReceiverWithKeys creates a new OTLP/HTTP receiver with per-service subagent attribute keys for automatic extraction.

func (*Receiver) Port

func (r *Receiver) Port() int

Port returns the configured port.

func (*Receiver) SetBindAll added in v0.13.0

func (r *Receiver) SetBindAll(v bool)

SetBindAll configures the receiver to listen on all interfaces (0.0.0.0) instead of localhost only. Required when remote sandboxes send OTEL data via host.openshell.internal.

func (*Receiver) Start

func (r *Receiver) Start() error

Start begins listening for OTLP/HTTP trace data on the configured port. Non-blocking -- runs the server in a goroutine.

func (*Receiver) Stats

func (r *Receiver) Stats() (traces, logs, other int)

Stats returns request counts for debugging. Thread-safe.

func (*Receiver) Stop

func (r *Receiver) Stop()

Stop shuts down the receiver.

type Span

type Span struct {
	SpanID   string
	TraceID  string
	ParentID string // empty for root spans
	Name     string // e.g., "invoke_agent", "chat", "execute_tool Read"
	Start    time.Time
	End      time.Time
	Status   SpanStatus
	Attrs    map[string]any // gen_ai.* attributes by OTEL convention names
	Children []*Span

	// aimux extensions (not in OTEL spec)
	Label string // GOOD/BAD/WASTE annotation
	Note  string // annotation rationale

	Subagent subagent.Info
}

Span is aimux's internal span representation, using OTEL GenAI semantic convention attribute names but as a simple data struct (not the OTEL SDK interface which is write-only). Supports hierarchy and aimux extensions.

func (*Span) Attr

func (s *Span) Attr(key string) any

Attr returns a span attribute value, or nil if not set.

func (*Span) AttrFloat64

func (s *Span) AttrFloat64(key string) float64

AttrFloat64 returns a span attribute as float64, or 0 if not set. Handles string-encoded numbers (Claude Code sends cost_usd as string).

func (*Span) AttrInt64

func (s *Span) AttrInt64(key string) int64

AttrInt64 returns a span attribute as int64, or 0 if not set. Handles string-encoded numbers (Claude Code sends tokens as strings).

func (*Span) AttrStr

func (s *Span) AttrStr(key string) string

AttrStr returns a span attribute as a string, or "" if not set.

type SpanStatus

type SpanStatus int

SpanStatus represents the outcome of a span.

const (
	StatusOK SpanStatus = iota
	StatusError
	StatusUnset
)

type SpanStore

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

SpanStore holds received OTEL spans in memory, indexed for fast lookup by session/conversation ID. Thread-safe.

func NewSpanStore

func NewSpanStore() *SpanStore

NewSpanStore creates an empty span store.

func (*SpanStore) Add

func (ss *SpanStore) Add(span *Span)

Add inserts a span into the store. If it has a conversation ID attribute, it's also indexed by conversation.

func (*SpanStore) AssembleTree

func (ss *SpanStore) AssembleTree(traceID string) *Span

AssembleTree builds parent-child relationships for all spans in a trace. Call after all spans for a trace have been added.

func (*SpanStore) ConversationIDs

func (ss *SpanStore) ConversationIDs() []string

ConversationIDs returns all conversation/session IDs in the store.

func (*SpanStore) GetByConversation

func (ss *SpanStore) GetByConversation(id string) *Span

GetByConversation returns the root span tree for a conversation/session ID.

func (*SpanStore) GetSpans

func (ss *SpanStore) GetSpans(traceID string) []*Span

GetSpans returns all spans for a trace ID.

func (*SpanStore) HasData

func (ss *SpanStore) HasData() bool

HasData returns true if the store has any spans.

func (*SpanStore) LastUpdate

func (ss *SpanStore) LastUpdate() time.Time

LastUpdate returns when data was last received.

func (*SpanStore) SubagentInfoBySession added in v0.5.0

func (ss *SpanStore) SubagentInfoBySession(sessionID string) subagent.Info

SubagentInfoBySession returns the subagent identity for a session ID.

func (*SpanStore) SubagentsBySession added in v0.5.0

func (ss *SpanStore) SubagentsBySession(sessionID string) []subagent.Info

SubagentsBySession returns all distinct subagent identities seen in OTEL events for a session. Used to create virtual agent entries for in-process subagents that don't have their own PID.

func (*SpanStore) TraceCount

func (ss *SpanStore) TraceCount() int

TraceCount returns the number of distinct trace IDs stored.

type ToolDetail added in v0.13.0

type ToolDetail struct {
	Tokens  int     `json:"tokens"`
	Calls   int     `json:"calls"`
	CostUSD float64 `json:"cost_usd,omitempty"`
}

ToolDetail holds per-tool token, call, and cost data.

type TrackerData added in v0.13.0

type TrackerData struct {
	Agents  int                   `json:"agents"`
	Tools   int                   `json:"tools"`
	MCP     int                   `json:"mcp"`
	Calls   int                   `json:"calls"`
	CostUSD float64               `json:"cost_usd,omitempty"`
	ByTool  map[string]ToolDetail `json:"by_tool,omitempty"`
	Last    string                `json:"last,omitempty"`
}

TrackerData is the per-session JSON written to ~/.aimux/data/context/. The schema matches what claude-hud's context-breakdown.ts expects.

Jump to

Keyboard shortcuts

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