summaryrefslogtreecommitdiff
path: root/plugins/security-guidance/hooks
diff options
context:
space:
mode:
authorMohamed Hegazy <mhegazy@anthropic.com>2026-10-15 16:31:46 +0000
committerClaude <noreply@anthropic.com>2026-10-15 16:31:46 +0000
commitced6733eee6aa246e2af55ce0c71e38c01a50141 (patch)
tree1c7abeca25d5625d06934d3ea1141cf554edcd92 /plugins/security-guidance/hooks
parentd876712c3801b10bb1258da9b8f71fa7b41320e4 (diff)
security-guidance: print one JSON document from the SessionStart hook on other hostsmhegazy/sg-portable-session-start
On a host other than Claude Code the SessionStart hook printed an async declaration line and then a metrics line. A host that reads hook output as one JSON document with a closed schema rejects that. In portable mode the hook now skips the async line and prints one object with only the standard fields. The portable-mode helpers move to _base.py so both hook scripts share them, and the mode is decided once at start-up. Output under Claude Code is unchanged.
Diffstat (limited to 'plugins/security-guidance/hooks')
-rw-r--r--plugins/security-guidance/hooks/_base.py41
-rw-r--r--plugins/security-guidance/hooks/ensure_agent_sdk.py10
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py32
3 files changed, 49 insertions, 34 deletions
diff --git a/plugins/security-guidance/hooks/_base.py b/plugins/security-guidance/hooks/_base.py
index 44b205f0..f05a0094 100644
--- a/plugins/security-guidance/hooks/_base.py
+++ b/plugins/security-guidance/hooks/_base.py
@@ -94,6 +94,47 @@ PROVENANCE_BANNER = (
)
+# Output that only Claude Code reads: the `metrics` and `rewakeSummary` fields,
+# and the separate `{"async": ...}` line an async hook prints first. Other hosts
+# that run this plugin's hooks can validate hook output against a closed schema
+# and reject the whole output over a field or a second line they do not know,
+# which shows up as a hook error.
+_CLAUDE_CODE_OUTPUT_FIELDS = ("metrics", "rewakeSummary")
+
+
+def _detect_portable_output():
+ forced = os.environ.get("SECURITY_GUIDANCE_PORTABLE_OUTPUT", "").strip().lower()
+ if forced in ("1", "true", "yes", "on"):
+ return True
+ if forced in ("0", "false", "no", "off"):
+ return False
+ if os.environ.get("CLAUDECODE") or os.environ.get("CLAUDE_CODE_ENTRYPOINT"):
+ return False
+ return bool(os.environ.get("PLUGIN_ROOT"))
+
+
+# Decided once, from the environment the host started the hook with: code the
+# hook runs in-process later can set these variables itself.
+_PORTABLE_OUTPUT = _detect_portable_output()
+
+
+def portable_output():
+ """True when stdout should carry only the standard hook output fields.
+
+ SECURITY_GUIDANCE_PORTABLE_OUTPUT=1 or =0 forces it on or off. Otherwise it
+ is on only when the host passes PLUGIN_ROOT and does not identify itself as
+ Claude Code, so Claude Code and direct invocations are unchanged."""
+ return _PORTABLE_OUTPUT
+
+
+def write_hook_output(out):
+ """Print one hook output line. In portable mode the Claude Code only
+ fields are left out; what remains (possibly `{}`) is still valid output."""
+ if portable_output():
+ out = {k: v for k, v in out.items() if k not in _CLAUDE_CODE_OUTPUT_FIELDS}
+ print(json.dumps(out), flush=True)
+
+
def _read_plugin_version_int():
"""Encode plugin.json version "M.m.p" as M*10000 + m*100 + p so it fits the
bool|number metrics constraint. Returns 0 if unreadable."""
diff --git a/plugins/security-guidance/hooks/ensure_agent_sdk.py b/plugins/security-guidance/hooks/ensure_agent_sdk.py
index f5d016db..f49e857d 100644
--- a/plugins/security-guidance/hooks/ensure_agent_sdk.py
+++ b/plugins/security-guidance/hooks/ensure_agent_sdk.py
@@ -27,7 +27,7 @@ from pathlib import Path
# → ~/.claude/security. See _base.state_dir for resolution precedence. Re-aliased
# here to match the existing local name (state_dir was already a local var in
# main() and _maybe_emit_user_notice).
-from _base import state_dir as _resolve_state_dir
+from _base import portable_output, state_dir as _resolve_state_dir, write_hook_output
# Outcome codes for the sdk_bootstrap metric. Values are stable for telemetry.
NOOP_SYSTEM = 0 # claude_agent_sdk already importable in system python
@@ -765,7 +765,11 @@ if __name__ == "__main__":
# SessionStart runs before the user's first prompt; doing this in the
# background means the first commit-review of the session usually finds
# the venv ready.
- print(json.dumps({"async": True, "asyncTimeout": 180000}), flush=True)
+ #
+ # Not printed in portable mode: a host that reads stdout as one JSON
+ # document rejects a second line, and runs this hook to completion anyway.
+ if not portable_output():
+ print(json.dumps({"async": True, "asyncTimeout": 180000}), flush=True)
t0 = time.perf_counter()
try:
outcome, err_phase, err_kind = main()
@@ -859,4 +863,4 @@ if __name__ == "__main__":
"additionalContext": notice,
}
response["systemMessage"] = notice
- print(json.dumps(response), flush=True)
+ write_hook_output(response)
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index 71e0c73e..c17d6265 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -84,6 +84,7 @@ from _base import ( # noqa: E402,F401
_read_plugin_version_int, _PV, _USAGE, _USAGE_LOCK,
_PRICE_PER_MTOK, _PRICE_DEFAULT, _record_usage, _usage_metrics,
state_dir as _resolve_state_dir,
+ write_hook_output as _write_hook_output,
)
import extensibility # noqa: E402
from patterns import ( # noqa: E402,F401
@@ -199,37 +200,6 @@ CONTINUATION_SUFFIX = (
"response."
)
-# Output fields that only Claude Code reads. Other hosts that run this plugin's
-# hooks can validate hook output against a closed schema and reject the whole
-# line over a field they do not know, which shows up as a hook error on every
-# turn.
-_CLAUDE_CODE_OUTPUT_FIELDS = ("metrics", "rewakeSummary")
-
-
-def _portable_output():
- """True when stdout should carry only the standard hook output fields.
-
- SECURITY_GUIDANCE_PORTABLE_OUTPUT=1 or =0 forces it on or off. Otherwise it
- is on only when the host passes PLUGIN_ROOT and does not identify itself as
- Claude Code, so Claude Code and direct invocations are unchanged."""
- forced = os.environ.get("SECURITY_GUIDANCE_PORTABLE_OUTPUT", "").strip().lower()
- if forced in ("1", "true", "yes", "on"):
- return True
- if forced in ("0", "false", "no", "off"):
- return False
- if os.environ.get("CLAUDECODE") or os.environ.get("CLAUDE_CODE_ENTRYPOINT"):
- return False
- return bool(os.environ.get("PLUGIN_ROOT"))
-
-
-def _write_hook_output(out):
- """Print one hook output line. In portable mode the Claude Code only
- fields are left out; what remains (possibly `{}`) is still valid output."""
- if _portable_output():
- out = {k: v for k, v in out.items() if k not in _CLAUDE_CODE_OUTPUT_FIELDS}
- print(json.dumps(out), flush=True)
-
-
# Extra keys emit_metrics appends to every row this invocation emits.
_TAIL_METRICS: Dict[str, Any] = {}