forked from robertelee78/claude-telegram-mirror
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtelegram-hook.sh
More file actions
executable file
·423 lines (359 loc) · 14.9 KB
/
telegram-hook.sh
File metadata and controls
executable file
·423 lines (359 loc) · 14.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
#!/bin/bash
#
# Claude Code Telegram Hook
# Captures hook events and forwards to bridge daemon
#
# Usage: This script is called by Claude Code's hook system
# It reads JSON from stdin and forwards to the bridge
#
# The hook is ENABLED when the bridge daemon is running (socket exists).
# No environment variable needed - just start the bridge!
#
# Debug logging disabled by default - set TELEGRAM_HOOK_DEBUG=1 to enable
TELEGRAM_HOOK_DEBUG="${TELEGRAM_HOOK_DEBUG:-0}"
set -e
# Trap to ensure clean exit and helpful error message
trap 'debug_log "Script exiting with code $?"' EXIT
# Get the directory of this script
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PACKAGE_DIR="$(dirname "$SCRIPT_DIR")"
CONFIG_DIR="$HOME/.config/claude-telegram-mirror"
# Socket path for bridge communication (now in user config dir, not /tmp)
SOCKET_PATH="${TELEGRAM_BRIDGE_SOCKET:-$CONFIG_DIR/bridge.sock}"
# Debug logging (set TELEGRAM_HOOK_DEBUG=1 to enable)
debug_log() {
if [[ "${TELEGRAM_HOOK_DEBUG}" == "1" ]]; then
# Log to config dir instead of world-readable /tmp
mkdir -p "$CONFIG_DIR" 2>/dev/null || true
echo "[telegram-hook] $(date '+%Y-%m-%d %H:%M:%S') $1" >> "$CONFIG_DIR/hook-debug.log"
fi
}
debug_log "Hook called, checking socket at $SOCKET_PATH"
# Check if bridge is running (socket exists = enabled)
if [[ ! -S "$SOCKET_PATH" ]]; then
# Bridge not running, pass through silently
debug_log "Bridge not running (no socket), passing through"
cat
exit 0
fi
debug_log "Bridge socket found, processing..."
# Read stdin into variable
INPUT=$(cat)
# If empty, just exit
if [[ -z "$INPUT" ]]; then
debug_log "Empty input, exiting"
exit 0
fi
# Log raw input for debugging
debug_log "Raw input: $INPUT"
# Parse hook type from input (field is "hook_event_name" not "type")
HOOK_TYPE=$(echo "$INPUT" | jq -r '.hook_event_name // .type // empty' 2>/dev/null || echo "")
debug_log "Hook type: $HOOK_TYPE"
# Use Claude's native session_id from the hook input - this is the canonical session identifier
# This ensures all events from the same Claude session go to the same Telegram topic
CLAUDE_SESSION_ID=$(echo "$INPUT" | jq -r '.session_id // empty' 2>/dev/null || echo "")
debug_log "Claude session_id: $CLAUDE_SESSION_ID"
# BUG-006 fix: Removed file-based session tracking
# Daemon SQLite is now the single source of truth for session state
# Hooks are stateless - they just forward events to the daemon
# Use Claude's native session_id, or generate one as fallback
SESSION_ID="${CLAUDE_SESSION_ID:-$(date +%s)-$$}"
debug_log "Using session ID: $SESSION_ID"
# Get tmux info and hostname for metadata
# Extracts socket path from $TMUX env var for explicit targeting
# Always includes hostname for topic naming
get_tmux_info() {
local host=$(hostname 2>/dev/null || echo "")
if [[ -z "$TMUX" ]]; then
# No tmux, but still include hostname
if [[ -n "$host" ]]; then
jq -cn --arg hostname "$host" '{hostname: $hostname}'
else
echo "{}"
fi
return
fi
# $TMUX format: /path/to/socket,pid,index
# Extract socket path (everything before first comma)
local socket_path="${TMUX%%,*}"
local session=$(tmux display-message -p "#S" 2>/dev/null || echo "")
local pane=$(tmux display-message -p "#P" 2>/dev/null || echo "")
local window=$(tmux display-message -p "#I" 2>/dev/null || echo "")
if [[ -n "$session" && -n "$window" && -n "$pane" ]]; then
local target="${session}:${window}.${pane}"
jq -cn \
--arg session "$session" \
--arg pane "$pane" \
--arg target "$target" \
--arg socket "$socket_path" \
--arg hostname "$host" \
'{tmuxSession: $session, tmuxPane: $pane, tmuxTarget: $target, tmuxSocket: $socket, hostname: $hostname}'
else
# tmux present but can't get details - still include hostname
if [[ -n "$host" ]]; then
jq -cn --arg hostname "$host" '{hostname: $hostname}'
else
echo "{}"
fi
fi
}
# Send message to bridge via netcat (fast)
# Works on both Linux (GNU netcat) and macOS (BSD netcat)
send_to_bridge() {
local message="$1"
debug_log "Sending to bridge: ${message:0:100}..."
if command -v nc &> /dev/null; then
local nc_stderr
local nc_exit
# Try GNU netcat first (-q0 = quit after EOF), fall back to BSD netcat (no -q flag)
if nc -h 2>&1 | grep -q '\-q'; then
# GNU netcat - supports -q flag
nc_stderr=$(echo "$message" | nc -U -q0 "$SOCKET_PATH" 2>&1)
nc_exit=$?
else
# BSD netcat (macOS) - no -q flag needed, closes on EOF
nc_stderr=$(echo "$message" | nc -U "$SOCKET_PATH" 2>&1)
nc_exit=$?
fi
debug_log "nc result: exit=$nc_exit, stderr=$nc_stderr"
if [[ $nc_exit -ne 0 ]]; then
debug_log "nc FAILED! socket=$SOCKET_PATH"
fi
elif [[ -S "$SOCKET_PATH" ]]; then
echo "$message" > "$SOCKET_PATH" 2>/dev/null || true
debug_log "Used direct write to socket"
else
debug_log "No nc and no socket!"
fi
}
# ============================================
# REAL-TIME TRANSCRIPT SYNC
# Extract new assistant text on EVERY hook event
# This provides real-time mirroring of Claude's responses
# ============================================
sync_new_assistant_text() {
local transcript_path=$(echo "$INPUT" | jq -r '.transcript_path // ""' 2>/dev/null)
if [[ -z "$transcript_path" || ! -f "$transcript_path" ]]; then
return
fi
# Use separate state file for continuous sync (different from Stop hook)
local state_file="$CONFIG_DIR/.sync_${SESSION_ID}"
local last_line=0
if [[ -f "$state_file" ]]; then
last_line=$(cat "$state_file" 2>/dev/null || echo 0)
fi
local current_line=$(wc -l < "$transcript_path")
# No new lines
if [[ $current_line -le $last_line ]]; then
return
fi
local new_count=$((current_line - last_line))
local timestamp=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
local found_text=0
# Process new lines for assistant text messages
while IFS= read -r line; do
local msg_type=$(echo "$line" | jq -r '.type // empty' 2>/dev/null)
if [[ "$msg_type" == "assistant" ]]; then
# Extract text content (skip tool_use blocks)
local text=$(echo "$line" | jq -r '.message.content[]? | select(.type == "text") | .text' 2>/dev/null)
if [[ -n "$text" && ${#text} -gt 10 ]]; then
debug_log "Sync: Found assistant text (${#text} chars)"
# Use printf + pipe to handle large content (avoids "Argument list too long")
local msg=$(printf '%s' "$text" | jq -Rsc \
--arg type "agent_response" \
--arg sessionId "$SESSION_ID" \
--arg timestamp "$timestamp" \
'{type: $type, sessionId: $sessionId, timestamp: $timestamp, content: .}')
send_to_bridge "$msg"
found_text=1
fi
fi
done < <(tail -n "$new_count" "$transcript_path")
# Update state (always, even if no text found - to track line position)
echo "$current_line" > "$state_file"
if [[ $found_text -eq 1 ]]; then
debug_log "Sync: Sent new assistant text"
fi
}
# ============================================
# REAL-TIME SYNC: DISABLED - causing replay issues
# TODO: Fix race conditions before re-enabling
# ============================================
# sync_new_assistant_text &
# Format bridge message based on hook type
# IMPORTANT: Every message includes current tmux info for auto-refresh (BUG-001 fix)
format_message() {
local hook_type="$1"
local input="$2"
local timestamp=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
# Get current tmux info for EVERY message (enables auto-refresh on pane changes)
local tmux_info=$(get_tmux_info)
case "$hook_type" in
"PreToolUse")
local tool_name=$(echo "$input" | jq -r '.tool_name // "unknown"')
local tool_input=$(echo "$input" | jq -c '.tool_input // {}')
# Send tool info (not just dangerous ones - for visibility)
# Include tmux info for auto-refresh
jq -cn \
--arg type "tool_start" \
--arg sessionId "$SESSION_ID" \
--arg timestamp "$timestamp" \
--arg tool "$tool_name" \
--argjson input "$tool_input" \
--argjson tmux "$tmux_info" \
'{type: $type, sessionId: $sessionId, timestamp: $timestamp, content: "Tool: \($tool)", metadata: ({tool: $tool, input: $input} + $tmux)}'
;;
"PostToolUse")
local tool_name=$(echo "$input" | jq -r '.tool_name // "unknown"')
local tool_output=$(echo "$input" | jq -r '.tool_output // ""' | head -c 2000)
# Only send significant outputs
# Include tmux info for auto-refresh
if [[ ${#tool_output} -gt 10 ]]; then
jq -cn \
--arg type "tool_result" \
--arg sessionId "$SESSION_ID" \
--arg timestamp "$timestamp" \
--arg tool "$tool_name" \
--arg output "$tool_output" \
--argjson tmux "$tmux_info" \
'{type: $type, sessionId: $sessionId, timestamp: $timestamp, content: $output, metadata: ({tool: $tool} + $tmux)}'
fi
;;
"Notification")
local message=$(echo "$input" | jq -r '.message // ""')
local notification_type=$(echo "$input" | jq -r '.notification_type // ""')
local level=$(echo "$input" | jq -r '.level // "info"')
# Skip idle_prompt notifications - they're just noise
if [[ "$notification_type" == "idle_prompt" ]]; then
debug_log "Skipping idle_prompt notification"
return
fi
# Include tmux info for auto-refresh
if [[ -n "$message" ]]; then
jq -cn \
--arg type "agent_response" \
--arg sessionId "$SESSION_ID" \
--arg timestamp "$timestamp" \
--arg message "$message" \
--arg level "$level" \
--argjson tmux "$tmux_info" \
'{type: $type, sessionId: $sessionId, timestamp: $timestamp, content: $message, metadata: ({level: $level} + $tmux)}'
fi
;;
"Stop")
local transcript_path=$(echo "$input" | jq -r '.transcript_path // ""')
debug_log "Stop: transcript_path='$transcript_path'"
debug_log "Stop: file exists=$(test -f "$transcript_path" && echo yes || echo no)"
# Extract NEW text content since last Stop
# Track what we've sent to avoid duplicates
if [[ -n "$transcript_path" && -f "$transcript_path" ]]; then
debug_log "Reading transcript: $transcript_path"
# Track last processed line using a state file
local state_file="$CONFIG_DIR/.last_line_${SESSION_ID}"
local last_line=0
if [[ -f "$state_file" ]]; then
last_line=$(cat "$state_file" 2>/dev/null || echo 0)
fi
local current_line=$(wc -l < "$transcript_path")
debug_log "Last processed: $last_line, Current: $current_line"
# Only process new lines
if [[ $current_line -gt $last_line ]]; then
local new_lines=$((current_line - last_line))
local all_text=""
# Process only NEW lines
while IFS= read -r line; do
local text=$(echo "$line" | jq -r 'select(.type == "assistant") | .message.content[]? | select(.type == "text") | .text' 2>/dev/null)
if [[ -n "$text" ]]; then
if [[ -n "$all_text" ]]; then
all_text="${all_text}
${text}"
else
all_text="$text"
fi
fi
done < <(tail -n "$new_lines" "$transcript_path")
debug_log "New text length: ${#all_text}"
debug_log "New text preview: ${all_text:0:200}"
if [[ -n "$all_text" ]]; then
# Use printf + pipe to handle large content (avoids "Argument list too long")
# Include tmux info for auto-refresh
local agent_msg=$(printf '%s' "$all_text" | jq -Rsc \
--arg type "agent_response" \
--arg sessionId "$SESSION_ID" \
--arg timestamp "$timestamp" \
--argjson tmux "$tmux_info" \
'{type: $type, sessionId: $sessionId, timestamp: $timestamp, content: ., metadata: $tmux}')
debug_log "Stop: sending agent_response: ${agent_msg:0:150}"
echo "$agent_msg"
else
debug_log "Stop: NO text extracted from new lines"
fi
# Update state
echo "$current_line" > "$state_file"
else
debug_log "Stop: no new lines (current=$current_line, last=$last_line)"
fi
else
debug_log "Stop: transcript not accessible (path='$transcript_path', exists=$(test -f "$transcript_path" && echo yes || echo no))"
fi
# DON'T send session_end on every Stop - Claude fires Stop after every turn!
# The session is still active. Only send a turn_complete notification.
# Session end should happen when user explicitly exits or connection drops.
# Include tmux info for auto-refresh
local turn_msg=$(jq -cn \
--arg type "turn_complete" \
--arg sessionId "$SESSION_ID" \
--arg timestamp "$timestamp" \
--argjson tmux "$tmux_info" \
'{type: $type, sessionId: $sessionId, timestamp: $timestamp, content: "Turn complete", metadata: $tmux}')
debug_log "Stop: sending turn_complete: $turn_msg"
echo "$turn_msg"
;;
"UserPromptSubmit")
local prompt=$(echo "$input" | jq -r '.prompt // ""')
# Include tmux info for auto-refresh
if [[ -n "$prompt" ]]; then
jq -cn \
--arg type "user_input" \
--arg sessionId "$SESSION_ID" \
--arg timestamp "$timestamp" \
--arg prompt "$prompt" \
--argjson tmux "$tmux_info" \
'{type: $type, sessionId: $sessionId, timestamp: $timestamp, content: $prompt, metadata: ({source: "cli"} + $tmux)}'
fi
;;
"PreCompact")
# Fires just before context compaction (manual or auto)
local trigger=$(echo "$input" | jq -r '.trigger // "auto"')
local custom_instructions=$(echo "$input" | jq -r '.custom_instructions // ""')
debug_log "PreCompact: trigger=$trigger"
# Include tmux info for auto-refresh
jq -cn \
--arg type "pre_compact" \
--arg sessionId "$SESSION_ID" \
--arg timestamp "$timestamp" \
--arg trigger "$trigger" \
--arg instructions "$custom_instructions" \
--argjson tmux "$tmux_info" \
'{type: $type, sessionId: $sessionId, timestamp: $timestamp, content: "Context compaction starting", metadata: ({trigger: $trigger, custom_instructions: $instructions} + $tmux)}'
;;
esac
}
# BUG-006 fix: Removed first-event detection and session_start sending from hook
# The daemon's ensureSessionExists() handles session creation via SQLite
# This makes hooks stateless - they just forward events
# Format and send message(s)
if [[ -n "$HOOK_TYPE" ]]; then
# format_message may return multiple JSON lines (e.g., Stop returns responses + session_end)
MESSAGES=$(format_message "$HOOK_TYPE" "$INPUT")
if [[ -n "$MESSAGES" ]]; then
# Send each line as a separate message
while IFS= read -r msg; do
if [[ -n "$msg" ]]; then
send_to_bridge "$msg"
fi
done <<< "$MESSAGES"
fi
fi
# Pass through original input for Claude Code
echo "$INPUT"