Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,11 @@ internal/cli/
install_doctor.go Top-level agora doctor — install self-test (PATH, network, auth, MCP host)
env_help.go agora env-help — authoritative env-var catalog
skills.go agora skills — curated workflow recipes (in-binary catalog)
telemetry.go telemetryClient interface + noop sink + Sentry placeholder (wire-up scheduled for next release)
telemetry.go Shared telemetry gate (telemetryAllowed / runtime opt-out) + diagnostics telemetryClient interface, noop sink and Sentry placeholder (no DSN shipped)
telemetry_notice.go Telemetry preference persistence, first-use disclosure, shared telemetry status result
analytics.go Usage analytics: operation lifecycle, installation ID, agent classification, init stages, allowlisted values
analytics_sender.go Usage analytics delivery: 64 KiB batching, allowlist validation, detached shell sender, in-process MCP sender
analytics_process_*.go Per-OS detach settings for the shell sender subprocess
local_project.go .agora/project.json read/write; repo-local project binding
runtime_support.go Template/runtime detection (nextjs, python, go), CI auto-detect, banner rules
app_test.go Unit tests for app init and config
Expand Down
32 changes: 23 additions & 9 deletions docs/telemetry.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,28 +22,42 @@ fails. Only attempts with a confirmed public catalog entry include a Recipe ID.
When reporting per-Recipe results, show unconfirmed attempts separately.
An existing target directory is reported as a local validation failure.

Project creation (`agora project create`, and the project step of `agora init`)
is reported when the create API call returns, and its duration covers only that
call. A project that is created successfully is recorded as a success even if a
later step, such as enabling features, fails; the outer command result still
reports that failure. A `project create` that fails before reaching the API
(for example, invalid flags or an unreadable local context) is reported as a
failure when the command finishes.

## Delivery

Each instrumented shell command collects its events in memory and flushes them
when the operation finishes. MCP flushes after each instrumented tool call,
independently of other calls and without waiting for the MCP server to exit.

The CLI passes one JSON batch through stdin to a detached sender subprocess.
The sender makes one HTTP request with a ten-second timeout. The business
command waits only for a local handoff of at most 100 ms, not for the network
response. Telemetry failures do not change business output or exit codes.
A shell command passes one JSON batch through stdin to a detached sender
subprocess, which outlives the command. The business command waits only for a
local handoff of at most 100 ms, not for the network response. Because
`agora mcp serve` is long-lived, it sends each tool call's batch from a
background goroutine in the same process instead of spawning a subprocess; the
tool response never waits for it. When the MCP host closes stdin, the server
waits at most one second for in-flight batches before exiting. Both paths
apply the same validation and make one HTTP request with a ten-second timeout.
Telemetry failures do not change business output or exit codes.

The complete request is limited to 64 KiB. There is no separate event-count or
per-event size cap. If an operation exceeds the request limit, its entire batch
is dropped. There is no disk queue or retry. A crash or forced termination before
handoff can lose all events for that operation; long-running operations are not
visible in telemetry until they finish. Successful delivery is best effort and
does not prove that PostHog has made the events available for queries.
handoff (or, for MCP, before the request completes) can lose all events for
that operation; long-running operations are not visible in telemetry until they
finish. Successful delivery is best effort and does not prove that PostHog has
made the events available for queries.

The sender honors `HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY` and their lowercase
forms, as the business HTTP client does. It also preserves `SSL_CERT_FILE` and
`SSL_CERT_DIR` for custom certificate authorities. Other parent environment
variables are not inherited. Business authorization headers are not attached to
`SSL_CERT_DIR` for custom certificate authorities. The shell sender subprocess
does not inherit other parent environment variables. Business authorization headers are not attached to
telemetry requests, and redirects are not followed.

## Inspect or change the setting
Expand Down
122 changes: 81 additions & 41 deletions internal/cli/analytics.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"path/filepath"
"regexp"
"runtime"
"slices"
"strings"
"time"

Expand All @@ -29,6 +30,42 @@ var analyticsSlugPattern = regexp.MustCompile(`^[a-z0-9]+(?:-[a-z0-9]+)*$`)
var analyticsVersionPattern = regexp.MustCompile(`^[A-Za-z0-9.+_-]{0,64}$`)
var analyticsCodePattern = regexp.MustCompile(`^[A-Z][A-Z0-9_]{0,63}$`)

// Init stage names. These and the agent value sets below are part of the
// collector allowlist: emit sites and validAnalyticsEvent share them so the
// two can never drift.
const (
analyticsStageValidate = "validate"
analyticsStageSourceResolve = "source_resolve"
analyticsStageLocalValidate = "local_validate"
analyticsStageProjectResolve = "project_resolve"
analyticsStageClone = "clone"
analyticsStageEnvWrite = "env_write"
analyticsStageBindingWrite = "binding_write"
analyticsStageContextWrite = "context_write"
analyticsStageAgentRulesWrite = "agent_rules_write"
)

var analyticsStages = []string{analyticsStageValidate, analyticsStageSourceResolve, analyticsStageLocalValidate, analyticsStageProjectResolve, analyticsStageClone, analyticsStageEnvWrite, analyticsStageBindingWrite, analyticsStageContextWrite, analyticsStageAgentRulesWrite}

const (
analyticsAgentCustom = "custom"
analyticsValueUnknown = "unknown"

analyticsSurfaceDesktop = "desktop"
analyticsSurfaceCLI = "cli"

analyticsDetectionExplicit = "explicit"
analyticsDetectionEnvironment = "environment"
analyticsDetectionNone = "none"
)

// analyticsKnownAgentFamilies are agent labels reported as-is; any other
// detected label is reported as analyticsAgentCustom.
var analyticsKnownAgentFamilies = []string{"codex", "claude-code", "kiro", "cursor", "cline", "windsurf", "aider"}
var analyticsAgentFamilies = append(slices.Clone(analyticsKnownAgentFamilies), analyticsAgentCustom, analyticsValueUnknown)
var analyticsAgentSurfaces = []string{analyticsSurfaceDesktop, analyticsSurfaceCLI, analyticsValueUnknown}
var analyticsDetectionSources = []string{analyticsDetectionExplicit, analyticsDetectionEnvironment, analyticsDetectionNone}

