Skip to content

Commit 9b77d51

Browse files
nik13claude
andcommitted
fix(hook-to-otlp): subshell hook guard for heredoc payloads; quiet failures (TH-8229)
Cursor's bundled headless agent host passes the hook payload as a trailing heredoc (`<command> <<'CURSOR_HOOK_EOF'`, commandHookPayloadTransport argv_heredoc). With `python3 ... 2>/dev/null || true` the heredoc binds to `true` and the emitter reads nothing. Every shipped command, the shared page, the Cursor page and the README now use the subshell form `(python3 -B <path>/emit.py cursor <Event> 2>/dev/null || true)`, which works for stdin and heredoc and still exits 0 with no output when the emitter or python3 is missing. - tests/test_cursor_hooks_config.py runs every shipped command (project and user hooks) through sh, zsh, bash and dash with the payload on stdin and as a trailing heredoc: emitter missing, python3 missing, and installed (exit 0, expected stdout, payload received verbatim, no __pycache__). A regression test shows the unparenthesized form loses a heredoc payload. - emit.py prints nothing (instead of "{}") when the adapter cannot be loaded, respond() raises, or run() fails, so a misregistered permission hook never gets schema-invalid "{}". - Home-path scrub handles user names with spaces (when a separator follows), ~name paths, and this machine's own home directory anywhere in the text. - replay.py --hooks-json/--cwd/--transport and run_e2e.sh HOOK_TRANSPORT run the installed hooks.json commands the way Cursor does. - cursor.mdx: CLI section no longer claims a CLI session was traced (it was not run); troubleshooting covers tools directly under the session (no marker) separately from coding_agent.turn.inferred. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 6513a26 commit 9b77d51

10 files changed

Lines changed: 295 additions & 91 deletions

File tree

