-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSessionManager.js
More file actions
2865 lines (2397 loc) · 100 KB
/
Copy pathSessionManager.js
File metadata and controls
2865 lines (2397 loc) · 100 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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const ClaudeStreamProcessor = require('./claude-stream-processor');
const ActivityWatchIntegration = require('./ActivityWatchIntegration');
const ClaudeCodeTokenCounter = require('./ClaudeCodeTokenCounter');
const TelegramMCPIntegration = require('./TelegramMCPIntegration');
/**
* Session Manager - Extracted from StreamTelegramBot
* Handles user session lifecycle, storage, and processor events
*/
class SessionManager {
constructor(formatter, options, bot, activeProcessors, activityIndicator, mainBot) {
this.formatter = formatter;
this.options = options;
this.bot = bot;
this.activeProcessors = activeProcessors;
this.activityIndicator = activityIndicator;
this.mainBot = mainBot; // Reference to main bot instance for safeSendMessage
this.configFilePath = options.configFilePath;
// Telegram MCP integration for file sending
this.telegramMCPIntegration = null;
if (mainBot && mainBot.botInstanceName && mainBot.bot && mainBot.bot.token) {
console.log('[SessionManager] Initializing Telegram MCP integration for bot:', mainBot.botInstanceName);
// We'll initialize this per-session with specific chat ID
}
// Session storage
this.userSessions = new Map(); // userId -> { processor, sessionId, lastTodoMessageId, etc }
this.sessionStorage = new Map(); // userId -> { currentSessionId, sessionHistory: [] }
// Token tracking across session chains
this.cumulativeTokenCache = new Map(); // sessionId -> { totalInputTokens, totalOutputTokens, cacheReadTokens, cacheCreationTokens, transactionCount }
// Message queuing for active sessions
this.messageQueues = new Map(); // userId -> [{ message: string, chatId: string, timestamp: number }]
// Title tracking for auto-pin functionality
this.sessionTitles = new Map(); // userId -> { lastTitle, chatId }
// ActivityWatch integration for time tracking
this.activityWatch = new ActivityWatchIntegration({
enabled: this.mainBot.configManager.getActivityWatchEnabled(),
timeMultiplier: this.mainBot.configManager.getActivityWatchTimeMultiplier()
});
// Claude Code accurate token counter
this.tokenCounter = new ClaudeCodeTokenCounter();
// Initialize ActivityWatch bucket asynchronously (don't block constructor)
this.initializeActivityWatch();
}
/**
* Initialize ActivityWatch integration
*/
async initializeActivityWatch() {
try {
await this.activityWatch.initialize();
console.log('[SessionManager] ActivityWatch integration ready');
} catch (error) {
console.error('[SessionManager] ActivityWatch initialization failed:', error.message);
}
}
/**
* Initialize static token cache for accurate Claude Code token counting
*/
async initializeStaticTokenCache(sessionId) {
try {
console.log(`[SessionManager] Initializing static token cache for session ${sessionId.slice(-8)}`);
await this.tokenCounter.refreshStaticTokenCache(this.options.workingDirectory);
console.log('[SessionManager] Static token cache initialized successfully');
} catch (error) {
console.error('[SessionManager] Static token cache initialization failed:', error.message);
// Continue with fallback values - the tokenCounter handles this gracefully
}
}
/**
* Get accurate token breakdown using Claude Code compatible counting
*/
async getAccurateTokenBreakdown(sessionId) {
try {
// Get sessions directory for this session's JSONL file
const os = require('os');
const path = require('path');
const claudeSessionsDir = path.join(os.homedir(), '.claude', 'sessions');
// Get accurate breakdown from token counter
const breakdown = await this.tokenCounter.getAccurateTokenBreakdown(sessionId, claudeSessionsDir);
return breakdown;
} catch (error) {
console.error('[SessionManager] Error getting accurate token breakdown:', error);
// Fallback to current system
const contextLimit = this.getContextWindowLimit(this.options.model);
return {
grandTotal: 0,
contextLimit,
usagePercentage: '0.0',
freeSpace: contextLimit,
systemPrompt: 0,
systemTools: 0,
mcpTools: 0,
customAgents: 0,
memoryFiles: 0,
conversation: 0,
conversationDetails: { inputTokens: 0, outputTokens: 0, totalTokens: 0 }
};
}
}
/**
* Create new user session with Claude processor
*/
async createUserSession(userId, chatId) {
console.log(`[User ${userId}] Creating new session`);
// Use user's preferred model or default to bot's model
const userModel = this.getUserModel(userId) || this.options.model;
console.log(`[SessionManager] Debug: userModel=${userModel}, getUserModel result=${this.getUserModel(userId)}, options.model=${this.options.model}, workingDir=${this.options.workingDirectory}`);
const processor = new ClaudeStreamProcessor({
model: userModel,
workingDirectory: this.options.workingDirectory
});
// Initialize Telegram MCP integration for file sending
let telegramMCPIntegration = null;
if (this.mainBot && this.mainBot.botInstanceName && this.mainBot.bot && this.mainBot.bot.token) {
try {
telegramMCPIntegration = new TelegramMCPIntegration(
this.mainBot.botInstanceName,
this.mainBot.bot.token,
chatId.toString()
);
// Create MCP config file for this bot instance
const mcpConfigPath = await telegramMCPIntegration.createMCPConfig();
// Pass session-compatible Claude Code arguments to processor
// Note: We use session-compatible args to avoid conflicts with --continue/--resume
const additionalArgs = telegramMCPIntegration.getSessionCompatibleArgs();
processor.setAdditionalArgs(additionalArgs);
console.log(`[User ${userId}] Telegram MCP integration initialized for ${this.mainBot.botInstanceName}`);
console.log(`[User ${userId}] MCP config: ${mcpConfigPath}`);
} catch (error) {
console.error(`[User ${userId}] Failed to initialize Telegram MCP integration:`, error.message);
// Continue without MCP integration
}
}
// Get stored session ID to check if this is a continuation
const storedSessionId = this.getStoredSessionId(userId);
let previousTokenUsage = null;
let sessionTitle = null;
// If we have a stored session, try to get its token usage and title for continuation
if (storedSessionId) {
previousTokenUsage = await this.getSessionTokenUsage(storedSessionId);
// Calculate and cache cumulative tokens from all parent sessions
// This ensures we have the full context usage for accurate status display
await this.getCumulativeTokens(storedSessionId);
// First try to get session title from config (faster), then from JSONL file
sessionTitle = this.getStoredSessionTitle(userId);
if (!sessionTitle) {
sessionTitle = await this.getSessionSummary(storedSessionId);
}
// For resumed sessions, thinking mode is already in memory (userPreferences)
// No need to restore from config - each bot process maintains its own thinking mode state
console.log(`[User ${userId}] Resumed session with current thinking mode: ${this.getUserThinkingMode(userId)}`);
}
const session = {
userId,
chatId,
processor,
telegramMCPIntegration, // Add MCP integration to session
messageCount: 0,
lastTodoMessageId: null,
lastTodos: null,
createdAt: new Date(),
// Status monitoring fields
tokenUsage: previousTokenUsage || {
totalInputTokens: 0,
totalOutputTokens: 0,
totalTokens: 0,
transactionCount: 0,
cacheReadTokens: 0,
cacheCreationTokens: 0
},
lastActivityTime: Date.now(),
isStreamActive: false,
isHealthy: true,
lastHealthCheck: Date.now(),
isContinuation: !!previousTokenUsage,
sessionTitle: sessionTitle,
autoCompactInProgress: false,
// Session duration tracking
sessionStartTime: null,
sessionDuration: null
};
// Setup event handlers for this processor
this.setupProcessorEvents(processor, session);
this.userSessions.set(userId, session);
this.activeProcessors.add(processor);
return session;
}
/**
* Setup event handlers for a Claude processor
*/
setupProcessorEvents(processor, session) {
const { chatId, userId } = session;
// Session initialization
processor.on('session-init', async (data) => {
console.log(`[User ${userId}] Session initialized: ${data.sessionId}`);
// Store session ID for user in memory
this.storeSessionId(userId, data.sessionId);
session.sessionId = data.sessionId;
// IMPORTANT: Save session to config file immediately for persistence across bot restarts
await this.saveCurrentSessionToConfig(userId, data.sessionId);
// Initialize static token cache for accurate token counting (async, don't block)
this.initializeStaticTokenCache(data.sessionId);
// Enhance data with additional information for better session display
const enhancedData = {
...data,
thinkingMode: this.getUserThinkingMode(userId),
isContinuation: session.isContinuation,
sessionTitle: this.getStoredSessionTitle(userId)
};
const formatted = this.formatter.formatSessionInit(enhancedData);
await this.mainBot.safeSendMessage(chatId, formatted);
});
// Assistant text responses
processor.on('assistant-text', async (data) => {
console.log(`[User ${userId}] Assistant text: ${data.text.substring(0, 100)}...`);
// Update activity tracking
this.updateSessionActivity(session);
// Update token usage if present in assistant message
if (data.usage) {
this.updateTokenUsage(session, { usage: data.usage });
await this.checkAutoCompact(session, chatId);
}
// Update session title from latest JSONL content (throttled to avoid excessive file reads)
await this.updateSessionTitle(session, userId);
// Typing indicator continues automatically
const formatted = this.formatter.formatAssistantText(data.text);
await this.mainBot.safeSendMessage(chatId, formatted);
});
// Thinking processes
processor.on('assistant-thinking', async (data) => {
console.log(`[User ${userId}] Claude thinking`);
const formatted = this.formatter.formatThinking(data.thinking, data.signature);
await this.mainBot.safeSendMessage(chatId, formatted);
});
// TodoWrite - with live updating
processor.on('todo-write', async (data) => {
console.log(`[User ${userId}] TodoWrite: ${data.todos.length} todos`);
await this.handleTodoWrite(session, data.todos, data.toolId);
});
// File operations
processor.on('file-edit', async (data) => {
console.log(`[User ${userId}] File edit: ${data.filePath}`);
const formatted = this.formatter.formatFileEdit(data.filePath, data.oldString, data.newString);
await this.mainBot.safeSendMessage(chatId, formatted);
});
processor.on('file-write', async (data) => {
console.log(`[User ${userId}] File write: ${data.filePath}`);
const formatted = this.formatter.formatFileWrite(data.filePath, data.content);
await this.mainBot.safeSendMessage(chatId, formatted);
});
processor.on('file-read', async (data) => {
console.log(`[User ${userId}] File read: ${data.filePath}`);
const formatted = this.formatter.formatFileRead(data.filePath);
await this.mainBot.safeSendMessage(chatId, formatted);
});
// Bash commands
processor.on('bash-command', async (data) => {
console.log(`[User ${userId}] Bash: ${data.command}`);
const formatted = this.formatter.formatBashCommand(data.command, data.description);
await this.mainBot.safeSendMessage(chatId, formatted);
});
// Task spawning
processor.on('task-spawn', async (data) => {
console.log(`[User ${userId}] Task: ${data.description}`);
const formatted = this.formatter.formatTaskSpawn(data.description, data.prompt, data.subagentType);
await this.mainBot.safeSendMessage(chatId, formatted);
});
// MCP tools
processor.on('mcp-tool', async (data) => {
console.log(`[User ${userId}] MCP tool: ${data.toolName}`);
const formatted = this.formatter.formatMCPTool(data.toolName, data.input);
await this.mainBot.safeSendMessage(chatId, formatted);
});
// Tool results - we can enhance tool messages with results
processor.on('tool-result', async (data) => {
// Tool results are automatically integrated - we don't need separate messages
console.log(`[User ${userId}] Tool result for: ${data.toolUseId}`);
});
// Execution completion - listen for execution-result which has usage data
processor.on('execution-result', async (data) => {
console.log(`[User ${userId}] Execution complete: ${data.success}`);
// Calculate session duration if timing was started
if (session.sessionStartTime) {
session.sessionDuration = Date.now() - session.sessionStartTime;
console.log(`[User ${userId}] Session duration: ${session.sessionDuration}ms`);
}
// Update activity and token tracking
this.updateSessionActivity(session);
this.updateTokenUsage(session, data);
// Check for auto-compact after token update
await this.checkAutoCompact(session, chatId);
// Stop typing indicator when Claude finishes
await this.activityIndicator.stop(chatId);
// Clean up temp files if they exist
const ImageHandler = require('./ImageHandler');
const FileHandler = require('./FileHandler');
ImageHandler.cleanupTempFile(session, userId);
FileHandler.cleanupTempFiles(session, userId);
// Add duration to the data for formatting
const dataWithDuration = {
...data,
sessionDuration: session.sessionDuration
};
// Record session in ActivityWatch for time tracking BEFORE sending response
if (session.sessionDuration && session.sessionId) {
// Get last user message for context (optional)
const lastMessage = session.lastUserMessage || 'No message';
// Get current project name
const path = require('path');
const projectName = path.basename(this.options.workingDirectory);
try {
await this.activityWatch.recordSession({
sessionId: session.sessionId,
userId: userId,
duration: session.sessionDuration, // in milliseconds
message: lastMessage,
projectName: projectName,
tokens: data.usage ? (data.usage.input_tokens || 0) + (data.usage.output_tokens || 0) : null,
cost: data.cost || null,
model: this.getUserModel(userId) || this.options.model,
botInstance: this.options.botInstanceName || 'unknown'
});
} catch (error) {
console.error(`[User ${userId}] ActivityWatch recording failed:`, error.message);
}
}
const formatted = this.formatter.formatExecutionResult(dataWithDuration, session.sessionId);
await this.mainBot.safeSendMessage(chatId, formatted);
// Check for title changes after Claude completes processing
const sessionId = session.sessionId || session.processor.getCurrentSessionId();
if (sessionId) {
const currentTitle = await this.getSessionSummary(sessionId);
if (currentTitle) {
await this.checkAndHandleTitleChange(userId, chatId, currentTitle);
}
}
// Process any queued messages after session completion
await this.processMessageQueue(userId);
});
// Keep the legacy 'complete' event for backward compatibility (but without usage updates)
processor.on('complete', async (data) => {
console.log(`[User ${userId}] Process complete (legacy): ${data.success}`);
// Only handle basic completion without token tracking since this event doesn't have usage data
this.updateSessionActivity(session);
await this.activityIndicator.stop(chatId);
// Clean up temp files if they exist
const ImageHandler = require('./ImageHandler');
const FileHandler = require('./FileHandler');
ImageHandler.cleanupTempFile(session, userId);
FileHandler.cleanupTempFiles(session, userId);
// Check for title changes after Claude completes processing
const sessionId = session.sessionId || session.processor.getCurrentSessionId();
if (sessionId) {
const currentTitle = await this.getSessionSummary(sessionId);
if (currentTitle) {
await this.checkAndHandleTitleChange(userId, chatId, currentTitle);
}
}
});
// Prompt too long errors - trigger auto-compact
processor.on('prompt-too-long', async (data) => {
console.log(`[User ${userId}] Prompt too long detected - triggering auto-compact`);
await this.handleClaudeCodeError(data.sessionId, data);
});
// Errors
processor.on('error', async (error) => {
console.error(`[User ${userId}] Claude error:`, error);
// Stop typing indicator on error
await this.activityIndicator.stop(chatId);
// Clean up temp files if they exist
const ImageHandler = require('./ImageHandler');
const FileHandler = require('./FileHandler');
ImageHandler.cleanupTempFile(session, userId);
FileHandler.cleanupTempFiles(session, userId);
await this.sendError(chatId, error);
});
}
/**
* Store session ID for user
*/
storeSessionId(userId, sessionId) {
if (!this.sessionStorage.has(userId)) {
this.sessionStorage.set(userId, {
currentSessionId: null,
sessionHistory: [],
sessionAccessTimes: new Map() // sessionId -> timestamp
});
}
const storage = this.sessionStorage.get(userId);
storage.currentSessionId = sessionId;
// Track access time
if (!storage.sessionAccessTimes) {
storage.sessionAccessTimes = new Map();
}
storage.sessionAccessTimes.set(sessionId, Date.now());
// Add to history and update access time
this.addSessionToHistory(userId, sessionId);
// Save to config file for persistence across bot restarts
this.saveCurrentSessionToConfig(userId, sessionId);
console.log(`[User ${userId}] Stored session ID: ${sessionId}`);
}
/**
* Clear current session ID
*/
clearCurrentSessionId(userId) {
if (this.sessionStorage.has(userId)) {
const storage = this.sessionStorage.get(userId);
storage.currentSessionId = null;
}
}
/**
* Clear session from both memory and config file (for new sessions)
*/
async clearStoredSession(userId) {
// Clear in-memory session
this.clearCurrentSessionId(userId);
// Clear session from config file
if (!this.configFilePath) {
console.warn('[Session] No config file path provided, cannot clear stored session');
return;
}
try {
const fs = require('fs');
const configData = fs.readFileSync(this.configFilePath, 'utf8');
const config = JSON.parse(configData);
const currentProject = this.options.workingDirectory;
// Remove session from project-specific config
if (config.projectSessions && config.projectSessions[currentProject]) {
const projectSession = config.projectSessions[currentProject];
if (projectSession.userId === userId.toString()) {
delete config.projectSessions[currentProject];
console.log(`[Session] Cleared stored session for project ${currentProject}`);
}
}
// Write back to file
fs.writeFileSync(this.configFilePath, JSON.stringify(config, null, 2));
} catch (error) {
console.error('[Session] Error clearing stored session from config:', error.message);
}
}
/**
* Add session to history
*/
addSessionToHistory(userId, sessionId) {
if (!this.sessionStorage.has(userId)) {
this.sessionStorage.set(userId, {
currentSessionId: null,
sessionHistory: [],
sessionAccessTimes: new Map()
});
}
const storage = this.sessionStorage.get(userId);
// Initialize sessionAccessTimes if not present
if (!storage.sessionAccessTimes) {
storage.sessionAccessTimes = new Map();
}
if (!storage.sessionHistory.includes(sessionId)) {
storage.sessionHistory.push(sessionId);
// Keep only last 50 sessions
if (storage.sessionHistory.length > 50) {
storage.sessionHistory = storage.sessionHistory.slice(-50);
}
console.log(`[User ${userId}] Added session to history: ${sessionId}`);
}
}
/**
* Get session history for user
*/
getSessionHistory(userId) {
const storage = this.sessionStorage.get(userId);
if (!storage) {
return [];
}
// Sort by access time (most recent first)
return storage.sessionHistory
.filter(sessionId => storage.sessionAccessTimes && storage.sessionAccessTimes.has(sessionId))
.sort((a, b) => {
const timeA = storage.sessionAccessTimes.get(a) || 0;
const timeB = storage.sessionAccessTimes.get(b) || 0;
return timeB - timeA; // Descending order (newest first)
})
.slice(0, 10); // Return top 10 sessions
}
/**
* Save current session to config file (project-specific)
*/
async saveCurrentSessionToConfig(userId, sessionId) {
if (!this.configFilePath) {
console.warn('[Session] No config file path provided, cannot save session');
return;
}
try {
// Read current config
const fs = require('fs');
const configData = fs.readFileSync(this.configFilePath, 'utf8');
const config = JSON.parse(configData);
// Initialize projectSessions if it doesn't exist
if (!config.projectSessions) {
config.projectSessions = {};
}
// Save session info for current project
const currentProject = this.options.workingDirectory;
config.projectSessions[currentProject] = {
userId: userId.toString(),
sessionId: sessionId,
timestamp: new Date().toISOString(),
model: this.options.model
};
// Also update currentProject
config.currentProject = currentProject;
// Write back to file
fs.writeFileSync(this.configFilePath, JSON.stringify(config, null, 2));
console.log(`[Session] Saved session ${sessionId.slice(-8)} for project ${currentProject}`);
} catch (error) {
console.error('[Session] Error saving session to config:', error.message);
}
}
/**
* Handle TodoWrite with live updating
*/
async handleTodoWrite(session, todos, _toolId) {
const { chatId, lastTodoMessageId, lastTodos } = session;
// Check if todos changed
if (lastTodos && !this.formatter.todosChanged(lastTodos, todos)) {
console.log(`[User ${session.userId}] Todos unchanged, skipping update`);
return;
}
const formatted = this.formatter.formatTodoWrite(todos);
try {
if (lastTodoMessageId) {
// Try to edit existing message using safeEditMessage
try {
await this.mainBot.safeEditMessage(chatId, lastTodoMessageId, formatted);
console.log(`[User ${session.userId}] Updated todo message ${lastTodoMessageId}`);
} catch {
// If edit fails (message too old, etc.), send new message
console.log(`[User ${session.userId}] Edit failed, sending new todo message`);
await this.mainBot.safeSendMessage(chatId, formatted);
// Note: We can't get message_id from safeSendMessage, but that's okay for now
}
} else {
// Send new message using safeSendMessage
await this.mainBot.safeSendMessage(chatId, formatted);
console.log(`[User ${session.userId}] Created new todo message`);
}
// Update stored todos
session.lastTodos = todos;
} catch (error) {
console.error(`[User ${session.userId}] Error updating todos:`, error);
}
}
/**
* Send error message
*/
async sendError(chatId, error) {
const formatted = this.formatter.formatError(error);
await this.mainBot.safeSendMessage(chatId, formatted, {
forceNotification: true // Always notify for internal errors
});
}
/**
* Get user's preferred model for current project
*/
getUserModel(userId) {
if (!this.configFilePath) {
return null;
}
try {
const fs = require('fs');
const configData = fs.readFileSync(this.configFilePath, 'utf8');
const config = JSON.parse(configData);
const currentProject = this.options.workingDirectory;
// Get model preference from project-specific session
if (config.projectSessions && config.projectSessions[currentProject]) {
const projectSession = config.projectSessions[currentProject];
if (projectSession.userId === userId.toString() && projectSession.model) {
return projectSession.model;
}
}
return null;
} catch (error) {
console.error('[SessionManager] Error getting user model:', error.message);
return null;
}
}
/**
* Get user session
*/
getUserSession(userId) {
return this.userSessions.get(userId);
}
/**
* Start timing for session duration
*/
startSessionTiming(userId, userMessage = null) {
const session = this.getUserSession(userId);
if (session) {
session.sessionStartTime = Date.now();
session.lastUserMessage = userMessage; // Store for ActivityWatch
console.log(`[User ${userId}] Session timing started`);
}
}
/**
* Delete user session
*/
deleteUserSession(userId) {
const session = this.userSessions.get(userId);
if (session) {
// Add to history before deleting
if (session.sessionId) {
this.addSessionToHistory(userId, session.sessionId);
}
// Cleanup Telegram MCP integration
if (session.telegramMCPIntegration) {
session.telegramMCPIntegration.cleanupMCPConfig().catch(error => {
console.error(`[User ${userId}] Error cleaning up MCP config:`, error.message);
});
}
// Remove from active processors
if (session.processor) {
this.activeProcessors.delete(session.processor);
}
this.userSessions.delete(userId);
}
}
/**
* Cleanup all sessions
*/
cleanup() {
// Add all active sessions to history
for (const [userId, session] of this.userSessions) {
if (session.sessionId) {
this.addSessionToHistory(userId, session.sessionId);
}
}
this.userSessions.clear();
// Note: We keep sessionStorage for session persistence
console.log(`💾 Preserved session data for ${this.sessionStorage.size} users`);
}
/**
* Cancel user session
*/
async cancelUserSession(chatId) {
const userId = this.mainBot.getUserIdFromChat(chatId);
const session = this.getUserSession(userId);
if (session && session.processor) {
// Record cancelled session in ActivityWatch before stopping
if (session.sessionStartTime && session.sessionId) {
// Calculate session duration up to cancellation
const sessionDuration = Date.now() - session.sessionStartTime;
// Get last user message for context
const lastMessage = session.lastUserMessage || 'Session cancelled by user';
// Get current project name
const path = require('path');
const projectName = path.basename(this.options.workingDirectory);
try {
await this.activityWatch.recordSession({
sessionId: session.sessionId,
userId: userId,
duration: sessionDuration, // in milliseconds
message: lastMessage + ' [CANCELLED]',
projectName: projectName,
tokens: null, // No token count available for cancelled sessions
cost: null,
model: this.getUserModel(userId) || this.options.model,
botInstance: this.options.botInstanceName || 'unknown'
});
console.log(`[User ${userId}] Cancelled session recorded in ActivityWatch: ${(sessionDuration/1000).toFixed(1)}s`);
} catch (error) {
console.error(`[User ${userId}] Failed to record cancelled session in ActivityWatch:`, error.message);
}
}
session.processor.cancel();
await this.mainBot.safeSendMessage(chatId, '❌ **Session cancelled**');
// Process any queued messages after cancellation
await this.processMessageQueue(userId);
} else {
await this.mainBot.safeSendMessage(chatId, '⚠️ **No active session to cancel**');
}
}
/**
* Queue a message for processing after current session ends
*/
queueMessage(userId, chatId, message) {
if (!this.messageQueues.has(userId)) {
this.messageQueues.set(userId, []);
}
const queue = this.messageQueues.get(userId);
queue.push({
message: message,
chatId: chatId,
timestamp: Date.now()
});
console.log(`[User ${userId}] Message queued: "${message.substring(0, 50)}..."`);
console.log(`[User ${userId}] Queue length: ${queue.length}`);
}
/**
* Process all queued messages for a user
*/
async processMessageQueue(userId) {
const queue = this.messageQueues.get(userId);
if (!queue || queue.length === 0) {
return;
}
console.log(`[User ${userId}] Processing message queue with ${queue.length} messages`);
// Process the first (oldest) message in the queue
const queuedMessage = queue.shift();
// If queue is now empty, remove it
if (queue.length === 0) {
this.messageQueues.delete(userId);
}
console.log(`[User ${userId}] Processing queued message: "${queuedMessage.message.substring(0, 50)}..."`);
// Send the queued message to the bot's message processor
// This will trigger a new Claude Code session
try {
await this.mainBot.processUserMessage({
chat: { id: queuedMessage.chatId },
from: { id: userId },
text: queuedMessage.message
});
} catch (error) {
console.error(`[User ${userId}] Error processing queued message:`, error);
await this.mainBot.safeSendMessage(queuedMessage.chatId,
'❌ **Error processing queued message**\n\n' +
`Message: "${queuedMessage.message.substring(0, 100)}..."`
);
}
}
/**
* Show detailed context breakdown similar to Claude Code /context
*/
async showContextBreakdown(chatId) {
const userId = this.mainBot.getUserIdFromChat(chatId);
const session = this.getUserSession(userId);
let storedSessionId = this.getStoredSessionId(userId);
// If no stored session from config file, check sessionStorage
if (!storedSessionId) {
const sessionStorage = this.sessionStorage.get(userId);
if (sessionStorage && sessionStorage.currentSessionId) {
storedSessionId = sessionStorage.currentSessionId;
}
}
const sessionId = session?.sessionId || storedSessionId;
if (!sessionId) {
await this.mainBot.safeSendMessage(chatId,
'❌ **No Active Session**\n\n' +
'No session found. Start a new session with /new to see context breakdown.'
);
return;
}
try {
// Get accurate token breakdown
const breakdown = await this.getAccurateTokenBreakdown(sessionId);
// Format output similar to Claude Code /context
let text = `**Context Usage**\n`;
text += `**${this.options.model}** • **${Math.round(breakdown.grandTotal/1000)}k/${Math.round(breakdown.contextLimit/1000)}k tokens (${breakdown.usagePercentage}%)**\n\n`;
// Component breakdown
text += `⛁ **System prompt:** ${(breakdown.systemPrompt/1000).toFixed(1)}k tokens (${(breakdown.systemPrompt/breakdown.contextLimit*100).toFixed(1)}%)\n`;
text += `⛁ **System tools:** ${(breakdown.systemTools/1000).toFixed(1)}k tokens (${(breakdown.systemTools/breakdown.contextLimit*100).toFixed(1)}%)\n`;
text += `⛁ **MCP tools:** ${(breakdown.mcpTools/1000).toFixed(1)}k tokens (${(breakdown.mcpTools/breakdown.contextLimit*100).toFixed(1)}%)\n`;
text += `⛁ **Custom agents:** ${(breakdown.customAgents/1000).toFixed(1)}k tokens (${(breakdown.customAgents/breakdown.contextLimit*100).toFixed(1)}%)\n`;
text += `⛁ **Memory files:** ${(breakdown.memoryFiles/1000).toFixed(1)}k tokens (${(breakdown.memoryFiles/breakdown.contextLimit*100).toFixed(1)}%)\n`;
if (breakdown.conversation > 0) {
text += `⛁ **Conversation:** ${(breakdown.conversation/1000).toFixed(1)}k tokens (${(breakdown.conversation/breakdown.contextLimit*100).toFixed(1)}%)\n`;
text += ` ↳ ${breakdown.conversationDetails.inputTokens} input, ${breakdown.conversationDetails.outputTokens} output\n`;
}
text += `⛶ **Free space:** ${(breakdown.freeSpace/1000).toFixed(1)}k (${(breakdown.freeSpace/breakdown.contextLimit*100).toFixed(1)}%)\n\n`;
if (breakdown.breakdown && breakdown.breakdown.mcpTools && breakdown.breakdown.mcpTools.length > 0) {
text += `**MCP Tools:**\n`;
for (const tool of breakdown.breakdown.mcpTools.slice(0, 5)) { // Show first 5
text += `└ ${tool.name}: ${tool.tokens} tokens\n`;
}
if (breakdown.breakdown.mcpTools.length > 5) {
text += `└ ... and ${breakdown.breakdown.mcpTools.length - 5} more\n`;
}
text += '\n';
}
if (breakdown.breakdown && breakdown.breakdown.customAgents && breakdown.breakdown.customAgents.length > 0) {
text += `**Custom Agents:**\n`;
for (const agent of breakdown.breakdown.customAgents.slice(0, 5)) { // Show first 5
text += `└ ${agent.name}: ${agent.tokens} tokens\n`;
}
if (breakdown.breakdown.customAgents.length > 5) {
text += `└ ... and ${breakdown.breakdown.customAgents.length - 5} more\n`;
}
}
await this.mainBot.safeSendMessage(chatId, text);
} catch (error) {
console.error('[SessionManager] Error showing context breakdown:', error);
await this.mainBot.safeSendMessage(chatId,
'❌ **Context Breakdown Error**\n\n' +
'Unable to calculate accurate context breakdown. The token counting system may need initialization.'
);
}
}
/**
* Show session status
*/
async showSessionStatus(chatId) {
const userId = this.mainBot.getUserIdFromChat(chatId);
const session = this.getUserSession(userId);
let storedSessionId = this.getStoredSessionId(userId);
// If no stored session from config file, check sessionStorage
if (!storedSessionId) {
const sessionStorage = this.sessionStorage.get(userId);
if (sessionStorage && sessionStorage.currentSessionId) {
storedSessionId = sessionStorage.currentSessionId;
}
}
const sessionHistory = this.getSessionHistory(userId);
// Check if we have any session info (active or stored)
if (!session && !storedSessionId) {
await this.mainBot.safeSendMessage(chatId, '📋 **No active session**\n\nSend a message to start!',
{});
return;
}
let text = '📊 **Session Status**\n\n';
// Get session summary/title for better identification
let sessionSummary = null;
const targetSessionId = session ? (session.sessionId || session.processor.getCurrentSessionId()) : storedSessionId;
if (targetSessionId) {
sessionSummary = await this.getSessionSummary(targetSessionId);
}
// Add session summary at the top if available
if (sessionSummary) {
text += `💡 **Current Work:** ${sessionSummary}\n\n`;
// Check if title has changed and handle auto-pin
await this.checkAndHandleTitleChange(userId, chatId, sessionSummary);
}
if (session) {
// Active session exists
const isActive = session.processor.isActive();
const sessionId = session.sessionId || session.processor.getCurrentSessionId();
const messageCount = session.messageCount;
const uptime = Math.round((Date.now() - session.createdAt.getTime()) / 1000);
// Get health status
const healthStatus = this.checkSessionHealth(session);