Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
80 changes: 80 additions & 0 deletions common/commands/execution_context.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package commands

import (
"os"

"golang.org/x/term"
)

// ExecutionContext describes how a CLI invocation was launched.
// Dimensions are independent: an agent may run inside CI; both will be reported.
type ExecutionContext struct {
Agent string // e.g. "claude", "cursor", "gemini", "" if none
CISystem string // e.g. "github_actions", "" if not CI
Comment thread
fluxxBot marked this conversation as resolved.
Outdated
IsCI bool
IsAgent bool
IsInteractive bool // stdin is a TTY
TraceID string // propagated trace ID (e.g. CURSOR_TRACEID), empty if none
}

// agent env var detection table. First match wins.
var agentEnvDetectors = []struct {
name string
envs []string
}{
{"claude", []string{"CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT"}},
{"gemini", []string{"GEMINI_CLI"}},
{"goose", []string{"GOOSE_TERMINAL"}},
{"cursor", []string{"CURSOR_AGENT", "CURSOR_TRACEID"}},
{"copilot", []string{"COPILOT_CLI"}},
{"kilocode", []string{"KILO_IPC_SOCKET_PATH", "KILO_SERVER_PASSWORD"}},
Comment thread
fluxxBot marked this conversation as resolved.
{"roo_code", []string{"ROO_CODE_IPC_SOCKET_PATH"}},
{"replit", []string{"REPLIT_AGENT"}},
{"windsurf", []string{"WINDSURF_SESSION_ID"}},
Comment thread
fluxxBot marked this conversation as resolved.
Outdated
{"aider", []string{"AIDER_MODEL"}},
{"codex", []string{"CODEX_HOME"}},
Comment thread
fluxxBot marked this conversation as resolved.
Outdated
}

// DetectExecutionContext captures all signals about who executed the CLI.
func DetectExecutionContext() ExecutionContext {
ec := ExecutionContext{
IsInteractive: term.IsTerminal(int(os.Stdin.Fd())),
Comment thread
fluxxBot marked this conversation as resolved.
Outdated
}

ec.Agent = detectAgent()
ec.IsAgent = ec.Agent != ""
ec.TraceID = detectAgentTraceID(ec.Agent)

ec.CISystem = detectCISystem()
ec.IsCI = ec.CISystem != ""

return ec
}

func detectAgent() string {
for _, d := range agentEnvDetectors {
for _, e := range d.envs {
if os.Getenv(e) != "" {
return d.name
}
}
}
// Fallback: generic AGENT env var (goose convention, codex pending).
if v := os.Getenv("AGENT"); v != "" {
return v
}
Comment thread
fluxxBot marked this conversation as resolved.
Outdated
return ""
}

// detectAgentTraceID returns a trace ID propagated by the parent agent, if any.
// Only used when the detected agent itself owns the trace ID env var, so we don't
// reuse a stale ID leaked from an outer shell (e.g. CURSOR_TRACEID present while
// the actual invoker is Claude Code). Empty result means the CLI should generate
// its own trace ID.
func detectAgentTraceID(agent string) string {
switch agent {

Check failure on line 75 in common/commands/execution_context.go

View workflow job for this annotation

GitHub Actions / Static-Check

singleCaseSwitch: should rewrite switch statement to if statement (gocritic)

Check failure on line 75 in common/commands/execution_context.go

View workflow job for this annotation

GitHub Actions / Static-Check

singleCaseSwitch: should rewrite switch statement to if statement (gocritic)
case "cursor":
return os.Getenv("CURSOR_TRACEID")
Comment thread
fluxxBot marked this conversation as resolved.
Outdated
}
return ""
}
112 changes: 112 additions & 0 deletions common/commands/execution_context_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
package commands

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestDetectAgent_EnvVar(t *testing.T) {
cases := []struct {
envVar string
want string
}{
{"CLAUDECODE", "claude"},
{"CLAUDE_CODE_ENTRYPOINT", "claude"},
{"GEMINI_CLI", "gemini"},
{"GOOSE_TERMINAL", "goose"},
{"CURSOR_AGENT", "cursor"},
{"CURSOR_TRACEID", "cursor"},
{"COPILOT_CLI", "copilot"},
Comment thread
fluxxBot marked this conversation as resolved.
Outdated
{"KILO_IPC_SOCKET_PATH", "kilocode"},
{"ROO_CODE_IPC_SOCKET_PATH", "roo_code"},
{"REPLIT_AGENT", "replit"},
{"WINDSURF_SESSION_ID", "windsurf"},
{"AIDER_MODEL", "aider"},
{"CODEX_HOME", "codex"},
}
for _, c := range cases {
t.Run(c.envVar, func(t *testing.T) {
clearAgentEnvVars(t)
t.Setenv(c.envVar, "1")
assert.Equal(t, c.want, detectAgent())
})
}
}

func TestDetectAgent_GenericFallback(t *testing.T) {
clearAgentEnvVars(t)
t.Setenv("AGENT", "custom_bot")
assert.Equal(t, "custom_bot", detectAgent())
}

