infinex commited on
Commit
fb52d98
·
verified ·
1 Parent(s): 5bc66d8

Uploading dataset files from the local data folder.

Browse files
Files changed (1) hide show
  1. lf_hooks.py +744 -0
lf_hooks.py ADDED
@@ -0,0 +1,744 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env uv run
2
+ """
3
+ Claude Code -> Langfuse hook
4
+
5
+ Sends Claude Code conversation turns to Langfuse as traces with spans,
6
+ generations, and tool observations. Runs on the "Stop" hook (after each
7
+ assistant turn) and reads the JSONL transcript incrementally.
8
+
9
+ Setup
10
+ =====
11
+
12
+ 1. Register the hook in .claude/settings.json (committed to repo):
13
+
14
+ {
15
+ "hooks": {
16
+ "Stop": [
17
+ {
18
+ "hooks": [
19
+ {
20
+ "type": "command",
21
+ "command": "uv run --project /path/to/project .claude/hooks/langfuse_hook.py"
22
+ }
23
+ ]
24
+ }
25
+ ]
26
+ }
27
+ }
28
+
29
+ 2. Add credentials and config in .claude/settings.local.json (gitignored):
30
+
31
+ {
32
+ "env": {
33
+ "TRACE_TO_LANGFUSE": "true",
34
+ "LANGFUSE_PUBLIC_KEY": "pk-lf-...",
35
+ "LANGFUSE_SECRET_KEY": "sk-lf-...",
36
+ "LANGFUSE_BASE_URL": "https://cloud.langfuse.com",
37
+ "CC_LANGFUSE_USER_ID": "user@example.com",
38
+ "CC_LANGFUSE_ENVIRONMENT": "my-project"
39
+ }
40
+ }
41
+
42
+ Environment variables
43
+ =====================
44
+
45
+ Required (in settings.local.json env):
46
+ TRACE_TO_LANGFUSE Set to "true" to enable tracing.
47
+ LANGFUSE_PUBLIC_KEY Langfuse project public key.
48
+ LANGFUSE_SECRET_KEY Langfuse project secret key.
49
+
50
+ Optional:
51
+ LANGFUSE_BASE_URL Langfuse host (default: https://cloud.langfuse.com).
52
+ CC_LANGFUSE_USER_ID User ID attached to all traces (e.g. email).
53
+ CC_LANGFUSE_ENVIRONMENT Environment name for Langfuse (e.g. project name).
54
+ Must match: ^(?!langfuse)[a-z0-9-_]+$ (max 40 chars).
55
+ CC_LANGFUSE_DEBUG Set to "true" for verbose logging.
56
+ CC_LANGFUSE_MAX_CHARS Max characters before truncation (default: 20000).
57
+
58
+ Trace metadata
59
+ ==============
60
+
61
+ Each trace/span includes the following metadata keys:
62
+
63
+ source Always "claude-code".
64
+ session_id Claude Code session UUID.
65
+ turn_number Sequential turn number within the session.
66
+ transcript_path Local path to the JSONL transcript file.
67
+ user_text Truncation info for the user message.
68
+ host_ip Public IP of the machine (via api.ipify.org).
69
+ host_name OS hostname of the machine.
70
+ host_cwd Working directory where Claude Code was invoked.
71
+
72
+ Notes
73
+ =====
74
+ - settings.json is committed and shared; settings.local.json holds secrets
75
+ and per-user config and should be gitignored.
76
+ - The hook fails open: if Langfuse is unreachable or misconfigured, Claude
77
+ Code continues normally.
78
+ """
79
+
80
+ import json
81
+ import os
82
+ import socket
83
+ import sys
84
+ import time
85
+ import hashlib
86
+ from dataclasses import dataclass
87
+ from datetime import datetime, timezone
88
+ from pathlib import Path
89
+ from typing import Any, Dict, List, Optional, Tuple
90
+
91
+ # --- Langfuse import (fail-open) ---
92
+ try:
93
+ from langfuse import Langfuse, propagate_attributes
94
+ except Exception:
95
+ sys.exit(0)
96
+
97
+ # --- Paths ---
98
+ STATE_DIR = Path.home() / ".claude" / "state"
99
+ LOG_FILE = STATE_DIR / "langfuse_hook.log"
100
+ STATE_FILE = STATE_DIR / "langfuse_state.json"
101
+ LOCK_FILE = STATE_DIR / "langfuse_state.lock"
102
+
103
+ DEBUG = os.environ.get("CC_LANGFUSE_DEBUG", "").lower() == "true"
104
+ MAX_CHARS = int(os.environ.get("CC_LANGFUSE_MAX_CHARS", "20000"))
105
+
106
+
107
+ # ----------------- Logging -----------------
108
+ def _log(level: str, message: str) -> None:
109
+ try:
110
+ STATE_DIR.mkdir(parents=True, exist_ok=True)
111
+ ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
112
+ with open(LOG_FILE, "a", encoding="utf-8") as f:
113
+ f.write(f"{ts} [{level}] {message}\n")
114
+ except Exception:
115
+ # Never block
116
+ pass
117
+
118
+
119
+ def debug(msg: str) -> None:
120
+ if DEBUG:
121
+ _log("DEBUG", msg)
122
+
123
+
124
+ def info(msg: str) -> None:
125
+ _log("INFO", msg)
126
+
127
+
128
+ def warn(msg: str) -> None:
129
+ _log("WARN", msg)
130
+
131
+
132
+ def error(msg: str) -> None:
133
+ _log("ERROR", msg)
134
+
135
+
136
+ # ----------------- State locking (best-effort) -----------------
137
+ class FileLock:
138
+ def __init__(self, path: Path, timeout_s: float = 2.0):
139
+ self.path = path
140
+ self.timeout_s = timeout_s
141
+ self._fh = None
142
+
143
+ def __enter__(self):
144
+ STATE_DIR.mkdir(parents=True, exist_ok=True)
145
+ self._fh = open(self.path, "a+", encoding="utf-8")
146
+ try:
147
+ import fcntl # Unix only
148
+
149
+ deadline = time.time() + self.timeout_s
150
+ while True:
151
+ try:
152
+ fcntl.flock(self._fh.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
153
+ break
154
+ except BlockingIOError:
155
+ if time.time() > deadline:
156
+ break
157
+ time.sleep(0.05)
158
+ except Exception:
159
+ # If locking isn't available, proceed without it.
160
+ pass
161
+ return self
162
+
163
+ def __exit__(self, exc_type, exc, tb):
164
+ try:
165
+ import fcntl
166
+
167
+ fcntl.flock(self._fh.fileno(), fcntl.LOCK_UN)
168
+ except Exception:
169
+ pass
170
+ try:
171
+ self._fh.close()
172
+ except Exception:
173
+ pass
174
+
175
+
176
+ def load_state() -> Dict[str, Any]:
177
+ try:
178
+ if not STATE_FILE.exists():
179
+ return {}
180
+ return json.loads(STATE_FILE.read_text(encoding="utf-8"))
181
+ except Exception:
182
+ return {}
183
+
184
+
185
+ def save_state(state: Dict[str, Any]) -> None:
186
+ try:
187
+ STATE_DIR.mkdir(parents=True, exist_ok=True)
188
+ tmp = STATE_FILE.with_suffix(".tmp")
189
+ tmp.write_text(json.dumps(state, indent=2, sort_keys=True), encoding="utf-8")
190
+ os.replace(tmp, STATE_FILE)
191
+ except Exception as e:
192
+ debug(f"save_state failed: {e}")
193
+
194
+
195
+ def state_key(session_id: str, transcript_path: str) -> str:
196
+ # stable key even if session_id collides
197
+ raw = f"{session_id}::{transcript_path}"
198
+ return hashlib.sha256(raw.encode("utf-8")).hexdigest()
199
+
200
+
201
+ # ----------------- Hook payload -----------------
202
+ def read_hook_payload() -> Dict[str, Any]:
203
+ """
204
+ Claude Code hooks pass a JSON payload on stdin.
205
+ This script tolerates missing/empty stdin by returning {}.
206
+ """
207
+ try:
208
+ data = sys.stdin.read()
209
+ if not data.strip():
210
+ return {}
211
+ return json.loads(data)
212
+ except Exception:
213
+ return {}
214
+
215
+
216
+ def extract_session_and_transcript(
217
+ payload: Dict[str, Any],
218
+ ) -> Tuple[Optional[str], Optional[Path]]:
219
+ """
220
+ Tries a few plausible field names; exact keys can vary across hook types/versions.
221
+ Prefer structured values from stdin over heuristics.
222
+ """
223
+ session_id = (
224
+ payload.get("sessionId")
225
+ or payload.get("session_id")
226
+ or payload.get("session", {}).get("id")
227
+ )
228
+
229
+ transcript = (
230
+ payload.get("transcriptPath")
231
+ or payload.get("transcript_path")
232
+ or payload.get("transcript", {}).get("path")
233
+ )
234
+
235
+ if transcript:
236
+ try:
237
+ transcript_path = Path(transcript).expanduser().resolve()
238
+ except Exception:
239
+ transcript_path = None
240
+ else:
241
+ transcript_path = None
242
+
243
+ return session_id, transcript_path
244
+
245
+
246
+ # ----------------- Transcript parsing helpers -----------------
247
+ def get_content(msg: Dict[str, Any]) -> Any:
248
+ if not isinstance(msg, dict):
249
+ return None
250
+ if "message" in msg and isinstance(msg.get("message"), dict):
251
+ return msg["message"].get("content")
252
+ return msg.get("content")
253
+
254
+
255
+ def get_role(msg: Dict[str, Any]) -> Optional[str]:
256
+ # Claude Code transcript lines commonly have type=user/assistant OR message.role
257
+ t = msg.get("type")
258
+ if t in ("user", "assistant"):
259
+ return t
260
+ m = msg.get("message")
261
+ if isinstance(m, dict):
262
+ r = m.get("role")
263
+ if r in ("user", "assistant"):
264
+ return r
265
+ return None
266
+
267
+
268
+ def is_tool_result(msg: Dict[str, Any]) -> bool:
269
+ role = get_role(msg)
270
+ if role != "user":
271
+ return False
272
+ content = get_content(msg)
273
+ if isinstance(content, list):
274
+ return any(
275
+ isinstance(x, dict) and x.get("type") == "tool_result" for x in content
276
+ )
277
+ return False
278
+
279
+
280
+ def iter_tool_results(content: Any) -> List[Dict[str, Any]]:
281
+ out: List[Dict[str, Any]] = []
282
+ if isinstance(content, list):
283
+ for x in content:
284
+ if isinstance(x, dict) and x.get("type") == "tool_result":
285
+ out.append(x)
286
+ return out
287
+
288
+
289
+ def iter_tool_uses(content: Any) -> List[Dict[str, Any]]:
290
+ out: List[Dict[str, Any]] = []
291
+ if isinstance(content, list):
292
+ for x in content:
293
+ if isinstance(x, dict) and x.get("type") == "tool_use":
294
+ out.append(x)
295
+ return out
296
+
297
+
298
+ def extract_text(content: Any) -> str:
299
+ if isinstance(content, str):
300
+ return content
301
+ if isinstance(content, list):
302
+ parts: List[str] = []
303
+ for x in content:
304
+ if isinstance(x, dict) and x.get("type") == "text":
305
+ parts.append(x.get("text", ""))
306
+ elif isinstance(x, str):
307
+ parts.append(x)
308
+ return "\n".join([p for p in parts if p])
309
+ return ""
310
+
311
+
312
+ def truncate_text(s: str, max_chars: int = MAX_CHARS) -> Tuple[str, Dict[str, Any]]:
313
+ if s is None:
314
+ return "", {"truncated": False, "orig_len": 0}
315
+ orig_len = len(s)
316
+ if orig_len <= max_chars:
317
+ return s, {"truncated": False, "orig_len": orig_len}
318
+ head = s[:max_chars]
319
+ return head, {
320
+ "truncated": True,
321
+ "orig_len": orig_len,
322
+ "kept_len": len(head),
323
+ "sha256": hashlib.sha256(s.encode("utf-8")).hexdigest(),
324
+ }
325
+
326
+
327
+ def get_model(msg: Dict[str, Any]) -> str:
328
+ m = msg.get("message")
329
+ if isinstance(m, dict):
330
+ return m.get("model") or "claude"
331
+ return "claude"
332
+
333
+
334
+ def get_message_id(msg: Dict[str, Any]) -> Optional[str]:
335
+ m = msg.get("message")
336
+ if isinstance(m, dict):
337
+ mid = m.get("id")
338
+ if isinstance(mid, str) and mid:
339
+ return mid
340
+ return None
341
+
342
+
343
+ # ----------------- Incremental reader -----------------
344
+ @dataclass
345
+ class SessionState:
346
+ offset: int = 0
347
+ buffer: str = ""
348
+ turn_count: int = 0
349
+
350
+
351
+ def load_session_state(global_state: Dict[str, Any], key: str) -> SessionState:
352
+ s = global_state.get(key, {})
353
+ return SessionState(
354
+ offset=int(s.get("offset", 0)),
355
+ buffer=str(s.get("buffer", "")),
356
+ turn_count=int(s.get("turn_count", 0)),
357
+ )
358
+
359
+
360
+ def write_session_state(
361
+ global_state: Dict[str, Any], key: str, ss: SessionState
362
+ ) -> None:
363
+ global_state[key] = {
364
+ "offset": ss.offset,
365
+ "buffer": ss.buffer,
366
+ "turn_count": ss.turn_count,
367
+ "updated": datetime.now(timezone.utc).isoformat(),
368
+ }
369
+
370
+
371
+ def read_new_jsonl(
372
+ transcript_path: Path, ss: SessionState
373
+ ) -> Tuple[List[Dict[str, Any]], SessionState]:
374
+ """
375
+ Reads only new bytes since ss.offset. Keeps ss.buffer for partial last line.
376
+ Returns parsed JSON lines (best-effort) and updated state.
377
+ """
378
+ if not transcript_path.exists():
379
+ return [], ss
380
+
381
+ try:
382
+ with open(transcript_path, "rb") as f:
383
+ f.seek(ss.offset)
384
+ chunk = f.read()
385
+ new_offset = f.tell()
386
+ except Exception as e:
387
+ debug(f"read_new_jsonl failed: {e}")
388
+ return [], ss
389
+
390
+ if not chunk:
391
+ return [], ss
392
+
393
+ try:
394
+ text = chunk.decode("utf-8", errors="replace")
395
+ except Exception:
396
+ text = chunk.decode(errors="replace")
397
+
398
+ combined = ss.buffer + text
399
+ lines = combined.split("\n")
400
+ # last element may be incomplete
401
+ ss.buffer = lines[-1]
402
+ ss.offset = new_offset
403
+
404
+ msgs: List[Dict[str, Any]] = []
405
+ for line in lines[:-1]:
406
+ line = line.strip()
407
+ if not line:
408
+ continue
409
+ try:
410
+ msgs.append(json.loads(line))
411
+ except Exception:
412
+ continue
413
+
414
+ return msgs, ss
415
+
416
+
417
+ # ----------------- Turn assembly -----------------
418
+ @dataclass
419
+ class Turn:
420
+ user_msg: Dict[str, Any]
421
+ assistant_msgs: List[Dict[str, Any]]
422
+ tool_results_by_id: Dict[str, Any]
423
+
424
+
425
+ def build_turns(messages: List[Dict[str, Any]]) -> List[Turn]:
426
+ """
427
+ Groups incremental transcript rows into turns:
428
+ user (non-tool-result) -> assistant messages -> (tool_result rows, possibly interleaved)
429
+ Uses:
430
+ - assistant message dedupe by message.id (latest row wins)
431
+ - tool results dedupe by tool_use_id (latest wins)
432
+ """
433
+ turns: List[Turn] = []
434
+ current_user: Optional[Dict[str, Any]] = None
435
+
436
+ # assistant messages for current turn:
437
+ assistant_order: List[
438
+ str
439
+ ] = [] # message ids in order of first appearance (or synthetic)
440
+ assistant_latest: Dict[str, Dict[str, Any]] = {} # id -> latest msg
441
+
442
+ tool_results_by_id: Dict[str, Any] = {} # tool_use_id -> content
443
+
444
+ def flush_turn():
445
+ nonlocal \
446
+ current_user, \
447
+ assistant_order, \
448
+ assistant_latest, \
449
+ tool_results_by_id, \
450
+ turns
451
+ if current_user is None:
452
+ return
453
+ if not assistant_latest:
454
+ return
455
+ assistants = [
456
+ assistant_latest[mid] for mid in assistant_order if mid in assistant_latest
457
+ ]
458
+ turns.append(
459
+ Turn(
460
+ user_msg=current_user,
461
+ assistant_msgs=assistants,
462
+ tool_results_by_id=dict(tool_results_by_id),
463
+ )
464
+ )
465
+
466
+ for msg in messages:
467
+ role = get_role(msg)
468
+
469
+ # tool_result rows show up as role=user with content blocks of type tool_result
470
+ if is_tool_result(msg):
471
+ for tr in iter_tool_results(get_content(msg)):
472
+ tid = tr.get("tool_use_id")
473
+ if tid:
474
+ tool_results_by_id[str(tid)] = tr.get("content")
475
+ continue
476
+
477
+ if role == "user":
478
+ # new user message -> finalize previous turn
479
+ flush_turn()
480
+
481
+ # start a new turn
482
+ current_user = msg
483
+ assistant_order = []
484
+ assistant_latest = {}
485
+ tool_results_by_id = {}
486
+ continue
487
+
488
+ if role == "assistant":
489
+ if current_user is None:
490
+ # ignore assistant rows until we see a user message
491
+ continue
492
+
493
+ mid = get_message_id(msg) or f"noid:{len(assistant_order)}"
494
+ if mid not in assistant_latest:
495
+ assistant_order.append(mid)
496
+ assistant_latest[mid] = msg
497
+ continue
498
+
499
+ # ignore unknown rows
500
+
501
+ # flush last
502
+ flush_turn()
503
+ return turns
504
+
505
+
506
+ # ----------------- Langfuse emit -----------------
507
+ def _tool_calls_from_assistants(
508
+ assistant_msgs: List[Dict[str, Any]],
509
+ ) -> List[Dict[str, Any]]:
510
+ calls: List[Dict[str, Any]] = []
511
+ for am in assistant_msgs:
512
+ for tu in iter_tool_uses(get_content(am)):
513
+ tid = tu.get("id") or ""
514
+ calls.append(
515
+ {
516
+ "id": str(tid),
517
+ "name": tu.get("name") or "unknown",
518
+ "input": tu.get("input")
519
+ if isinstance(tu.get("input"), (dict, list, str, int, float, bool))
520
+ else {},
521
+ }
522
+ )
523
+ return calls
524
+
525
+
526
+ def emit_turn(
527
+ langfuse: Langfuse,
528
+ session_id: str,
529
+ turn_num: int,
530
+ turn: Turn,
531
+ transcript_path: Path,
532
+ host_meta: Optional[Dict[str, str]] = None,
533
+ ) -> None:
534
+ user_text_raw = extract_text(get_content(turn.user_msg))
535
+ user_text, user_text_meta = truncate_text(user_text_raw)
536
+
537
+ last_assistant = turn.assistant_msgs[-1]
538
+ assistant_text_raw = extract_text(get_content(last_assistant))
539
+ assistant_text, assistant_text_meta = truncate_text(assistant_text_raw)
540
+
541
+ model = get_model(turn.assistant_msgs[0])
542
+
543
+ tool_calls = _tool_calls_from_assistants(turn.assistant_msgs)
544
+
545
+ # attach tool outputs
546
+ for c in tool_calls:
547
+ if c["id"] and c["id"] in turn.tool_results_by_id:
548
+ out_raw = turn.tool_results_by_id[c["id"]]
549
+ out_str = (
550
+ out_raw
551
+ if isinstance(out_raw, str)
552
+ else json.dumps(out_raw, ensure_ascii=False)
553
+ )
554
+ out_trunc, out_meta = truncate_text(out_str)
555
+ c["output"] = out_trunc
556
+ c["output_meta"] = out_meta
557
+ else:
558
+ c["output"] = None
559
+
560
+ user_id = os.environ.get("CC_LANGFUSE_USER_ID")
561
+
562
+ with propagate_attributes(
563
+ session_id=session_id,
564
+ user_id=user_id,
565
+ trace_name=f"Claude Code - Turn {turn_num}",
566
+ tags=["claude-code"],
567
+ metadata=host_meta or None,
568
+ ):
569
+ with langfuse.start_as_current_span(
570
+ name=f"Claude Code - Turn {turn_num}",
571
+ input={"role": "user", "content": user_text},
572
+ metadata={
573
+ "source": "claude-code",
574
+ "session_id": session_id,
575
+ "turn_number": turn_num,
576
+ "transcript_path": str(transcript_path),
577
+ "user_text": user_text_meta,
578
+ **(host_meta or {}),
579
+ },
580
+ ) as trace_span:
581
+ # LLM generation
582
+ with langfuse.start_as_current_observation(
583
+ name="Claude Response",
584
+ as_type="generation",
585
+ model=model,
586
+ input={"role": "user", "content": user_text},
587
+ output={"role": "assistant", "content": assistant_text},
588
+ metadata={
589
+ "assistant_text": assistant_text_meta,
590
+ "tool_count": len(tool_calls),
591
+ },
592
+ ):
593
+ pass
594
+
595
+ # Tool observations
596
+ for tc in tool_calls:
597
+ in_obj = tc["input"]
598
+ # truncate tool input if it's a large string payload
599
+ if isinstance(in_obj, str):
600
+ in_obj, in_meta = truncate_text(in_obj)
601
+ else:
602
+ in_meta = None
603
+
604
+ with langfuse.start_as_current_observation(
605
+ name=f"Tool: {tc['name']}",
606
+ as_type="tool",
607
+ input=in_obj,
608
+ metadata={
609
+ "tool_name": tc["name"],
610
+ "tool_id": tc["id"],
611
+ "input_meta": in_meta,
612
+ "output_meta": tc.get("output_meta"),
613
+ },
614
+ ) as tool_obs:
615
+ tool_obs.update(output=tc.get("output"))
616
+
617
+ trace_span.update(output={"role": "assistant", "content": assistant_text})
618
+
619
+
620
+ # ----------------- Main -----------------
621
+ def main() -> int:
622
+ start = time.time()
623
+ debug("Hook started")
624
+
625
+ if os.environ.get("TRACE_TO_LANGFUSE", "").lower() != "true":
626
+ return 0
627
+
628
+ public_key = os.environ.get("CC_LANGFUSE_PUBLIC_KEY") or os.environ.get(
629
+ "LANGFUSE_PUBLIC_KEY"
630
+ )
631
+ secret_key = os.environ.get("CC_LANGFUSE_SECRET_KEY") or os.environ.get(
632
+ "LANGFUSE_SECRET_KEY"
633
+ )
634
+ host = (
635
+ os.environ.get("CC_LANGFUSE_BASE_URL")
636
+ or os.environ.get("LANGFUSE_BASE_URL")
637
+ or "https://cloud.langfuse.com"
638
+ )
639
+
640
+ if not public_key or not secret_key:
641
+ return 0
642
+
643
+ # Set environment for Langfuse tracing (must be set before client init)
644
+ environment = os.environ.get("CC_LANGFUSE_ENVIRONMENT")
645
+ if environment:
646
+ os.environ.setdefault("LANGFUSE_TRACING_ENVIRONMENT", environment)
647
+
648
+ # Build host identifier for metadata
649
+ try:
650
+ import urllib.request
651
+
652
+ public_ip = (
653
+ urllib.request.urlopen("https://api.ipify.org", timeout=2)
654
+ .read()
655
+ .decode()
656
+ .strip()
657
+ )
658
+ except Exception:
659
+ public_ip = "unknown"
660
+ host_meta = {
661
+ "host_ip": public_ip,
662
+ "host_name": socket.gethostname(),
663
+ "host_cwd": os.getcwd(),
664
+ }
665
+
666
+ payload = read_hook_payload()
667
+ session_id, transcript_path = extract_session_and_transcript(payload)
668
+
669
+ if not session_id or not transcript_path:
670
+ # No structured payload; fail open (do not guess)
671
+ debug("Missing session_id or transcript_path from hook payload; exiting.")
672
+ return 0
673
+
674
+ if not transcript_path.exists():
675
+ debug(f"Transcript path does not exist: {transcript_path}")
676
+ return 0
677
+
678
+ try:
679
+ langfuse = Langfuse(
680
+ public_key=public_key,
681
+ secret_key=secret_key,
682
+ host=host,
683
+ environment=environment,
684
+ )
685
+ except Exception:
686
+ return 0
687
+
688
+ try:
689
+ with FileLock(LOCK_FILE):
690
+ state = load_state()
691
+ key = state_key(session_id, str(transcript_path))
692
+ ss = load_session_state(state, key)
693
+
694
+ msgs, ss = read_new_jsonl(transcript_path, ss)
695
+ if not msgs:
696
+ write_session_state(state, key, ss)
697
+ save_state(state)
698
+ return 0
699
+
700
+ turns = build_turns(msgs)
701
+ if not turns:
702
+ write_session_state(state, key, ss)
703
+ save_state(state)
704
+ return 0
705
+
706
+ # emit turns
707
+ emitted = 0
708
+ for t in turns:
709
+ emitted += 1
710
+ turn_num = ss.turn_count + emitted
711
+ try:
712
+ emit_turn(
713
+ langfuse, session_id, turn_num, t, transcript_path, host_meta
714
+ )
715
+ except Exception as e:
716
+ debug(f"emit_turn failed: {e}")
717
+ # continue emitting other turns
718
+
719
+ ss.turn_count += emitted
720
+ write_session_state(state, key, ss)
721
+ save_state(state)
722
+
723
+ try:
724
+ langfuse.flush()
725
+ except Exception:
726
+ pass
727
+
728
+ dur = time.time() - start
729
+ info(f"Processed {emitted} turns in {dur:.2f}s (session={session_id})")
730
+ return 0
731
+
732
+ except Exception as e:
733
+ debug(f"Unexpected failure: {e}")
734
+ return 0
735
+
736
+ finally:
737
+ try:
738
+ langfuse.shutdown()
739
+ except Exception:
740
+ pass
741
+
742
+
743
+ if __name__ == "__main__":
744
+ sys.exit(main())