Skip to content

feat(telemetry): add agent detection tag for AI coding tools#687

Merged
BYK merged 9 commits intomainfrom
feat/detect-agent
Apr 9, 2026
Merged

feat(telemetry): add agent detection tag for AI coding tools#687
BYK merged 9 commits intomainfrom
feat/detect-agent

Conversation

@betegon
Copy link
Copy Markdown
Member

@betegon betegon commented Apr 8, 2026

Summary

Adds an agent tag to telemetry spans when the CLI is invoked by a known AI coding tool. Detection uses two strategies:

  1. Environment variables (sync, instant) — agents inject these into child processes. Adapted from Vercel's @vercel/detect-agent (Apache-2.0).
  2. Process tree walking (async, non-blocking) — scans parent/grandparent process names for known agent executables. Fires in the background so it never delays CLI startup.

Supported agents (env vars)

Agent Env var(s)
Generic override AI_AGENT
Cursor CURSOR_TRACE_ID, CURSOR_AGENT
Gemini GEMINI_CLI
Codex CODEX_SANDBOX, CODEX_CI, CODEX_THREAD_ID
Antigravity ANTIGRAVITY_AGENT
Augment AUGMENT_AGENT
OpenCode OPENCODE_CLIENT
Claude Code CLAUDE_CODE, CLAUDECODE
Cowork CLAUDE_CODE + CLAUDE_CODE_IS_COWORK
GitHub Copilot COPILOT_MODEL, COPILOT_ALLOW_ALL
Goose GOOSE_TERMINAL
Amp AMP_THREAD_ID
Generic fallback AGENT

Intentionally excluded: REPL_ID (set in all Replit workspaces, not just AI agent sessions) and COPILOT_GITHUB_TOKEN (auth credential users may export persistently).

New agents can be added with a single ["ENV_VAR", "agent-name"] line in the ENV_VAR_AGENTS map.

Process tree detection (fallback)

When no env var matches, the CLI asynchronously walks the parent process tree (up to 5 levels) looking for known agent executables:

cursor, claude, goose, windsurf, amp, codex, augment, opencode, gemini

  • Linux: reads /proc/<pid>/status (in-memory filesystem, fast)
  • macOS: uses ps(1) with a 500ms timeout, child process unreffed to never block exit
  • Windows: not supported (env var detection still works)

Detection priority

  1. AI_AGENT env var (explicit override)
  2. Agent-specific env vars (ENV_VAR_AGENTS map)
  3. Claude Code / Cowork (conditional logic)
  4. AGENT env var (generic fallback — explicit signal beats heuristic)
  5. Process tree walking (async, best-effort — may miss very fast commands)

Known limitations

  • Fast commands: Process tree detection runs asynchronously. For commands completing in <50ms where no env vars are set, the tag may not be applied before the transaction ends. This is an intentional trade-off — env vars cover the vast majority of agent invocations instantly.
  • Windows: No process tree detection (no /proc/ or ps). Env var detection still works.

Test plan

  • 47 unit tests covering env var detection, process tree walking, depth limits, case-insensitive matching, priority ordering, map structure validation, and real /proc/ reads
  • Manual: CLAUDE_CODE=1 bunx sentry-cli auth status and verify span has agent: claude

@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Apr 8, 2026

Semver Impact of This PR

🟡 Minor (new features)

📋 Changelog Preview

This is how your changes will appear in the changelog.
Entries from this PR are highlighted with a left border (blockquote style).


New Features ✨

Docs

  • Deploy main branch preview alongside PR previews by BYK in #707
  • Enable sourcemap upload, releases, and environment tracking by BYK in #705

