-
Notifications
You must be signed in to change notification settings - Fork 1.2k
feat: detect AI agent invocations in telemetry #9127
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
madhavdonthula1
wants to merge
1
commit into
aws:develop
Choose a base branch
from
madhavdonthula1:add_opencode_copilot
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| """ | ||
| Module used for detecting whether SAMCLI is executed by an AI agent. | ||
| """ | ||
|
|
||
| import os | ||
| from enum import Enum, auto | ||
| from typing import Callable, Dict, Mapping, Optional, Union | ||
|
|
||
|
|
||
| class Agent(Enum): | ||
| ClaudeCode = auto() | ||
| Codex = auto() | ||
| Cursor = auto() | ||
| GeminiCLI = auto() | ||
| Kiro = auto() | ||
| OpenCode = auto() | ||
| GitHubCopilot = auto() | ||
|
|
||
|
|
||
| def _is_codex(environ: Mapping) -> bool: | ||
| """ | ||
| Whether it is running in Codex (OpenAI's Codex CLI). Codex sets a family of | ||
| CODEX_* variables rather than one canonical var (e.g. CODEX_SANDBOX, CODEX_CI, | ||
| CODEX_THREAD_ID), so match any name starting with "CODEX_". | ||
| """ | ||
| return any(key.startswith("CODEX_") for key in environ) | ||
|
|
||
|
|
||
| def _is_kiro(environ: Mapping) -> bool: | ||
| """ | ||
| Whether it is running in Kiro (the Kiro IDE, via TERM_PROGRAM=kiro, or the Kiro | ||
| CLI, the renamed Amazon Q Developer CLI, via AWS_EXECUTION_ENV). AWS_EXECUTION_ENV | ||
| is shared with AWS Lambda/CloudShell/CodeBuild (e.g. "AWS_Lambda_python3.12"), so | ||
| it is substring-matched on "amazonq"/"kiro", not checked for presence, to avoid | ||
| misattributing those environments. | ||
|
|
||
| NOTE: the "amazonq" substring also matches the genuine Amazon Q Developer CLI. | ||
| Amazon Q is deferred for now, so its CLI runs are attributed to kiro until a | ||
| dedicated Amazon Q agent is added (which must be ordered AFTER Kiro in the enum). | ||
| """ | ||
| if environ.get("TERM_PROGRAM", "") == "kiro": | ||
| return True | ||
| aws_execution_env: str = environ.get("AWS_EXECUTION_ENV", "").lower() | ||
| return "amazonq" in aws_execution_env or "kiro" in aws_execution_env | ||
|
|
||
|
|
||
| _ENV_VAR_OR_CALLABLE_BY_AGENT: Dict[Agent, Union[str, Callable[[Mapping], bool]]] = { | ||
| # https://docs.anthropic.com/en/docs/claude-code | ||
| Agent.ClaudeCode: "CLAUDECODE", | ||
| # https://developers.openai.com/codex/cli | ||
| Agent.Codex: _is_codex, | ||
| # match presence, not value: the value is not guaranteed stable | ||
| Agent.Cursor: "CURSOR_AGENT", | ||
| # exact name, not a prefix, so GEMINI_CLI_HOME / GEMINI_CLI_NO_RELAUNCH don't match | ||
| Agent.GeminiCLI: "GEMINI_CLI", | ||
| Agent.Kiro: _is_kiro, | ||
| # OpenCode sets OPENCODE=1 in its root CLI middleware | ||
| Agent.OpenCode: "OPENCODE", | ||
| Agent.GitHubCopilot: "COPILOT_AGENT_SESSION_ID", | ||
| } | ||
|
|
||
|
|
||
| def _is_agent(agent: Agent, environ: Mapping) -> bool: | ||
| """ | ||
| Check whether sam-cli is run by a particular AI agent based on certain environment variables. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| agent | ||
| an enum Agent object indicating which AI agent to check against. | ||
| environ | ||
| the mapping to look for environment variables, for example, os.environ. | ||
|
|
||
| Returns | ||
| ------- | ||
| bool | ||
| A boolean indicating whether there are environment variables matching the agent. | ||
| """ | ||
| env_var_or_callable = _ENV_VAR_OR_CALLABLE_BY_AGENT[agent] | ||
| if isinstance(env_var_or_callable, str): | ||
| return env_var_or_callable in environ | ||
|
|
||
| # it is a callable, use the return value | ||
| return env_var_or_callable(environ) | ||
|
|
||
|
|
||
| class AgentDetector: | ||
| _agent: Optional[Agent] | ||
|
|
||
| def __init__(self): | ||
| try: | ||
| self._agent: Optional[Agent] = next(agent for agent in Agent if _is_agent(agent, os.environ)) | ||
| except StopIteration: | ||
| self._agent = None | ||
|
|
||
| def agent(self) -> Optional[Agent]: | ||
| """ | ||
| Identify which AI agent SAM CLI is running in. | ||
| Returns | ||
| ------- | ||
| Agent | ||
| an optional Agent enum indicating the AI agent. | ||
| """ | ||
| return self._agent | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,91 @@ | ||
| from unittest import TestCase | ||
| from unittest.mock import patch | ||
|
|
||
| from parameterized import parameterized | ||
|
|
||
| from samcli.lib.telemetry.agent_detector import Agent, AgentDetector, _is_agent | ||
|
|
||
|
|
||
| class TestAgentDetector(TestCase): | ||
| @parameterized.expand( | ||
| [ | ||
| (Agent.ClaudeCode, "CLAUDECODE", "1"), | ||
| (Agent.Codex, "CODEX_SANDBOX", "seatbelt"), | ||
| (Agent.Cursor, "CURSOR_AGENT", "1"), | ||
| (Agent.GeminiCLI, "GEMINI_CLI", "1"), | ||
| (Agent.Kiro, "TERM_PROGRAM", "kiro"), | ||
| (Agent.Kiro, "AWS_EXECUTION_ENV", "AmazonQ-For-CLI Version/1.13.3"), | ||
| (Agent.OpenCode, "OPENCODE", "1"), | ||
| (Agent.GitHubCopilot, "COPILOT_AGENT_SESSION_ID", "0b8f6e2c-1a3d-4c9e-8f7a-2b1c0d9e8f7a"), | ||
| ] | ||
| ) | ||
| def test_is_agent(self, agent, env_var, env_var_value): | ||
| self.assertTrue(_is_agent(agent, {env_var: env_var_value})) | ||
|
|
||
| @parameterized.expand( | ||
| [ | ||
| (Agent.ClaudeCode, "NOT_CLAUDECODE", "1"), | ||
| (Agent.Codex, "NOT_CODEX_SANDBOX", "seatbelt"), | ||
| (Agent.Cursor, "NOT_CURSOR_AGENT", "1"), | ||
| # exact-name rule: GEMINI_CLI_HOME must not match Agent.GeminiCLI | ||
| (Agent.GeminiCLI, "GEMINI_CLI_HOME", "1"), | ||
| # shared-variable rule: a Lambda AWS_EXECUTION_ENV must not match Agent.Kiro | ||
| (Agent.Kiro, "AWS_EXECUTION_ENV", "AWS_Lambda_python3.12"), | ||
| # too-generic var: AGENT alone (no OPENCODE) must not match Agent.OpenCode | ||
| (Agent.OpenCode, "AGENT", "1"), | ||
| ] | ||
| ) | ||
| def test_is_not_agent(self, agent, env_var, env_var_value): | ||
| self.assertFalse(_is_agent(agent, {env_var: env_var_value})) | ||
|
|
||
| @patch.dict("samcli.lib.telemetry.agent_detector.os.environ", {"CLAUDECODE": "1"}, clear=True) | ||
| def test_detector_identifies_claude_code(self): | ||
| self.assertEqual(AgentDetector().agent(), Agent.ClaudeCode) | ||
|
|
||
| @patch.dict("samcli.lib.telemetry.agent_detector.os.environ", {"CODEX_SANDBOX": "seatbelt"}, clear=True) | ||
| def test_detector_identifies_codex(self): | ||
| self.assertEqual(AgentDetector().agent(), Agent.Codex) | ||
|
|
||
| @patch.dict("samcli.lib.telemetry.agent_detector.os.environ", {"CURSOR_AGENT": "1"}, clear=True) | ||
| def test_detector_identifies_cursor(self): | ||
| self.assertEqual(AgentDetector().agent(), Agent.Cursor) | ||
|
|
||
| @patch.dict("samcli.lib.telemetry.agent_detector.os.environ", {"GEMINI_CLI": "1"}, clear=True) | ||
| def test_detector_identifies_gemini_cli(self): | ||
| self.assertEqual(AgentDetector().agent(), Agent.GeminiCLI) | ||
|
|
||
| @patch.dict("samcli.lib.telemetry.agent_detector.os.environ", {"TERM_PROGRAM": "kiro"}, clear=True) | ||
| def test_detector_identifies_kiro_ide(self): | ||
| self.assertEqual(AgentDetector().agent(), Agent.Kiro) | ||
|
|
||
| @patch.dict( | ||
| "samcli.lib.telemetry.agent_detector.os.environ", | ||
| {"AWS_EXECUTION_ENV": "AmazonQ-For-CLI Version/1.13.3"}, | ||
| clear=True, | ||
| ) | ||
| def test_detector_identifies_kiro_cli(self): | ||
| self.assertEqual(AgentDetector().agent(), Agent.Kiro) | ||
|
|
||
| @patch.dict( | ||
| "samcli.lib.telemetry.agent_detector.os.environ", | ||
| {"AWS_EXECUTION_ENV": "AWS_Lambda_python3.12"}, | ||
| clear=True, | ||
| ) | ||
| def test_detector_does_not_identify_lambda_as_kiro(self): | ||
| self.assertIsNone(AgentDetector().agent()) | ||
|
|
||
| @patch.dict("samcli.lib.telemetry.agent_detector.os.environ", {"OPENCODE": "1"}, clear=True) | ||
| def test_detector_identifies_opencode(self): | ||
| self.assertEqual(AgentDetector().agent(), Agent.OpenCode) | ||
|
|
||
| @patch.dict( | ||
| "samcli.lib.telemetry.agent_detector.os.environ", | ||
| {"COPILOT_AGENT_SESSION_ID": "0b8f6e2c-1a3d-4c9e-8f7a-2b1c0d9e8f7a"}, | ||
| clear=True, | ||
| ) | ||
| def test_detector_identifies_github_copilot(self): | ||
| self.assertEqual(AgentDetector().agent(), Agent.GitHubCopilot) | ||
|
|
||
| @patch.dict("samcli.lib.telemetry.agent_detector.os.environ", {}, clear=True) | ||
| def test_detector_returns_none_when_no_agent(self): | ||
| self.assertIsNone(AgentDetector().agent()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm curious where you found this, I only see it when directly examining the code, but couldn't find it documented anywhere.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good catch, it's not documented anywhere official I also found it by directly reading OpenCode's source. It's set in the root CLI middleware here: github link