telemetry

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: MIT Imports: 39 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

Index

Constants

View Source
const DefaultFlushInterval = 30 * time.Second

DefaultFlushInterval balances delivery latency against small-object overhead.

View Source
const MaxTurnTextBytes = 64 * 1024

MaxTurnTextBytes bounds retained text per composite identity.

View Source
const OmittedBufferLimit = "buffer_limit"
View Source
const OmittedInvalidUTF8 = "invalid_utf8"

Variables

View Source
var (
	ErrQueueFull  = errors.New("telemetry queue full")
	ErrSinkClosed = errors.New("telemetry sink closed")
)
View Source
var (
	ErrInvalidSegmentID = errors.New("invalid telemetry segment ID")
	ErrSegmentConflict  = errors.New("telemetry segment ID has different content")
	ErrSegmentTooLarge  = errors.New("telemetry record exceeds segment size limit")
)

Functions

func DefaultRedactor

func DefaultRedactor(text string) string

DefaultRedactor strips ANSI controls and common inline secret assignments.

func LoadOrCreateIdentityKey

func LoadOrCreateIdentityKey(path string) ([]byte, error)

LoadOrCreateIdentityKey loads a private 32-byte HMAC key or atomically creates one so concurrent first starts converge on the same value.

func ResolveSourceID

func ResolveSourceID(configured, path string) (string, error)

ResolveSourceID returns a configured source ID or securely persists a generated UUID. Linking a complete temporary file makes concurrent first starts converge on one identity without exposing a partial file.

func ValidSourceID

func ValidSourceID(sourceID string) bool

ValidSourceID reports whether sourceID is safe to use as a telemetry identity.

func VisitEvents

func VisitEvents(path string, visit func(Event) error) error

VisitEvents streams complete events from immutable retained segments.

Types

type Analyzer

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

Analyzer correlates agent questions with subsequent human input.

func NewAnalyzer

func NewAnalyzer(sink Sink, redactor Redactor, opts ...AnalyzerOption) *Analyzer

func (*Analyzer) Feedback

func (a *Analyzer) Feedback() Feedback

Feedback returns aggregate data sorted by frequency. Higher-level analysis does not need raw transcripts to identify recurring questions.

func (*Analyzer) ObserveInput

func (a *Analyzer) ObserveInput(session Session, data []byte)

ObserveInput correlates human input with the most recent question in the session. The raw answer is redacted before it reaches the sink.

func (*Analyzer) ObserveOmittedInteraction

func (a *Analyzer) ObserveOmittedInteraction(session Session, direction Direction, kind EventKind, stream StreamType, data []byte, reason string)

func (*Analyzer) ObserveOutput

func (a *Analyzer) ObserveOutput(session Session, data []byte)

ObserveOutput inspects agent output. It records only likely questions rather than every output byte, which keeps the feedback dataset useful and bounded.

func (*Analyzer) ObserveProviderInteraction

func (a *Analyzer) ObserveProviderInteraction(session Session, stream StreamType, data []byte)

ObserveProviderInteraction records a complete provider chunk before logical framing so a selected full-capture stream can be reconstructed in order.

func (*Analyzer) ObserveSessionContext

func (a *Analyzer) ObserveSessionContext(session Session, context SessionContext)

func (*Analyzer) ObserveSessionEnd

func (a *Analyzer) ObserveSessionEnd(session Session)

func (*Analyzer) ObserveSessionStart

func (a *Analyzer) ObserveSessionStart(session Session)

func (*Analyzer) ObserveUserInteraction

func (a *Analyzer) ObserveUserInteraction(session Session, data []byte)

ObserveUserInteraction records only input that already passed the bridge's active-writer authorization check.

type AnalyzerOption

type AnalyzerOption func(*Analyzer)

func WithIncludeRedactedText

func WithIncludeRedactedText(include bool) AnalyzerOption

type AsyncSink

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

AsyncSink isolates a synchronous Sink behind a bounded, non-blocking queue.

func NewAsyncSink

func NewAsyncSink(sink Sink, queueSize int, onError func(error)) *AsyncSink

func (*AsyncSink) Close

func (s *AsyncSink) Close(ctx context.Context) error

func (*AsyncSink) Dropped

func (s *AsyncSink) Dropped() uint64

func (*AsyncSink) Failures

func (s *AsyncSink) Failures() uint64

func (*AsyncSink) Record

func (s *AsyncSink) Record(event Event) error

type Completeness

type Completeness struct {
	AttemptedEvents        uint64      `json:"attempted_events"`
	LastSequence           uint64      `json:"last_sequence"`
	QueueDroppedEvents     uint64      `json:"queue_dropped_events"`
	SinkFailedEvents       uint64      `json:"sink_failed_events"`
	OmittedEvents          uint64      `json:"omitted_events"`
	SessionStartedObserved bool        `json:"session_started_observed"`
	SessionEndedObserved   bool        `json:"session_ended_observed"`
	CaptureKinds           []EventKind `json:"capture_kinds"`
	IncludeRedactedText    bool        `json:"include_redacted_text"`
}

Completeness measures events selected by the capture policy, before the bounded async queue. It does not claim to measure uninstrumented activity.

type DataQuality

type DataQuality struct {
	Events           int `json:"events"`
	Duplicates       int `json:"duplicates"`
	OutOfOrder       int `json:"out_of_order"`
	MissingSequences int `json:"missing_sequences"`
	LegacyEvents     int `json:"legacy_events"`
	OmittedEvents    int `json:"omitted_events"`
	Redactions       int `json:"redactions"`
}

DataQuality summarizes evidence integrity observed during reconstruction.

type Decision

type Decision string

Decision is the normalized outcome of a question.

const (
	DecisionAccepted Decision = "accepted"
	DecisionRejected Decision = "rejected"
	DecisionChanged  Decision = "changed"
	DecisionUnknown  Decision = "unknown"
)

type Direction

type Direction string

Direction identifies which side of an agent session produced an event.

const (
	DirectionAgent Direction = "agent"
	DirectionHuman Direction = "human"
)

type Event

type Event struct {
	Terminal      *TerminalSnapshot `json:"terminal,omitempty"`
	SchemaVersion int               `json:"schema_version"`
	Timestamp     time.Time         `json:"timestamp"`
	SourceID      string            `json:"source_id,omitempty"`
	ActorID       string            `json:"actor_id,omitempty"`
	SessionID     string            `json:"session_id"`
	ProjectID     string            `json:"project_id,omitempty"`
	Provider      string            `json:"provider,omitempty"`
	Direction     Direction         `json:"direction,omitempty"`
	Kind          EventKind         `json:"kind"`
	Stream        StreamType        `json:"stream,omitempty"`
	Sequence      uint64            `json:"sequence"`
	Class         QuestionClass     `json:"class,omitempty"`
	Decision      Decision          `json:"decision,omitempty"`
	Fingerprint   string            `json:"fingerprint,omitempty"`
	Text          string            `json:"text,omitempty"`
	ByteCount     int               `json:"byte_count,omitempty"`
	Redactions    int               `json:"redactions,omitempty"`
	ContentHash   string            `json:"content_sha256,omitempty"`
	OmittedReason string            `json:"omitted_reason,omitempty"`
	LatencyMS     int64             `json:"latency_ms,omitempty"`
	Context       *SessionContext   `json:"context,omitempty"`
	Completeness  *Completeness     `json:"completeness,omitempty"`
	// contains filtered or unexported fields
}

Event is safe to persist after redaction of its text and terminal cells.

func ReadEvents

func ReadEvents(path string) ([]Event, error)

type EventKind

type EventKind string

EventKind is the normalized telemetry event type.

const (
	EventQuestion       EventKind = "question"
	EventAnswer         EventKind = "answer"
	EventSessionStarted EventKind = "session_started"
	EventSessionContext EventKind = "session_context"
	EventSessionEnded   EventKind = "session_ended"
	EventProviderOutput EventKind = "provider_output"
	EventUserInput      EventKind = "user_input"
)
const EventTelemetryCheckpoint EventKind = "telemetry_checkpoint"