Other

  • (commands) Add buildRouteMap wrapper with standard subcommand aliases by BYK in #690
  • (config) Support .sentryclirc config file for per-directory defaults by BYK in #693
  • (init) Add fuzzy edit replacers and edits-based apply-patchset by betegon in #698
  • (install) Add SENTRY_INIT env var to run wizard after install by betegon in #685
  • (release) Surface adoption and health metrics in list and view (Add release command group with adoption/health subcommand #463) by BYK in #680
  • (telemetry) Add agent detection tag for AI coding tools by betegon in #687

Bug Fixes 🐛

Dashboard

  • Add --layout flag to widget add for predictable placement by BYK in #700
  • Render tracemetrics widgets in dashboard view by BYK in #695

Other

  • (build) Enable sourcemap resolution for compiled binaries by BYK in #701
  • (init) Narrow command validation to actual shell injection vectors by betegon in #697
  • (init,feedback) Default to tracing only in feature select and attach user email to feedback by MathurAditya724 in #688
  • (setup) Handle read-only .claude directory in sandboxed environments by BYK in #702

Internal Changes 🔧

  • (docs) Gitignore generated command docs, extract fragments by BYK in #696
  • (eval) Replace OpenAI with Anthropic SDK in init-eval judge by betegon in #683
  • (init) Use markdown pipeline for spinner messages by betegon in #686
  • Regenerate skill files and command docs by github-actions[bot] in 584ec0e0

🤖 This preview updates automatically when you update the PR.

@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Apr 8, 2026

PR Preview Action v1.8.1

QR code for preview link

🚀 View preview at
https://cli.sentry.dev/pr-preview/pr-687/

Built to branch gh-pages at 2026-04-09 17:16 UTC.
Preview will be ready when the GitHub Pages deployment is complete.

@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Apr 8, 2026

Codecov Results 📊

134 passed | Total: 134 | Pass Rate: 100% | Execution Time: 0ms

📊 Comparison with Base Branch

Metric Change
Total Tests
Passed Tests
Failed Tests
Skipped Tests

✨ No test changes detected

All tests are passing successfully.

✅ Patch coverage is 95.93%. Project has 1574 uncovered lines.
✅ Project coverage is 95.3%. Comparing base (base) to head (head).

Files with missing lines (2)
File Patch % Lines
src/lib/telemetry.ts 78.57% ⚠️ 3 Missing
src/lib/detect-agent.ts 98.17% ⚠️ 2 Missing
Coverage diff
@@            Coverage Diff             @@
##          main       #PR       +/-##
==========================================
+ Coverage    95.30%    95.30%        —%
==========================================
  Files          229       230        +1
  Lines        33377     33499      +122
  Branches         0         0         —
==========================================
+ Hits         31808     31925      +117
- Misses        1569      1574        +5
- Partials         0         0         —

Generated by Codecov Action

@betegon betegon marked this pull request as ready for review April 8, 2026 11:30
@betegon betegon requested a review from BYK April 8, 2026 11:39
@betegon
Copy link
Copy Markdown
Member Author

betegon commented Apr 8, 2026

@BYK We're missing some of the smaller ones but these should be a good list to start with. @vercel/detect-agent gets these and Devin. haven't included Devin as I believe checking /opt/.devin is the only way to identify it. I'll add it in a follow up PR

betegon and others added 3 commits April 9, 2026 15:11
Detect whether the CLI is being driven by an AI coding agent and tag
the telemetry span with the agent name. Uses environment variables that
agents inject into child processes (e.g. CLAUDE_CODE, CURSOR_TRACE_ID).

Supports a generic AI_AGENT override and an AGENT fallback so new tools
work out of the box. Adapted from Vercel's @vercel/detect-agent.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
…ection

- Convert AGENT_ENV_VARS array-of-objects to a flat Map<string, string>
  mapping each env var directly to its agent name (simpler lookups,
  one-line additions for new agents)
- Add process tree walking as fallback detection: scan parent →
  grandparent → ... for known agent executables (up to 5 levels)
- Linux: reads /proc/<pid>/status (in-memory, no subprocess overhead)
- macOS: falls back to ps(1) via execFileSync
- Injectable via setProcessInfoProvider() for testing (same pattern
  as setEnv)
- 50 tests (up from 29) covering env vars, Map structure, process
  tree walking, depth limits, and real process info reads
@BYK BYK force-pushed the feat/detect-agent branch from 4ec842e to 15f3696 Compare April 9, 2026 15:42
Users may export COPILOT_GITHUB_TOKEN persistently in their shell
config for authentication purposes, not just when Copilot is actively
driving the CLI. This caused false-positive agent tagging. Keep
COPILOT_MODEL and COPILOT_ALLOW_ALL which indicate active agent control.
Prevents CLI from hanging indefinitely on macOS if ps is unresponsive
during agent detection at startup.
BYK added 2 commits April 9, 2026 16:10
REPL_ID is set in ALL Replit workspaces, not just when the Replit AI
agent is driving the CLI. Same class of false positive as
COPILOT_GITHUB_TOKEN — a platform environment marker rather than an
agent control signal.
Process tree detection (reading /proc/ or spawning ps) should never
block CLI startup for a telemetry side-effect. Split the detection:

- detectAgent() is sync — env var lookups only (instant)
- detectAgentFromProcessTree() is async — fires as a background task
  in initSentry(), sets the Sentry tag when it resolves

Uses readFile (node:fs/promises) and promisified execFile instead of
their sync counterparts. Windows is explicitly unsupported for process
tree detection (env var detection still works everywhere).
BYK added 2 commits April 9, 2026 16:51
Prevents unhandled promise rejection if the async detection fails,
particularly important in library mode where OnUnhandledRejection
is excluded.
- Replace promisify(execFile) with a manual wrapper that calls
  child.unref() so the spawned ps process never prevents CLI exit
- Log a warning via logger.withTag('agent') instead of silently
  swallowing errors in the .catch() handler
Copy link
Copy Markdown
Contributor

@cursor cursor bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit e1d4849. Configure here.

@BYK BYK merged commit fc2ac72 into main Apr 9, 2026
28 checks passed
@BYK BYK deleted the feat/detect-agent branch April 9, 2026 18:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants