telemetry

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2025 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Overview

Package telemetry provides anonymous usage tracking for cagent.

This package implements a comprehensive telemetry system that collects anonymous usage data to help improve the tool. All events are processed asynchronously and never block command execution. Telemetry can be disabled at any time.

The system tracks: - Command names and success/failure status - Agent names and model types - Tool names and whether calls succeed or fail - Token counts (input/output totals) and estimated costs - Session metadata (durations, error counts)

The system does NOT collect: - User input or prompts - Agent responses or generated content - File contents or paths - API keys or credentials - Personally identifying information

Files in this package: - client.go: Core client functionality, lifecycle management - events.go: Event tracking methods for sessions, tools, tokens - http.go: HTTP request handling and event transmission - global.go: Global telemetry functions and initialization - utils.go: Utility functions and system information collection - types.go: Event types and data structures

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func EnsureGlobalTelemetryInitialized

func EnsureGlobalTelemetryInitialized()

EnsureGlobalTelemetryInitialized makes the private initialization function public

func GetTelemetryEnabled

func GetTelemetryEnabled() bool

GetTelemetryEnabled checks if telemetry should be enabled based on environment

func SetGlobalTelemetryDebugMode

func SetGlobalTelemetryDebugMode(debug bool)

SetGlobalTelemetryDebugMode sets the debug mode for automatic telemetry initialization This should be called by the root package to pass the --debug flag state

func SetGlobalTelemetryVersion

func SetGlobalTelemetryVersion(version string)

SetGlobalTelemetryVersion sets the version for automatic telemetry initialization This should be called by the root package to provide the correct version

func SetGlobalToolTelemetryClient

func SetGlobalToolTelemetryClient(client *Client, logger *slog.Logger)

SetGlobalToolTelemetryClient sets the global client for tool telemetry This allows other packages to record tool events without context passing This is now optional - if not called, automatic initialization will happen

func TrackCommand

func TrackCommand(action string, args []string)

TrackCommand records a command event using automatic telemetry initialization

func WithClient

func WithClient(ctx context.Context, client *Client) context.Context

WithClient adds a telemetry client to the context

Types

type Client

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

Client provides simplified telemetry functionality for cagent

func FromContext

func FromContext(ctx context.Context) *Client

FromContext retrieves the telemetry client from context

func GetGlobalTelemetryClient

func GetGlobalTelemetryClient() *Client

GetGlobalTelemetryClient returns the global telemetry client for adding to context

func NewClient

func NewClient(logger *slog.Logger, enabled, debugMode bool, version string) (*Client, error)

NewClient creates a new simplified telemetry client with explicit debug control

func NewClientWithHTTPClient

func NewClientWithHTTPClient(logger *slog.Logger, enabled, debugMode bool, version string, httpClient HTTPClient) (*Client, error)

NewClientWithHTTPClient creates a new telemetry client with a custom HTTP client (useful for testing)

func (*Client) IsEnabled

func (tc *Client) IsEnabled() bool

IsEnabled returns whether telemetry is enabled

func (*Client) RecordError

func (tc *Client) RecordError(ctx context.Context, errorMsg string)

RecordError records a general session error

func (*Client) RecordSessionEnd

func (tc *Client) RecordSessionEnd(ctx context.Context)

RecordSessionEnd finalizes session tracking

func (*Client) RecordSessionStart

func (tc *Client) RecordSessionStart(ctx context.Context, agentName, sessionID string) string

RecordSessionStart initializes session tracking

func (*Client) RecordTokenUsage

func (tc *Client) RecordTokenUsage(ctx context.Context, model string, inputTokens, outputTokens int64, cost float64)

RecordTokenUsage records token usage metrics

func (*Client) RecordToolCall

func (tc *Client) RecordToolCall(ctx context.Context, toolName, sessionID, agentName string, duration time.Duration, err error)

RecordToolCall records a tool call event

func (*Client) Shutdown

func (tc *Client) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the telemetry client

func (*Client) Track

func (tc *Client) Track(ctx context.Context, structuredEvent StructuredEvent)

Track records a structured telemetry event with type-safe properties (non-blocking) This is the only method for telemetry tracking, all event-specific methods are wrappers around this one

type CommandEvent

type CommandEvent struct {
	Action  string   `json:"action"`
	Args    []string `json:"args,omitempty"`
	Success bool     `json:"success"`
	Error   string   `json:"error,omitempty"`
}

CommandEvent represents command execution events

func (*CommandEvent) GetEventType

func (e *CommandEvent) GetEventType() EventType

func (*CommandEvent) ToStructuredProperties

func (e *CommandEvent) ToStructuredProperties() interface{}

type CommandInfo

type CommandInfo struct {
	Action string
	Args   []string
	Flags  []string
}

CommandInfo represents the parsed command information

func BuildCommandInfo

func BuildCommandInfo(cmd *cobra.Command, args []string, baseName string) CommandInfo

BuildCommandInfo extracts detailed command information for telemetry

type CommandPayload

type CommandPayload struct {
	Action    string   `json:"action"`
	Args      []string `json:"args,omitempty"`
	IsSuccess bool     `json:"is_success"`
	Error     string   `json:"error,omitempty"`
}

CommandPayload represents the HTTP payload structure for command events

type EventPayload

type EventPayload struct {
	Event          EventType `json:"event"`
	EventTimestamp int64     `json:"event_timestamp"`
	Source         string    `json:"source"`

	Properties map[string]interface{} `json:"properties,omitempty"`
}

EventPayload represents a structured telemetry event

type EventType

type EventType string

EventType represents the type of telemetry event

