@llblab/pi-telegram 0.2.0
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/AGENTS.md +90 -0
- package/BACKLOG.md +5 -0
- package/CHANGELOG.md +17 -0
- package/README.md +202 -0
- package/docs/README.md +9 -0
- package/docs/architecture.md +148 -0
- package/index.ts +1968 -0
- package/lib/api.ts +222 -0
- package/lib/attachments.ts +98 -0
- package/lib/media.ts +234 -0
- package/lib/menu.ts +951 -0
- package/lib/model-switch.ts +62 -0
- package/lib/polling.ts +122 -0
- package/lib/queue.ts +534 -0
- package/lib/registration.ts +163 -0
- package/lib/rendering.ts +697 -0
- package/lib/replies.ts +313 -0
- package/lib/setup.ts +41 -0
- package/lib/status.ts +109 -0
- package/lib/turns.ts +144 -0
- package/lib/updates.ts +397 -0
- package/package.json +40 -0
- package/screenshot.png +0 -0
- package/tests/api.test.ts +89 -0
- package/tests/attachments.test.ts +132 -0
- package/tests/config.test.ts +80 -0
- package/tests/media.test.ts +77 -0
- package/tests/menu.test.ts +645 -0
- package/tests/polling.test.ts +129 -0
- package/tests/queue.test.ts +2982 -0
- package/tests/registration.test.ts +268 -0
- package/tests/rendering.test.ts +308 -0
- package/tests/replies.test.ts +362 -0
- package/tests/turns.test.ts +132 -0
- package/tests/updates.test.ts +366 -0
package/index.ts
ADDED
|
@@ -0,0 +1,1968 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Telegram bridge extension entrypoint and orchestration layer
|
|
3
|
+
* Keeps the runtime wiring in one place while delegating reusable domain logic to /lib modules
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { mkdir, readFile, stat } from "node:fs/promises";
|
|
7
|
+
import { homedir } from "node:os";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
|
|
10
|
+
import type { AgentMessage } from "@mariozechner/pi-agent-core";
|
|
11
|
+
import type { Model } from "@mariozechner/pi-ai";
|
|
12
|
+
import type {
|
|
13
|
+
ExtensionAPI,
|
|
14
|
+
ExtensionContext,
|
|
15
|
+
} from "@mariozechner/pi-coding-agent";
|
|
16
|
+
import { SettingsManager } from "@mariozechner/pi-coding-agent";
|
|
17
|
+
|
|
18
|
+
import {
|
|
19
|
+
createTelegramApiClient,
|
|
20
|
+
readTelegramConfig,
|
|
21
|
+
writeTelegramConfig,
|
|
22
|
+
type TelegramConfig,
|
|
23
|
+
} from "./lib/api.ts";
|
|
24
|
+
import { sendQueuedTelegramAttachments } from "./lib/attachments.ts";
|
|
25
|
+
import {
|
|
26
|
+
collectTelegramFileInfos,
|
|
27
|
+
extractFirstTelegramMessageText,
|
|
28
|
+
extractTelegramMessagesText,
|
|
29
|
+
guessMediaType,
|
|
30
|
+
} from "./lib/media.ts";
|
|
31
|
+
import {
|
|
32
|
+
buildTelegramModelMenuState,
|
|
33
|
+
getCanonicalModelId,
|
|
34
|
+
handleTelegramMenuCallbackEntry,
|
|
35
|
+
handleTelegramModelMenuCallbackAction,
|
|
36
|
+
handleTelegramStatusMenuCallbackAction,
|
|
37
|
+
handleTelegramThinkingMenuCallbackAction,
|
|
38
|
+
sendTelegramModelMenuMessage,
|
|
39
|
+
sendTelegramStatusMessage,
|
|
40
|
+
updateTelegramModelMenuMessage,
|
|
41
|
+
updateTelegramStatusMessage,
|
|
42
|
+
updateTelegramThinkingMenuMessage,
|
|
43
|
+
type ScopedTelegramModel,
|
|
44
|
+
type TelegramModelMenuState,
|
|
45
|
+
type TelegramReplyMarkup,
|
|
46
|
+
type ThinkingLevel,
|
|
47
|
+
} from "./lib/menu.ts";
|
|
48
|
+
import {
|
|
49
|
+
buildTelegramModelSwitchContinuationText,
|
|
50
|
+
canRestartTelegramTurnForModelSwitch,
|
|
51
|
+
restartTelegramModelSwitchContinuation,
|
|
52
|
+
shouldTriggerPendingTelegramModelSwitchAbort,
|
|
53
|
+
} from "./lib/model-switch.ts";
|
|
54
|
+
import { runTelegramPollLoop } from "./lib/polling.ts";
|
|
55
|
+
import {
|
|
56
|
+
buildTelegramAgentEndPlan,
|
|
57
|
+
buildTelegramAgentStartPlan,
|
|
58
|
+
buildTelegramSessionShutdownState,
|
|
59
|
+
buildTelegramSessionStartState,
|
|
60
|
+
canDispatchTelegramTurnState,
|
|
61
|
+
clearTelegramQueuePromptPriority,
|
|
62
|
+
compareTelegramQueueItems,
|
|
63
|
+
consumeDispatchedTelegramPrompt,
|
|
64
|
+
executeTelegramControlItemRuntime,
|
|
65
|
+
executeTelegramQueueDispatchPlan,
|
|
66
|
+
formatQueuedTelegramItemsStatus,
|
|
67
|
+
getNextTelegramToolExecutionCount,
|
|
68
|
+
partitionTelegramQueueItemsForHistory,
|
|
69
|
+
planNextTelegramQueueAction,
|
|
70
|
+
prioritizeTelegramQueuePrompt,
|
|
71
|
+
removeTelegramQueueItemsByMessageIds,
|
|
72
|
+
shouldDispatchAfterTelegramAgentEnd,
|
|
73
|
+
shouldStartTelegramPolling,
|
|
74
|
+
type PendingTelegramControlItem,
|
|
75
|
+
type PendingTelegramTurn,
|
|
76
|
+
type TelegramQueueItem,
|
|
77
|
+
} from "./lib/queue.ts";
|
|
78
|
+
import {
|
|
79
|
+
registerTelegramAttachmentTool,
|
|
80
|
+
registerTelegramCommands,
|
|
81
|
+
registerTelegramLifecycleHooks,
|
|
82
|
+
} from "./lib/registration.ts";
|
|
83
|
+
import {
|
|
84
|
+
MAX_MESSAGE_LENGTH,
|
|
85
|
+
renderMarkdownPreviewText,
|
|
86
|
+
renderTelegramMessage,
|
|
87
|
+
type TelegramRenderMode,
|
|
88
|
+
} from "./lib/rendering.ts";
|
|
89
|
+
import {
|
|
90
|
+
buildTelegramReplyTransport,
|
|
91
|
+
clearTelegramPreview,
|
|
92
|
+
finalizeTelegramMarkdownPreview,
|
|
93
|
+
finalizeTelegramPreview,
|
|
94
|
+
flushTelegramPreview,
|
|
95
|
+
sendTelegramMarkdownReply,
|
|
96
|
+
sendTelegramPlainReply,
|
|
97
|
+
} from "./lib/replies.ts";
|
|
98
|
+
import {
|
|
99
|
+
getTelegramBotTokenInputDefault,
|
|
100
|
+
getTelegramBotTokenPromptSpec,
|
|
101
|
+
} from "./lib/setup.ts";
|
|
102
|
+
import { buildStatusHtml } from "./lib/status.ts";
|
|
103
|
+
import {
|
|
104
|
+
buildTelegramPromptTurn,
|
|
105
|
+
truncateTelegramQueueSummary,
|
|
106
|
+
} from "./lib/turns.ts";
|
|
107
|
+
import {
|
|
108
|
+
collectTelegramReactionEmojis,
|
|
109
|
+
executeTelegramUpdate,
|
|
110
|
+
getTelegramAuthorizationState,
|
|
111
|
+
} from "./lib/updates.ts";
|
|
112
|
+
|
|
113
|
+
// --- Telegram API Types ---
|
|
114
|
+
|
|
115
|
+
interface TelegramApiResponse<T> {
|
|
116
|
+
ok: boolean;
|
|
117
|
+
result?: T;
|
|
118
|
+
description?: string;
|
|
119
|
+
error_code?: number;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
interface TelegramUser {
|
|
123
|
+
id: number;
|
|
124
|
+
is_bot: boolean;
|
|
125
|
+
first_name: string;
|
|
126
|
+
username?: string;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
interface TelegramChat {
|
|
130
|
+
id: number;
|
|
131
|
+
type: string;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
interface TelegramPhotoSize {
|
|
135
|
+
file_id: string;
|
|
136
|
+
file_size?: number;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
interface TelegramDocument {
|
|
140
|
+
file_id: string;
|
|
141
|
+
file_name?: string;
|
|
142
|
+
mime_type?: string;
|
|
143
|
+
file_size?: number;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
interface TelegramVideo {
|
|
147
|
+
file_id: string;
|
|
148
|
+
file_name?: string;
|
|
149
|
+
mime_type?: string;
|
|
150
|
+
file_size?: number;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
interface TelegramAudio {
|
|
154
|
+
file_id: string;
|
|
155
|
+
file_name?: string;
|
|
156
|
+
mime_type?: string;
|
|
157
|
+
file_size?: number;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
interface TelegramVoice {
|
|
161
|
+
file_id: string;
|
|
162
|
+
mime_type?: string;
|
|
163
|
+
file_size?: number;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
interface TelegramAnimation {
|
|
167
|
+
file_id: string;
|
|
168
|
+
file_name?: string;
|
|
169
|
+
mime_type?: string;
|
|
170
|
+
file_size?: number;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
interface TelegramSticker {
|
|
174
|
+
file_id: string;
|
|
175
|
+
emoji?: string;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
interface TelegramFileInfo {
|
|
179
|
+
file_id: string;
|
|
180
|
+
fileName: string;
|
|
181
|
+
mimeType?: string;
|
|
182
|
+
isImage: boolean;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
interface TelegramMessage {
|
|
186
|
+
message_id: number;
|
|
187
|
+
chat: TelegramChat;
|
|
188
|
+
from?: TelegramUser;
|
|
189
|
+
text?: string;
|
|
190
|
+
caption?: string;
|
|
191
|
+
media_group_id?: string;
|
|
192
|
+
photo?: TelegramPhotoSize[];
|
|
193
|
+
document?: TelegramDocument;
|
|
194
|
+
video?: TelegramVideo;
|
|
195
|
+
audio?: TelegramAudio;
|
|
196
|
+
voice?: TelegramVoice;
|
|
197
|
+
animation?: TelegramAnimation;
|
|
198
|
+
sticker?: TelegramSticker;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
interface TelegramCallbackQuery {
|
|
202
|
+
id: string;
|
|
203
|
+
from: TelegramUser;
|
|
204
|
+
message?: TelegramMessage;
|
|
205
|
+
data?: string;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
interface TelegramReactionTypeEmoji {
|
|
209
|
+
type: "emoji";
|
|
210
|
+
emoji: string;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
interface TelegramReactionTypeCustomEmoji {
|
|
214
|
+
type: "custom_emoji";
|
|
215
|
+
custom_emoji_id: string;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
interface TelegramReactionTypePaid {
|
|
219
|
+
type: "paid";
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
type TelegramReactionType =
|
|
223
|
+
| TelegramReactionTypeEmoji
|
|
224
|
+
| TelegramReactionTypeCustomEmoji
|
|
225
|
+
| TelegramReactionTypePaid;
|
|
226
|
+
|
|
227
|
+
interface TelegramMessageReactionUpdated {
|
|
228
|
+
chat: TelegramChat;
|
|
229
|
+
message_id: number;
|
|
230
|
+
user?: TelegramUser;
|
|
231
|
+
actor_chat?: TelegramChat;
|
|
232
|
+
old_reaction: TelegramReactionType[];
|
|
233
|
+
new_reaction: TelegramReactionType[];
|
|
234
|
+
date: number;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
interface TelegramUpdate {
|
|
238
|
+
_: string;
|
|
239
|
+
update_id: number;
|
|
240
|
+
message?: TelegramMessage;
|
|
241
|
+
edited_message?: TelegramMessage;
|
|
242
|
+
callback_query?: TelegramCallbackQuery;
|
|
243
|
+
message_reaction?: TelegramMessageReactionUpdated;
|
|
244
|
+
deleted_business_messages?: { message_ids?: unknown };
|
|
245
|
+
messages?: unknown;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
interface TelegramGetFileResult {
|
|
249
|
+
file_path: string;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
interface TelegramSentMessage {
|
|
253
|
+
message_id: number;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
interface TelegramBotCommand {
|
|
257
|
+
command: string;
|
|
258
|
+
description: string;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// --- Extension State Types ---
|
|
262
|
+
|
|
263
|
+
interface DownloadedTelegramFile {
|
|
264
|
+
path: string;
|
|
265
|
+
fileName: string;
|
|
266
|
+
isImage: boolean;
|
|
267
|
+
mimeType?: string;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
type ActiveTelegramTurn = PendingTelegramTurn;
|
|
271
|
+
|
|
272
|
+
interface TelegramPreviewState {
|
|
273
|
+
mode: "draft" | "message";
|
|
274
|
+
draftId?: number;
|
|
275
|
+
messageId?: number;
|
|
276
|
+
pendingText: string;
|
|
277
|
+
lastSentText: string;
|
|
278
|
+
flushTimer?: ReturnType<typeof setTimeout>;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
interface TelegramMediaGroupState {
|
|
282
|
+
messages: TelegramMessage[];
|
|
283
|
+
flushTimer?: ReturnType<typeof setTimeout>;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const AGENT_DIR = join(homedir(), ".pi", "agent");
|
|
287
|
+
const CONFIG_PATH = join(AGENT_DIR, "telegram.json");
|
|
288
|
+
const TEMP_DIR = join(AGENT_DIR, "tmp", "telegram");
|
|
289
|
+
const TELEGRAM_PREFIX = "[telegram]";
|
|
290
|
+
const MAX_ATTACHMENTS_PER_TURN = 10;
|
|
291
|
+
const PREVIEW_THROTTLE_MS = 750;
|
|
292
|
+
const TELEGRAM_DRAFT_ID_MAX = 2_147_483_647;
|
|
293
|
+
const TELEGRAM_MEDIA_GROUP_DEBOUNCE_MS = 1200;
|
|
294
|
+
const SYSTEM_PROMPT_SUFFIX = `
|
|
295
|
+
|
|
296
|
+
Telegram bridge extension is active.
|
|
297
|
+
- Messages forwarded from Telegram are prefixed with "[telegram]".
|
|
298
|
+
- [telegram] messages may include local temp file paths for Telegram attachments. Read those files as needed.
|
|
299
|
+
- If a [telegram] user asked for a file or generated artifact, use the telegram_attach tool with the local file path so the extension can send it with your next final reply.
|
|
300
|
+
- Do not assume mentioning a local file path in plain text will send it to Telegram. Use telegram_attach.`;
|
|
301
|
+
|
|
302
|
+
// --- Generic Utilities ---
|
|
303
|
+
|
|
304
|
+
function isTelegramPrompt(prompt: string): boolean {
|
|
305
|
+
return prompt.trimStart().startsWith(TELEGRAM_PREFIX);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function sanitizeFileName(name: string): string {
|
|
309
|
+
return name.replace(/[^a-zA-Z0-9._-]+/g, "_");
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
function parseTelegramCommand(
|
|
313
|
+
text: string,
|
|
314
|
+
): { name: string; args: string } | undefined {
|
|
315
|
+
const trimmed = text.trim();
|
|
316
|
+
if (!trimmed.startsWith("/")) return undefined;
|
|
317
|
+
const [head, ...tail] = trimmed.split(/\s+/);
|
|
318
|
+
const name = head.slice(1).split("@")[0]?.toLowerCase();
|
|
319
|
+
if (!name) return undefined;
|
|
320
|
+
return { name, args: tail.join(" ").trim() };
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function getCliScopedModelPatterns(): string[] | undefined {
|
|
324
|
+
const args = process.argv.slice(2);
|
|
325
|
+
for (let i = 0; i < args.length; i++) {
|
|
326
|
+
const arg = args[i];
|
|
327
|
+
if (arg === "--models") {
|
|
328
|
+
const value = args[i + 1] ?? "";
|
|
329
|
+
const patterns = value
|
|
330
|
+
.split(",")
|
|
331
|
+
.map((pattern) => pattern.trim())
|
|
332
|
+
.filter(Boolean);
|
|
333
|
+
return patterns.length > 0 ? patterns : undefined;
|
|
334
|
+
}
|
|
335
|
+
if (arg.startsWith("--models=")) {
|
|
336
|
+
const patterns = arg
|
|
337
|
+
.slice("--models=".length)
|
|
338
|
+
.split(",")
|
|
339
|
+
.map((pattern) => pattern.trim())
|
|
340
|
+
.filter(Boolean);
|
|
341
|
+
return patterns.length > 0 ? patterns : undefined;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
return undefined;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function truncateTelegramButtonLabel(label: string, maxLength = 56): string {
|
|
348
|
+
return label.length <= maxLength
|
|
349
|
+
? label
|
|
350
|
+
: `${label.slice(0, maxLength - 1)}…`;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// --- Extension Runtime ---
|
|
354
|
+
|
|
355
|
+
export const __telegramTestUtils = {
|
|
356
|
+
MAX_MESSAGE_LENGTH,
|
|
357
|
+
renderTelegramMessage,
|
|
358
|
+
compareTelegramQueueItems,
|
|
359
|
+
removeTelegramQueueItemsByMessageIds,
|
|
360
|
+
clearTelegramQueuePromptPriority,
|
|
361
|
+
prioritizeTelegramQueuePrompt,
|
|
362
|
+
partitionTelegramQueueItemsForHistory,
|
|
363
|
+
consumeDispatchedTelegramPrompt,
|
|
364
|
+
planNextTelegramQueueAction,
|
|
365
|
+
shouldDispatchAfterTelegramAgentEnd,
|
|
366
|
+
buildTelegramAgentEndPlan,
|
|
367
|
+
canDispatchTelegramTurnState,
|
|
368
|
+
getTelegramBotTokenInputDefault,
|
|
369
|
+
getTelegramBotTokenPromptSpec,
|
|
370
|
+
canRestartTelegramTurnForModelSwitch,
|
|
371
|
+
restartTelegramModelSwitchContinuation,
|
|
372
|
+
shouldTriggerPendingTelegramModelSwitchAbort,
|
|
373
|
+
buildTelegramModelSwitchContinuationText: (
|
|
374
|
+
model: Pick<Model<any>, "provider" | "id">,
|
|
375
|
+
thinkingLevel?: ThinkingLevel,
|
|
376
|
+
) =>
|
|
377
|
+
buildTelegramModelSwitchContinuationText(
|
|
378
|
+
TELEGRAM_PREFIX,
|
|
379
|
+
model,
|
|
380
|
+
thinkingLevel,
|
|
381
|
+
),
|
|
382
|
+
};
|
|
383
|
+
|
|
384
|
+
export default function (pi: ExtensionAPI) {
|
|
385
|
+
let config: TelegramConfig = {};
|
|
386
|
+
let pollingController: AbortController | undefined;
|
|
387
|
+
let pollingPromise: Promise<void> | undefined;
|
|
388
|
+
let queuedTelegramItems: TelegramQueueItem[] = [];
|
|
389
|
+
let nextQueuedTelegramItemOrder = 0;
|
|
390
|
+
let nextQueuedTelegramControlOrder = 0;
|
|
391
|
+
let nextPriorityReactionOrder = 0;
|
|
392
|
+
let activeTelegramTurn: ActiveTelegramTurn | undefined;
|
|
393
|
+
let activeTelegramToolExecutions = 0;
|
|
394
|
+
let pendingTelegramModelSwitch: ScopedTelegramModel | undefined;
|
|
395
|
+
let telegramTurnDispatchPending = false;
|
|
396
|
+
let typingInterval: ReturnType<typeof setInterval> | undefined;
|
|
397
|
+
let currentAbort: (() => void) | undefined;
|
|
398
|
+
let preserveQueuedTurnsAsHistory = false;
|
|
399
|
+
let compactionInProgress = false;
|
|
400
|
+
let setupInProgress = false;
|
|
401
|
+
let previewState: TelegramPreviewState | undefined;
|
|
402
|
+
let draftSupport: "unknown" | "supported" | "unsupported" = "unknown";
|
|
403
|
+
let nextDraftId = 0;
|
|
404
|
+
let currentTelegramModel: Model<any> | undefined;
|
|
405
|
+
const mediaGroups = new Map<string, TelegramMediaGroupState>();
|
|
406
|
+
const modelMenus = new Map<number, TelegramModelMenuState>();
|
|
407
|
+
|
|
408
|
+
// --- Runtime State ---
|
|
409
|
+
|
|
410
|
+
function allocateDraftId(): number {
|
|
411
|
+
nextDraftId = nextDraftId >= TELEGRAM_DRAFT_ID_MAX ? 1 : nextDraftId + 1;
|
|
412
|
+
return nextDraftId;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
function canDispatchQueuedTelegramTurn(ctx: ExtensionContext): boolean {
|
|
416
|
+
return canDispatchTelegramTurnState({
|
|
417
|
+
compactionInProgress,
|
|
418
|
+
hasActiveTelegramTurn: !!activeTelegramTurn,
|
|
419
|
+
hasPendingTelegramDispatch: telegramTurnDispatchPending,
|
|
420
|
+
isIdle: ctx.isIdle(),
|
|
421
|
+
hasPendingMessages: ctx.hasPendingMessages(),
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
function executeQueuedTelegramControlItem(
|
|
426
|
+
item: PendingTelegramControlItem,
|
|
427
|
+
ctx: ExtensionContext,
|
|
428
|
+
): void {
|
|
429
|
+
void executeTelegramControlItemRuntime(item, {
|
|
430
|
+
ctx,
|
|
431
|
+
sendTextReply,
|
|
432
|
+
onSettled: () => {
|
|
433
|
+
updateStatus(ctx);
|
|
434
|
+
dispatchNextQueuedTelegramTurn(ctx);
|
|
435
|
+
},
|
|
436
|
+
});
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function dispatchNextQueuedTelegramTurn(ctx: ExtensionContext): void {
|
|
440
|
+
const dispatchPlan = planNextTelegramQueueAction(
|
|
441
|
+
queuedTelegramItems,
|
|
442
|
+
canDispatchQueuedTelegramTurn(ctx),
|
|
443
|
+
);
|
|
444
|
+
if (dispatchPlan.kind !== "none") {
|
|
445
|
+
queuedTelegramItems = dispatchPlan.remainingItems;
|
|
446
|
+
}
|
|
447
|
+
executeTelegramQueueDispatchPlan(dispatchPlan, {
|
|
448
|
+
executeControlItem: (item) => {
|
|
449
|
+
updateStatus(ctx);
|
|
450
|
+
executeQueuedTelegramControlItem(item, ctx);
|
|
451
|
+
},
|
|
452
|
+
onPromptDispatchStart: (chatId) => {
|
|
453
|
+
telegramTurnDispatchPending = true;
|
|
454
|
+
startTypingLoop(ctx, chatId);
|
|
455
|
+
updateStatus(ctx);
|
|
456
|
+
},
|
|
457
|
+
sendUserMessage: (content) => {
|
|
458
|
+
pi.sendUserMessage(content);
|
|
459
|
+
},
|
|
460
|
+
onPromptDispatchFailure: (message) => {
|
|
461
|
+
telegramTurnDispatchPending = false;
|
|
462
|
+
stopTypingLoop();
|
|
463
|
+
updateStatus(ctx, `dispatch failed: ${message}`);
|
|
464
|
+
},
|
|
465
|
+
onIdle: () => {
|
|
466
|
+
updateStatus(ctx);
|
|
467
|
+
},
|
|
468
|
+
});
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
// --- Status ---
|
|
472
|
+
|
|
473
|
+
function updateStatus(ctx: ExtensionContext, error?: string): void {
|
|
474
|
+
const theme = ctx.ui.theme;
|
|
475
|
+
const label = theme.fg("accent", "telegram");
|
|
476
|
+
if (error) {
|
|
477
|
+
ctx.ui.setStatus(
|
|
478
|
+
"telegram",
|
|
479
|
+
`${label} ${theme.fg("error", "error")} ${theme.fg("muted", error)}`,
|
|
480
|
+
);
|
|
481
|
+
return;
|
|
482
|
+
}
|
|
483
|
+
if (!config.botToken) {
|
|
484
|
+
ctx.ui.setStatus(
|
|
485
|
+
"telegram",
|
|
486
|
+
`${label} ${theme.fg("muted", "not configured")}`,
|
|
487
|
+
);
|
|
488
|
+
return;
|
|
489
|
+
}
|
|
490
|
+
if (!pollingPromise) {
|
|
491
|
+
ctx.ui.setStatus(
|
|
492
|
+
"telegram",
|
|
493
|
+
`${label} ${theme.fg("muted", "disconnected")}`,
|
|
494
|
+
);
|
|
495
|
+
return;
|
|
496
|
+
}
|
|
497
|
+
if (!config.allowedUserId) {
|
|
498
|
+
ctx.ui.setStatus(
|
|
499
|
+
"telegram",
|
|
500
|
+
`${label} ${theme.fg("warning", "awaiting pairing")}`,
|
|
501
|
+
);
|
|
502
|
+
return;
|
|
503
|
+
}
|
|
504
|
+
if (compactionInProgress) {
|
|
505
|
+
const queued = theme.fg(
|
|
506
|
+
"muted",
|
|
507
|
+
formatQueuedTelegramItemsStatus(queuedTelegramItems),
|
|
508
|
+
);
|
|
509
|
+
ctx.ui.setStatus(
|
|
510
|
+
"telegram",
|
|
511
|
+
`${label} ${theme.fg("accent", "compacting")}${queued}`,
|
|
512
|
+
);
|
|
513
|
+
return;
|
|
514
|
+
}
|
|
515
|
+
if (
|
|
516
|
+
activeTelegramTurn ||
|
|
517
|
+
telegramTurnDispatchPending ||
|
|
518
|
+
queuedTelegramItems.length > 0
|
|
519
|
+
) {
|
|
520
|
+
const queued = theme.fg(
|
|
521
|
+
"muted",
|
|
522
|
+
formatQueuedTelegramItemsStatus(queuedTelegramItems),
|
|
523
|
+
);
|
|
524
|
+
ctx.ui.setStatus(
|
|
525
|
+
"telegram",
|
|
526
|
+
`${label} ${theme.fg("accent", "processing")}${queued}`,
|
|
527
|
+
);
|
|
528
|
+
return;
|
|
529
|
+
}
|
|
530
|
+
ctx.ui.setStatus(
|
|
531
|
+
"telegram",
|
|
532
|
+
`${label} ${theme.fg("success", "connected")}`,
|
|
533
|
+
);
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
// --- Telegram API ---
|
|
537
|
+
|
|
538
|
+
const telegramApi = createTelegramApiClient(() => config.botToken);
|
|
539
|
+
|
|
540
|
+
const callTelegramApi = <TResponse>(
|
|
541
|
+
method: string,
|
|
542
|
+
body: Record<string, unknown>,
|
|
543
|
+
options?: { signal?: AbortSignal },
|
|
544
|
+
): Promise<TResponse> => {
|
|
545
|
+
return telegramApi.call<TResponse>(method, body, options);
|
|
546
|
+
};
|
|
547
|
+
|
|
548
|
+
const callTelegramMultipartApi = <TResponse>(
|
|
549
|
+
method: string,
|
|
550
|
+
fields: Record<string, string>,
|
|
551
|
+
fileField: string,
|
|
552
|
+
filePath: string,
|
|
553
|
+
fileName: string,
|
|
554
|
+
options?: { signal?: AbortSignal },
|
|
555
|
+
): Promise<TResponse> => {
|
|
556
|
+
return telegramApi.callMultipart<TResponse>(
|
|
557
|
+
method,
|
|
558
|
+
fields,
|
|
559
|
+
fileField,
|
|
560
|
+
filePath,
|
|
561
|
+
fileName,
|
|
562
|
+
options,
|
|
563
|
+
);
|
|
564
|
+
};
|
|
565
|
+
|
|
566
|
+
const downloadTelegramBridgeFile = (
|
|
567
|
+
fileId: string,
|
|
568
|
+
suggestedName: string,
|
|
569
|
+
): Promise<string> => {
|
|
570
|
+
return telegramApi.downloadFile(fileId, suggestedName, TEMP_DIR);
|
|
571
|
+
};
|
|
572
|
+
|
|
573
|
+
const answerCallbackQuery = (
|
|
574
|
+
callbackQueryId: string,
|
|
575
|
+
text?: string,
|
|
576
|
+
): Promise<void> => {
|
|
577
|
+
return telegramApi.answerCallbackQuery(callbackQueryId, text);
|
|
578
|
+
};
|
|
579
|
+
|
|
580
|
+
// --- Message Delivery & Preview ---
|
|
581
|
+
|
|
582
|
+
function startTypingLoop(ctx: ExtensionContext, chatId?: number): void {
|
|
583
|
+
const targetChatId = chatId ?? activeTelegramTurn?.chatId;
|
|
584
|
+
if (typingInterval || targetChatId === undefined) return;
|
|
585
|
+
|
|
586
|
+
const sendTyping = async (): Promise<void> => {
|
|
587
|
+
try {
|
|
588
|
+
await callTelegramApi("sendChatAction", {
|
|
589
|
+
chat_id: targetChatId,
|
|
590
|
+
action: "typing",
|
|
591
|
+
});
|
|
592
|
+
} catch (error) {
|
|
593
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
594
|
+
updateStatus(ctx, `typing failed: ${message}`);
|
|
595
|
+
}
|
|
596
|
+
};
|
|
597
|
+
|
|
598
|
+
void sendTyping();
|
|
599
|
+
typingInterval = setInterval(() => {
|
|
600
|
+
void sendTyping();
|
|
601
|
+
}, 4000);
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
function stopTypingLoop(): void {
|
|
605
|
+
if (!typingInterval) return;
|
|
606
|
+
clearInterval(typingInterval);
|
|
607
|
+
typingInterval = undefined;
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
function isAssistantMessage(message: AgentMessage): boolean {
|
|
611
|
+
return (message as unknown as { role?: string }).role === "assistant";
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
function extractTextContent(content: unknown): string {
|
|
615
|
+
const blocks = Array.isArray(content) ? content : [];
|
|
616
|
+
return blocks
|
|
617
|
+
.filter(
|
|
618
|
+
(block): block is { type: string; text?: string } =>
|
|
619
|
+
typeof block === "object" && block !== null && "type" in block,
|
|
620
|
+
)
|
|
621
|
+
.filter(
|
|
622
|
+
(block) => block.type === "text" && typeof block.text === "string",
|
|
623
|
+
)
|
|
624
|
+
.map((block) => block.text as string)
|
|
625
|
+
.join("")
|
|
626
|
+
.trim();
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
function getMessageText(message: AgentMessage): string {
|
|
630
|
+
return extractTextContent(
|
|
631
|
+
(message as unknown as Record<string, unknown>).content,
|
|
632
|
+
);
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
function createPreviewState(): TelegramPreviewState {
|
|
636
|
+
return {
|
|
637
|
+
mode: draftSupport === "unsupported" ? "message" : "draft",
|
|
638
|
+
pendingText: "",
|
|
639
|
+
lastSentText: "",
|
|
640
|
+
};
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
function isTelegramMessageNotModifiedError(error: unknown): boolean {
|
|
644
|
+
return (
|
|
645
|
+
error instanceof Error &&
|
|
646
|
+
error.message.includes("message is not modified")
|
|
647
|
+
);
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
async function editTelegramMessageText(
|
|
651
|
+
body: Record<string, unknown>,
|
|
652
|
+
): Promise<"edited" | "unchanged"> {
|
|
653
|
+
try {
|
|
654
|
+
await callTelegramApi("editMessageText", body);
|
|
655
|
+
return "edited";
|
|
656
|
+
} catch (error) {
|
|
657
|
+
if (isTelegramMessageNotModifiedError(error)) return "unchanged";
|
|
658
|
+
throw error;
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
const replyTransport = buildTelegramReplyTransport<TelegramReplyMarkup>({
|
|
663
|
+
sendMessage: async (body) => {
|
|
664
|
+
return callTelegramApi<TelegramSentMessage>("sendMessage", body);
|
|
665
|
+
},
|
|
666
|
+
editMessage: async (body) => {
|
|
667
|
+
await editTelegramMessageText(body);
|
|
668
|
+
},
|
|
669
|
+
});
|
|
670
|
+
|
|
671
|
+
function getPreviewRuntimeDeps() {
|
|
672
|
+
return {
|
|
673
|
+
getState: () => previewState,
|
|
674
|
+
setState: (state: TelegramPreviewState | undefined) => {
|
|
675
|
+
previewState = state;
|
|
676
|
+
},
|
|
677
|
+
clearScheduledFlush: (state: TelegramPreviewState) => {
|
|
678
|
+
if (!state.flushTimer) return;
|
|
679
|
+
clearTimeout(state.flushTimer);
|
|
680
|
+
state.flushTimer = undefined;
|
|
681
|
+
},
|
|
682
|
+
maxMessageLength: MAX_MESSAGE_LENGTH,
|
|
683
|
+
renderPreviewText: renderMarkdownPreviewText,
|
|
684
|
+
getDraftSupport: () => draftSupport,
|
|
685
|
+
setDraftSupport: (support: "unknown" | "supported" | "unsupported") => {
|
|
686
|
+
draftSupport = support;
|
|
687
|
+
},
|
|
688
|
+
allocateDraftId,
|
|
689
|
+
sendDraft: async (chatId: number, draftId: number, text: string) => {
|
|
690
|
+
await callTelegramApi("sendMessageDraft", {
|
|
691
|
+
chat_id: chatId,
|
|
692
|
+
draft_id: draftId,
|
|
693
|
+
text,
|
|
694
|
+
});
|
|
695
|
+
},
|
|
696
|
+
sendMessage: async (chatId: number, text: string) => {
|
|
697
|
+
return callTelegramApi<TelegramSentMessage>("sendMessage", {
|
|
698
|
+
chat_id: chatId,
|
|
699
|
+
text,
|
|
700
|
+
});
|
|
701
|
+
},
|
|
702
|
+
editMessageText: async (
|
|
703
|
+
chatId: number,
|
|
704
|
+
messageId: number,
|
|
705
|
+
text: string,
|
|
706
|
+
) => {
|
|
707
|
+
await editTelegramMessageText({
|
|
708
|
+
chat_id: chatId,
|
|
709
|
+
message_id: messageId,
|
|
710
|
+
text,
|
|
711
|
+
});
|
|
712
|
+
},
|
|
713
|
+
renderTelegramMessage,
|
|
714
|
+
sendRenderedChunks: replyTransport.sendRenderedChunks,
|
|
715
|
+
editRenderedMessage: replyTransport.editRenderedMessage,
|
|
716
|
+
};
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
async function clearPreview(chatId: number): Promise<void> {
|
|
720
|
+
await clearTelegramPreview(chatId, getPreviewRuntimeDeps());
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
async function flushPreview(chatId: number): Promise<void> {
|
|
724
|
+
await flushTelegramPreview(chatId, getPreviewRuntimeDeps());
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
function schedulePreviewFlush(chatId: number): void {
|
|
728
|
+
if (!previewState || previewState.flushTimer) return;
|
|
729
|
+
previewState.flushTimer = setTimeout(() => {
|
|
730
|
+
void flushPreview(chatId);
|
|
731
|
+
}, PREVIEW_THROTTLE_MS);
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
async function finalizePreview(chatId: number): Promise<boolean> {
|
|
735
|
+
return finalizeTelegramPreview(chatId, getPreviewRuntimeDeps());
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
async function finalizeMarkdownPreview(
|
|
739
|
+
chatId: number,
|
|
740
|
+
markdown: string,
|
|
741
|
+
): Promise<boolean> {
|
|
742
|
+
return finalizeTelegramMarkdownPreview(
|
|
743
|
+
chatId,
|
|
744
|
+
markdown,
|
|
745
|
+
getPreviewRuntimeDeps(),
|
|
746
|
+
);
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
async function sendTextReply(
|
|
750
|
+
chatId: number,
|
|
751
|
+
_replyToMessageId: number,
|
|
752
|
+
text: string,
|
|
753
|
+
options?: { parseMode?: "HTML" },
|
|
754
|
+
): Promise<number | undefined> {
|
|
755
|
+
return sendTelegramPlainReply(
|
|
756
|
+
text,
|
|
757
|
+
{
|
|
758
|
+
renderTelegramMessage,
|
|
759
|
+
sendRenderedChunks: async (chunks) =>
|
|
760
|
+
replyTransport.sendRenderedChunks(chatId, chunks),
|
|
761
|
+
},
|
|
762
|
+
options,
|
|
763
|
+
);
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
async function sendMarkdownReply(
|
|
767
|
+
chatId: number,
|
|
768
|
+
replyToMessageId: number,
|
|
769
|
+
markdown: string,
|
|
770
|
+
): Promise<number | undefined> {
|
|
771
|
+
return sendTelegramMarkdownReply(markdown, {
|
|
772
|
+
renderTelegramMessage,
|
|
773
|
+
sendRenderedChunks: async (chunks) => {
|
|
774
|
+
if (chunks.length === 0) {
|
|
775
|
+
return sendTextReply(chatId, replyToMessageId, markdown);
|
|
776
|
+
}
|
|
777
|
+
return replyTransport.sendRenderedChunks(chatId, chunks);
|
|
778
|
+
},
|
|
779
|
+
});
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
async function sendQueuedAttachments(
|
|
783
|
+
turn: ActiveTelegramTurn,
|
|
784
|
+
): Promise<void> {
|
|
785
|
+
await sendQueuedTelegramAttachments(turn, {
|
|
786
|
+
sendMultipart: async (method, fields, fileField, filePath, fileName) => {
|
|
787
|
+
await callTelegramMultipartApi<TelegramSentMessage>(
|
|
788
|
+
method,
|
|
789
|
+
fields,
|
|
790
|
+
fileField,
|
|
791
|
+
filePath,
|
|
792
|
+
fileName,
|
|
793
|
+
);
|
|
794
|
+
},
|
|
795
|
+
sendTextReply,
|
|
796
|
+
});
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
function extractAssistantText(messages: AgentMessage[]): {
|
|
800
|
+
text?: string;
|
|
801
|
+
stopReason?: string;
|
|
802
|
+
errorMessage?: string;
|
|
803
|
+
} {
|
|
804
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
805
|
+
const message = messages[i] as unknown as Record<string, unknown>;
|
|
806
|
+
if (message.role !== "assistant") continue;
|
|
807
|
+
const stopReason =
|
|
808
|
+
typeof message.stopReason === "string" ? message.stopReason : undefined;
|
|
809
|
+
const errorMessage =
|
|
810
|
+
typeof message.errorMessage === "string"
|
|
811
|
+
? message.errorMessage
|
|
812
|
+
: undefined;
|
|
813
|
+
const text = extractTextContent(message.content);
|
|
814
|
+
return { text: text || undefined, stopReason, errorMessage };
|
|
815
|
+
}
|
|
816
|
+
return {};
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
// --- Bridge Setup ---
|
|
820
|
+
|
|
821
|
+
async function promptForConfig(ctx: ExtensionContext): Promise<void> {
|
|
822
|
+
if (!ctx.hasUI || setupInProgress) return;
|
|
823
|
+
setupInProgress = true;
|
|
824
|
+
try {
|
|
825
|
+
const tokenPrompt = getTelegramBotTokenPromptSpec(
|
|
826
|
+
process.env,
|
|
827
|
+
config.botToken,
|
|
828
|
+
);
|
|
829
|
+
// Use the editor when a real default exists because ctx.ui.input only
|
|
830
|
+
// exposes placeholder text, not an editable prefilled value.
|
|
831
|
+
const token =
|
|
832
|
+
tokenPrompt.method === "editor"
|
|
833
|
+
? await ctx.ui.editor("Telegram bot token", tokenPrompt.value)
|
|
834
|
+
: await ctx.ui.input("Telegram bot token", tokenPrompt.value);
|
|
835
|
+
if (!token) return;
|
|
836
|
+
|
|
837
|
+
const nextConfig: TelegramConfig = { ...config, botToken: token.trim() };
|
|
838
|
+
const response = await fetch(
|
|
839
|
+
`https://api.telegram.org/bot${nextConfig.botToken}/getMe`,
|
|
840
|
+
);
|
|
841
|
+
const data = (await response.json()) as TelegramApiResponse<TelegramUser>;
|
|
842
|
+
if (!data.ok || !data.result) {
|
|
843
|
+
ctx.ui.notify(
|
|
844
|
+
data.description || "Invalid Telegram bot token",
|
|
845
|
+
"error",
|
|
846
|
+
);
|
|
847
|
+
return;
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
nextConfig.botId = data.result.id;
|
|
851
|
+
nextConfig.botUsername = data.result.username;
|
|
852
|
+
config = nextConfig;
|
|
853
|
+
await writeTelegramConfig(AGENT_DIR, CONFIG_PATH, config);
|
|
854
|
+
ctx.ui.notify(
|
|
855
|
+
`Telegram bot connected: @${config.botUsername ?? "unknown"}`,
|
|
856
|
+
"info",
|
|
857
|
+
);
|
|
858
|
+
ctx.ui.notify(
|
|
859
|
+
"Send /start to your bot in Telegram to pair this extension with your account.",
|
|
860
|
+
"info",
|
|
861
|
+
);
|
|
862
|
+
await startPolling(ctx);
|
|
863
|
+
updateStatus(ctx);
|
|
864
|
+
} finally {
|
|
865
|
+
setupInProgress = false;
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
async function registerTelegramBotCommands(): Promise<void> {
|
|
870
|
+
const commands: TelegramBotCommand[] = [
|
|
871
|
+
{
|
|
872
|
+
command: "start",
|
|
873
|
+
description: "Show help and pair the Telegram bridge",
|
|
874
|
+
},
|
|
875
|
+
{
|
|
876
|
+
command: "status",
|
|
877
|
+
description: "Show model, usage, cost, and context status",
|
|
878
|
+
},
|
|
879
|
+
{ command: "model", description: "Open the interactive model selector" },
|
|
880
|
+
{ command: "compact", description: "Compact the current pi session" },
|
|
881
|
+
{ command: "stop", description: "Abort the current pi task" },
|
|
882
|
+
];
|
|
883
|
+
await callTelegramApi<boolean>("setMyCommands", { commands });
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
function getCurrentTelegramModel(
|
|
887
|
+
ctx: ExtensionContext,
|
|
888
|
+
): Model<any> | undefined {
|
|
889
|
+
return currentTelegramModel ?? ctx.model;
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
// --- Interactive Menu State & Builders ---
|
|
893
|
+
|
|
894
|
+
async function getModelMenuState(
|
|
895
|
+
chatId: number,
|
|
896
|
+
ctx: ExtensionContext,
|
|
897
|
+
): Promise<TelegramModelMenuState> {
|
|
898
|
+
const settingsManager = SettingsManager.create(ctx.cwd);
|
|
899
|
+
await settingsManager.reload();
|
|
900
|
+
ctx.modelRegistry.refresh();
|
|
901
|
+
const activeModel = getCurrentTelegramModel(ctx);
|
|
902
|
+
const availableModels = ctx.modelRegistry.getAvailable();
|
|
903
|
+
const cliScopedModels = getCliScopedModelPatterns();
|
|
904
|
+
const configuredScopedModels =
|
|
905
|
+
cliScopedModels ?? settingsManager.getEnabledModels() ?? [];
|
|
906
|
+
return buildTelegramModelMenuState({
|
|
907
|
+
chatId,
|
|
908
|
+
activeModel,
|
|
909
|
+
availableModels,
|
|
910
|
+
configuredScopedModelPatterns: configuredScopedModels,
|
|
911
|
+
cliScopedModelPatterns: cliScopedModels ?? undefined,
|
|
912
|
+
});
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
// --- Interactive Menu Actions ---
|
|
916
|
+
|
|
917
|
+
async function updateModelMenuMessage(
|
|
918
|
+
state: TelegramModelMenuState,
|
|
919
|
+
ctx: ExtensionContext,
|
|
920
|
+
): Promise<void> {
|
|
921
|
+
await updateTelegramModelMenuMessage(state, getCurrentTelegramModel(ctx), {
|
|
922
|
+
editInteractiveMessage,
|
|
923
|
+
sendInteractiveMessage,
|
|
924
|
+
});
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
async function updateThinkingMenuMessage(
|
|
928
|
+
state: TelegramModelMenuState,
|
|
929
|
+
ctx: ExtensionContext,
|
|
930
|
+
): Promise<void> {
|
|
931
|
+
await updateTelegramThinkingMenuMessage(
|
|
932
|
+
state,
|
|
933
|
+
getCurrentTelegramModel(ctx),
|
|
934
|
+
pi.getThinkingLevel(),
|
|
935
|
+
{ editInteractiveMessage, sendInteractiveMessage },
|
|
936
|
+
);
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
async function editInteractiveMessage(
|
|
940
|
+
chatId: number,
|
|
941
|
+
messageId: number,
|
|
942
|
+
text: string,
|
|
943
|
+
mode: TelegramRenderMode,
|
|
944
|
+
replyMarkup: TelegramReplyMarkup,
|
|
945
|
+
): Promise<void> {
|
|
946
|
+
await replyTransport.editRenderedMessage(
|
|
947
|
+
chatId,
|
|
948
|
+
messageId,
|
|
949
|
+
renderTelegramMessage(text, { mode }),
|
|
950
|
+
{ replyMarkup },
|
|
951
|
+
);
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
async function sendInteractiveMessage(
|
|
955
|
+
chatId: number,
|
|
956
|
+
text: string,
|
|
957
|
+
mode: TelegramRenderMode,
|
|
958
|
+
replyMarkup: TelegramReplyMarkup,
|
|
959
|
+
): Promise<number | undefined> {
|
|
960
|
+
return replyTransport.sendRenderedChunks(
|
|
961
|
+
chatId,
|
|
962
|
+
renderTelegramMessage(text, { mode }),
|
|
963
|
+
{ replyMarkup },
|
|
964
|
+
);
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
async function ensureIdleOrNotify(
|
|
968
|
+
ctx: ExtensionContext,
|
|
969
|
+
chatId: number,
|
|
970
|
+
replyToMessageId: number,
|
|
971
|
+
busyMessage: string,
|
|
972
|
+
): Promise<boolean> {
|
|
973
|
+
if (ctx.isIdle()) return true;
|
|
974
|
+
await sendTextReply(chatId, replyToMessageId, busyMessage);
|
|
975
|
+
return false;
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
async function showStatusMessage(
|
|
979
|
+
state: TelegramModelMenuState,
|
|
980
|
+
ctx: ExtensionContext,
|
|
981
|
+
): Promise<void> {
|
|
982
|
+
await updateTelegramStatusMessage(
|
|
983
|
+
state,
|
|
984
|
+
buildStatusHtml(ctx, getCurrentTelegramModel(ctx)),
|
|
985
|
+
getCurrentTelegramModel(ctx),
|
|
986
|
+
pi.getThinkingLevel(),
|
|
987
|
+
{ editInteractiveMessage, sendInteractiveMessage },
|
|
988
|
+
);
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
async function sendStatusMessage(
|
|
992
|
+
chatId: number,
|
|
993
|
+
replyToMessageId: number,
|
|
994
|
+
ctx: ExtensionContext,
|
|
995
|
+
): Promise<void> {
|
|
996
|
+
const isIdle = await ensureIdleOrNotify(
|
|
997
|
+
ctx,
|
|
998
|
+
chatId,
|
|
999
|
+
replyToMessageId,
|
|
1000
|
+
"Cannot open status while pi is busy. Send /stop first.",
|
|
1001
|
+
);
|
|
1002
|
+
if (!isIdle) return;
|
|
1003
|
+
const state = await getModelMenuState(chatId, ctx);
|
|
1004
|
+
const messageId = await sendTelegramStatusMessage(
|
|
1005
|
+
state,
|
|
1006
|
+
buildStatusHtml(ctx, getCurrentTelegramModel(ctx)),
|
|
1007
|
+
getCurrentTelegramModel(ctx),
|
|
1008
|
+
pi.getThinkingLevel(),
|
|
1009
|
+
{ editInteractiveMessage, sendInteractiveMessage },
|
|
1010
|
+
);
|
|
1011
|
+
if (messageId === undefined) return;
|
|
1012
|
+
state.messageId = messageId;
|
|
1013
|
+
state.mode = "status";
|
|
1014
|
+
modelMenus.set(messageId, state);
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
function canOfferInFlightTelegramModelSwitch(ctx: ExtensionContext): boolean {
|
|
1018
|
+
return canRestartTelegramTurnForModelSwitch({
|
|
1019
|
+
isIdle: ctx.isIdle(),
|
|
1020
|
+
hasActiveTelegramTurn: !!activeTelegramTurn,
|
|
1021
|
+
hasAbortHandler: !!currentAbort,
|
|
1022
|
+
});
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
function createTelegramControlItem(
|
|
1026
|
+
chatId: number,
|
|
1027
|
+
replyToMessageId: number,
|
|
1028
|
+
controlType: PendingTelegramControlItem["controlType"],
|
|
1029
|
+
statusSummary: string,
|
|
1030
|
+
execute: PendingTelegramControlItem["execute"],
|
|
1031
|
+
): PendingTelegramControlItem {
|
|
1032
|
+
const queueOrder = nextQueuedTelegramItemOrder++;
|
|
1033
|
+
return {
|
|
1034
|
+
kind: "control",
|
|
1035
|
+
controlType,
|
|
1036
|
+
chatId,
|
|
1037
|
+
replyToMessageId,
|
|
1038
|
+
queueOrder,
|
|
1039
|
+
queueLane: "control",
|
|
1040
|
+
laneOrder: nextQueuedTelegramControlOrder++,
|
|
1041
|
+
statusSummary,
|
|
1042
|
+
execute,
|
|
1043
|
+
};
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
function enqueueTelegramControlItem(
|
|
1047
|
+
item: PendingTelegramControlItem,
|
|
1048
|
+
ctx: ExtensionContext,
|
|
1049
|
+
): void {
|
|
1050
|
+
queuedTelegramItems.push(item);
|
|
1051
|
+
reorderQueuedTelegramTurns(ctx);
|
|
1052
|
+
dispatchNextQueuedTelegramTurn(ctx);
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
function createTelegramModelSwitchContinuationTurn(
|
|
1056
|
+
turn: ActiveTelegramTurn,
|
|
1057
|
+
selection: ScopedTelegramModel,
|
|
1058
|
+
): PendingTelegramTurn {
|
|
1059
|
+
const statusLabel = truncateTelegramQueueSummary(
|
|
1060
|
+
`continue on ${selection.model.id}`,
|
|
1061
|
+
4,
|
|
1062
|
+
32,
|
|
1063
|
+
);
|
|
1064
|
+
return {
|
|
1065
|
+
kind: "prompt",
|
|
1066
|
+
chatId: turn.chatId,
|
|
1067
|
+
replyToMessageId: turn.replyToMessageId,
|
|
1068
|
+
sourceMessageIds: [],
|
|
1069
|
+
queueOrder: nextQueuedTelegramItemOrder++,
|
|
1070
|
+
queueLane: "control",
|
|
1071
|
+
laneOrder: nextQueuedTelegramControlOrder++,
|
|
1072
|
+
queuedAttachments: [],
|
|
1073
|
+
content: [
|
|
1074
|
+
{
|
|
1075
|
+
type: "text",
|
|
1076
|
+
text: buildTelegramModelSwitchContinuationText(
|
|
1077
|
+
TELEGRAM_PREFIX,
|
|
1078
|
+
selection.model,
|
|
1079
|
+
selection.thinkingLevel,
|
|
1080
|
+
),
|
|
1081
|
+
},
|
|
1082
|
+
],
|
|
1083
|
+
historyText: `Continue interrupted Telegram request on ${getCanonicalModelId(selection.model)}`,
|
|
1084
|
+
statusSummary: `↻ ${statusLabel || "continue"}`,
|
|
1085
|
+
};
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
function queueTelegramModelSwitchContinuation(
|
|
1089
|
+
turn: ActiveTelegramTurn,
|
|
1090
|
+
selection: ScopedTelegramModel,
|
|
1091
|
+
ctx: ExtensionContext,
|
|
1092
|
+
): void {
|
|
1093
|
+
queuedTelegramItems.push(
|
|
1094
|
+
createTelegramModelSwitchContinuationTurn(turn, selection),
|
|
1095
|
+
);
|
|
1096
|
+
reorderQueuedTelegramTurns(ctx);
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
function triggerPendingTelegramModelSwitchAbort(
|
|
1100
|
+
ctx: ExtensionContext,
|
|
1101
|
+
): boolean {
|
|
1102
|
+
if (
|
|
1103
|
+
!shouldTriggerPendingTelegramModelSwitchAbort({
|
|
1104
|
+
hasPendingModelSwitch: !!pendingTelegramModelSwitch,
|
|
1105
|
+
hasActiveTelegramTurn: !!activeTelegramTurn,
|
|
1106
|
+
hasAbortHandler: !!currentAbort,
|
|
1107
|
+
activeToolExecutions: activeTelegramToolExecutions,
|
|
1108
|
+
})
|
|
1109
|
+
) {
|
|
1110
|
+
return false;
|
|
1111
|
+
}
|
|
1112
|
+
const selection = pendingTelegramModelSwitch;
|
|
1113
|
+
const turn = activeTelegramTurn;
|
|
1114
|
+
const abort = currentAbort;
|
|
1115
|
+
if (!selection || !turn || !abort) return false;
|
|
1116
|
+
pendingTelegramModelSwitch = undefined;
|
|
1117
|
+
queueTelegramModelSwitchContinuation(turn, selection, ctx);
|
|
1118
|
+
abort();
|
|
1119
|
+
return true;
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
async function openModelMenu(
|
|
1123
|
+
chatId: number,
|
|
1124
|
+
replyToMessageId: number,
|
|
1125
|
+
ctx: ExtensionContext,
|
|
1126
|
+
): Promise<void> {
|
|
1127
|
+
if (!ctx.isIdle() && !canOfferInFlightTelegramModelSwitch(ctx)) {
|
|
1128
|
+
await sendTextReply(
|
|
1129
|
+
chatId,
|
|
1130
|
+
replyToMessageId,
|
|
1131
|
+
"Cannot switch model while pi is busy. Send /stop first.",
|
|
1132
|
+
);
|
|
1133
|
+
return;
|
|
1134
|
+
}
|
|
1135
|
+
const state = await getModelMenuState(chatId, ctx);
|
|
1136
|
+
if (state.allModels.length === 0) {
|
|
1137
|
+
await sendTextReply(
|
|
1138
|
+
chatId,
|
|
1139
|
+
replyToMessageId,
|
|
1140
|
+
"No available models with configured auth.",
|
|
1141
|
+
);
|
|
1142
|
+
return;
|
|
1143
|
+
}
|
|
1144
|
+
const activeModel = getCurrentTelegramModel(ctx);
|
|
1145
|
+
const messageId = await sendTelegramModelMenuMessage(state, activeModel, {
|
|
1146
|
+
editInteractiveMessage,
|
|
1147
|
+
sendInteractiveMessage,
|
|
1148
|
+
});
|
|
1149
|
+
if (messageId === undefined) return;
|
|
1150
|
+
state.messageId = messageId;
|
|
1151
|
+
state.mode = "model";
|
|
1152
|
+
modelMenus.set(messageId, state);
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
async function handleStatusCallbackAction(
|
|
1156
|
+
query: TelegramCallbackQuery,
|
|
1157
|
+
state: TelegramModelMenuState,
|
|
1158
|
+
ctx: ExtensionContext,
|
|
1159
|
+
): Promise<boolean> {
|
|
1160
|
+
return handleTelegramStatusMenuCallbackAction(
|
|
1161
|
+
query.id,
|
|
1162
|
+
query.data,
|
|
1163
|
+
getCurrentTelegramModel(ctx),
|
|
1164
|
+
{
|
|
1165
|
+
updateModelMenuMessage: async () => updateModelMenuMessage(state, ctx),
|
|
1166
|
+
updateThinkingMenuMessage: async () =>
|
|
1167
|
+
updateThinkingMenuMessage(state, ctx),
|
|
1168
|
+
answerCallbackQuery,
|
|
1169
|
+
},
|
|
1170
|
+
);
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
async function handleThinkingCallbackAction(
|
|
1174
|
+
query: TelegramCallbackQuery,
|
|
1175
|
+
state: TelegramModelMenuState,
|
|
1176
|
+
ctx: ExtensionContext,
|
|
1177
|
+
): Promise<boolean> {
|
|
1178
|
+
return handleTelegramThinkingMenuCallbackAction(
|
|
1179
|
+
query.id,
|
|
1180
|
+
query.data,
|
|
1181
|
+
getCurrentTelegramModel(ctx),
|
|
1182
|
+
{
|
|
1183
|
+
setThinkingLevel: (level) => pi.setThinkingLevel(level),
|
|
1184
|
+
getCurrentThinkingLevel: () => pi.getThinkingLevel(),
|
|
1185
|
+
updateStatusMessage: async () => showStatusMessage(state, ctx),
|
|
1186
|
+
answerCallbackQuery,
|
|
1187
|
+
},
|
|
1188
|
+
);
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
async function handleModelCallbackAction(
|
|
1192
|
+
query: TelegramCallbackQuery,
|
|
1193
|
+
state: TelegramModelMenuState,
|
|
1194
|
+
ctx: ExtensionContext,
|
|
1195
|
+
): Promise<boolean> {
|
|
1196
|
+
try {
|
|
1197
|
+
return await handleTelegramModelMenuCallbackAction(
|
|
1198
|
+
query.id,
|
|
1199
|
+
{
|
|
1200
|
+
data: query.data,
|
|
1201
|
+
state,
|
|
1202
|
+
activeModel: getCurrentTelegramModel(ctx),
|
|
1203
|
+
currentThinkingLevel: pi.getThinkingLevel(),
|
|
1204
|
+
isIdle: ctx.isIdle(),
|
|
1205
|
+
canRestartBusyRun: !!activeTelegramTurn && !!currentAbort,
|
|
1206
|
+
hasActiveToolExecutions: activeTelegramToolExecutions > 0,
|
|
1207
|
+
},
|
|
1208
|
+
{
|
|
1209
|
+
updateModelMenuMessage: async () =>
|
|
1210
|
+
updateModelMenuMessage(state, ctx),
|
|
1211
|
+
updateStatusMessage: async () => showStatusMessage(state, ctx),
|
|
1212
|
+
answerCallbackQuery,
|
|
1213
|
+
setModel: (model) => pi.setModel(model),
|
|
1214
|
+
setCurrentModel: (model) => {
|
|
1215
|
+
currentTelegramModel = model;
|
|
1216
|
+
},
|
|
1217
|
+
setThinkingLevel: (level) => pi.setThinkingLevel(level),
|
|
1218
|
+
stagePendingModelSwitch: (selection) => {
|
|
1219
|
+
pendingTelegramModelSwitch = selection;
|
|
1220
|
+
},
|
|
1221
|
+
restartInterruptedTelegramTurn: (selection) => {
|
|
1222
|
+
return restartTelegramModelSwitchContinuation({
|
|
1223
|
+
activeTurn: activeTelegramTurn,
|
|
1224
|
+
abort: currentAbort,
|
|
1225
|
+
selection,
|
|
1226
|
+
queueContinuation: (turn, nextSelection) => {
|
|
1227
|
+
queueTelegramModelSwitchContinuation(turn, nextSelection, ctx);
|
|
1228
|
+
},
|
|
1229
|
+
});
|
|
1230
|
+
},
|
|
1231
|
+
},
|
|
1232
|
+
);
|
|
1233
|
+
} catch (error) {
|
|
1234
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1235
|
+
await answerCallbackQuery(query.id, message);
|
|
1236
|
+
return true;
|
|
1237
|
+
}
|
|
1238
|
+
}
|
|
1239
|
+
|
|
1240
|
+
async function handleAuthorizedTelegramCallbackQuery(
|
|
1241
|
+
query: TelegramCallbackQuery,
|
|
1242
|
+
ctx: ExtensionContext,
|
|
1243
|
+
): Promise<void> {
|
|
1244
|
+
const messageId = query.message?.message_id;
|
|
1245
|
+
await handleTelegramMenuCallbackEntry(
|
|
1246
|
+
query.id,
|
|
1247
|
+
query.data,
|
|
1248
|
+
messageId ? modelMenus.get(messageId) : undefined,
|
|
1249
|
+
{
|
|
1250
|
+
handleStatusAction: async () => {
|
|
1251
|
+
const state = messageId ? modelMenus.get(messageId) : undefined;
|
|
1252
|
+
if (!state) return false;
|
|
1253
|
+
return handleStatusCallbackAction(query, state, ctx);
|
|
1254
|
+
},
|
|
1255
|
+
handleThinkingAction: async () => {
|
|
1256
|
+
const state = messageId ? modelMenus.get(messageId) : undefined;
|
|
1257
|
+
if (!state) return false;
|
|
1258
|
+
return handleThinkingCallbackAction(query, state, ctx);
|
|
1259
|
+
},
|
|
1260
|
+
handleModelAction: async () => {
|
|
1261
|
+
const state = messageId ? modelMenus.get(messageId) : undefined;
|
|
1262
|
+
if (!state) return false;
|
|
1263
|
+
return handleModelCallbackAction(query, state, ctx);
|
|
1264
|
+
},
|
|
1265
|
+
answerCallbackQuery,
|
|
1266
|
+
},
|
|
1267
|
+
);
|
|
1268
|
+
}
|
|
1269
|
+
|
|
1270
|
+
// --- Status Rendering ---
|
|
1271
|
+
|
|
1272
|
+
// --- Turn Queue & Message Dispatch ---
|
|
1273
|
+
|
|
1274
|
+
async function buildTelegramFiles(
|
|
1275
|
+
messages: TelegramMessage[],
|
|
1276
|
+
): Promise<DownloadedTelegramFile[]> {
|
|
1277
|
+
const downloaded: DownloadedTelegramFile[] = [];
|
|
1278
|
+
for (const file of collectTelegramFileInfos(messages)) {
|
|
1279
|
+
const path = await downloadTelegramBridgeFile(
|
|
1280
|
+
file.file_id,
|
|
1281
|
+
file.fileName,
|
|
1282
|
+
);
|
|
1283
|
+
downloaded.push({
|
|
1284
|
+
path,
|
|
1285
|
+
fileName: file.fileName,
|
|
1286
|
+
isImage: file.isImage,
|
|
1287
|
+
mimeType: file.mimeType,
|
|
1288
|
+
});
|
|
1289
|
+
}
|
|
1290
|
+
return downloaded;
|
|
1291
|
+
}
|
|
1292
|
+
|
|
1293
|
+
function reorderQueuedTelegramTurns(ctx: ExtensionContext): void {
|
|
1294
|
+
queuedTelegramItems.sort(compareTelegramQueueItems);
|
|
1295
|
+
updateStatus(ctx);
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
function removePendingMediaGroupMessages(messageIds: number[]): void {
|
|
1299
|
+
if (messageIds.length === 0 || mediaGroups.size === 0) return;
|
|
1300
|
+
const deletedMessageIds = new Set(messageIds);
|
|
1301
|
+
for (const [key, state] of mediaGroups.entries()) {
|
|
1302
|
+
if (
|
|
1303
|
+
!state.messages.some((message) =>
|
|
1304
|
+
deletedMessageIds.has(message.message_id),
|
|
1305
|
+
)
|
|
1306
|
+
) {
|
|
1307
|
+
continue;
|
|
1308
|
+
}
|
|
1309
|
+
if (state.flushTimer) clearTimeout(state.flushTimer);
|
|
1310
|
+
mediaGroups.delete(key);
|
|
1311
|
+
}
|
|
1312
|
+
}
|
|
1313
|
+
|
|
1314
|
+
function removeQueuedTelegramTurnsByMessageIds(
|
|
1315
|
+
messageIds: number[],
|
|
1316
|
+
ctx: ExtensionContext,
|
|
1317
|
+
): number {
|
|
1318
|
+
const result = removeTelegramQueueItemsByMessageIds(
|
|
1319
|
+
queuedTelegramItems,
|
|
1320
|
+
messageIds,
|
|
1321
|
+
);
|
|
1322
|
+
if (result.removedCount === 0) return 0;
|
|
1323
|
+
queuedTelegramItems = result.items;
|
|
1324
|
+
updateStatus(ctx);
|
|
1325
|
+
return result.removedCount;
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
function clearQueuedTelegramTurnPriorityByMessageId(
|
|
1329
|
+
messageId: number,
|
|
1330
|
+
ctx: ExtensionContext,
|
|
1331
|
+
): boolean {
|
|
1332
|
+
const result = clearTelegramQueuePromptPriority(
|
|
1333
|
+
queuedTelegramItems,
|
|
1334
|
+
messageId,
|
|
1335
|
+
);
|
|
1336
|
+
if (!result.changed) return false;
|
|
1337
|
+
queuedTelegramItems = result.items;
|
|
1338
|
+
reorderQueuedTelegramTurns(ctx);
|
|
1339
|
+
return true;
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1342
|
+
function prioritizeQueuedTelegramTurnByMessageId(
|
|
1343
|
+
messageId: number,
|
|
1344
|
+
ctx: ExtensionContext,
|
|
1345
|
+
): boolean {
|
|
1346
|
+
const result = prioritizeTelegramQueuePrompt(
|
|
1347
|
+
queuedTelegramItems,
|
|
1348
|
+
messageId,
|
|
1349
|
+
nextPriorityReactionOrder,
|
|
1350
|
+
);
|
|
1351
|
+
if (!result.changed) return false;
|
|
1352
|
+
queuedTelegramItems = result.items;
|
|
1353
|
+
nextPriorityReactionOrder += 1;
|
|
1354
|
+
reorderQueuedTelegramTurns(ctx);
|
|
1355
|
+
return true;
|
|
1356
|
+
}
|
|
1357
|
+
|
|
1358
|
+
async function handleAuthorizedTelegramReactionUpdate(
|
|
1359
|
+
reactionUpdate: TelegramMessageReactionUpdated,
|
|
1360
|
+
ctx: ExtensionContext,
|
|
1361
|
+
): Promise<void> {
|
|
1362
|
+
const reactionUser = reactionUpdate.user;
|
|
1363
|
+
if (
|
|
1364
|
+
reactionUpdate.chat.type !== "private" ||
|
|
1365
|
+
!reactionUser ||
|
|
1366
|
+
reactionUser.is_bot ||
|
|
1367
|
+
reactionUser.id !== config.allowedUserId
|
|
1368
|
+
) {
|
|
1369
|
+
return;
|
|
1370
|
+
}
|
|
1371
|
+
const oldEmojis = collectTelegramReactionEmojis(
|
|
1372
|
+
reactionUpdate.old_reaction,
|
|
1373
|
+
);
|
|
1374
|
+
const newEmojis = collectTelegramReactionEmojis(
|
|
1375
|
+
reactionUpdate.new_reaction,
|
|
1376
|
+
);
|
|
1377
|
+
const dislikeAdded = !oldEmojis.has("👎") && newEmojis.has("👎");
|
|
1378
|
+
if (dislikeAdded) {
|
|
1379
|
+
removePendingMediaGroupMessages([reactionUpdate.message_id]);
|
|
1380
|
+
removeQueuedTelegramTurnsByMessageIds([reactionUpdate.message_id], ctx);
|
|
1381
|
+
return;
|
|
1382
|
+
}
|
|
1383
|
+
const likeRemoved = oldEmojis.has("👍") && !newEmojis.has("👍");
|
|
1384
|
+
if (likeRemoved) {
|
|
1385
|
+
clearQueuedTelegramTurnPriorityByMessageId(
|
|
1386
|
+
reactionUpdate.message_id,
|
|
1387
|
+
ctx,
|
|
1388
|
+
);
|
|
1389
|
+
}
|
|
1390
|
+
const likeAdded = !oldEmojis.has("👍") && newEmojis.has("👍");
|
|
1391
|
+
if (!likeAdded) return;
|
|
1392
|
+
prioritizeQueuedTelegramTurnByMessageId(reactionUpdate.message_id, ctx);
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1395
|
+
async function createTelegramTurn(
|
|
1396
|
+
messages: TelegramMessage[],
|
|
1397
|
+
historyTurns: PendingTelegramTurn[] = [],
|
|
1398
|
+
): Promise<PendingTelegramTurn> {
|
|
1399
|
+
return buildTelegramPromptTurn({
|
|
1400
|
+
telegramPrefix: TELEGRAM_PREFIX,
|
|
1401
|
+
messages,
|
|
1402
|
+
historyTurns,
|
|
1403
|
+
queueOrder: nextQueuedTelegramItemOrder++,
|
|
1404
|
+
rawText: extractTelegramMessagesText(messages),
|
|
1405
|
+
files: await buildTelegramFiles(messages),
|
|
1406
|
+
readBinaryFile: async (path) => readFile(path),
|
|
1407
|
+
inferImageMimeType: guessMediaType,
|
|
1408
|
+
});
|
|
1409
|
+
}
|
|
1410
|
+
|
|
1411
|
+
async function handleStopCommand(
|
|
1412
|
+
message: TelegramMessage,
|
|
1413
|
+
ctx: ExtensionContext,
|
|
1414
|
+
): Promise<void> {
|
|
1415
|
+
if (currentAbort) {
|
|
1416
|
+
pendingTelegramModelSwitch = undefined;
|
|
1417
|
+
if (queuedTelegramItems.length > 0) {
|
|
1418
|
+
preserveQueuedTurnsAsHistory = true;
|
|
1419
|
+
}
|
|
1420
|
+
currentAbort();
|
|
1421
|
+
updateStatus(ctx);
|
|
1422
|
+
await sendTextReply(
|
|
1423
|
+
message.chat.id,
|
|
1424
|
+
message.message_id,
|
|
1425
|
+
"Aborted current turn.",
|
|
1426
|
+
);
|
|
1427
|
+
return;
|
|
1428
|
+
}
|
|
1429
|
+
await sendTextReply(message.chat.id, message.message_id, "No active turn.");
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1432
|
+
async function handleCompactCommand(
|
|
1433
|
+
message: TelegramMessage,
|
|
1434
|
+
ctx: ExtensionContext,
|
|
1435
|
+
): Promise<void> {
|
|
1436
|
+
if (
|
|
1437
|
+
!ctx.isIdle() ||
|
|
1438
|
+
ctx.hasPendingMessages() ||
|
|
1439
|
+
activeTelegramTurn ||
|
|
1440
|
+
telegramTurnDispatchPending ||
|
|
1441
|
+
queuedTelegramItems.length > 0 ||
|
|
1442
|
+
compactionInProgress
|
|
1443
|
+
) {
|
|
1444
|
+
await sendTextReply(
|
|
1445
|
+
message.chat.id,
|
|
1446
|
+
message.message_id,
|
|
1447
|
+
"Cannot compact while pi or the Telegram queue is busy. Wait for queued turns to finish or send /stop first.",
|
|
1448
|
+
);
|
|
1449
|
+
return;
|
|
1450
|
+
}
|
|
1451
|
+
compactionInProgress = true;
|
|
1452
|
+
updateStatus(ctx);
|
|
1453
|
+
try {
|
|
1454
|
+
ctx.compact({
|
|
1455
|
+
onComplete: () => {
|
|
1456
|
+
compactionInProgress = false;
|
|
1457
|
+
updateStatus(ctx);
|
|
1458
|
+
dispatchNextQueuedTelegramTurn(ctx);
|
|
1459
|
+
void sendTextReply(
|
|
1460
|
+
message.chat.id,
|
|
1461
|
+
message.message_id,
|
|
1462
|
+
"Compaction completed.",
|
|
1463
|
+
);
|
|
1464
|
+
},
|
|
1465
|
+
onError: (error) => {
|
|
1466
|
+
compactionInProgress = false;
|
|
1467
|
+
updateStatus(ctx);
|
|
1468
|
+
dispatchNextQueuedTelegramTurn(ctx);
|
|
1469
|
+
const errorMessage =
|
|
1470
|
+
error instanceof Error ? error.message : String(error);
|
|
1471
|
+
void sendTextReply(
|
|
1472
|
+
message.chat.id,
|
|
1473
|
+
message.message_id,
|
|
1474
|
+
`Compaction failed: ${errorMessage}`,
|
|
1475
|
+
);
|
|
1476
|
+
},
|
|
1477
|
+
});
|
|
1478
|
+
} catch (error) {
|
|
1479
|
+
compactionInProgress = false;
|
|
1480
|
+
updateStatus(ctx);
|
|
1481
|
+
const errorMessage =
|
|
1482
|
+
error instanceof Error ? error.message : String(error);
|
|
1483
|
+
await sendTextReply(
|
|
1484
|
+
message.chat.id,
|
|
1485
|
+
message.message_id,
|
|
1486
|
+
`Compaction failed: ${errorMessage}`,
|
|
1487
|
+
);
|
|
1488
|
+
return;
|
|
1489
|
+
}
|
|
1490
|
+
await sendTextReply(
|
|
1491
|
+
message.chat.id,
|
|
1492
|
+
message.message_id,
|
|
1493
|
+
"Compaction started.",
|
|
1494
|
+
);
|
|
1495
|
+
}
|
|
1496
|
+
|
|
1497
|
+
async function handleStatusCommand(
|
|
1498
|
+
message: TelegramMessage,
|
|
1499
|
+
ctx: ExtensionContext,
|
|
1500
|
+
): Promise<void> {
|
|
1501
|
+
enqueueTelegramControlItem(
|
|
1502
|
+
createTelegramControlItem(
|
|
1503
|
+
message.chat.id,
|
|
1504
|
+
message.message_id,
|
|
1505
|
+
"status",
|
|
1506
|
+
"⚡ status",
|
|
1507
|
+
async (controlCtx) => {
|
|
1508
|
+
await sendStatusMessage(
|
|
1509
|
+
message.chat.id,
|
|
1510
|
+
message.message_id,
|
|
1511
|
+
controlCtx,
|
|
1512
|
+
);
|
|
1513
|
+
},
|
|
1514
|
+
),
|
|
1515
|
+
ctx,
|
|
1516
|
+
);
|
|
1517
|
+
}
|
|
1518
|
+
|
|
1519
|
+
async function handleModelCommand(
|
|
1520
|
+
message: TelegramMessage,
|
|
1521
|
+
ctx: ExtensionContext,
|
|
1522
|
+
): Promise<void> {
|
|
1523
|
+
enqueueTelegramControlItem(
|
|
1524
|
+
createTelegramControlItem(
|
|
1525
|
+
message.chat.id,
|
|
1526
|
+
message.message_id,
|
|
1527
|
+
"model",
|
|
1528
|
+
"⚡ model",
|
|
1529
|
+
async (controlCtx) => {
|
|
1530
|
+
await openModelMenu(message.chat.id, message.message_id, controlCtx);
|
|
1531
|
+
},
|
|
1532
|
+
),
|
|
1533
|
+
ctx,
|
|
1534
|
+
);
|
|
1535
|
+
}
|
|
1536
|
+
|
|
1537
|
+
async function handleHelpCommand(
|
|
1538
|
+
message: TelegramMessage,
|
|
1539
|
+
commandName: string,
|
|
1540
|
+
ctx: ExtensionContext,
|
|
1541
|
+
): Promise<void> {
|
|
1542
|
+
let helpText =
|
|
1543
|
+
"Send me a message and I will forward it to pi. Commands: /status, /model, /compact, /stop.";
|
|
1544
|
+
if (commandName === "start") {
|
|
1545
|
+
try {
|
|
1546
|
+
await registerTelegramBotCommands();
|
|
1547
|
+
} catch (error) {
|
|
1548
|
+
const errorMessage =
|
|
1549
|
+
error instanceof Error ? error.message : String(error);
|
|
1550
|
+
helpText += `\n\nWarning: failed to register bot commands menu: ${errorMessage}`;
|
|
1551
|
+
}
|
|
1552
|
+
}
|
|
1553
|
+
await sendTextReply(message.chat.id, message.message_id, helpText);
|
|
1554
|
+
if (config.allowedUserId === undefined && message.from) {
|
|
1555
|
+
config.allowedUserId = message.from.id;
|
|
1556
|
+
await writeTelegramConfig(AGENT_DIR, CONFIG_PATH, config);
|
|
1557
|
+
updateStatus(ctx);
|
|
1558
|
+
}
|
|
1559
|
+
}
|
|
1560
|
+
|
|
1561
|
+
async function handleTelegramCommand(
|
|
1562
|
+
commandName: string | undefined,
|
|
1563
|
+
message: TelegramMessage,
|
|
1564
|
+
ctx: ExtensionContext,
|
|
1565
|
+
): Promise<boolean> {
|
|
1566
|
+
if (!commandName) return false;
|
|
1567
|
+
const handlers: Partial<Record<string, () => Promise<void>>> = {
|
|
1568
|
+
stop: () => handleStopCommand(message, ctx),
|
|
1569
|
+
compact: () => handleCompactCommand(message, ctx),
|
|
1570
|
+
status: () => handleStatusCommand(message, ctx),
|
|
1571
|
+
model: () => handleModelCommand(message, ctx),
|
|
1572
|
+
help: () => handleHelpCommand(message, commandName, ctx),
|
|
1573
|
+
start: () => handleHelpCommand(message, commandName, ctx),
|
|
1574
|
+
};
|
|
1575
|
+
const handler = handlers[commandName];
|
|
1576
|
+
if (!handler) return false;
|
|
1577
|
+
await handler();
|
|
1578
|
+
return true;
|
|
1579
|
+
}
|
|
1580
|
+
|
|
1581
|
+
async function enqueueTelegramTurn(
|
|
1582
|
+
messages: TelegramMessage[],
|
|
1583
|
+
ctx: ExtensionContext,
|
|
1584
|
+
): Promise<void> {
|
|
1585
|
+
const historyResult = preserveQueuedTurnsAsHistory
|
|
1586
|
+
? partitionTelegramQueueItemsForHistory(queuedTelegramItems)
|
|
1587
|
+
: { historyTurns: [], remainingItems: queuedTelegramItems };
|
|
1588
|
+
queuedTelegramItems = historyResult.remainingItems;
|
|
1589
|
+
preserveQueuedTurnsAsHistory = false;
|
|
1590
|
+
const turn = await createTelegramTurn(messages, historyResult.historyTurns);
|
|
1591
|
+
queuedTelegramItems.push(turn);
|
|
1592
|
+
updateStatus(ctx);
|
|
1593
|
+
dispatchNextQueuedTelegramTurn(ctx);
|
|
1594
|
+
}
|
|
1595
|
+
|
|
1596
|
+
async function dispatchAuthorizedTelegramMessages(
|
|
1597
|
+
messages: TelegramMessage[],
|
|
1598
|
+
ctx: ExtensionContext,
|
|
1599
|
+
): Promise<void> {
|
|
1600
|
+
const firstMessage = messages[0];
|
|
1601
|
+
if (!firstMessage) return;
|
|
1602
|
+
const rawText = extractFirstTelegramMessageText(messages);
|
|
1603
|
+
const commandName = parseTelegramCommand(rawText)?.name;
|
|
1604
|
+
const handled = await handleTelegramCommand(commandName, firstMessage, ctx);
|
|
1605
|
+
if (handled) return;
|
|
1606
|
+
await enqueueTelegramTurn(messages, ctx);
|
|
1607
|
+
}
|
|
1608
|
+
|
|
1609
|
+
async function handleAuthorizedTelegramMessage(
|
|
1610
|
+
message: TelegramMessage,
|
|
1611
|
+
ctx: ExtensionContext,
|
|
1612
|
+
): Promise<void> {
|
|
1613
|
+
if (message.media_group_id) {
|
|
1614
|
+
const key = `${message.chat.id}:${message.media_group_id}`;
|
|
1615
|
+
const existing = mediaGroups.get(key) ?? { messages: [] };
|
|
1616
|
+
existing.messages.push(message);
|
|
1617
|
+
if (existing.flushTimer) clearTimeout(existing.flushTimer);
|
|
1618
|
+
existing.flushTimer = setTimeout(() => {
|
|
1619
|
+
const state = mediaGroups.get(key);
|
|
1620
|
+
mediaGroups.delete(key);
|
|
1621
|
+
if (!state) return;
|
|
1622
|
+
void dispatchAuthorizedTelegramMessages(state.messages, ctx);
|
|
1623
|
+
}, TELEGRAM_MEDIA_GROUP_DEBOUNCE_MS);
|
|
1624
|
+
mediaGroups.set(key, existing);
|
|
1625
|
+
return;
|
|
1626
|
+
}
|
|
1627
|
+
|
|
1628
|
+
await dispatchAuthorizedTelegramMessages([message], ctx);
|
|
1629
|
+
}
|
|
1630
|
+
|
|
1631
|
+
async function pairTelegramUserIfNeeded(
|
|
1632
|
+
userId: number,
|
|
1633
|
+
ctx: ExtensionContext,
|
|
1634
|
+
): Promise<boolean> {
|
|
1635
|
+
const authorization = getTelegramAuthorizationState(
|
|
1636
|
+
userId,
|
|
1637
|
+
config.allowedUserId,
|
|
1638
|
+
);
|
|
1639
|
+
if (authorization.kind !== "pair") return false;
|
|
1640
|
+
config.allowedUserId = authorization.userId;
|
|
1641
|
+
await writeTelegramConfig(AGENT_DIR, CONFIG_PATH, config);
|
|
1642
|
+
updateStatus(ctx);
|
|
1643
|
+
return true;
|
|
1644
|
+
}
|
|
1645
|
+
|
|
1646
|
+
async function handleUpdate(
|
|
1647
|
+
update: TelegramUpdate,
|
|
1648
|
+
ctx: ExtensionContext,
|
|
1649
|
+
): Promise<void> {
|
|
1650
|
+
await executeTelegramUpdate(update, config.allowedUserId, {
|
|
1651
|
+
ctx,
|
|
1652
|
+
removePendingMediaGroupMessages,
|
|
1653
|
+
removeQueuedTelegramTurnsByMessageIds,
|
|
1654
|
+
handleAuthorizedTelegramReactionUpdate: async (
|
|
1655
|
+
reactionUpdate,
|
|
1656
|
+
nextCtx,
|
|
1657
|
+
) => {
|
|
1658
|
+
await handleAuthorizedTelegramReactionUpdate(
|
|
1659
|
+
reactionUpdate as TelegramMessageReactionUpdated,
|
|
1660
|
+
nextCtx,
|
|
1661
|
+
);
|
|
1662
|
+
},
|
|
1663
|
+
pairTelegramUserIfNeeded,
|
|
1664
|
+
answerCallbackQuery,
|
|
1665
|
+
handleAuthorizedTelegramCallbackQuery: async (query, nextCtx) => {
|
|
1666
|
+
await handleAuthorizedTelegramCallbackQuery(
|
|
1667
|
+
query as TelegramCallbackQuery,
|
|
1668
|
+
nextCtx,
|
|
1669
|
+
);
|
|
1670
|
+
},
|
|
1671
|
+
sendTextReply,
|
|
1672
|
+
handleAuthorizedTelegramMessage: async (message, nextCtx) => {
|
|
1673
|
+
await handleAuthorizedTelegramMessage(
|
|
1674
|
+
message as TelegramMessage,
|
|
1675
|
+
nextCtx,
|
|
1676
|
+
);
|
|
1677
|
+
},
|
|
1678
|
+
});
|
|
1679
|
+
}
|
|
1680
|
+
|
|
1681
|
+
// --- Polling ---
|
|
1682
|
+
|
|
1683
|
+
async function stopPolling(): Promise<void> {
|
|
1684
|
+
stopTypingLoop();
|
|
1685
|
+
pollingController?.abort();
|
|
1686
|
+
pollingController = undefined;
|
|
1687
|
+
await pollingPromise?.catch(() => undefined);
|
|
1688
|
+
pollingPromise = undefined;
|
|
1689
|
+
}
|
|
1690
|
+
|
|
1691
|
+
async function pollLoop(
|
|
1692
|
+
ctx: ExtensionContext,
|
|
1693
|
+
signal: AbortSignal,
|
|
1694
|
+
): Promise<void> {
|
|
1695
|
+
await runTelegramPollLoop<TelegramUpdate>({
|
|
1696
|
+
ctx,
|
|
1697
|
+
signal,
|
|
1698
|
+
config,
|
|
1699
|
+
deleteWebhook: async (pollSignal) => {
|
|
1700
|
+
await callTelegramApi(
|
|
1701
|
+
"deleteWebhook",
|
|
1702
|
+
{ drop_pending_updates: false },
|
|
1703
|
+
{ signal: pollSignal },
|
|
1704
|
+
);
|
|
1705
|
+
},
|
|
1706
|
+
getUpdates: async (body, pollSignal) => {
|
|
1707
|
+
return callTelegramApi<TelegramUpdate[]>("getUpdates", body, {
|
|
1708
|
+
signal: pollSignal,
|
|
1709
|
+
});
|
|
1710
|
+
},
|
|
1711
|
+
persistConfig: async () => {
|
|
1712
|
+
await writeTelegramConfig(AGENT_DIR, CONFIG_PATH, config);
|
|
1713
|
+
},
|
|
1714
|
+
handleUpdate: async (update, loopCtx) => {
|
|
1715
|
+
await handleUpdate(update, loopCtx);
|
|
1716
|
+
},
|
|
1717
|
+
onErrorStatus: (message) => {
|
|
1718
|
+
updateStatus(ctx, message);
|
|
1719
|
+
},
|
|
1720
|
+
onStatusReset: () => {
|
|
1721
|
+
updateStatus(ctx);
|
|
1722
|
+
},
|
|
1723
|
+
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
1724
|
+
});
|
|
1725
|
+
}
|
|
1726
|
+
|
|
1727
|
+
async function startPolling(ctx: ExtensionContext): Promise<void> {
|
|
1728
|
+
if (
|
|
1729
|
+
!shouldStartTelegramPolling({
|
|
1730
|
+
hasBotToken: !!config.botToken,
|
|
1731
|
+
hasPollingPromise: !!pollingPromise,
|
|
1732
|
+
})
|
|
1733
|
+
) {
|
|
1734
|
+
return;
|
|
1735
|
+
}
|
|
1736
|
+
pollingController = new AbortController();
|
|
1737
|
+
pollingPromise = pollLoop(ctx, pollingController.signal).finally(() => {
|
|
1738
|
+
pollingPromise = undefined;
|
|
1739
|
+
pollingController = undefined;
|
|
1740
|
+
updateStatus(ctx);
|
|
1741
|
+
});
|
|
1742
|
+
updateStatus(ctx);
|
|
1743
|
+
}
|
|
1744
|
+
|
|
1745
|
+
// --- Extension Registration ---
|
|
1746
|
+
|
|
1747
|
+
registerTelegramAttachmentTool(pi, {
|
|
1748
|
+
maxAttachmentsPerTurn: MAX_ATTACHMENTS_PER_TURN,
|
|
1749
|
+
getActiveTurn: () => activeTelegramTurn,
|
|
1750
|
+
statPath: stat,
|
|
1751
|
+
});
|
|
1752
|
+
|
|
1753
|
+
registerTelegramCommands(pi, {
|
|
1754
|
+
promptForConfig,
|
|
1755
|
+
getStatusLines: () => {
|
|
1756
|
+
return [
|
|
1757
|
+
`bot: ${config.botUsername ? `@${config.botUsername}` : "not configured"}`,
|
|
1758
|
+
`allowed user: ${config.allowedUserId ?? "not paired"}`,
|
|
1759
|
+
`polling: ${pollingPromise ? "running" : "stopped"}`,
|
|
1760
|
+
`active telegram turn: ${activeTelegramTurn ? "yes" : "no"}`,
|
|
1761
|
+
`queued telegram turns: ${queuedTelegramItems.length}`,
|
|
1762
|
+
];
|
|
1763
|
+
},
|
|
1764
|
+
reloadConfig: async () => {
|
|
1765
|
+
config = await readTelegramConfig(CONFIG_PATH);
|
|
1766
|
+
},
|
|
1767
|
+
hasBotToken: () => !!config.botToken,
|
|
1768
|
+
startPolling,
|
|
1769
|
+
stopPolling,
|
|
1770
|
+
updateStatus,
|
|
1771
|
+
});
|
|
1772
|
+
|
|
1773
|
+
// --- Lifecycle Hooks ---
|
|
1774
|
+
|
|
1775
|
+
registerTelegramLifecycleHooks(pi, {
|
|
1776
|
+
onSessionStart: async (_event, ctx) => {
|
|
1777
|
+
config = await readTelegramConfig(CONFIG_PATH);
|
|
1778
|
+
const sessionStartState = buildTelegramSessionStartState(ctx.model);
|
|
1779
|
+
currentTelegramModel = sessionStartState.currentTelegramModel;
|
|
1780
|
+
activeTelegramToolExecutions =
|
|
1781
|
+
sessionStartState.activeTelegramToolExecutions;
|
|
1782
|
+
pendingTelegramModelSwitch = sessionStartState.pendingTelegramModelSwitch;
|
|
1783
|
+
nextQueuedTelegramItemOrder =
|
|
1784
|
+
sessionStartState.nextQueuedTelegramItemOrder;
|
|
1785
|
+
nextQueuedTelegramControlOrder =
|
|
1786
|
+
sessionStartState.nextQueuedTelegramControlOrder;
|
|
1787
|
+
telegramTurnDispatchPending =
|
|
1788
|
+
sessionStartState.telegramTurnDispatchPending;
|
|
1789
|
+
compactionInProgress = sessionStartState.compactionInProgress;
|
|
1790
|
+
await mkdir(TEMP_DIR, { recursive: true });
|
|
1791
|
+
updateStatus(ctx);
|
|
1792
|
+
},
|
|
1793
|
+
onSessionShutdown: async (_event, _ctx) => {
|
|
1794
|
+
const shutdownState =
|
|
1795
|
+
buildTelegramSessionShutdownState<TelegramQueueItem>();
|
|
1796
|
+
queuedTelegramItems = shutdownState.queuedTelegramItems;
|
|
1797
|
+
nextQueuedTelegramItemOrder = shutdownState.nextQueuedTelegramItemOrder;
|
|
1798
|
+
nextQueuedTelegramControlOrder =
|
|
1799
|
+
shutdownState.nextQueuedTelegramControlOrder;
|
|
1800
|
+
nextPriorityReactionOrder = shutdownState.nextPriorityReactionOrder;
|
|
1801
|
+
currentTelegramModel = shutdownState.currentTelegramModel;
|
|
1802
|
+
activeTelegramToolExecutions = shutdownState.activeTelegramToolExecutions;
|
|
1803
|
+
pendingTelegramModelSwitch = shutdownState.pendingTelegramModelSwitch;
|
|
1804
|
+
telegramTurnDispatchPending = shutdownState.telegramTurnDispatchPending;
|
|
1805
|
+
compactionInProgress = shutdownState.compactionInProgress;
|
|
1806
|
+
for (const state of mediaGroups.values()) {
|
|
1807
|
+
if (state.flushTimer) clearTimeout(state.flushTimer);
|
|
1808
|
+
}
|
|
1809
|
+
mediaGroups.clear();
|
|
1810
|
+
modelMenus.clear();
|
|
1811
|
+
if (activeTelegramTurn) {
|
|
1812
|
+
await clearPreview(activeTelegramTurn.chatId);
|
|
1813
|
+
}
|
|
1814
|
+
activeTelegramTurn = undefined;
|
|
1815
|
+
currentAbort = undefined;
|
|
1816
|
+
preserveQueuedTurnsAsHistory = false;
|
|
1817
|
+
await stopPolling();
|
|
1818
|
+
},
|
|
1819
|
+
onBeforeAgentStart: (event) => {
|
|
1820
|
+
const nextEvent = event as { prompt: string; systemPrompt: string };
|
|
1821
|
+
const suffix = isTelegramPrompt(nextEvent.prompt)
|
|
1822
|
+
? `${SYSTEM_PROMPT_SUFFIX}\n- The current user message came from Telegram.`
|
|
1823
|
+
: SYSTEM_PROMPT_SUFFIX;
|
|
1824
|
+
return {
|
|
1825
|
+
systemPrompt: nextEvent.systemPrompt + suffix,
|
|
1826
|
+
};
|
|
1827
|
+
},
|
|
1828
|
+
onModelSelect: (event) => {
|
|
1829
|
+
currentTelegramModel = (event as { model: Model<any> }).model;
|
|
1830
|
+
},
|
|
1831
|
+
onAgentStart: async (_event, ctx) => {
|
|
1832
|
+
currentAbort = () => ctx.abort();
|
|
1833
|
+
const startPlan = buildTelegramAgentStartPlan({
|
|
1834
|
+
queuedItems: queuedTelegramItems,
|
|
1835
|
+
hasPendingDispatch: telegramTurnDispatchPending,
|
|
1836
|
+
hasActiveTurn: !!activeTelegramTurn,
|
|
1837
|
+
});
|
|
1838
|
+
if (startPlan.shouldResetToolExecutions) {
|
|
1839
|
+
activeTelegramToolExecutions = 0;
|
|
1840
|
+
}
|
|
1841
|
+
if (startPlan.shouldResetPendingModelSwitch) {
|
|
1842
|
+
pendingTelegramModelSwitch = undefined;
|
|
1843
|
+
}
|
|
1844
|
+
queuedTelegramItems = startPlan.remainingItems;
|
|
1845
|
+
if (startPlan.shouldClearDispatchPending) {
|
|
1846
|
+
telegramTurnDispatchPending = false;
|
|
1847
|
+
}
|
|
1848
|
+
if (startPlan.activeTurn) {
|
|
1849
|
+
activeTelegramTurn = { ...startPlan.activeTurn };
|
|
1850
|
+
previewState = createPreviewState();
|
|
1851
|
+
startTypingLoop(ctx);
|
|
1852
|
+
}
|
|
1853
|
+
updateStatus(ctx);
|
|
1854
|
+
},
|
|
1855
|
+
onToolExecutionStart: () => {
|
|
1856
|
+
activeTelegramToolExecutions = getNextTelegramToolExecutionCount({
|
|
1857
|
+
hasActiveTurn: !!activeTelegramTurn,
|
|
1858
|
+
currentCount: activeTelegramToolExecutions,
|
|
1859
|
+
event: "start",
|
|
1860
|
+
});
|
|
1861
|
+
},
|
|
1862
|
+
onToolExecutionEnd: (_event, ctx) => {
|
|
1863
|
+
activeTelegramToolExecutions = getNextTelegramToolExecutionCount({
|
|
1864
|
+
hasActiveTurn: !!activeTelegramTurn,
|
|
1865
|
+
currentCount: activeTelegramToolExecutions,
|
|
1866
|
+
event: "end",
|
|
1867
|
+
});
|
|
1868
|
+
if (!activeTelegramTurn) return;
|
|
1869
|
+
triggerPendingTelegramModelSwitchAbort(ctx);
|
|
1870
|
+
},
|
|
1871
|
+
onMessageStart: async (event, _ctx) => {
|
|
1872
|
+
const nextEvent = event as { message: AgentMessage };
|
|
1873
|
+
if (!activeTelegramTurn || !isAssistantMessage(nextEvent.message)) return;
|
|
1874
|
+
if (
|
|
1875
|
+
previewState &&
|
|
1876
|
+
(previewState.pendingText.trim().length > 0 ||
|
|
1877
|
+
previewState.lastSentText.trim().length > 0)
|
|
1878
|
+
) {
|
|
1879
|
+
const previousText = previewState.pendingText.trim();
|
|
1880
|
+
if (previousText.length > 0) {
|
|
1881
|
+
await finalizeMarkdownPreview(
|
|
1882
|
+
activeTelegramTurn.chatId,
|
|
1883
|
+
previousText,
|
|
1884
|
+
);
|
|
1885
|
+
} else {
|
|
1886
|
+
await finalizePreview(activeTelegramTurn.chatId);
|
|
1887
|
+
}
|
|
1888
|
+
}
|
|
1889
|
+
previewState = createPreviewState();
|
|
1890
|
+
},
|
|
1891
|
+
onMessageUpdate: async (event, _ctx) => {
|
|
1892
|
+
const nextEvent = event as { message: AgentMessage };
|
|
1893
|
+
if (!activeTelegramTurn || !isAssistantMessage(nextEvent.message)) return;
|
|
1894
|
+
if (!previewState) {
|
|
1895
|
+
previewState = createPreviewState();
|
|
1896
|
+
}
|
|
1897
|
+
previewState.pendingText = getMessageText(nextEvent.message);
|
|
1898
|
+
schedulePreviewFlush(activeTelegramTurn.chatId);
|
|
1899
|
+
},
|
|
1900
|
+
onAgentEnd: async (event, ctx) => {
|
|
1901
|
+
const turn = activeTelegramTurn;
|
|
1902
|
+
currentAbort = undefined;
|
|
1903
|
+
stopTypingLoop();
|
|
1904
|
+
activeTelegramTurn = undefined;
|
|
1905
|
+
activeTelegramToolExecutions = 0;
|
|
1906
|
+
pendingTelegramModelSwitch = undefined;
|
|
1907
|
+
telegramTurnDispatchPending = false;
|
|
1908
|
+
updateStatus(ctx);
|
|
1909
|
+
const assistant = turn
|
|
1910
|
+
? extractAssistantText((event as { messages: AgentMessage[] }).messages)
|
|
1911
|
+
: {};
|
|
1912
|
+
const finalText = assistant.text;
|
|
1913
|
+
const endPlan = buildTelegramAgentEndPlan({
|
|
1914
|
+
hasTurn: !!turn,
|
|
1915
|
+
stopReason: assistant.stopReason,
|
|
1916
|
+
hasFinalText: !!finalText,
|
|
1917
|
+
hasQueuedAttachments: (turn?.queuedAttachments.length ?? 0) > 0,
|
|
1918
|
+
preserveQueuedTurnsAsHistory,
|
|
1919
|
+
});
|
|
1920
|
+
if (!turn) {
|
|
1921
|
+
if (endPlan.shouldDispatchNext) {
|
|
1922
|
+
dispatchNextQueuedTelegramTurn(ctx);
|
|
1923
|
+
}
|
|
1924
|
+
return;
|
|
1925
|
+
}
|
|
1926
|
+
if (endPlan.shouldClearPreview) {
|
|
1927
|
+
await clearPreview(turn.chatId);
|
|
1928
|
+
}
|
|
1929
|
+
if (endPlan.shouldSendErrorMessage) {
|
|
1930
|
+
await sendTextReply(
|
|
1931
|
+
turn.chatId,
|
|
1932
|
+
turn.replyToMessageId,
|
|
1933
|
+
assistant.errorMessage ||
|
|
1934
|
+
"Telegram bridge: pi failed while processing the request.",
|
|
1935
|
+
);
|
|
1936
|
+
if (endPlan.shouldDispatchNext) {
|
|
1937
|
+
dispatchNextQueuedTelegramTurn(ctx);
|
|
1938
|
+
}
|
|
1939
|
+
return;
|
|
1940
|
+
}
|
|
1941
|
+
if (previewState) {
|
|
1942
|
+
previewState.pendingText = finalText ?? previewState.pendingText;
|
|
1943
|
+
}
|
|
1944
|
+
if (endPlan.kind === "text" && finalText) {
|
|
1945
|
+
const finalized = await finalizeMarkdownPreview(turn.chatId, finalText);
|
|
1946
|
+
if (!finalized) {
|
|
1947
|
+
await clearPreview(turn.chatId);
|
|
1948
|
+
await sendMarkdownReply(
|
|
1949
|
+
turn.chatId,
|
|
1950
|
+
turn.replyToMessageId,
|
|
1951
|
+
finalText,
|
|
1952
|
+
);
|
|
1953
|
+
}
|
|
1954
|
+
}
|
|
1955
|
+
if (endPlan.shouldSendAttachmentNotice) {
|
|
1956
|
+
await sendTextReply(
|
|
1957
|
+
turn.chatId,
|
|
1958
|
+
turn.replyToMessageId,
|
|
1959
|
+
"Attached requested file(s).",
|
|
1960
|
+
);
|
|
1961
|
+
}
|
|
1962
|
+
await sendQueuedAttachments(turn);
|
|
1963
|
+
if (endPlan.shouldDispatchNext) {
|
|
1964
|
+
dispatchNextQueuedTelegramTurn(ctx);
|
|
1965
|
+
}
|
|
1966
|
+
},
|
|
1967
|
+
});
|
|
1968
|
+
}
|