type Feedback

type Feedback struct {
	SchemaVersion int            `json:"schema_version"`
	GeneratedAt   time.Time      `json:"generated_at"`
	Questions     []QuestionStat `json:"questions"`
}

Feedback is a stable, provider-neutral aggregate export. Higher-level analysis can turn it into distilled findings for policy systems.

func BuildFeedback

func BuildFeedback(events []Event, since, until time.Time) Feedback

func BuildFeedbackFromPath

func BuildFeedbackFromPath(path string, since, until time.Time) (Feedback, error)

BuildFeedbackFromPath streams retained JSONL into a provider-neutral export.

func (Feedback) JSON

func (f Feedback) JSON() ([]byte, error)

type FilteredSink

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

FilteredSink forwards only explicitly allowed event kinds. An empty allow-list preserves all events for backward compatibility.

func NewFilteredSink

func NewFilteredSink(sink Sink, kinds ...EventKind) *FilteredSink

func (*FilteredSink) Record

func (s *FilteredSink) Record(event Event) error

type Framer

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

Framer converts arbitrary terminal chunks into logical line/question frames.

func NewFramer

func NewFramer(maxBytes int) *Framer

func (*Framer) BufferedOutput

func (f *Framer) BufferedOutput(sessionID string) string

func (*Framer) FeedInput

func (f *Framer) FeedInput(sessionID string, data []byte) []string

func (*Framer) FeedOutput

func (f *Framer) FeedOutput(sessionID string, data []byte) []string

func (*Framer) FlushInput

func (f *Framer) FlushInput(sessionID string) string

func (*Framer) FlushOutput

func (f *Framer) FlushOutput(sessionID string) string

func (*Framer) Reset

func (f *Framer) Reset(sessionID string)

type GRPCCollectorServer

type GRPCCollectorServer struct {
	bridgev1.UnimplementedTelemetryCollectorServiceServer
	// contains filtered or unexported fields
}

GRPCCollectorServer accepts immutable telemetry segments and acknowledges only after SegmentSpool.Accept has durably persisted them.

func NewGRPCCollectorServer

func NewGRPCCollectorServer(spool *SegmentSpool, maxSegmentBytes int64, kinds ...EventKind) *GRPCCollectorServer

func (*GRPCCollectorServer) StreamSegments

type GRPCForwardingSink

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

GRPCForwardingSink durably records events before forwarding sealed segments. Network work happens only in its worker and never in Record's caller beyond the local spool append.

func NewGRPCForwardingSink

func NewGRPCForwardingSink(spool *SegmentSpool, client bridgev1.TelemetryCollectorServiceClient, closer io.Closer, flushInterval, retryInterval time.Duration, onError func(error)) *GRPCForwardingSink

func (*GRPCForwardingSink) Close

func (s *GRPCForwardingSink) Close(ctx context.Context) (returnErr error)

func (*GRPCForwardingSink) Record

func (s *GRPCForwardingSink) Record(event Event) error

type HTTPForwardingSink

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

HTTPForwardingSink delivers the existing normalized JSONL spool to Bridge's HTTPS collector. The credential is held only in memory and is never logged.

func NewHTTPForwardingSink

func NewHTTPForwardingSink(spool *SegmentSpool, endpoint, credential, collectorVersion string, flushInterval, retryInterval time.Duration, onError func(error)) *HTTPForwardingSink

NewHTTPForwardingSink starts delivery on flushInterval, retrying sooner (with exponential backoff starting at retryInterval, capped at 30s) after a failed delivery, matching GRPCForwardingSink's retry behavior. A single timer schedules every attempt so a pending backoff is never raced by an independent flush tick, which would otherwise retry an unavailable collector more often than the backoff intends.

func (*HTTPForwardingSink) Close

func (s *HTTPForwardingSink) Close(ctx context.Context) error

func (*HTTPForwardingSink) Record

func (s *HTTPForwardingSink) Record(event Event) error