const (
	EventTypeCommand EventType = "command"
	EventTypeSession EventType = "session"
	EventTypeToken   EventType = "token"
	EventTypeTool    EventType = "tool"
)

type EventWithContext

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

EventWithContext wraps an event with its context for async processing

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPClient interface for making HTTP requests (allows mocking in tests)

type SessionEndEvent

type SessionEndEvent struct {
	Action       string   `json:"action"`
	SessionID    string   `json:"session_id"`
	AgentName    string   `json:"agent_name"`
	Duration     int64    `json:"duration_ms"`
	ToolCalls    int      `json:"tool_calls"`
	InputTokens  int64    `json:"input_tokens"`
	OutputTokens int64    `json:"output_tokens"`
	TotalTokens  int64    `json:"total_tokens"`
	ErrorCount   int      `json:"error_count"`
	Cost         float64  `json:"cost"`
	IsSuccess    bool     `json:"is_success"`
	Error        []string `json:"error"`
}

SessionEndEvent represents session events

func (*SessionEndEvent) GetEventType

func (e *SessionEndEvent) GetEventType() EventType

func (*SessionEndEvent) ToStructuredProperties

func (e *SessionEndEvent) ToStructuredProperties() interface{}

type SessionEndPayload

type SessionEndPayload struct {
	Action       string   `json:"action"`
	SessionID    string   `json:"session_id"`
	AgentName    string   `json:"agent_name"`
	DurationMs   int64    `json:"duration_ms"`
	ToolCalls    int      `json:"tool_calls"`
	InputTokens  int64    `json:"input_tokens"`
	OutputTokens int64    `json:"output_tokens"`
	TotalTokens  int64    `json:"total_tokens"`
	Cost         float64  `json:"cost"`
	ErrorCount   int      `json:"error_count"`
	IsSuccess    bool     `json:"is_success"`
	Error        []string `json:"error"`
}

SessionEndPayload represents the HTTP payload structure for session events

type SessionStartEvent

type SessionStartEvent struct {
	Action    string `json:"action"`
	SessionID string `json:"session_id"`
	AgentName string `json:"agent_name"`
}

SessionStartEvent represents session events

func (*SessionStartEvent) GetEventType

func (e *SessionStartEvent) GetEventType() EventType

func (*SessionStartEvent) ToStructuredProperties

func (e *SessionStartEvent) ToStructuredProperties() interface{}

type SessionStartPayload

type SessionStartPayload struct {
	Action    string `json:"action"`
	SessionID string `json:"session_id"`
	AgentName string `json:"agent_name"`
}

SessionStartPayload represents the HTTP payload structure for session events

type SessionState

type SessionState struct {
	ID           string
	AgentName    string
	StartTime    time.Time
	ToolCalls    int
	TokenUsage   SessionTokenUsage
	ErrorCount   int
	Error        []string
	SessionEnded bool
}

SessionState consolidates all session-related tracking

type SessionTokenUsage

type SessionTokenUsage struct {
	InputTokens  int64   `json:"input_tokens"`
	OutputTokens int64   `json:"output_tokens"`
	Cost         float64 `json:"cost"`
}

SessionTokenUsage tracks token consumption

type StructuredEvent

type StructuredEvent interface {
	GetEventType() EventType
	ToStructuredProperties() interface{}
}

StructuredEvent represents a type-safe telemetry event with structured properties

type TokenEvent

type TokenEvent struct {
	Action       string  `json:"action"`
	ModelName    string  `json:"model_name"`
	SessionID    string  `json:"session_id"`
	AgentName    string  `json:"agent_name"`
	InputTokens  int64   `json:"input_tokens"`
	OutputTokens int64   `json:"output_tokens"`
	TotalTokens  int64   `json:"total_tokens"`
	Cost         float64 `json:"cost"`
}

TokenEvent represents token usage events

func (*TokenEvent) GetEventType

func (e *TokenEvent) GetEventType() EventType

func (*TokenEvent) ToStructuredProperties

func (e *TokenEvent) ToStructuredProperties() interface{}

type TokenPayload

type TokenPayload struct {
	Action       string  `json:"action"`
	SessionID    string  `json:"session_id"`
	AgentName    string  `json:"agent_name"`
	ModelName    string  `json:"model_name"`
	InputTokens  int64   `json:"input_tokens"`
	OutputTokens int64   `json:"output_tokens"`
	TotalTokens  int64   `json:"total_tokens"`
	Cost         float64 `json:"cost"`
}

TokenPayload represents the HTTP payload structure for token events

type ToolEvent

type ToolEvent struct {
	Action    string `json:"action"`
	ToolName  string `json:"tool_name"`
	SessionID string `json:"session_id"`
	AgentName string `json:"agent_name"`
	Duration  int64  `json:"duration_ms"`
	Success   bool   `json:"success"`
	Error     string `json:"error,omitempty"`
}

ToolEvent represents tool call events

func (*ToolEvent) GetEventType

func (e *ToolEvent) GetEventType() EventType

func (*ToolEvent) ToStructuredProperties

func (e *ToolEvent) ToStructuredProperties() interface{}

type ToolPayload

type ToolPayload struct {
	Action     string `json:"action"`
	SessionID  string `json:"session_id"`
	AgentName  string `json:"agent_name"`
	ToolName   string `json:"tool_name"`
	DurationMs int64  `json:"duration_ms"`
	IsSuccess  bool   `json:"is_success"`
	Error      string `json:"error,omitempty"`
}

ToolPayload represents the HTTP payload structure for tool events

Jump to

Keyboard shortcuts

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