‎examples/coding-agents/cursor/hooks.json‎

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,61 +3,61 @@
33
"hooks": {
44
"sessionStart": [
55
{
6-
"command": "python3 -B .cursor/hooks/fi-hook-to-otlp/emit.py cursor sessionStart 2>/dev/null || true",
6+
"command": "(python3 -B .cursor/hooks/fi-hook-to-otlp/emit.py cursor sessionStart 2>/dev/null || true)",
77
"timeout": 10
88
}
99
],
1010
"beforeSubmitPrompt": [
1111
{
12-
"command": "python3 -B .cursor/hooks/fi-hook-to-otlp/emit.py cursor beforeSubmitPrompt 2>/dev/null || true",
12+
"command": "(python3 -B .cursor/hooks/fi-hook-to-otlp/emit.py cursor beforeSubmitPrompt 2>/dev/null || true)",
1313
"timeout": 10
1414
}
1515
],
1616
"postToolUse": [
1717
{
18-
"command": "python3 -B .cursor/hooks/fi-hook-to-otlp/emit.py cursor postToolUse 2>/dev/null || true",
18+
"command": "(python3 -B .cursor/hooks/fi-hook-to-otlp/emit.py cursor postToolUse 2>/dev/null || true)",
1919
"timeout": 10
2020
}
2121
],
2222
"postToolUseFailure": [
2323
{
24-
"command": "python3 -B .cursor/hooks/fi-hook-to-otlp/emit.py cursor postToolUseFailure 2>/dev/null || true",
24+
"command": "(python3 -B .cursor/hooks/fi-hook-to-otlp/emit.py cursor postToolUseFailure 2>/dev/null || true)",
2525
"timeout": 10
2626
}
2727
],
2828
"subagentStop": [
2929
{
30-
"command": "python3 -B .cursor/hooks/fi-hook-to-otlp/emit.py cursor subagentStop 2>/dev/null || true",
30+
"command": "(python3 -B .cursor/hooks/fi-hook-to-otlp/emit.py cursor subagentStop 2>/dev/null || true)",
3131
"timeout": 10
3232
}
3333
],
3434
"afterAgentThought": [
3535
{
36-
"command": "python3 -B .cursor/hooks/fi-hook-to-otlp/emit.py cursor afterAgentThought 2>/dev/null || true",
36+
"command": "(python3 -B .cursor/hooks/fi-hook-to-otlp/emit.py cursor afterAgentThought 2>/dev/null || true)",
3737
"timeout": 10
3838
}
3939
],
4040
"afterAgentResponse": [
4141
{
42-
"command": "python3 -B .cursor/hooks/fi-hook-to-otlp/emit.py cursor afterAgentResponse 2>/dev/null || true",
42+
"command": "(python3 -B .cursor/hooks/fi-hook-to-otlp/emit.py cursor afterAgentResponse 2>/dev/null || true)",
4343
"timeout": 10
4444
}
4545
],
4646
"preCompact": [
4747
{
48-
"command": "python3 -B .cursor/hooks/fi-hook-to-otlp/emit.py cursor preCompact 2>/dev/null || true",
48+
"command": "(python3 -B .cursor/hooks/fi-hook-to-otlp/emit.py cursor preCompact 2>/dev/null || true)",
4949
"timeout": 10
5050
}
5151
],
5252
"stop": [
5353
{
54-
"command": "python3 -B .cursor/hooks/fi-hook-to-otlp/emit.py cursor stop 2>/dev/null || true",
54+
"command": "(python3 -B .cursor/hooks/fi-hook-to-otlp/emit.py cursor stop 2>/dev/null || true)",
5555
"timeout": 10
5656
}
5757
],
5858
"sessionEnd": [
5959
{
60-
"command": "python3 -B .cursor/hooks/fi-hook-to-otlp/emit.py cursor sessionEnd 2>/dev/null || true",
60+
"command": "(python3 -B .cursor/hooks/fi-hook-to-otlp/emit.py cursor sessionEnd 2>/dev/null || true)",
6161
"timeout": 10
6262
}
6363
]

‎examples/coding-agents/cursor/hooks.user.json‎

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,61 +3,61 @@
33
"hooks": {
44
"sessionStart": [
55
{
6-
"command": "python3 -B ./hooks/fi-hook-to-otlp/emit.py cursor sessionStart 2>/dev/null || true",
6+
"command": "(python3 -B ./hooks/fi-hook-to-otlp/emit.py cursor sessionStart 2>/dev/null || true)",
77
"timeout": 10
88
}
99
],
1010
"beforeSubmitPrompt": [
1111
{
12-
"command": "python3 -B ./hooks/fi-hook-to-otlp/emit.py cursor beforeSubmitPrompt 2>/dev/null || true",
12+
"command": "(python3 -B ./hooks/fi-hook-to-otlp/emit.py cursor beforeSubmitPrompt 2>/dev/null || true)",
1313
"timeout": 10
1414
}
1515
],
1616
"postToolUse": [
1717
{
18-
"command": "python3 -B ./hooks/fi-hook-to-otlp/emit.py cursor postToolUse 2>/dev/null || true",
18+
"command": "(python3 -B ./hooks/fi-hook-to-otlp/emit.py cursor postToolUse 2>/dev/null || true)",
1919
"timeout": 10
2020
}
2121
],
2222
"postToolUseFailure": [
2323
{
24-
"command": "python3 -B ./hooks/fi-hook-to-otlp/emit.py cursor postToolUseFailure 2>/dev/null || true",
24+
"command": "(python3 -B ./hooks/fi-hook-to-otlp/emit.py cursor postToolUseFailure 2>/dev/null || true)",
2525
"timeout": 10
2626
}
2727
],
2828
"subagentStop": [
2929
{
30-
"command": "python3 -B ./hooks/fi-hook-to-otlp/emit.py cursor subagentStop 2>/dev/null || true",
30+
"command": "(python3 -B ./hooks/fi-hook-to-otlp/emit.py cursor subagentStop 2>/dev/null || true)",
3131
"timeout": 10
3232
}
3333
],
3434
"afterAgentThought": [
3535
{
36-
"command": "python3 -B ./hooks/fi-hook-to-otlp/emit.py cursor afterAgentThought 2>/dev/null || true",
36+
"command": "(python3 -B ./hooks/fi-hook-to-otlp/emit.py cursor afterAgentThought 2>/dev/null || true)",
3737
"timeout": 10
3838
}
3939
],
4040
"afterAgentResponse": [
4141
{
42-
"command": "python3 -B ./hooks/fi-hook-to-otlp/emit.py cursor afterAgentResponse 2>/dev/null || true",
42+
"command": "(python3 -B ./hooks/fi-hook-to-otlp/emit.py cursor afterAgentResponse 2>/dev/null || true)",
4343
"timeout": 10
4444
}
4545
],
4646
"preCompact": [
4747
{
48-
"command": "python3 -B ./hooks/fi-hook-to-otlp/emit.py cursor preCompact 2>/dev/null || true",
48+
"command": "(python3 -B ./hooks/fi-hook-to-otlp/emit.py cursor preCompact 2>/dev/null || true)",
4949
"timeout": 10
5050
}
5151
],
5252
"stop": [
5353
{
54-
"command": "python3 -B ./hooks/fi-hook-to-otlp/emit.py cursor stop 2>/dev/null || true",
54+
"command": "(python3 -B ./hooks/fi-hook-to-otlp/emit.py cursor stop 2>/dev/null || true)",
5555
"timeout": 10
5656
}
5757
],
5858
"sessionEnd": [
5959
{
60-
"command": "python3 -B ./hooks/fi-hook-to-otlp/emit.py cursor sessionEnd 2>/dev/null || true",
60+
"command": "(python3 -B ./hooks/fi-hook-to-otlp/emit.py cursor sessionEnd 2>/dev/null || true)",
6161
"timeout": 10
6262
}
6363
]

‎examples/coding-agents/cursor/run_e2e.sh‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,10 @@
1414
# Set FI_HOOK_CAPTURE_CONTENT=1 to exercise the content opt-in.
1515
# REPLAY_SLEEP (default 1s) spaces the hooks out so the fixture's reported
1616
# tool durations fit inside the turn, as they would in a real session.
17+
# HOOK_TRANSPORT=stdin|heredoc installs the hooks into a temporary project
18+
# with install.sh and runs the shipped hooks.json commands through $SHELL -c,
19+
# passing the payload on stdin (IDE agent) or as a trailing heredoc (Cursor's
20+
# headless agent host), instead of calling emit.py directly.
1721
set -euo pipefail
1822

1923
HERE="$(cd "$(dirname "$0")" && pwd)"
@@ -35,7 +39,15 @@ PY
3539

3640
REPLACE=(--replace "$SRC_CONV=$CONV")
3741
if [ "$SRC_GEN" != "-" ]; then REPLACE+=(--replace "$SRC_GEN=$GEN"); fi
38-
python3 -B "$EMITTER/replay.py" cursor "$FIXTURE" "${REPLACE[@]}" \
42+
VIA=()
43+
if [ -n "${HOOK_TRANSPORT:-}" ]; then
44+
PROJECT="$(mktemp -d)"
45+
trap 'rm -rf "$PROJECT"' EXIT
46+
"$HERE/install.sh" "$PROJECT" >/dev/null
47+
VIA=(--hooks-json "$PROJECT/.cursor/hooks.json" --cwd "$PROJECT" --transport "$HOOK_TRANSPORT")
48+
echo "via installed hooks.json, transport=$HOOK_TRANSPORT"
49+
fi
50+
python3 -B "$EMITTER/replay.py" cursor "$FIXTURE" "${REPLACE[@]}" ${VIA[@]+"${VIA[@]}"} \
3951
--sleep "${REPLAY_SLEEP:-1}" ${@+"$@"}
4052

4153
TRACE_ID="$(cd "$EMITTER" && python3 -B -c 'import sys, emit; print(emit.trace_id("cursor", sys.argv[1]))' "$CONV")"

‎examples/coding-agents/hook-to-otlp/README.md‎

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ echo '{"conversation_id":"c1","generation_id":"g1","tool_name":"Shell","duration
2424

2525
`python3 emit.py <app> [<event>] [--env-file PATH]` reads one JSON object on
2626
stdin, prints what the host expects on stdout (`{}` unless the adapter says
27-
otherwise), and always exits 0. On macOS and Linux the network send happens in a
27+
otherwise; nothing if the adapter cannot be loaded or the script fails), and exits 0. On macOS and Linux the network send happens in a
2828
detached child process so the host is not kept waiting. Windows has no fork: the
2929
send is inline (default timeout 3 s) and state files are not locked.
3030

@@ -35,17 +35,22 @@ Every app ships its hook commands in this form, so a missing emitter, a missing
3535
"block") and never prints a decision:
3636