Record fails with ErrSinkClosed once Close has been called, matching GRPCForwardingSink and LocalSpoolingSink: without this guard, a late or direct Record call after Close returns would still append to the spool with no worker left running to ever deliver it.

type InteractionAnalyzer

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

InteractionAnalyzer incrementally reconstructs turns without retaining the entire raw event corpus.

func NewInteractionAnalyzer

func NewInteractionAnalyzer() *InteractionAnalyzer

func (*InteractionAnalyzer) Finish

func (a *InteractionAnalyzer) Finish() []Turn

Finish returns incomplete turns in deterministic composite-identity order.

func (*InteractionAnalyzer) Observe

func (a *InteractionAnalyzer) Observe(event Event) []Turn

Observe consumes one event and returns any turns completed by that event.

func (*InteractionAnalyzer) Quality

func (a *InteractionAnalyzer) Quality() DataQuality

type JSONLSink

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

JSONLSink appends one normalized event per line and bounds retained storage with size-based rotation. It owns no upload policy.

func NewJSONLSink

func NewJSONLSink(path string) *JSONLSink

func NewRotatingJSONLSink

func NewRotatingJSONLSink(path string, maxBytes int64, maxFiles int) *JSONLSink

func (*JSONLSink) Record

func (s *JSONLSink) Record(event Event) error

type LiveCollector

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

LiveCollector combines framing, analysis, and bounded asynchronous delivery.

func NewLiveCollector

func NewLiveCollector(sink Sink, queueSize int, includeRedactedText bool, onError func(error), kinds ...EventKind) *LiveCollector

func NewLiveCollectorForSource

func NewLiveCollectorForSource(sink Sink, queueSize int, includeRedactedText bool, sourceID string, onError func(error), kinds ...EventKind) *LiveCollector

func NewLiveCollectorWithIdentity

func NewLiveCollectorWithIdentity(sink Sink, queueSize int, includeRedactedText bool, identity LiveIdentity, onError func(error), kinds ...EventKind) *LiveCollector

func (*LiveCollector) Close

func (c *LiveCollector) Close(ctx context.Context) error

func (*LiveCollector) Dropped

func (c *LiveCollector) Dropped() uint64

func (*LiveCollector) Failures

func (c *LiveCollector) Failures() uint64

func (*LiveCollector) Feedback

func (c *LiveCollector) Feedback() Feedback

func (*LiveCollector) ObserveInputChunk

func (c *LiveCollector) ObserveInputChunk(session Session, data []byte)

func (*LiveCollector) ObserveOutputChunk

func (c *LiveCollector) ObserveOutputChunk(session Session, data []byte)

func (*LiveCollector) ObserveProviderChunk

func (c *LiveCollector) ObserveProviderChunk(session Session, stream StreamType, data []byte)

func (*LiveCollector) SessionEnded

func (c *LiveCollector) SessionEnded(session Session)

func (*LiveCollector) SessionStarted

func (c *LiveCollector) SessionStarted(session Session)

type LiveIdentity

type LiveIdentity struct {
	SourceID    string
	ActorID     string
	SourceLabel string
	ContextKey  []byte
}

type LocalSpoolingSink

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

LocalSpoolingSink owns timed sealing for local-only telemetry. Persistence callers run behind AsyncSink; sealed segments are safe for concurrent reports.

func NewLocalSpoolingSink

func NewLocalSpoolingSink(spool *SegmentSpool, flushInterval time.Duration, onError func(error)) *LocalSpoolingSink

func (*LocalSpoolingSink) Close

func (s *LocalSpoolingSink) Close(ctx context.Context) error

func (*LocalSpoolingSink) Record

func (s *LocalSpoolingSink) Record(event Event) error

type ObjectStore

type ObjectStore interface {
	Put(context.Context, string, string, []byte) error
}

ObjectStore is the immutable object boundary used by the collector uploader.

type QuestionClass

type QuestionClass string

QuestionClass describes why an agent appears to be asking for input.

