ensure_agent_sdk.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. #!/usr/bin/env python3
  2. """SessionStart bootstrap: ensure claude_agent_sdk is importable for the
  3. agentic commit reviewer.
  4. If claude_agent_sdk already imports in the current python3, this is a no-op.
  5. Otherwise it creates a venv at ~/.claude/security/agent-sdk-venv and installs
  6. the SDK there. security_reminder_hook.py prepends that venv's site-packages to
  7. sys.path before attempting the SDK import, so the venv is used as a
  8. fallback only when the system install is missing.
  9. The venv lives under ~/.claude/security/ (same dir the plugin already uses
  10. for per-session state) so it persists across plugin updates — rebuilding
  11. on every update is 30-60s of wasted work for a package that changes far
  12. less often than the plugin does.
  13. """
  14. from __future__ import annotations
  15. import importlib.util
  16. import json
  17. import os
  18. import subprocess
  19. import sys
  20. import time
  21. from pathlib import Path
  22. # Shared state-dir resolver: SECURITY_WARNINGS_STATE_DIR → CLAUDE_CONFIG_DIR/security
  23. # → ~/.claude/security. See _base.state_dir for resolution precedence. Re-aliased
  24. # here to match the existing local name (state_dir was already a local var in
  25. # main() and _maybe_emit_user_notice).
  26. from _base import state_dir as _resolve_state_dir
  27. # Outcome codes for the sdk_bootstrap metric. Values are stable for telemetry.
  28. NOOP_SYSTEM = 0 # claude_agent_sdk already importable in system python
  29. NOOP_VENV = 1 # venv already built and SDK imports from it
  30. BUILT = 2 # venv created + SDK pip-installed this run
  31. BUILD_FAILED = 3 # venv create or pip install raised/timed out
  32. # Outcome 4 was previously SKIP_WIN32; retired now that the consumer glob in
  33. # llm.py also matches Windows venv layout (Lib/site-packages). Don't reuse the
  34. # value — telemetry rows from older plugin builds still emit 4.
  35. SKIP_SENTINEL = 5 # another SessionStart is currently building
  36. HOOK_PY_INCOMPATIBLE = 6 # hook interpreter is <3.10 — SDK syntax can't load
  37. # here no matter how the venv was built. See #2071.
  38. # Phase + err-kind integer encoding for sdk_bootstrap_phase / sdk_bootstrap_err.
  39. #
  40. # Earlier versions emitted these as STRINGS (e.g. "pip", "dns_fail"). CC's
  41. # plugin-metrics pipeline silently drops plugin-emitted string values —
  42. # only `bool|finite-number` plugin metrics reach BigQuery. (CC-core
  43. # metrics like `subscription_type` are exempt because they're injected
  44. # downstream of plugin validation.) Confirmed empirically: 185K
  45. # BUILD_FAILED rows in BQ had `sdk_bootstrap_phase`/`sdk_bootstrap_err`
  46. # = NULL despite the Python code emitting them. This left ~28K
  47. # BUILD_FAILED sessions/day with no diagnostic split — flying blind on
  48. # the real failure modes (pip-no-match vs dns-fail vs ssl-verify etc.).
  49. #
  50. # Fix: encode as small integers per the maps below. Values are
  51. # APPEND-ONLY for telemetry stability. Reserve 99 as the "unknown /
  52. # uncategorized" bucket so an unmapped err_kind (e.g., a new exception
  53. # type) still emits a non-zero signal.
  54. SDK_BOOTSTRAP_PHASE_CODES = {
  55. "pre": 1, # pre-venv (state_dir.mkdir, sentinel open)
  56. "venv": 2, # python -m venv --clear
  57. "pip": 3, # pip install
  58. "main": 4, # uncaught exception above main()
  59. }
  60. SDK_BOOTSTRAP_ERR_CODES = {
  61. "pip_no_match": 1,
  62. "dns_fail": 2,
  63. "conn_refused": 3,
  64. "ssl_verify": 4,
  65. "perm_denied": 5,
  66. "no_pip": 6,
  67. "disk_full": 7,
  68. "proxy_auth": 8,
  69. "stderr_timeout": 9, # pip stderr containing "timeout"/"timed out"
  70. "subprocess_timeout": 10, # subprocess.TimeoutExpired (>120s)
  71. # Venv-stage specific categories added after PR #2112 telemetry surfaced
  72. # 2,406 phase=2/err=99 sessions in the first 3h of v2.0.1 — venv phase
  73. # failing in ways the original pip-flavored patterns didn't catch. These
  74. # all split out of what was previously collapsing to _uncategorized.
  75. "venv_ensurepip_fail": 11, # Debian/Ubuntu missing python3-venv;
  76. # stderr mentions ensurepip non-zero exit
  77. # or "ensurepip is not available"
  78. "venv_path_too_long": 12, # Windows MAX_PATH (260) or POSIX
  79. # ENAMETOOLONG — venv writes deep paths
  80. # under state_dir/agent-sdk-venv/Lib/...
  81. "venv_no_module": 13, # `python3 -m venv` itself missing — "No
  82. # module named 'venv'" / "No module named venv"
  83. "venv_already_exists": 14, # Errno 17 / "file exists" — sentinel race
  84. # past O_EXCL or stale dir survived --clear
  85. "venv_setup_failed": 15, # Generic "virtual environment was not
  86. # created successfully" — catches the long
  87. # tail of venv setup failures that don't
  88. # match a more specific category above
  89. # 16–98 reserved for future categories; APPEND-ONLY.
  90. # 99 catches everything else (including "exc:<TypeName>" and "other:<tail>"
  91. # — the original string is debug-loggable but the integer is what makes
  92. # it to telemetry). For the "other:" tail, `sdk_bootstrap_stderr_sig`
  93. # carries a bounded integer hash so we can still distinguish patterns
  94. # in BQ aggregation.
  95. "_uncategorized": 99,
  96. }
  97. # Exception-type encoding for the "exc:<TypeName>" err_kinds (the generic
  98. # `except Exception` path — venv/pip raised a Python exception rather than
  99. # a CalledProcessError with categorizable stderr).
  100. #
  101. # #2154 telemetry surfaced that the dominant remaining venv BUILD_FAILED
  102. # bucket (phase=venv, err=99) is ~99% `exc:` with stderr_sig=NULL — i.e.
  103. # exceptions, not stderr-bearing subprocess failures — so the stderr_sig
  104. # hash couldn't distinguish them. This maps the exception TYPE to a stable
  105. # code so BQ can tell FileNotFoundError (python/venv binary missing) from
  106. # PermissionError (read-only home) from a bare OSError, etc.
  107. #
  108. # All the FileNotFoundError/PermissionError/etc. entries are OSError
  109. # subclasses, so they ALSO carry an errno (see _encode_errno) — the type
  110. # code gives the Python class, errno gives the OS-level cause. APPEND-ONLY.
  111. SDK_BOOTSTRAP_EXC_CODES = {
  112. "FileNotFoundError": 1, # interpreter/venv path component missing
  113. "PermissionError": 2, # read-only home, sandboxed FS
  114. "NotADirectoryError": 3,
  115. "IsADirectoryError": 4,
  116. "FileExistsError": 5, # (sentinel race is handled separately; this
  117. # is FileExistsError from elsewhere in venv)
  118. "OSError": 6, # bare OSError — errno carries the real cause
  119. "BlockingIOError": 7,
  120. "BrokenPipeError": 8,
  121. "ConnectionError": 9,
  122. "TimeoutError": 10, # distinct from subprocess.TimeoutExpired
  123. "InterruptedError": 11,
  124. "MemoryError": 12,
  125. "UnicodeDecodeError": 13,
  126. "ValueError": 14,
  127. "RuntimeError": 15,
  128. # 16–98 reserved; APPEND-ONLY.
  129. "_other_exc": 99, # an exception type not in this map
  130. }
  131. def _encode_phase(s):
  132. """Map err_phase string to its telemetry integer code, or 0 if unset.
  133. Empty/None → 0 lets `if encoded:` cleanly skip emission. Per
  134. SDK_BOOTSTRAP_PHASE_CODES, valid codes are 1-4."""
  135. return SDK_BOOTSTRAP_PHASE_CODES.get((s or "").strip(), 0)
  136. def _encode_err_kind(s):
  137. """Map err_kind string to its telemetry integer code, or 0 if unset.
  138. Direct hits use the static map; "exc:<X>" and "other:<tail>" both
  139. collapse to _uncategorized (99) — the raw string survives in debug
  140. logs, only the integer reaches BQ."""
  141. s = (s or "").strip()
  142. if not s:
  143. return 0
  144. if s in SDK_BOOTSTRAP_ERR_CODES:
  145. return SDK_BOOTSTRAP_ERR_CODES[s]
  146. # Prefix matches for the catch-all categories
  147. if s.startswith("exc:") or s.startswith("other:") or s == "other":
  148. return SDK_BOOTSTRAP_ERR_CODES["_uncategorized"]
  149. # Unknown string — still emit as uncategorized rather than dropping
  150. return SDK_BOOTSTRAP_ERR_CODES["_uncategorized"]
  151. def _encode_stderr_sig(err_kind):
  152. """Bounded integer hash of the stderr tail captured in "other:<tail>"
  153. err_kinds. Lets us distinguish patterns INSIDE the _uncategorized
  154. (code 99) bucket without unbounded cardinality.
  155. Returns 0 for non-"other:" err_kinds (so the field auto-omits from
  156. emit_metrics on categorized failures — see the emit block in main()).
  157. Strategy: take the tail's first ~30 chars (post-lowercase, post-trim),
  158. SHA-1, fold the first 2 bytes to 0–999. Different stderr messages
  159. cluster into different buckets; same stderr always maps to the same
  160. bucket. Cardinality is bounded at 1000, well below any "high
  161. cardinality" alarm — and a real failure mode typically produces
  162. near-identical stderr across thousands of machines, so 1000 buckets
  163. is comfortably wide.
  164. Why first ~30 chars: stderr like "ERROR: Command failed: <full
  165. path>" varies the tail wildly (paths) but the categorization signal
  166. is in the leading words. Dropping the suffix focuses the hash on
  167. the discriminative part.
  168. """
  169. if not err_kind or not err_kind.startswith("other:"):
  170. return 0
  171. import hashlib
  172. tail = err_kind[len("other:"):].strip().lower()[:30]
  173. if not tail:
  174. return 0
  175. h = hashlib.sha1(tail.encode("utf-8", errors="replace")).digest()
  176. return int.from_bytes(h[:2], "big") % 1000
  177. def _encode_exc_kind(err_kind):
  178. """Map an "exc:<TypeName>[:errno]" err_kind to its exception-type code
  179. (SDK_BOOTSTRAP_EXC_CODES). Returns 0 for non-exc err_kinds (so the
  180. sdk_bootstrap_exc field auto-omits on stderr/categorized failures).
  181. Unmapped exception types → 99 (_other_exc)."""
  182. if not err_kind or not err_kind.startswith("exc:"):
  183. return 0
  184. # "exc:OSError:28" → "OSError"; "exc:RuntimeError" → "RuntimeError"
  185. name = err_kind[len("exc:"):].split(":", 1)[0].strip()
  186. if not name:
  187. return 0
  188. return SDK_BOOTSTRAP_EXC_CODES.get(name, SDK_BOOTSTRAP_EXC_CODES["_other_exc"])
  189. def _encode_errno(err_kind):
  190. """Extract the OS errno from an "exc:<TypeName>:<errno>" err_kind.
  191. OSError-family exceptions embed their errno (ENOENT=2, EACCES=13,
  192. ENOSPC=28, …) — the OS-level cause is far more actionable than the
  193. Python class alone. Returns 0 when absent/non-numeric (field omitted)."""
  194. if not err_kind or not err_kind.startswith("exc:"):
  195. return 0
  196. parts = err_kind.split(":")
  197. if len(parts) < 3:
  198. return 0
  199. try:
  200. return int(parts[2])
  201. except (ValueError, IndexError):
  202. return 0
  203. def _probe_has_pip() -> bool:
  204. """True iff the current interpreter can run pip (`-m pip --version`).
  205. Probed only on the venv_ensurepip_fail path (see __main__), NOT on the
  206. happy path — it's an extra subprocess we only want when diagnosing a
  207. failure. The result decides whether a `pip install --target` fallback
  208. (Option A) is even viable for this machine: ensurepip/venv missing but
  209. pip present → --target would work; pip also missing → it wouldn't, and
  210. the user needs a system package (python3-venv / a complete Python)."""
  211. try:
  212. r = subprocess.run(
  213. [sys.executable, "-m", "pip", "--version"],
  214. capture_output=True, timeout=10,
  215. )
  216. return r.returncode == 0
  217. except Exception:
  218. return False
  219. def _sdk_on_syspath() -> bool:
  220. # find_spec is ~10ms; actually importing the SDK pulls in
  221. # transitive deps and costs ~800ms — too heavy for a
  222. # per-SessionStart no-op check that most sessions hit.
  223. try:
  224. return importlib.util.find_spec("claude_agent_sdk") is not None
  225. except Exception:
  226. return False
  227. def _plugin_version_int() -> int:
  228. # Same encoding as security_reminder_hook._read_plugin_version_int so
  229. # metrics rows from both hooks join on pv.
  230. try:
  231. p = Path(__file__).parent.parent / ".claude-plugin" / "plugin.json"
  232. v = json.loads(p.read_text())["version"]
  233. major, minor, patch = (int(x) for x in v.split(".")[:3])
  234. return major * 10000 + minor * 100 + patch
  235. except Exception:
  236. return 0
  237. def main() -> tuple[int, str, str]:
  238. """Run the bootstrap. Returns (outcome, err_phase, err_kind).
  239. err_phase / err_kind are non-empty only on BUILD_FAILED — they let
  240. telemetry split bootstrap failures by root cause.
  241. """
  242. # Honesty check (fixes the misleading NOOP_VENV in #2071): the SDK
  243. # requires Python >=3.10 and uses 3.10+ syntax (match statements,
  244. # PEP 604 unions). On a 3.9 hook interpreter we CANNOT import it no
  245. # matter how the venv was built — llm.py runs in this same interpreter
  246. # and the syntax-level import will SyntaxError. macOS ships 3.9.6 as
  247. # the default `python3` and `/usr/bin` precedes Homebrew in PATH, so
  248. # this case is the default state for a large share of macOS users.
  249. #
  250. # sg-python.sh now prefers python3.10+ binaries so most users won't
  251. # reach this branch; the fallback to 3.9 is preserved for the
  252. # pattern-warning hooks that don't need the SDK. Reporting
  253. # HOOK_PY_INCOMPATIBLE here:
  254. # (a) avoids 30-60s of wasted pip install,
  255. # (b) avoids the lie where the venv_py probe says NOOP_VENV but the
  256. # consumer import fails, and
  257. # (c) gives telemetry a clean bucket to size the affected fleet.
  258. if sys.version_info < (3, 10):
  259. return (
  260. HOOK_PY_INCOMPATIBLE,
  261. "hook_py",
  262. f"py_{sys.version_info[0]}.{sys.version_info[1]}",
  263. )
  264. if _sdk_on_syspath():
  265. return NOOP_SYSTEM, "", ""
  266. state_dir = Path(_resolve_state_dir())
  267. venv = state_dir / "agent-sdk-venv"
  268. # Windows venvs put the interpreter at Scripts\python.exe; POSIX uses bin/python.
  269. if sys.platform == "win32":
  270. venv_py = venv / "Scripts" / "python.exe"
  271. else:
  272. venv_py = venv / "bin" / "python"
  273. # Another SessionStart (concurrent CC instance, same plugin) may already
  274. # be building. The sentinel lives NEXT TO the venv, not inside it —
  275. # `python -m venv --clear` wipes the target dir's contents, so an
  276. # in-venv sentinel would be deleted the instant we create the venv.
  277. # Stale sentinels (>5min) from a SIGKILL'd build are ignored.
  278. sentinel = state_dir / "agent-sdk-venv.building"
  279. if sentinel.exists():
  280. try:
  281. if time.time() - sentinel.stat().st_mtime < 300:
  282. return SKIP_SENTINEL, "", ""
  283. sentinel.unlink(missing_ok=True)
  284. except OSError:
  285. return SKIP_SENTINEL, "", ""
  286. # If a venv already exists and its python can import the SDK, done.
  287. if venv_py.exists():
  288. try:
  289. r = subprocess.run(
  290. [str(venv_py), "-c", "import claude_agent_sdk"],
  291. capture_output=True, timeout=10,
  292. )
  293. if r.returncode == 0:
  294. return NOOP_VENV, "", ""
  295. except Exception:
  296. pass # broken venv; rebuild below
  297. err_phase = ""
  298. err_kind = ""
  299. we_own_sentinel = False
  300. try:
  301. state_dir.mkdir(parents=True, exist_ok=True)
  302. # O_EXCL makes the sentinel an atomic lock — if two SessionStarts
  303. # race past the exists() check above, only one creates it.
  304. try:
  305. os.close(os.open(sentinel, os.O_CREAT | os.O_EXCL | os.O_WRONLY))
  306. except FileExistsError:
  307. return SKIP_SENTINEL, "", ""
  308. we_own_sentinel = True
  309. err_phase = "venv"
  310. subprocess.run(
  311. [sys.executable, "-m", "venv", "--clear", str(venv)],
  312. capture_output=True, timeout=60, check=True,
  313. )
  314. # Some machines route pip through a private registry; we
  315. # don't pass --index-url here so we inherit that default. Outside
  316. # the user's machine, pip's own default registry applies — that's the same
  317. # exposure the user would have running `pip install` themselves, so
  318. # we're not widening the supply-chain surface.
  319. #
  320. # --prefer-binary: on ARM64 Windows, pip's default resolver picks a
  321. # `cryptography` version with no published binary wheel and tries to
  322. # build from source, which needs Rust/Cargo (almost never present
  323. # on user machines). The build fails and the whole bootstrap returns
  324. # BUILD_FAILED. A binary wheel exists on PyPI for an adjacent
  325. # version (`cryptography-46.0.3-cp311-abi3-win_arm64.whl`);
  326. # --prefer-binary tells pip to pick it. Cross-platform safe: no-op
  327. # on platforms where the latest version already has a wheel.
  328. err_phase = "pip"
  329. subprocess.run(
  330. [str(venv_py), "-m", "pip", "install", "--quiet",
  331. "--disable-pip-version-check", "--prefer-binary",
  332. "claude-agent-sdk"],
  333. capture_output=True, timeout=120, check=True,
  334. )
  335. return BUILT, "", ""
  336. except subprocess.CalledProcessError as e:
  337. # Capture a stderr fingerprint so telemetry can split BUILD_FAILED by
  338. # root cause (no-network, package-not-found, dns-fail, etc.).
  339. # Categorize first, then keep a short raw tail for the long tail of
  340. # unexpected modes.
  341. stderr_b = e.stderr or b""
  342. if isinstance(stderr_b, bytes):
  343. stderr_str = stderr_b.decode("utf-8", errors="replace")
  344. else:
  345. stderr_str = str(stderr_b)
  346. s = stderr_str.lower()
  347. # Venv-specific patterns checked FIRST — they overlap with some pip
  348. # patterns (e.g. "no module named ensurepip" could match no_pip OR
  349. # venv_ensurepip_fail; the venv-stage interpretation is the right
  350. # one when err_phase=="venv"). Order is venv-most-specific →
  351. # pip-historical → generic.
  352. if err_phase == "venv" and (
  353. "ensurepip is not available" in s
  354. or ("ensurepip" in s and "returned non-zero" in s)
  355. or "the virtual environment was not created" in s and "ensurepip" in s
  356. ):
  357. err_kind = "venv_ensurepip_fail"
  358. elif err_phase == "venv" and (
  359. "[errno 36]" in s
  360. or "file name too long" in s
  361. or "path too long" in s
  362. ):
  363. err_kind = "venv_path_too_long"
  364. elif err_phase == "venv" and (
  365. "no module named venv" in s
  366. or "no module named 'venv'" in s
  367. ):
  368. err_kind = "venv_no_module"
  369. elif err_phase == "venv" and (
  370. "[errno 17]" in s
  371. or ("file exists" in s and "venv" in s)
  372. ):
  373. err_kind = "venv_already_exists"
  374. elif "no matching distribution" in s or "could not find a version" in s:
  375. err_kind = "pip_no_match"
  376. elif "name or service not known" in s or "name resolution" in s \
  377. or "nodename nor servname" in s or "temporary failure in name" in s:
  378. err_kind = "dns_fail"
  379. elif "connection refused" in s or "connection reset" in s:
  380. err_kind = "conn_refused"
  381. elif "ssl" in s and ("verify" in s or "certificate" in s):
  382. err_kind = "ssl_verify"
  383. elif "permission denied" in s or "read-only file system" in s:
  384. err_kind = "perm_denied"
  385. elif "no module named pip" in s or "no module named ensurepip" in s:
  386. err_kind = "no_pip"
  387. elif "no space left" in s or "disk quota" in s:
  388. err_kind = "disk_full"
  389. elif "proxy" in s and ("authent" in s or "tunnel" in s or "407" in s):
  390. err_kind = "proxy_auth"
  391. elif "timeout" in s or "timed out" in s:
  392. err_kind = "stderr_timeout"
  393. elif err_phase == "venv" and (
  394. "virtual environment was not created" in s
  395. or "error: command" in s and "venv" in s
  396. ):
  397. # Generic venv-setup catch-all — matched AFTER the more specific
  398. # venv patterns above so we don't shadow them, but BEFORE the
  399. # other: fallback so generic venv setup failures get their own
  400. # bucket instead of polluting the long-tail signature space.
  401. err_kind = "venv_setup_failed"
  402. else:
  403. # First 60 chars of the last non-empty stderr line — bounded to
  404. # stay inside CC's metric value-length budget. Real failure modes
  405. # we haven't categorized show up here as a low-cardinality bucket.
  406. tail = next(
  407. (ln.strip() for ln in reversed(stderr_str.splitlines()) if ln.strip()),
  408. "",
  409. )[:60]
  410. err_kind = f"other:{tail}" if tail else "other"
  411. return BUILD_FAILED, err_phase, err_kind
  412. except subprocess.TimeoutExpired:
  413. return BUILD_FAILED, err_phase, "subprocess_timeout"
  414. except Exception as e:
  415. # Embed errno for OSError-family exceptions ("exc:OSError:28") so
  416. # telemetry can decode the OS-level cause (ENOENT/EACCES/ENOSPC/…),
  417. # not just the Python class. #2154 follow-up: this is the dominant
  418. # remaining venv BUILD_FAILED bucket. See _encode_exc_kind/_encode_errno.
  419. errno = getattr(e, "errno", None)
  420. if isinstance(errno, int):
  421. return BUILD_FAILED, err_phase, f"exc:{type(e).__name__}:{errno}"
  422. return BUILD_FAILED, err_phase, f"exc:{type(e).__name__}"
  423. finally:
  424. # Only remove the sentinel if THIS process created it. The
  425. # FileExistsError path above means another process owns the lock;
  426. # unconditionally unlinking here would delete its sentinel and let
  427. # a third concurrent SessionStart `venv --clear` over the in-flight
  428. # build.
  429. if we_own_sentinel:
  430. sentinel.unlink(missing_ok=True)
  431. def _maybe_emit_user_notice(outcome: int, pv: int) -> str | None:
  432. """Return a one-time user-visible notice when the agentic reviewer is
  433. in a persistent broken state on this machine, or None if we've already
  434. shown the notice for this plugin version (or shouldn't show one).
  435. The marker file is plugin-version-keyed: a future plugin update can
  436. re-notify if behavior changes (e.g. we ship out-of-process SDK in v3
  437. and want to tell affected users it's fixed). Failures to write the
  438. marker degrade to "skip the notice this session" so we don't spam
  439. every SessionStart on a read-only home dir.
  440. Currently only HOOK_PY_INCOMPATIBLE qualifies. BUILD_FAILED is
  441. intentionally excluded — it covers transient causes (network failure,
  442. pip registry hiccup, in-flight rebuild) where the next session may
  443. succeed and a permanent notice would mislead.
  444. """
  445. if outcome != HOOK_PY_INCOMPATIBLE:
  446. return None
  447. try:
  448. state_dir = Path(_resolve_state_dir())
  449. marker = state_dir / f".agentic_unavailable_notice_v{pv or 0}"
  450. if marker.exists():
  451. return None
  452. state_dir.mkdir(parents=True, exist_ok=True)
  453. # Write timestamp + Python version so the marker is self-documenting
  454. # if a user goes looking. O_EXCL would be racier with no real win
  455. # (two concurrent SessionStarts both showing the notice once is fine).
  456. marker.write_text(
  457. f"{time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())} "
  458. f"py={sys.version_info[0]}.{sys.version_info[1]}\n"
  459. )
  460. except OSError:
  461. return None
  462. return (
  463. f"⚠ security-guidance plugin: the cross-file commit reviewer "
  464. f"(layer 3 of 3 — catches IDOR, auth-bypass, cross-file SSRF) "
  465. f"is unavailable in this environment. It requires Python ≥3.10, "
  466. f"but the hook is running on "
  467. f"{sys.version_info[0]}.{sys.version_info[1]}.\n\n"
  468. f"Pattern checks and the single-shot LLM diff review are still "
  469. f"active. To enable the deeper reviewer, install Python 3.10+ "
  470. f"(e.g. `brew install python` on macOS) and restart Claude Code.\n\n"
  471. f"This notice is shown once per plugin version. "
  472. f"See: github.com/anthropics/claude-plugins-official/issues/2071"
  473. )
  474. if __name__ == "__main__":
  475. # Tell the harness this is async — venv create + pip install can take
  476. # 30-60s on a cold cache, well past the default sync hook timeout.
  477. # SessionStart runs before the user's first prompt; doing this in the
  478. # background means the first commit-review of the session usually finds
  479. # the venv ready.
  480. print(json.dumps({"async": True, "asyncTimeout": 180000}), flush=True)
  481. t0 = time.perf_counter()
  482. try:
  483. outcome, err_phase, err_kind = main()
  484. except Exception as exc:
  485. outcome, err_phase, err_kind = (
  486. BUILD_FAILED, "main", f"exc:{type(exc).__name__}"
  487. )
  488. # CC's async-hook registry scans stdout line-by-line after process exit
  489. # and takes the FIRST non-{"async":...} JSON line as the hook response;
  490. # its `metrics` key is forwarded to the hook metrics event on the
  491. # next attachments pass. Must be a single line — the registry splits on
  492. # \n and json-parses each independently.
  493. #
  494. # IMPORTANT — values must be bool|finite-number. The validation comment
  495. # has historically said "or short strings" but that was wrong: CC's
  496. # plugin-metrics pipeline silently drops plugin-emitted string values.
  497. # Stay inside the 10-key emit cap.
  498. metrics: dict[str, object] = {
  499. "sdk_bootstrap": outcome,
  500. "sdk_bootstrap_ms": round((time.perf_counter() - t0) * 1000),
  501. }
  502. if err_kind:
  503. # Encode phase + err_kind as integer codes (see
  504. # SDK_BOOTSTRAP_PHASE_CODES / SDK_BOOTSTRAP_ERR_CODES). Earlier
  505. # versions emitted these as strings and CC dropped them — restoring
  506. # the diagnostic split that 28K BUILD_FAILED/day need to triage by
  507. # root cause. err_phase defaults to "pre" when empty (pre-venv
  508. # failure path, e.g. state_dir.mkdir perm-denied).
  509. metrics["sdk_bootstrap_phase"] = _encode_phase(err_phase or "pre")
  510. metrics["sdk_bootstrap_err"] = _encode_err_kind(err_kind)
  511. # For "other:<tail>" (encoded err==99), emit a bounded integer
  512. # hash of the stderr tail so BQ can distinguish patterns inside
  513. # the _uncategorized bucket without unbounded cardinality. Zero
  514. # when err_kind is categorized — the schema reader treats 0 as
  515. # "no signal", matching the absence convention.
  516. sig = _encode_stderr_sig(err_kind)
  517. if sig:
  518. metrics["sdk_bootstrap_stderr_sig"] = sig
  519. # Exception-type + errno for the "exc:" bucket (the dominant
  520. # remaining venv BUILD_FAILED mode per #2154 telemetry). Both
  521. # auto-omit (0) on stderr/categorized failures.
  522. exc = _encode_exc_kind(err_kind)
  523. if exc:
  524. metrics["sdk_bootstrap_exc"] = exc
  525. exc_errno = _encode_errno(err_kind)
  526. if exc_errno:
  527. metrics["sdk_bootstrap_errno"] = exc_errno
  528. # venv_ensurepip_fail (code 11) is the top categorizable venv
  529. # failure, and telemetry shows it's NOT just Debian — macOS has the
  530. # most distinct affected users. Probe whether this interpreter has
  531. # pip so we know if a `pip install --target` fallback (Option A)
  532. # would actually help, vs the user needing a system package. Probed
  533. # only here (not on the happy path) to avoid an extra subprocess
  534. # per healthy session.
  535. if _encode_err_kind(err_kind) == 11:
  536. metrics["sdk_has_pip"] = _probe_has_pip()
  537. # Interpreter version (major*100 + minor, e.g. 309 / 312), emitted on
  538. # every bootstrap. Disambiguates the macOS cohort (Apple 3.9 vs a 3.10+
  539. # with broken ensurepip) for both venv_ensurepip_fail AND
  540. # HOOK_PY_INCOMPATIBLE (whose "py_3.9" err_kind otherwise collapses to
  541. # err=99, losing the version). Cheap — no subprocess, just sys.version_info.
  542. metrics["sdk_hook_py"] = sys.version_info[0] * 100 + sys.version_info[1]
  543. pv = _plugin_version_int()
  544. if pv:
  545. metrics["pv"] = pv
  546. response: dict[str, object] = {"metrics": metrics}
  547. # One-time user-visible notice when the agentic reviewer is dead on
  548. # arrival. Uses hookSpecificOutput.additionalContext (SessionStart's
  549. # supported channel for surfacing text to both the model and the user)
  550. # plus systemMessage as a belt-and-suspenders. Marker-file-gated so
  551. # this fires exactly once per plugin version per install — see
  552. # _maybe_emit_user_notice.
  553. notice = _maybe_emit_user_notice(outcome, pv)
  554. if notice:
  555. response["hookSpecificOutput"] = {
  556. "hookEventName": "SessionStart",
  557. "additionalContext": notice,
  558. }
  559. response["systemMessage"] = notice
  560. print(json.dumps(response), flush=True)