3737
```bash
38-
python3 -B <path-to>/emit.py <app> <EventName> 2>/dev/null || true
38+
(python3 -B <path-to>/emit.py <app> <EventName> 2>/dev/null || true)
3939
```
4040

41-
`|| true` makes every failure exit 0 with empty stdout; `2>/dev/null` keeps Python's
42-
own error text out of host logs (the emitter never writes to stderr); `-B` keeps
43-
`__pycache__` out of the customer's repo. Pass the event name explicitly. Do not add
44-
`echo` fallbacks (a second JSON object is invalid output). The form needs a POSIX shell;
45-
document the equivalent on hosts whose hook runner is not one. Add a config test like
46-
`tests/test_cursor_hooks_config.py`: run every shipped command through `sh -c` with the
41+
`|| true` makes every failure exit 0 with empty stdout. The parentheses make it a
42+
subshell, so the payload reaches `python3` whether the host pipes it to stdin or
43+
appends it as a trailing heredoc (Cursor's headless agent host runs
44+
`<command> <<'CURSOR_HOOK_EOF'`); without them the heredoc binds to `true` and the
45+
emitter reads nothing. `2>/dev/null` keeps Python's own error text out of host logs
46+
(the emitter never writes to stderr); `-B` keeps `__pycache__` out of the customer's
47+
repo. Pass the event name explicitly. Do not add `echo` fallbacks (a second JSON object
48+
is invalid output). The form needs a POSIX shell; document the equivalent on hosts whose
49+
hook runner is not one (and note that a host that execs the command without a shell gets
50+
no guard). Add a config test like `tests/test_cursor_hooks_config.py`: run every shipped
51+
command through `sh -c` with the payload on stdin and as a trailing heredoc, with the
4752
emitter missing, with `python3` missing, and installed, and assert exit 0 plus the
48-
expected (or empty) stdout.
53+
expected (or empty) stdout and that the installed emitter received the payload.
4954