const (
	ClassPermission    QuestionClass = "permission"
	ClassConfirmation  QuestionClass = "confirmation"
	ClassChoice        QuestionClass = "choice"
	ClassClarification QuestionClass = "clarification"
	ClassUnknown       QuestionClass = "unknown"
)

type QuestionStat

type QuestionStat struct {
	Fingerprint string        `json:"fingerprint"`
	Class       QuestionClass `json:"class"`
	Example     string        `json:"example"`
	Asked       int           `json:"asked"`
	Accepted    int           `json:"accepted"`
	Rejected    int           `json:"rejected"`
	Changed     int           `json:"changed"`
	Unknown     int           `json:"unknown"`
}

QuestionStat is the provider-neutral aggregate for one recurring question.

type Redactor

type Redactor func(string) string

Redactor removes secrets and other sensitive material before persistence.

type Report

type Report struct {
	Since                 time.Time      `json:"since"`
	Until                 time.Time      `json:"until"`
	Sessions              int            `json:"sessions"`
	AgentHours            float64        `json:"agent_hours"`
	Questions             int            `json:"questions"`
	QuestionsPerSession   float64        `json:"questions_per_session"`
	QuestionsPerAgentHour float64        `json:"questions_per_agent_hour"`
	AcceptanceRate        float64        `json:"acceptance_rate"`
	RejectionRate         float64        `json:"rejection_rate"`
	ChangeRate            float64        `json:"change_rate"`
	UnknownRate           float64        `json:"unknown_rate"`
	MedianLatencyMS       int64          `json:"median_latency_ms"`
	TopQuestions          []QuestionStat `json:"top_questions"`
}

func BuildReport

func BuildReport(events []Event, opts ReportOptions) Report

func BuildReportFromPath

func BuildReportFromPath(path string, opts ReportOptions) (Report, error)

BuildReportFromPath streams retained JSONL into the report accumulator so transcript-only events do not need to be materialized in memory.

type ReportOptions

type ReportOptions struct {
	Since time.Time
	Until time.Time
	Top   int
}

type S3ObjectStore

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

S3ObjectStore writes immutable telemetry segments through the standard AWS SDK credential and region provider chains.

func NewS3ObjectStore

func NewS3ObjectStore(ctx context.Context, region, endpoint string, forcePathStyle bool) (*S3ObjectStore, error)

func (*S3ObjectStore) Put

func (s *S3ObjectStore) Put(ctx context.Context, bucket, key string, data []byte) error

type Segment

type Segment struct {
	ID   string
	Path string
	Size int64
}

Segment identifies an immutable JSONL file in a SegmentSpool.

type SegmentSpool

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

SegmentSpool stores bounded immutable JSONL segments. The active segment is private and is atomically renamed when sealed, so a restart can recover it.

func NewSegmentSpool

func NewSegmentSpool(dir string, maxSegmentBytes, maxDiskBytes int64, onEvict func(Segment)) (*SegmentSpool, error)

func (*SegmentSpool) Accept

func (s *SegmentSpool) Accept(id string, data []byte) (bool, error)

Accept durably stores a remotely supplied immutable segment. Repeating the same ID and bytes is idempotent; reusing an ID for different bytes fails.

func (*SegmentSpool) Append

func (s *SegmentSpool) Append(data []byte) error

func (*SegmentSpool) Close

func (s *SegmentSpool) Close(ctx context.Context) error

func (*SegmentSpool) Dir

func (s *SegmentSpool) Dir() string

func (*SegmentSpool) Pending

func (s *SegmentSpool) Pending() ([]Segment, error)

func (*SegmentSpool) Read

func (s *SegmentSpool) Read(id string) ([]byte, error)

func (*SegmentSpool) Record

func (s *SegmentSpool) Record(event Event) error

Record implements Sink by appending one JSON event to the active segment.

func (*SegmentSpool) Remove

func (s *SegmentSpool) Remove(id string) error

func (*SegmentSpool) Seal

func (s *SegmentSpool) Seal() (Segment, error)

Seal atomically closes the active segment. An empty Segment means there was no active data to seal.

