Skip to content
182 changes: 116 additions & 66 deletions sentry_sdk/_agent_hint.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,22 @@
import atexit
import os
import subprocess
import sys
import time
from typing import TYPE_CHECKING

from sentry_sdk.utils import (
_git,
_is_external_source,
capture_internal_exceptions,
env_to_bool,
)

if TYPE_CHECKING:
from types import FrameType
from typing import Any, Dict, Optional
from typing import Any, Dict

SETUP_CHECKLIST_PATH = os.path.join(os.path.dirname(__file__), "SETUP_CHECKLIST.md")

# Set by coding agents in the commands they run. AI_AGENT is the cross-tool
# convention; the rest cover agents that don't set it.
CODING_AGENT_ENV_VARS = (
"CLAUDECODE",
"CODEX_THREAD_ID",
Expand All @@ -27,7 +25,6 @@
"GEMINI_CLI",
)

# How long after a change to the file that calls init() the setup counts as in progress.
# Without git we can't tell whose change it is, so the window is shorter.
SETUP_IN_PROGRESS_SECONDS = 60 * 60
SETUP_IN_PROGRESS_SECONDS_WITHOUT_GIT = 10 * 60
Expand All @@ -48,31 +45,7 @@ def _running_under_coding_agent() -> bool:
return any(os.environ.get(name) for name in CODING_AGENT_ENV_VARS)


_MISSING_PRODUCTS = {
(False, False): (
"Sentry will get errors from this app but not the request trace around them, "
"and its logs only as breadcrumbs.",
"Tracing and logs are off, so Sentry only gets errors.",
"they're",
"them",
),
(False, True): (
"Sentry will get errors from this app but not the request trace around them.",
"Tracing is off, so Sentry gets errors and logs but no traces.",
"it's",
"it",
),
(True, False): (
"Sentry will get errors from this app but its logs only as breadcrumbs.",
"Logs are off, so Sentry gets errors and traces but no logs.",
"it's",
"it",
),
}


def _setup_in_progress(init_file: str) -> bool:
"""Whether this user changed the file that calls init() a short time ago."""
now = time.time()
cutoff = now - SETUP_IN_PROGRESS_SECONDS
try:
Expand All @@ -82,73 +55,154 @@ def _setup_in_progress(init_file: str) -> bool:
if changed < cutoff:
return False

def git(*args: str) -> "Optional[str]":
# Read only: don't take the index lock (the user or an agent may be running
# git at the same time) and don't run a configured fsmonitor command.
return _git(
"--no-optional-locks",
"-c",
"core.fsmonitor=false",
*args,
cwd=os.path.dirname(init_file),
)
cwd = os.path.dirname(init_file)

# --branch adds a header line, so an empty answer means git has no answer.
status = git("status", "--porcelain", "--branch", "--", init_file)
try:
status = subprocess.run(
[
"git",
"--no-optional-locks",
"-c",
"core.fsmonitor=false",
"status",
"--porcelain",
"--branch",
"--",
init_file,
],
cwd=cwd,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
encoding="utf-8",
timeout=0.25,
).stdout.strip()
except (OSError, subprocess.TimeoutExpired):
status = ""
if not status:
return changed >= now - SETUP_IN_PROGRESS_SECONDS_WITHOUT_GIT
if "\n" in status:
return True

# A checkout also gives a clean file a new mtime, so only count a commit
# that was made here.
committer = git(
"log", "-1", f"--since={int(cutoff)}", "--format=%ce", "--", init_file
)
return bool(committer) and committer == git("config", "user.email")
try:
committer = subprocess.run(
[
"git",
"--no-optional-locks",
"-c",
"core.fsmonitor=false",
"log",
"-1",
f"--since={int(cutoff)}",
"--format=%ce",
"--",
init_file,
],
cwd=cwd,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
encoding="utf-8",
timeout=0.25,
).stdout.strip()
except (OSError, subprocess.TimeoutExpired):
return False
if not committer:
return False

try:
user_email = subprocess.run(
[
"git",
"--no-optional-locks",
"-c",
"core.fsmonitor=false",
"config",
"user.email",
],
cwd=cwd,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
encoding="utf-8",
timeout=0.25,
).stdout.strip()
except (OSError, subprocess.TimeoutExpired):
return False
return committer == user_email


def _write_coding_agent_hint(
init_file: str, not_shown: str, off: str, its: str, it: str
) -> None:
def _write_coding_agent_hint(init_file: str, tracing_on: bool, logs_on: bool) -> None:
with capture_internal_exceptions():
if not _setup_in_progress(init_file):
return