func TestDetectAgent_None(t *testing.T) {
clearAgentEnvVars(t)
assert.Equal(t, "", detectAgent())
}

func TestDetectAgentTraceID(t *testing.T) {
t.Setenv("CURSOR_TRACEID", "trace-abc")
assert.Equal(t, "trace-abc", detectAgentTraceID("cursor"))
// Trace ID gated on agent identity: a leaked CURSOR_TRACEID from an outer
// shell must not be reused when the real invoker is a different agent.
assert.Equal(t, "", detectAgentTraceID("claude"))
assert.Equal(t, "", detectAgentTraceID(""))
}

func TestDetectExecutionContext_AgentAndCI(t *testing.T) {
clearAgentEnvVars(t)
clearCIEnvVars(t)
t.Setenv("CLAUDECODE", "1")
t.Setenv("GITHUB_ACTIONS", "true")

inv := DetectExecutionContext()
assert.True(t, inv.IsAgent)
assert.True(t, inv.IsCI)
assert.Equal(t, "claude", inv.Agent)
assert.Equal(t, "github_actions", inv.CISystem)
}

func TestDetectExecutionContext_CIOnly(t *testing.T) {
clearAgentEnvVars(t)
clearCIEnvVars(t)
t.Setenv("GITHUB_ACTIONS", "true")

inv := DetectExecutionContext()
assert.False(t, inv.IsAgent)
assert.True(t, inv.IsCI)
assert.Equal(t, "github_actions", inv.CISystem)
}

func TestDetectExecutionContext_NoEnv(t *testing.T) {
clearAgentEnvVars(t)
clearCIEnvVars(t)

inv := DetectExecutionContext()
assert.False(t, inv.IsAgent)
assert.False(t, inv.IsCI)
assert.Equal(t, "", inv.Agent)
assert.Equal(t, "", inv.CISystem)
}

func clearAgentEnvVars(t *testing.T) {
t.Helper()
for _, d := range agentEnvDetectors {
for _, e := range d.envs {
t.Setenv(e, "")
}
}
t.Setenv("AGENT", "")
}

func clearCIEnvVars(t *testing.T) {
t.Helper()
for _, e := range []string{
"JENKINS_URL", "TRAVIS", "CIRCLECI", "GITHUB_ACTIONS", "GITLAB_CI",
"BUILDKITE", "BAMBOO_BUILD_KEY", "TF_BUILD", "TEAMCITY_VERSION",
"DRONE", "BITBUCKET_BUILD_NUMBER", "CODEBUILD_BUILD_ID",
"CI", "CONTINUOUS_INTEGRATION", "BUILD_ID", "BUILD_NUMBER",
} {
t.Setenv(e, "")
}
}
24 changes: 12 additions & 12 deletions common/commands/metrics_collector.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,24 +30,21 @@ func CollectMetrics(commandName string, flags []string) {
globalMetricsCollector.mu.Lock()
defer globalMetricsCollector.mu.Unlock()

ciSystem := detectCISystem()
isCI := ciSystem != ""
ec := DetectExecutionContext()

pkgAliasTool := globalMetricsCollector.packageAliasContext
globalMetricsCollector.packageAliasContext = ""

metricsData := &MetricsData{
Flags: flags,
Platform: runtime.GOOS,
Architecture: runtime.GOARCH,
IsCI: isCI,
CISystem: func() string {
if isCI {
return ciSystem
}
return ""
}(),
Flags: flags,
Platform: runtime.GOOS,
Architecture: runtime.GOARCH,
IsCI: ec.IsCI,
CISystem: ec.CISystem,
IsContainer: isRunningInContainer(),
IsAgent: ec.IsAgent,
Agent: ec.Agent,
Comment thread
fluxxBot marked this conversation as resolved.
IsInteractive: ec.IsInteractive,
PackageAlias: pkgAliasTool != "",
PackageManager: pkgAliasTool,
}
Expand All @@ -73,6 +70,9 @@ func GetCollectedMetrics(commandName string) *MetricsData {
IsCI: metrics.IsCI,
CISystem: metrics.CISystem,
IsContainer: metrics.IsContainer,
IsAgent: metrics.IsAgent,
Agent: metrics.Agent,
IsInteractive: metrics.IsInteractive,
PackageAlias: metrics.PackageAlias,
PackageManager: metrics.PackageManager,
}
Expand Down
3 changes: 3 additions & 0 deletions utils/metrics/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ type MetricsData struct {
IsCI bool `json:"is_ci,omitempty"`
CISystem string `json:"ci_system,omitempty"`
IsContainer bool `json:"is_container,omitempty"`
IsAgent bool `json:"is_agent,omitempty"`
Agent string `json:"agent,omitempty"`
IsInteractive bool `json:"is_interactive,omitempty"`
PackageAlias bool `json:"package_alias,omitempty"`
PackageManager string `json:"package_manager,omitempty"`
}
Loading