telegram-claude-mcp 1.6.1 → 2.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ARCHITECTURE.md +234 -0
- package/README.md +122 -0
- package/bin/daemon-ctl.js +207 -0
- package/bin/daemon.js +20 -0
- package/bin/proxy.js +22 -0
- package/hooks/stop-hook.sh +2 -0
- package/hooks-v2/notify-hook.sh +32 -0
- package/hooks-v2/permission-hook.sh +43 -0
- package/hooks-v2/stop-hook.sh +47 -0
- package/package.json +16 -5
- package/src/daemon/index.ts +415 -0
- package/src/daemon/progress-display.ts +184 -0
- package/src/daemon/progress-tracker.ts +365 -0
- package/src/daemon/session-manager.ts +173 -0
- package/src/daemon/telegram-multi.ts +611 -0
- package/src/proxy/index.ts +429 -0
- package/src/shared/protocol.ts +146 -0
- package/src/telegram.ts +69 -69
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Progress Display Utilities
|
|
3
|
+
*
|
|
4
|
+
* Visual rendering for progress tracking in Telegram messages.
|
|
5
|
+
* Inspired by DnD-Books telegram-bot ProgressIndicator.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export enum ProgressStage {
|
|
9
|
+
IDLE = 'idle',
|
|
10
|
+
THINKING = 'thinking',
|
|
11
|
+
TOOL_QUEUED = 'queued',
|
|
12
|
+
TOOL_RUNNING = 'running',
|
|
13
|
+
TOOL_COMPLETE = 'complete',
|
|
14
|
+
WAITING_USER = 'waiting',
|
|
15
|
+
FINISHED = 'finished',
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
interface StageDisplay {
|
|
19
|
+
emoji: string;
|
|
20
|
+
label: string;
|
|
21
|
+
progress: number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export const stageDisplay: Record<ProgressStage, StageDisplay> = {
|
|
25
|
+
[ProgressStage.IDLE]: { emoji: '💤', label: 'Idle', progress: 0 },
|
|
26
|
+
[ProgressStage.THINKING]: { emoji: '🧠', label: 'Thinking', progress: 10 },
|
|
27
|
+
[ProgressStage.TOOL_QUEUED]: { emoji: '📋', label: 'Tool queued', progress: 20 },
|
|
28
|
+
[ProgressStage.TOOL_RUNNING]: { emoji: '🔧', label: 'Executing', progress: 50 },
|
|
29
|
+
[ProgressStage.TOOL_COMPLETE]: { emoji: '✅', label: 'Tool done', progress: 80 },
|
|
30
|
+
[ProgressStage.WAITING_USER]: { emoji: '💬', label: 'Waiting for you', progress: 90 },
|
|
31
|
+
[ProgressStage.FINISHED]: { emoji: '🏁', label: 'Finished', progress: 100 },
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Build a visual progress bar using block characters.
|
|
36
|
+
*/
|
|
37
|
+
export function buildProgressBar(percent: number): string {
|
|
38
|
+
const total = 10;
|
|
39
|
+
const filled = Math.floor(percent / 10);
|
|
40
|
+
const empty = total - filled;
|
|
41
|
+
|
|
42
|
+
const filledChar = '▓';
|
|
43
|
+
const emptyChar = '░';
|
|
44
|
+
|
|
45
|
+
return `[${filledChar.repeat(filled)}${emptyChar.repeat(empty)}] ${percent}%`;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Format tool name for display.
|
|
50
|
+
*/
|
|
51
|
+
export function formatToolName(toolName: string): string {
|
|
52
|
+
// Shorten common tool names
|
|
53
|
+
const shortNames: Record<string, string> = {
|
|
54
|
+
'Read': 'Read',
|
|
55
|
+
'Write': 'Write',
|
|
56
|
+
'Edit': 'Edit',
|
|
57
|
+
'Bash': 'Bash',
|
|
58
|
+
'Glob': 'Glob',
|
|
59
|
+
'Grep': 'Grep',
|
|
60
|
+
'Task': 'Task',
|
|
61
|
+
'WebFetch': 'Web',
|
|
62
|
+
'WebSearch': 'Search',
|
|
63
|
+
'TodoWrite': 'Todo',
|
|
64
|
+
'AskUserQuestion': 'Ask',
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
return shortNames[toolName] || toolName;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Format elapsed time for display.
|
|
72
|
+
*/
|
|
73
|
+
export function formatElapsedTime(startTime: number): string {
|
|
74
|
+
const elapsed = Math.floor((Date.now() - startTime) / 1000);
|
|
75
|
+
|
|
76
|
+
if (elapsed < 60) {
|
|
77
|
+
return `${elapsed}s`;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const minutes = Math.floor(elapsed / 60);
|
|
81
|
+
const seconds = elapsed % 60;
|
|
82
|
+
return `${minutes}m ${seconds}s`;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Build tool statistics summary.
|
|
87
|
+
*/
|
|
88
|
+
export function buildToolStats(toolCounts: Map<string, number>): string {
|
|
89
|
+
if (toolCounts.size === 0) return '';
|
|
90
|
+
|
|
91
|
+
const entries = Array.from(toolCounts.entries())
|
|
92
|
+
.sort((a, b) => b[1] - a[1])
|
|
93
|
+
.slice(0, 5) // Top 5 tools
|
|
94
|
+
.map(([tool, count]) => `${formatToolName(tool)} (${count})`)
|
|
95
|
+
.join(', ');
|
|
96
|
+
|
|
97
|
+
return entries;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export interface ProgressMessageOptions {
|
|
101
|
+
sessionName: string;
|
|
102
|
+
stage: ProgressStage;
|
|
103
|
+
currentTool: string | null;
|
|
104
|
+
toolStack: string[];
|
|
105
|
+
startTime: number;
|
|
106
|
+
toolsExecuted: number;
|
|
107
|
+
toolCounts: Map<string, number>;
|
|
108
|
+
showDetails?: boolean;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Build the complete progress message text.
|
|
113
|
+
*/
|
|
114
|
+
export function buildProgressMessage(options: ProgressMessageOptions): string {
|
|
115
|
+
const {
|
|
116
|
+
sessionName,
|
|
117
|
+
stage,
|
|
118
|
+
currentTool,
|
|
119
|
+
toolStack,
|
|
120
|
+
startTime,
|
|
121
|
+
toolsExecuted,
|
|
122
|
+
toolCounts,
|
|
123
|
+
showDetails = true,
|
|
124
|
+
} = options;
|
|
125
|
+
|
|
126
|
+
const display = stageDisplay[stage];
|
|
127
|
+
const elapsed = formatElapsedTime(startTime);
|
|
128
|
+
|
|
129
|
+
let text = `[${sessionName}] Working...\n\n`;
|
|
130
|
+
|
|
131
|
+
// Current stage with emoji
|
|
132
|
+
text += `${display.emoji} *${display.label}*`;
|
|
133
|
+
|
|
134
|
+
// Current tool (if any)
|
|
135
|
+
if (currentTool) {
|
|
136
|
+
const toolDisplay = toolStack.length > 1
|
|
137
|
+
? toolStack.map(formatToolName).join(' > ')
|
|
138
|
+
: formatToolName(currentTool);
|
|
139
|
+
text += `: \`${toolDisplay}\``;
|
|
140
|
+
}
|
|
141
|
+
text += '\n\n';
|
|
142
|
+
|
|
143
|
+
// Progress bar
|
|
144
|
+
text += buildProgressBar(display.progress) + '\n\n';
|
|
145
|
+
|
|
146
|
+
// Stats line
|
|
147
|
+
text += `⏱ ${elapsed}`;
|
|
148
|
+
if (toolsExecuted > 0) {
|
|
149
|
+
text += ` | Tools: ${toolsExecuted}`;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// Detailed tool breakdown (for finished state)
|
|
153
|
+
if (showDetails && stage === ProgressStage.FINISHED && toolCounts.size > 0) {
|
|
154
|
+
text += '\n\n---\n';
|
|
155
|
+
text += `Tools used: ${buildToolStats(toolCounts)}`;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
return text;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Build a completion message.
|
|
163
|
+
*/
|
|
164
|
+
export function buildCompletionMessage(options: {
|
|
165
|
+
sessionName: string;
|
|
166
|
+
startTime: number;
|
|
167
|
+
toolsExecuted: number;
|
|
168
|
+
toolCounts: Map<string, number>;
|
|
169
|
+
}): string {
|
|
170
|
+
const { sessionName, startTime, toolsExecuted, toolCounts } = options;
|
|
171
|
+
const elapsed = formatElapsedTime(startTime);
|
|
172
|
+
|
|
173
|
+
let text = `[${sessionName}] Task Complete\n\n`;
|
|
174
|
+
text += `🏁 *Finished*\n\n`;
|
|
175
|
+
text += buildProgressBar(100) + '\n\n';
|
|
176
|
+
text += `⏱ ${elapsed} | Tools: ${toolsExecuted}`;
|
|
177
|
+
|
|
178
|
+
if (toolCounts.size > 0) {
|
|
179
|
+
text += '\n\n---\n';
|
|
180
|
+
text += `Tools used: ${buildToolStats(toolCounts)}`;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
return text;
|
|
184
|
+
}
|
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Progress Tracker
|
|
3
|
+
*
|
|
4
|
+
* Manages per-session progress state and updates Telegram messages
|
|
5
|
+
* in-place using editMessageText.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import TelegramBot from 'node-telegram-bot-api';
|
|
9
|
+
import type { SessionManager } from './session-manager.js';
|
|
10
|
+
import {
|
|
11
|
+
ProgressStage,
|
|
12
|
+
buildProgressMessage,
|
|
13
|
+
buildCompletionMessage,
|
|
14
|
+
} from './progress-display.js';
|
|
15
|
+
|
|
16
|
+
export interface SessionProgress {
|
|
17
|
+
sessionId: string;
|
|
18
|
+
sessionName: string;
|
|
19
|
+
|
|
20
|
+
// Message tracking
|
|
21
|
+
progressMessageId: number | null;
|
|
22
|
+
lastUpdateTime: number;
|
|
23
|
+
|
|
24
|
+
// Progress state
|
|
25
|
+
stage: ProgressStage;
|
|
26
|
+
currentTool: string | null;
|
|
27
|
+
toolStack: string[];
|
|
28
|
+
|
|
29
|
+
// Statistics
|
|
30
|
+
startTime: number;
|
|
31
|
+
toolsExecuted: number;
|
|
32
|
+
toolCounts: Map<string, number>;
|
|
33
|
+
|
|
34
|
+
// Settings
|
|
35
|
+
isActive: boolean;
|
|
36
|
+
showProgress: boolean;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface ProgressEvent {
|
|
40
|
+
type: 'pre_tool' | 'post_tool' | 'notification' | 'stop' | 'start';
|
|
41
|
+
session_name: string;
|
|
42
|
+
timestamp: string;
|
|
43
|
+
tool_name?: string;
|
|
44
|
+
tool_input?: Record<string, unknown>;
|
|
45
|
+
success?: boolean;
|
|
46
|
+
error?: string;
|
|
47
|
+
transcript_path?: string;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export class ProgressTracker {
|
|
51
|
+
private sessions: Map<string, SessionProgress> = new Map();
|
|
52
|
+
private bot: TelegramBot;
|
|
53
|
+
private chatId: number;
|
|
54
|
+
private sessionManager: SessionManager;
|
|
55
|
+
|
|
56
|
+
// Rate limiting
|
|
57
|
+
private lastUpdate: Map<string, number> = new Map();
|
|
58
|
+
private pendingUpdates: Map<string, NodeJS.Timeout> = new Map();
|
|
59
|
+
private readonly MIN_UPDATE_INTERVAL = 1000; // 1 second minimum between updates
|
|
60
|
+
|
|
61
|
+
constructor(bot: TelegramBot, chatId: number, sessionManager: SessionManager) {
|
|
62
|
+
this.bot = bot;
|
|
63
|
+
this.chatId = chatId;
|
|
64
|
+
this.sessionManager = sessionManager;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Get or create progress state for a session.
|
|
69
|
+
*/
|
|
70
|
+
private getOrCreateProgress(sessionName: string): SessionProgress {
|
|
71
|
+
let progress = this.sessions.get(sessionName);
|
|
72
|
+
|
|
73
|
+
if (!progress) {
|
|
74
|
+
const session = this.sessionManager.getByName(sessionName);
|
|
75
|
+
progress = {
|
|
76
|
+
sessionId: session?.sessionId || sessionName,
|
|
77
|
+
sessionName,
|
|
78
|
+
progressMessageId: null,
|
|
79
|
+
lastUpdateTime: 0,
|
|
80
|
+
stage: ProgressStage.IDLE,
|
|
81
|
+
currentTool: null,
|
|
82
|
+
toolStack: [],
|
|
83
|
+
startTime: Date.now(),
|
|
84
|
+
toolsExecuted: 0,
|
|
85
|
+
toolCounts: new Map(),
|
|
86
|
+
isActive: true,
|
|
87
|
+
showProgress: true,
|
|
88
|
+
};
|
|
89
|
+
this.sessions.set(sessionName, progress);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
return progress;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Handle session start event.
|
|
97
|
+
*/
|
|
98
|
+
async handleSessionStart(sessionName: string): Promise<void> {
|
|
99
|
+
const progress = this.getOrCreateProgress(sessionName);
|
|
100
|
+
progress.startTime = Date.now();
|
|
101
|
+
progress.stage = ProgressStage.THINKING;
|
|
102
|
+
progress.isActive = true;
|
|
103
|
+
progress.toolsExecuted = 0;
|
|
104
|
+
progress.toolCounts.clear();
|
|
105
|
+
progress.toolStack = [];
|
|
106
|
+
progress.currentTool = null;
|
|
107
|
+
|
|
108
|
+
await this.sendOrUpdateProgressMessage(progress);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Handle PreToolUse hook event.
|
|
113
|
+
*/
|
|
114
|
+
async handlePreTool(sessionName: string, toolName: string, toolInput?: Record<string, unknown>): Promise<void> {
|
|
115
|
+
const progress = this.getOrCreateProgress(sessionName);
|
|
116
|
+
|
|
117
|
+
// Reset start time if this is the first tool
|
|
118
|
+
if (progress.stage === ProgressStage.IDLE) {
|
|
119
|
+
progress.startTime = Date.now();
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Push tool onto stack (for nested tool calls)
|
|
123
|
+
progress.toolStack.push(toolName);
|
|
124
|
+
progress.currentTool = toolName;
|
|
125
|
+
progress.stage = ProgressStage.TOOL_RUNNING;
|
|
126
|
+
progress.isActive = true;
|
|
127
|
+
|
|
128
|
+
await this.sendOrUpdateProgressMessage(progress);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Handle PostToolUse hook event.
|
|
133
|
+
*/
|
|
134
|
+
async handlePostTool(sessionName: string, toolName: string, success: boolean = true): Promise<void> {
|
|
135
|
+
const progress = this.getOrCreateProgress(sessionName);
|
|
136
|
+
|
|
137
|
+
// Pop tool from stack
|
|
138
|
+
const poppedTool = progress.toolStack.pop();
|
|
139
|
+
|
|
140
|
+
// Update statistics
|
|
141
|
+
progress.toolsExecuted++;
|
|
142
|
+
const currentCount = progress.toolCounts.get(toolName) || 0;
|
|
143
|
+
progress.toolCounts.set(toolName, currentCount + 1);
|
|
144
|
+
|
|
145
|
+
// Update state
|
|
146
|
+
if (progress.toolStack.length > 0) {
|
|
147
|
+
// Still have parent tools running
|
|
148
|
+
progress.currentTool = progress.toolStack[progress.toolStack.length - 1];
|
|
149
|
+
progress.stage = ProgressStage.TOOL_RUNNING;
|
|
150
|
+
} else {
|
|
151
|
+
// All tools complete
|
|
152
|
+
progress.currentTool = null;
|
|
153
|
+
progress.stage = ProgressStage.TOOL_COMPLETE;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
await this.sendOrUpdateProgressMessage(progress);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Handle Stop hook event.
|
|
161
|
+
*/
|
|
162
|
+
async handleStop(sessionName: string): Promise<void> {
|
|
163
|
+
const progress = this.sessions.get(sessionName);
|
|
164
|
+
|
|
165
|
+
if (!progress) {
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
progress.stage = ProgressStage.FINISHED;
|
|
170
|
+
progress.currentTool = null;
|
|
171
|
+
progress.toolStack = [];
|
|
172
|
+
progress.isActive = false;
|
|
173
|
+
|
|
174
|
+
// Send final completion message
|
|
175
|
+
await this.sendCompletionMessage(progress);
|
|
176
|
+
|
|
177
|
+
// Clean up pending updates
|
|
178
|
+
const pendingTimeout = this.pendingUpdates.get(sessionName);
|
|
179
|
+
if (pendingTimeout) {
|
|
180
|
+
clearTimeout(pendingTimeout);
|
|
181
|
+
this.pendingUpdates.delete(sessionName);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Handle notification event.
|
|
187
|
+
*/
|
|
188
|
+
async handleNotification(sessionName: string, message: string): Promise<void> {
|
|
189
|
+
const progress = this.getOrCreateProgress(sessionName);
|
|
190
|
+
|
|
191
|
+
// Just update the timestamp, don't change stage
|
|
192
|
+
progress.lastUpdateTime = Date.now();
|
|
193
|
+
|
|
194
|
+
// Optionally could update the message with notification info
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Toggle progress display for a session.
|
|
199
|
+
*/
|
|
200
|
+
setShowProgress(sessionName: string, show: boolean): void {
|
|
201
|
+
const progress = this.sessions.get(sessionName);
|
|
202
|
+
if (progress) {
|
|
203
|
+
progress.showProgress = show;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Send or update the progress message with rate limiting.
|
|
209
|
+
*/
|
|
210
|
+
private async sendOrUpdateProgressMessage(progress: SessionProgress): Promise<void> {
|
|
211
|
+
if (!progress.showProgress) {
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
const now = Date.now();
|
|
216
|
+
const lastTime = this.lastUpdate.get(progress.sessionName) || 0;
|
|
217
|
+
|
|
218
|
+
if (now - lastTime < this.MIN_UPDATE_INTERVAL) {
|
|
219
|
+
// Schedule update for later if not already scheduled
|
|
220
|
+
if (!this.pendingUpdates.has(progress.sessionName)) {
|
|
221
|
+
const timeout = setTimeout(async () => {
|
|
222
|
+
this.pendingUpdates.delete(progress.sessionName);
|
|
223
|
+
await this.doUpdateProgressMessage(progress);
|
|
224
|
+
}, this.MIN_UPDATE_INTERVAL - (now - lastTime));
|
|
225
|
+
|
|
226
|
+
this.pendingUpdates.set(progress.sessionName, timeout);
|
|
227
|
+
}
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
await this.doUpdateProgressMessage(progress);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Actually send or update the progress message.
|
|
236
|
+
*/
|
|
237
|
+
private async doUpdateProgressMessage(progress: SessionProgress): Promise<void> {
|
|
238
|
+
this.lastUpdate.set(progress.sessionName, Date.now());
|
|
239
|
+
|
|
240
|
+
const messageText = buildProgressMessage({
|
|
241
|
+
sessionName: progress.sessionName,
|
|
242
|
+
stage: progress.stage,
|
|
243
|
+
currentTool: progress.currentTool,
|
|
244
|
+
toolStack: progress.toolStack,
|
|
245
|
+
startTime: progress.startTime,
|
|
246
|
+
toolsExecuted: progress.toolsExecuted,
|
|
247
|
+
toolCounts: progress.toolCounts,
|
|
248
|
+
showDetails: false,
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
try {
|
|
252
|
+
if (progress.progressMessageId) {
|
|
253
|
+
// Edit existing message
|
|
254
|
+
await this.bot.editMessageText(messageText, {
|
|
255
|
+
chat_id: this.chatId,
|
|
256
|
+
message_id: progress.progressMessageId,
|
|
257
|
+
parse_mode: 'Markdown',
|
|
258
|
+
});
|
|
259
|
+
} else {
|
|
260
|
+
// Send new message with mute button
|
|
261
|
+
const sent = await this.bot.sendMessage(this.chatId, messageText, {
|
|
262
|
+
parse_mode: 'Markdown',
|
|
263
|
+
reply_markup: {
|
|
264
|
+
inline_keyboard: [[
|
|
265
|
+
{ text: '🔕 Mute', callback_data: `progress_mute:${progress.sessionName}` },
|
|
266
|
+
]],
|
|
267
|
+
},
|
|
268
|
+
});
|
|
269
|
+
progress.progressMessageId = sent.message_id;
|
|
270
|
+
}
|
|
271
|
+
} catch (error) {
|
|
272
|
+
// Message might have been deleted or content unchanged
|
|
273
|
+
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
|
274
|
+
|
|
275
|
+
// If message was deleted or not found, create a new one
|
|
276
|
+
if (errorMessage.includes('message to edit not found') ||
|
|
277
|
+
errorMessage.includes('message is not modified')) {
|
|
278
|
+
// Content unchanged is fine, just skip
|
|
279
|
+
if (!errorMessage.includes('message is not modified')) {
|
|
280
|
+
progress.progressMessageId = null;
|
|
281
|
+
// Don't retry immediately to avoid spam
|
|
282
|
+
}
|
|
283
|
+
} else {
|
|
284
|
+
console.error('[ProgressTracker] Error updating message:', errorMessage);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Send final completion message.
|
|
291
|
+
*/
|
|
292
|
+
private async sendCompletionMessage(progress: SessionProgress): Promise<void> {
|
|
293
|
+
const messageText = buildCompletionMessage({
|
|
294
|
+
sessionName: progress.sessionName,
|
|
295
|
+
startTime: progress.startTime,
|
|
296
|
+
toolsExecuted: progress.toolsExecuted,
|
|
297
|
+
toolCounts: progress.toolCounts,
|
|
298
|
+
});
|
|
299
|
+
|
|
300
|
+
try {
|
|
301
|
+
if (progress.progressMessageId) {
|
|
302
|
+
// Edit existing message to show completion
|
|
303
|
+
await this.bot.editMessageText(messageText, {
|
|
304
|
+
chat_id: this.chatId,
|
|
305
|
+
message_id: progress.progressMessageId,
|
|
306
|
+
parse_mode: 'Markdown',
|
|
307
|
+
reply_markup: { inline_keyboard: [] }, // Remove mute button
|
|
308
|
+
});
|
|
309
|
+
} else {
|
|
310
|
+
// Send new completion message
|
|
311
|
+
await this.bot.sendMessage(this.chatId, messageText, {
|
|
312
|
+
parse_mode: 'Markdown',
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
} catch (error) {
|
|
316
|
+
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
|
317
|
+
if (!errorMessage.includes('message is not modified')) {
|
|
318
|
+
console.error('[ProgressTracker] Error sending completion:', errorMessage);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// Clean up session progress
|
|
323
|
+
this.sessions.delete(progress.sessionName);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Handle callback query for mute button.
|
|
328
|
+
*/
|
|
329
|
+
async handleCallback(query: TelegramBot.CallbackQuery): Promise<boolean> {
|
|
330
|
+
if (!query.data?.startsWith('progress_mute:')) {
|
|
331
|
+
return false;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
const sessionName = query.data.replace('progress_mute:', '');
|
|
335
|
+
this.setShowProgress(sessionName, false);
|
|
336
|
+
|
|
337
|
+
// Remove the progress message
|
|
338
|
+
const progress = this.sessions.get(sessionName);
|
|
339
|
+
if (progress?.progressMessageId && query.message) {
|
|
340
|
+
try {
|
|
341
|
+
await this.bot.deleteMessage(this.chatId, progress.progressMessageId);
|
|
342
|
+
} catch {
|
|
343
|
+
// Ignore deletion errors
|
|
344
|
+
}
|
|
345
|
+
progress.progressMessageId = null;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
await this.bot.answerCallbackQuery(query.id, { text: 'Progress muted' });
|
|
349
|
+
return true;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* Clean up inactive sessions.
|
|
354
|
+
*/
|
|
355
|
+
cleanup(): void {
|
|
356
|
+
const now = Date.now();
|
|
357
|
+
const maxAge = 30 * 60 * 1000; // 30 minutes
|
|
358
|
+
|
|
359
|
+
for (const [sessionName, progress] of this.sessions) {
|
|
360
|
+
if (!progress.isActive && now - progress.lastUpdateTime > maxAge) {
|
|
361
|
+
this.sessions.delete(sessionName);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session Manager for the Telegram Claude Daemon
|
|
3
|
+
*
|
|
4
|
+
* Tracks all connected Claude Code sessions and their state.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { Socket } from 'net';
|
|
8
|
+
import type { SessionInfo } from '../shared/protocol.js';
|
|
9
|
+
|
|
10
|
+
export interface ConnectedSession extends SessionInfo {
|
|
11
|
+
socket: Socket;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export class SessionManager {
|
|
15
|
+
private sessions: Map<string, ConnectedSession> = new Map();
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Register a new session
|
|
19
|
+
*/
|
|
20
|
+
register(
|
|
21
|
+
sessionId: string,
|
|
22
|
+
sessionName: string,
|
|
23
|
+
socket: Socket,
|
|
24
|
+
projectPath?: string
|
|
25
|
+
): ConnectedSession {
|
|
26
|
+
const session: ConnectedSession = {
|
|
27
|
+
sessionId,
|
|
28
|
+
sessionName,
|
|
29
|
+
projectPath,
|
|
30
|
+
socket,
|
|
31
|
+
connectedAt: new Date(),
|
|
32
|
+
lastActivity: new Date(),
|
|
33
|
+
activeChats: new Set(),
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
this.sessions.set(sessionId, session);
|
|
37
|
+
console.error(`[SessionManager] Registered session: ${sessionId} (${sessionName})`);
|
|
38
|
+
|
|
39
|
+
return session;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Unregister a session
|
|
44
|
+
*/
|
|
45
|
+
unregister(sessionId: string): boolean {
|
|
46
|
+
const session = this.sessions.get(sessionId);
|
|
47
|
+
if (session) {
|
|
48
|
+
this.sessions.delete(sessionId);
|
|
49
|
+
console.error(`[SessionManager] Unregistered session: ${sessionId}`);
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Get session by ID
|
|
57
|
+
*/
|
|
58
|
+
get(sessionId: string): ConnectedSession | undefined {
|
|
59
|
+
return this.sessions.get(sessionId);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Get session by name (returns first match)
|
|
64
|
+
*/
|
|
65
|
+
getByName(sessionName: string): ConnectedSession | undefined {
|
|
66
|
+
for (const session of this.sessions.values()) {
|
|
67
|
+
if (session.sessionName === sessionName) {
|
|
68
|
+
return session;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return undefined;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Get all sessions
|
|
76
|
+
*/
|
|
77
|
+
getAll(): ConnectedSession[] {
|
|
78
|
+
return Array.from(this.sessions.values());
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Get count of active sessions
|
|
83
|
+
*/
|
|
84
|
+
count(): number {
|
|
85
|
+
return this.sessions.size;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Update last activity timestamp
|
|
90
|
+
*/
|
|
91
|
+
touch(sessionId: string): void {
|
|
92
|
+
const session = this.sessions.get(sessionId);
|
|
93
|
+
if (session) {
|
|
94
|
+
session.lastActivity = new Date();
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Add active chat to session
|
|
100
|
+
*/
|
|
101
|
+
addChat(sessionId: string, chatId: string): void {
|
|
102
|
+
const session = this.sessions.get(sessionId);
|
|
103
|
+
if (session) {
|
|
104
|
+
session.activeChats.add(chatId);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Remove active chat from session
|
|
110
|
+
*/
|
|
111
|
+
removeChat(sessionId: string, chatId: string): void {
|
|
112
|
+
const session = this.sessions.get(sessionId);
|
|
113
|
+
if (session) {
|
|
114
|
+
session.activeChats.delete(chatId);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Find session by socket
|
|
120
|
+
*/
|
|
121
|
+
findBySocket(socket: Socket): ConnectedSession | undefined {
|
|
122
|
+
for (const session of this.sessions.values()) {
|
|
123
|
+
if (session.socket === socket) {
|
|
124
|
+
return session;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return undefined;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Get most recently active session
|
|
132
|
+
*/
|
|
133
|
+
getMostRecentActive(): ConnectedSession | undefined {
|
|
134
|
+
let mostRecent: ConnectedSession | undefined;
|
|
135
|
+
let latestTime = 0;
|
|
136
|
+
|
|
137
|
+
for (const session of this.sessions.values()) {
|
|
138
|
+
const time = session.lastActivity.getTime();
|
|
139
|
+
if (time > latestTime) {
|
|
140
|
+
latestTime = time;
|
|
141
|
+
mostRecent = session;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
return mostRecent;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Find session that should receive a hook event
|
|
150
|
+
* Priority: explicit session name > most recently active
|
|
151
|
+
*/
|
|
152
|
+
findForHook(sessionName?: string): ConnectedSession | undefined {
|
|
153
|
+
if (sessionName) {
|
|
154
|
+
return this.getByName(sessionName);
|
|
155
|
+
}
|
|
156
|
+
return this.getMostRecentActive();
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Clean up disconnected sessions
|
|
161
|
+
*/
|
|
162
|
+
cleanup(): number {
|
|
163
|
+
let cleaned = 0;
|
|
164
|
+
for (const [sessionId, session] of this.sessions.entries()) {
|
|
165
|
+
if (session.socket.destroyed) {
|
|
166
|
+
this.sessions.delete(sessionId);
|
|
167
|
+
cleaned++;
|
|
168
|
+
console.error(`[SessionManager] Cleaned up dead session: ${sessionId}`);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return cleaned;
|
|
172
|
+
}
|
|
173
|
+
}
|