codex = "codex" in (os.environ.get("AI_AGENT") or "").lower() or any(
os.environ.get(name) for name in ("CODEX_THREAD_ID", "CODEX_SANDBOX")
)
if codex:
# Codex treats instructions in tool output as untrusted and won't turn on
# more data collection without the user, but it passes a fact on to them.
if codex and tracing_on:
hint = (
"Logs are off, so Sentry gets errors and traces but no logs. If you "
"leave it off, tell the user it's off and that you can turn it on if "
"they want. Sentry's official setup checklist, included in the "
f"sentry-sdk package you installed: {SETUP_CHECKLIST_PATH}"
)
elif codex and logs_on:
hint = (
"Tracing is off, so Sentry gets errors and logs but no traces. If you "
"leave it off, tell the user it's off and that you can turn it on if "
"they want. Sentry's official setup checklist, included in the "
f"sentry-sdk package you installed: {SETUP_CHECKLIST_PATH}"
)
elif codex:
hint = (
"Tracing and logs are off, so Sentry only gets errors. If you leave "
"them off, tell the user they're off and that you can turn them on if "
"they want. Sentry's official setup checklist, included in the "
f"sentry-sdk package you installed: {SETUP_CHECKLIST_PATH}"
)
elif tracing_on:
hint = (
"Sentry will get errors from this app but its logs only as "
"breadcrumbs. The checklist shows what to change. If you're setting "
"up Sentry, it is strongly recommended to check your setup against "
"Sentry's official setup checklist, included in the sentry-sdk "
f"package you installed: {SETUP_CHECKLIST_PATH}"
)
elif logs_on:
hint = (
f"{off} If you leave {it} off, tell the user {its} off and that you can "
f"turn {it} on if they want. Sentry's official setup checklist, included "
f"in the sentry-sdk package you installed: {SETUP_CHECKLIST_PATH}"
"Sentry will get errors from this app but not the request trace "
"around them. The checklist shows what to change. If you're setting "
"up Sentry, it is strongly recommended to check your setup against "
"Sentry's official setup checklist, included in the sentry-sdk "
f"package you installed: {SETUP_CHECKLIST_PATH}"
)
else:
# Say what Sentry won't show, not which settings are off. An agent that
# sees the setting names doesn't open the checklist.
hint = (
f"{not_shown} The checklist shows what to change. If you're setting up "
"Sentry, it is strongly recommended to check your setup against Sentry's "
"official setup checklist, included in the sentry-sdk package you "
f"installed: {SETUP_CHECKLIST_PATH}"
"Sentry will get errors from this app but not the request trace "
"around them, and its logs only as breadcrumbs. The checklist shows "
"what to change. If you're setting up Sentry, it is strongly "
"recommended to check your setup against Sentry's official setup "
"checklist, included in the sentry-sdk package you installed: "
f"{SETUP_CHECKLIST_PATH}"
)
sys.stdout.flush()
sys.stderr.write(f"[sentry] {hint} (hide with SENTRY_AGENT_HINTS=0)\n")
sys.stderr.flush()


def show_coding_agent_hint(options: "Dict[str, Any]", caller: "FrameType") -> None:
"""Point a coding agent at the setup checklist while Sentry is being set up."""
global _coding_agent_hint_shown

rate = options["traces_sample_rate"]
tracing_on = options["traces_sampler"] is not None or rate not in (0, None)
logs_on = bool(options["enable_logs"])
if (
_coding_agent_hint_shown
or sys.version_info < (3, 9)
or sys.platform not in ("darwin", "linux")
or not options["dsn"]
or options["agent_setup_complete"]
Expand All @@ -157,9 +211,7 @@ def show_coding_agent_hint(options: "Dict[str, Any]", caller: "FrameType") -> No
):
return

# A script's own path is relative on Python 3.8 and older.
init_file = os.path.abspath(caller.f_code.co_filename)
# An installed tool that uses Sentry itself isn't the user's app.
init_file = caller.f_code.co_filename
if _is_external_source(init_file):
return
try:
Expand All @@ -170,6 +222,4 @@ def show_coding_agent_hint(options: "Dict[str, Any]", caller: "FrameType") -> No

_coding_agent_hint_shown = True
# Agents often cut a command's output with `| tail`, so the hint goes last.
atexit.register(
_write_coding_agent_hint, init_file, *_MISSING_PRODUCTS[(tracing_on, logs_on)]
)
atexit.register(_write_coding_agent_hint, init_file, tracing_on, logs_on)
13 changes: 4 additions & 9 deletions sentry_sdk/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ def json_dumps(data: "Any") -> bytes:
return json.dumps(data, allow_nan=False, separators=(",", ":")).encode("utf-8")


def _git(*args: str, cwd: "Optional[str]" = None) -> "Optional[str]":
def get_git_revision() -> "Optional[str]":
try:
with open(os.path.devnull, "w+") as null:
# prevent command prompt windows from popping up on windows
Expand All @@ -137,10 +137,9 @@ def _git(*args: str, cwd: "Optional[str]" = None) -> "Optional[str]":
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW

output = (
revision = (
subprocess.Popen(
["git", *args],
cwd=cwd,
["git", "rev-parse", "HEAD"],
startupinfo=startupinfo,
stdout=subprocess.PIPE,
stderr=null,
Expand All @@ -153,11 +152,7 @@ def _git(*args: str, cwd: "Optional[str]" = None) -> "Optional[str]":
except (OSError, IOError, FileNotFoundError):
return None

return output


def get_git_revision() -> "Optional[str]":
return _git("rev-parse", "HEAD")
return revision


def get_default_release() -> "Optional[str]":
Expand Down
Loading
Loading