This repository was archived by the owner on Mar 15, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsmart_auto_tracker.py
More file actions
349 lines (296 loc) · 12.3 KB
/
Copy pathsmart_auto_tracker.py
File metadata and controls
349 lines (296 loc) · 12.3 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
#!/usr/bin/env python3
"""
Smart Automatic Claude Usage Tracker
Detects and tracks ALL Claude usage automatically using multiple detection methods
"""
import subprocess
import time
import requests
import psutil
import os
import sys
from datetime import datetime, timedelta
from pathlib import Path
import re
import threading
import queue
# Ensure output is visible
sys.stdout.reconfigure(line_buffering=True)
class SmartClaudeTracker:
def __init__(self):
self.tracker_url = "http://localhost:5001"
self.current_session = None
self.last_activity = datetime.now()
self.idle_timeout = 180 # 3 minutes
self.check_interval = 2 # Check every 2 seconds
# Detection patterns
self.browser_patterns = {
'claude.ai': 'claude.ai',
'claude-code': 'Claude Code',
'anthropic': 'anthropic.com'
}
# Process patterns for Claude Code
self.process_patterns = [
'claude',
'Claude',
'anthropic'
]
# Network patterns
self.network_domains = [
'claude.ai',
'anthropic.com',
'claude-api'
]
# Activity queue for threaded detection
self.activity_queue = queue.Queue()
self.detection_methods = []
def detect_browser_claude(self):
"""Detect Claude usage in browsers"""
try:
# Check all browsers
browsers = {
'Google Chrome': 'tell application "Google Chrome" to return URL of active tab of front window',
'Safari': 'tell application "Safari" to return URL of front document',
'Arc': 'tell application "Arc" to return URL of active tab of front window',
'Microsoft Edge': 'tell application "Microsoft Edge" to return URL of active tab of front window',
'Firefox': None # Firefox requires different approach
}
# Get active app
active_app_script = '''
tell application "System Events"
return name of first application process whose frontmost is true
end tell
'''
result = subprocess.run(['osascript', '-e', active_app_script],
capture_output=True, text=True, timeout=1)
if result.returncode == 0:
active_app = result.stdout.strip()
# Check if it's a browser
if active_app in browsers and browsers[active_app]:
# Get URL
url_result = subprocess.run(['osascript', '-e', browsers[active_app]],
capture_output=True, text=True, timeout=1)
if url_result.returncode == 0:
url = url_result.stdout.strip()
# Check for Claude patterns
if 'claude.ai' in url:
if '/code' in url:
return 'claude-code'
return 'claude.ai'
elif 'anthropic.com' in url:
return 'api'
except:
pass
return None
def detect_terminal_claude(self):
"""Detect Claude Code in Terminal"""
try:
# Get active app and window title
script = '''
tell application "System Events"
set frontApp to name of first application process whose frontmost is true
if frontApp contains "Terminal" or frontApp contains "iTerm" then
try
tell process frontApp
return name of front window
end tell
end try
end if
end tell
'''
result = subprocess.run(['osascript', '-e', script],
capture_output=True, text=True, timeout=1)
if result.returncode == 0:
window_title = result.stdout.strip()
# Check for Claude Code patterns in terminal
if any(pattern in window_title for pattern in ['claude', 'Claude', 'anthropic']):
return 'claude-code'
# Check if using Claude via CLI
if 'claude' in window_title.lower():
return 'claude-code'
except:
pass
return None
def detect_process_activity(self):
"""Detect Claude-related processes"""
try:
for proc in psutil.process_iter(['pid', 'name', 'cmdline']):
try:
# Check process name
pname = proc.info['name'].lower()
if any(pattern.lower() in pname for pattern in self.process_patterns):
return 'claude-code'
# Check command line arguments
if proc.info['cmdline']:
cmdline = ' '.join(proc.info['cmdline']).lower()
if 'claude' in cmdline or 'anthropic' in cmdline:
return 'claude-code'
except:
continue
except:
pass
return None
def detect_network_activity(self):
"""Detect network connections to Claude services"""
try:
connections = psutil.net_connections()
for conn in connections:
if conn.status == 'ESTABLISHED' and conn.raddr:
# Check if connected to Claude domains
# This would need reverse DNS lookup
# For now, we'll skip this as it's complex
pass
except:
pass
return None
def detect_file_activity(self):
"""Detect recent file changes that suggest Claude usage"""
try:
# Check for recently modified files in common Claude Code locations
home = Path.home()
claude_paths = [
home / '.claude',
home / '.config' / 'claude',
home / 'Documents',
home / 'Desktop'
]
for path in claude_paths:
if path.exists():
# Check for recent modifications (within last 5 seconds)
for file in path.rglob('*'):
if file.is_file():
mtime = datetime.fromtimestamp(file.stat().st_mtime)
if (datetime.now() - mtime).total_seconds() < 5:
# Recent file activity detected
return 'claude-code'
except:
pass
return None
def detect_claude_service(self):
"""Run all detection methods and return detected service"""
# Try each detection method
methods = [
('Browser', self.detect_browser_claude),
('Terminal', self.detect_terminal_claude),
('Process', self.detect_process_activity),
('Files', self.detect_file_activity),
]
for name, method in methods:
result = method()
if result:
return result, name
return None, None
def start_session(self, service_type, detection_method):
"""Start a new tracking session"""
try:
response = requests.post(f"{self.tracker_url}/api/session/start",
json={
'service_type': service_type,
'model': 'claude-3-opus',
'metadata': {
'auto_tracked': True,
'detection_method': detection_method
}
},
timeout=2)
if response.status_code == 200:
data = response.json()
self.current_session = {
'id': data['session_id'],
'service': service_type,
'start_time': datetime.now(),
'detection_method': detection_method
}
print(f"✅ Started {service_type} session (via {detection_method})")
return True
except Exception as e:
print(f"Error starting session: {e}")
return False
def end_session(self):
"""End current session"""
if not self.current_session:
return
try:
duration = (datetime.now() - self.current_session['start_time']).total_seconds() / 60
estimated_messages = max(1, int(duration * 0.5)) # 0.5 messages per minute
response = requests.post(
f"{self.tracker_url}/api/session/end/{self.current_session['id']}",
json={
'messages_sent': estimated_messages,
'messages_received': estimated_messages,
'estimated_tokens': estimated_messages * 500
},
timeout=2)
if response.status_code == 200:
print(f"⏹️ Ended {self.current_session['service']} session "
f"(Duration: {duration:.1f} min)")
self.current_session = None
return True
except Exception as e:
print(f"Error ending session: {e}")
return False
def run(self):
"""Main tracking loop"""
print("🚀 Smart Claude Auto-Tracker Started")
print("📊 Using multiple detection methods:")
print(" • Browser URL monitoring")
print(" • Terminal/process detection")
print(" • File activity monitoring")
print(f"⏱️ Sessions auto-end after {self.idle_timeout}s of inactivity\n")
# Check if tracker server is running
try:
response = requests.get(f"{self.tracker_url}/api/dashboard/overview", timeout=2)
if response.status_code != 200:
raise Exception("Server not responding")
except:
print(f"❌ Cannot connect to tracker at {self.tracker_url}")
print("Please ensure app_v2.py is running")
return
last_service = None
idle_counter = 0
while True:
try:
# Detect Claude usage
service, method = self.detect_claude_service()
if service:
# Claude detected
idle_counter = 0
self.last_activity = datetime.now()
if not self.current_session:
# Start new session
self.start_session(service, method)
last_service = service
elif self.current_session['service'] != service:
# Service changed
print(f"🔄 Switching from {self.current_session['service']} to {service}")
self.end_session()
self.start_session(service, method)
last_service = service
# else: Continue current session
else:
# No Claude detected
if self.current_session:
idle_counter += self.check_interval
if idle_counter >= self.idle_timeout:
print(f"⏱️ No activity for {self.idle_timeout}s")
self.end_session()
idle_counter = 0
time.sleep(self.check_interval)
except KeyboardInterrupt:
print("\n⏹️ Stopping tracker...")
if self.current_session:
self.end_session()
break
except Exception as e:
print(f"Error: {e}")
time.sleep(self.check_interval)
if __name__ == "__main__":
# Check for required packages
try:
import psutil
except ImportError:
print("Installing required package: psutil")
subprocess.run([sys.executable, "-m", "pip", "install", "psutil"])
import psutil
tracker = SmartClaudeTracker()
tracker.run()