5055
| Variable | Default | Meaning |
5156
| --- | --- | --- |
@@ -80,7 +85,8 @@ expected (or empty) stdout.
8085
from the payload, else the hook time, never earlier than the root's start once the
8186
root has been sent. A turn opens on the first event that names it.
8287
- A tool/subagent/llm/event span without `turn_id` goes under the open turn and gets
83-
`coding_agent.turn.inferred=true`; with no open turn it goes under the session.
88+
`coding_agent.turn.inferred=true`; with no open turn it goes under the session with no
89+
turn marker.
8490
- A turn end closes still-open children of that turn (`coding_agent.incomplete=true`);
8591
a session end closes everything and deletes the state file.
8692
- One turn is open per session: a turn START closes any other open turn (and its
@@ -92,7 +98,9 @@ expected (or empty) stdout.
9298
spans add `llm.model_name` when the payload names a model (the root uses the last model
9399
reported by a session, turn or llm event).
94100
- Opted-in content keeps paths but replaces the user name in home-directory paths with
95-
`<user>` (`/Users/<user>/...`, `/home/<user>/...`, `C:\Users\<user>\...`).
101+
`<user>` (`/Users/<user>/...`, `/home/<user>/...`, `C:\Users\<user>\...`, `~<user>/...`),
102+
including names with spaces when a path separator follows them, and this machine's own
103+
home directory wherever it appears.
96104

97105
## Writing an adapter
98106

@@ -159,4 +167,7 @@ adapter and its test are the reference.
159167
python3 -m unittest discover -s tests -t .
160168
# replay a recorded session into a real collector with a fresh session id
161169
python3 replay.py cursor tests/fixtures/cursor/session.jsonl --replace fixture-conv-0001=run-$(date +%s)
170+
# same, through the commands of an installed hooks file, payload as a trailing heredoc
171+
python3 replay.py cursor tests/fixtures/cursor/session.jsonl --replace fixture-conv-0001=run-$(date +%s) \
172+
--hooks-json /path/to/project/.cursor/hooks.json --cwd /path/to/project --transport heredoc
162173
```

‎examples/coding-agents/hook-to-otlp/emit.py‎

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
``<app>`` selects ``adapters/<app>.py``. ``<event>`` is the hook name when
99
the host does not put it in the payload. The script reads one JSON object
1010
from stdin, prints what the host expects on stdout, and always exits 0.
11+
If the adapter cannot be loaded or the script fails, it prints nothing
12+
(the same as a missing emitter behind the guarded hook command).
1113
1214
One agent session becomes one trace (the trace id is derived from the
1315
session id). Turns, tools, subagents, and model responses become child
@@ -65,10 +67,13 @@
6567
re.compile(r"(?i)\b(bearer\s+)[A-Za-z0-9._~+/=-]{12,}"),
6668
re.compile(r"(?i)\b((?:api[_-]?key|secret[_-]?key|access[_-]?token|password|passwd|token)\b[\"']?\s*[:=]\s*[\"']?)[^\s\"',}]+"),
6769
)
68-
# Opted-in content keeps paths but not the account name inside them.
70+
# Opted-in content keeps paths but not the account name inside them. A name
71+
# may contain spaces when a path separator follows it ("/Users/Jo Ann/x").
72+
_NAME = r"(?:[^/\\\s\"']+(?: [^/\\\s\"']+)*(?=[/\\])|[^/\\\s\"']+)"
6973
HOME_PATTERNS = (
70-
re.compile(r"(/Users/|/home/)[^/\s\"'\\]+"),
71-
re.compile(r"([A-Za-z]:(?:\\\\|\\|/)+Users(?:\\\\|\\|/)+)[^\\/\s\"']+"),
74+
re.compile(r"(/Users/|/home/)" + _NAME),
75+
re.compile(r"([A-Za-z]:(?:\\\\|\\|/)+Users(?:\\\\|\\|/)+)" + _NAME),
76+
re.compile(r"((?<![\w~])~)[A-Za-z_][A-Za-z0-9._-]*(?=/)"),
7277
)
7378
MAX_ENDED_TURNS = 64
7479
MAX_ENDED_RECS = 8
@@ -174,8 +179,20 @@ def redact(text: str) -> str:
174179
return text
175180

176181

182+
def _own_home() -> Optional[Tuple[str, str]]:
183+
"""This machine's home directory and its <user> form, if it is a usual one."""
184+
home = os.path.expanduser("~")
185+
match = re.fullmatch(r"(/Users/|/home/|[A-Za-z]:\\Users\\)([^/\\]+)", home or "")
186+
return (home, match.group(1) + "<user>") if match else None
187+
188+
177189
def scrub_home(text: str) -> str:
178190
"""Replace the user name in home-directory paths with <user>."""
191+
own = _own_home()
192+
if own: # this machine's home first: catches a spaced name at the end of a string
193+
home, scrubbed = own
194+
for raw, repl in {home: scrubbed, json.dumps(home)[1:-1]: json.dumps(scrubbed)[1:-1]}.items():
195+
text = re.sub(re.escape(raw) + r"(?![^/\\\s\"'])", lambda _m, r=repl: r, text)
179196
for pattern in HOME_PATTERNS:
180197
text = pattern.sub(lambda m: m.group(1) + "<user>", text)
181198
return text
@@ -625,7 +642,9 @@ def respond(adapter: Any, event: str, payload: Dict[str, Any]) -> str:
625642
try:
626643
out = fn(event, payload)
627644
except Exception:
628-
return "{}"
645+
# Print nothing, like a missing emitter: "{}" can be invalid output for
646+
# a hook that decides something (Cursor blocks permission hooks on it).
647+
return ""
629648
# None means "use the default"; "" means "print nothing" (hosts that add
630649
# hook stdout to the model context).
631650
return "{}" if out is None else str(out)
@@ -776,7 +795,9 @@ def run(argv: List[str], stdin_text: str, env: Mapping[str, str]) -> str:
776795
try:
777796
adapter = load_adapter(app)
778797
except Exception:
779-
return "{}"
798+
# Without the adapter we cannot tell an observation hook from a
799+
# permission hook, so print nothing (same as a missing emitter).
800+
return ""
780801
try:
781802
payload = json.loads(stdin_text) if stdin_text.strip() else {}
782803
except ValueError:
@@ -819,7 +840,7 @@ def main() -> int:
819840
try:
820841
out = run(sys.argv[1:], stdin_text, os.environ)
821842
except Exception:
822-
out = "{}"
843+
out = ""
823844
with contextlib.suppress(Exception):
824845
_write_stdout(out)
825846
return 0

0 commit comments

Comments
 (0)