func (*SegmentSpool) SetSealNotifier

func (s *SegmentSpool) SetSealNotifier(notify func(Segment))

SetSealNotifier installs a non-blocking notification hook for newly sealed segments, including segments sealed automatically by size rotation.

type SegmentUploader

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

SegmentUploader copies collector segments to immutable object storage and removes local copies only after Put returns success.

func NewSegmentUploader

func NewSegmentUploader(spool *SegmentSpool, store ObjectStore, bucket, prefix string) *SegmentUploader

func (*SegmentUploader) Run

func (u *SegmentUploader) Run(ctx context.Context, interval time.Duration, onError func(error))

func (*SegmentUploader) UploadPending

func (u *SegmentUploader) UploadPending(ctx context.Context) error

type Session

type Session struct {
	// Cols and Rows are set only for native PTY sessions, not stream-JSON output.
	Cols      uint32
	Rows      uint32
	SourceID  string
	SessionID string
	ActorID   string
	ProjectID string
	Provider  string
	RepoPath  string
}

Session identifies an agent session without requiring telemetry to depend on the bridge package.

type SessionContext

type SessionContext struct {
	ActorID            string `json:"actor_id,omitempty"`
	SourceLabel        string `json:"source_label,omitempty"`
	OS                 string `json:"os"`
	Arch               string `json:"arch"`
	MachineID          string `json:"machine_id,omitempty"`
	WorkingDirectoryID string `json:"working_directory_id,omitempty"`
	RepositoryID       string `json:"repository_id,omitempty"`
	Branch             string `json:"branch,omitempty"`
	CommitSHA          string `json:"commit_sha,omitempty"`
}

SessionContext is bounded, privacy-safe metadata captured once per session.

func DiscoverSessionContext

func DiscoverSessionContext(repoPath, actorID, sourceLabel string, key []byte) SessionContext

DiscoverSessionContext derives stable keyed identifiers without returning raw paths or repository URLs.

type Sink

type Sink interface {
	Record(Event) error
}

Sink synchronously receives normalized telemetry events. Analyzer ignores sink errors; live integrations must also move Record off provider I/O paths.

type StreamType

type StreamType string

StreamType distinguishes normal provider output, model thinking, and human input without coupling telemetry to the bridge transport's chunk enum.

const (
	StreamOutput   StreamType = "output"
	StreamThinking StreamType = "thinking"
	StreamInput    StreamType = "input"
)

type TerminalSnapshot added in v1.4.6

type TerminalSnapshot struct {
	Version    int    `json:"version"`
	Cols       int    `json:"cols"`
	Rows       int    `json:"rows"`
	ANSI       string `json:"ansi"`
	Scrollback string `json:"scrollback,omitempty"`
}

TerminalSnapshot is a self-contained, redacted screen revision. ANSI contains printable cells and SGR attributes only, never cursor/device/clipboard controls. Every revision is a checkpoint, so archived pages need no earlier raw bytes.

type Turn

type Turn struct {
	SourceID      string     `json:"source_id,omitempty"`
	SessionID     string     `json:"session_id"`
	ActorID       string     `json:"actor_id,omitempty"`
	Direction     Direction  `json:"direction"`
	Stream        StreamType `json:"stream"`
	SequenceStart uint64     `json:"sequence_start"`
	SequenceEnd   uint64     `json:"sequence_end"`
	StartedAt     time.Time  `json:"started_at"`
	EndedAt       time.Time  `json:"ended_at"`
	Text          string     `json:"text,omitempty"`
	ByteCount     int        `json:"byte_count"`
	Redactions    int        `json:"redactions"`
	ChunkIndex    int        `json:"chunk_index"`
	Continues     bool       `json:"continues,omitempty"`
}

Turn is a reconstructed contiguous human or agent interaction, emitted in bounded chunks. ChunkIndex is zero for the first chunk of a logical turn; Continues marks a size-sealed chunk. Chunks of one oversized event can share sequence numbers. ByteCount and Redactions are additive across chunks.

Jump to

Keyboard shortcuts

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