type analyticsEvent struct {
Event string `json:"event"`
EventID string `json:"event_id"`
Expand All @@ -40,6 +77,7 @@ type analyticsEvent struct {

type analyticsOperation struct {
command string
channel string
id string
distinctID string
properties map[string]any
Expand All @@ -50,6 +88,9 @@ type analyticsOperation struct {
events []json.RawMessage
batchBytes int
endpoint string
// projectCreateReported is set once the createProject API boundary has
// emitted cli_project_create_completed for this operation.
projectCreateReported bool
}

type analyticsContextKey struct{}
Expand All @@ -65,24 +106,10 @@ func analyticsUUID() string {
return h[:8] + "-" + h[8:12] + "-" + h[12:16] + "-" + h[16:20] + "-" + h[20:]
}

// analyticsEnabled applies the shared telemetry gate to the startup
// preference. Shell commands use this snapshot for their whole run.
func (a *App) analyticsEnabled() bool {
if a.analyticsOptedOut() {
return false
}
return a.cfg.TelemetryEnabled
}

func (a *App) analyticsOptedOut() bool {
if a == nil || strings.TrimSpace(a.env["DO_NOT_TRACK"]) != "" || a.env["AGORA_TELEMETRY_ENABLED"] == "0" {
return true
}
sentryOverride := a.env["AGORA_SENTRY_ENABLED"]
if a.cfgState.ConfigFilePath != "" {
// applyConfigToEnv also writes this key. Only an explicit OS override
// should mask a preference changed since this MCP process started.
sentryOverride = a.osEnv["AGORA_SENTRY_ENABLED"]
}
return sentryOverride == "0"
return a.telemetryAllowed(a.cfg.TelemetryEnabled)
}

func (a *App) currentTelemetryPreference() bool {
Expand Down Expand Up @@ -173,7 +200,7 @@ func (a *App) beginAnalytics(command, channel string) *analyticsOperation {
endpoint := a.analyticsURL()
enabled := a.analyticsEnabled()
if channel == "mcp" {
enabled = a.currentTelemetryPreference() && !a.analyticsOptedOut()
enabled = a.telemetryAllowed(a.currentTelemetryPreference())
}
if !enabled || endpoint == "" {
return nil
Expand All @@ -190,48 +217,53 @@ func (a *App) beginAnalytics(command, channel string) *analyticsOperation {
if id == "" {
return nil
}
op := &analyticsOperation{command: command, id: analyticsUUID(), distinctID: id, properties: props, started: time.Now(), endpoint: endpoint}
op := &analyticsOperation{command: command, channel: channel, id: analyticsUUID(), distinctID: id, properties: props, started: time.Now(), endpoint: endpoint}
op.batchBytes = len(analyticsBatchEnvelope)
if command == "init" {
event := op.newEvent("cli_init_started", nil)
start, err := json.Marshal(event)
if err != nil {
return nil
}
op.initStarted = &event
op.beginStage("validate")
// flush prepends this event after copying source attribution onto it,
// so reserve its worst-case size (plus the separating comma) up front.
op.batchBytes += len(start) + analyticsStartAttributionReserve + 1
op.beginStage(analyticsStageValidate)
}
return op
}

func analyticsAgent(env map[string]string) (family, surface, source string) {
surface, source = "unknown", "none"
family, surface, source = analyticsValueUnknown, analyticsValueUnknown, analyticsDetectionNone
label := agentLabelFromOSEnv(env)
family = "unknown"
if label == "" {
return
}
source = "environment"
source = analyticsDetectionEnvironment
if strings.TrimSpace(env["AGORA_AGENT"]) != "" {
source = "explicit"
source = analyticsDetectionExplicit
}
switch label {
case "codex", "claude-code", "kiro", "cursor", "cline", "windsurf", "aider":
family = analyticsAgentCustom
if slices.Contains(analyticsKnownAgentFamilies, label) {
family = label
default:
family = "custom"
}
if family == "claude-code" {
switch env["CLAUDE_CODE_ENTRYPOINT"] {
case "cli":
surface = "cli"
surface = analyticsSurfaceCLI
case "claude-desktop":
surface = "desktop"
surface = analyticsSurfaceDesktop
}
}
if family == "codex" && env["CODEX_INTERNAL_ORIGINATOR_OVERRIDE"] == "Codex Desktop" {
surface = "desktop"
surface = analyticsSurfaceDesktop
}
if family == "kiro" {
if env["AWS_SDK_UA_APP_ID"] == "kiro-ide" {
surface = "desktop"
surface = analyticsSurfaceDesktop
} else if env["KIRO_CLI_ACP_CLIENT_NAME"] == "kiro-tui" {
surface = "cli"
surface = analyticsSurfaceCLI
}
}
return
Expand Down Expand Up @@ -302,7 +334,10 @@ func (op *analyticsOperation) finish(err error) {
if op.command == "init" && failedStage != "" {
fields["failed_stage"] = failedStage
}
if op.command != "project create" {
// `project create` normally reports at the API boundary (projectCreated)
// so its timing excludes later feature work. A failure before that call
// (not logged in, unreadable context, invalid flags) reports here instead.
if op.command != "project create" || !op.projectCreateReported {
op.emit(event, fields)
}
op.flush()
Expand Down Expand Up @@ -333,13 +368,6 @@ func (a *App) instrumentAnalytics(cmd *cobra.Command, command string) {
}
}

func firstAnalytics(ops []*analyticsOperation) *analyticsOperation {
if len(ops) > 0 {
return ops[0]
}
return nil
}

func (op *analyticsOperation) setInitSourceType(recipe, template string) {
if op == nil {
return
Expand Down Expand Up @@ -373,6 +401,17 @@ func (op *analyticsOperation) setAppID(id string) {
op.properties["app_id"] = id
}

// setProjectAction records whether init created a project or reused one.
func (op *analyticsOperation) setProjectAction(action string) {
if op == nil {
return
}
op.properties["project_action"] = "reused"
if action == "created" {
op.properties["project_action"] = "created"
}
}

func (op *analyticsOperation) projectCreated(id string, started time.Time, err error) {
if op == nil {
return
Expand All @@ -386,4 +425,5 @@ func (op *analyticsOperation) projectCreated(id string, started time.Time, err e
exit = exitCodeForError(err)
}
op.emit("cli_project_create_completed", map[string]any{"outcome": outcome, "error_code": code, "duration_ms": time.Since(started).Milliseconds(), "exit_code": exit})
op.projectCreateReported = true
}
Loading
Loading