@shliamb/dsh-telegram-bot 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +310 -2
- package/README.ru.md +311 -0
- package/cordis.patch.yml +6 -0
- package/lib/client.js +275 -0
- package/lib/client.js.map +1 -0
- package/lib/index.d.ts +106 -0
- package/lib/index.js +2020 -0
- package/lib/logging/index.d.ts +28 -0
- package/lib/logging/index.js +106 -0
- package/lib/state/index.d.ts +69 -0
- package/lib/state/index.js +94 -0
- package/package.json +83 -4
package/lib/index.js
ADDED
|
@@ -0,0 +1,2020 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @shliamb/dsh-telegram-bot — Telegram bridge for DeepSeek Harness.
|
|
3
|
+
*
|
|
4
|
+
* Telegram workspace picker, text prompts into the selected DSH Session, one
|
|
5
|
+
* edited progress message per Turn, and plain final text. All Host services
|
|
6
|
+
* are described locally; no DSH package is imported at runtime.
|
|
7
|
+
*/
|
|
8
|
+
import { spawn } from 'node:child_process';
|
|
9
|
+
import { randomUUID } from 'node:crypto';
|
|
10
|
+
import { openSync } from 'node:fs';
|
|
11
|
+
import { Bot, InlineKeyboard, InputFile } from 'grammy';
|
|
12
|
+
import z from '@deepseek-ai/schemastery';
|
|
13
|
+
import { createPluginLogger } from './logging/index.js';
|
|
14
|
+
import { BindingStore } from './state/index.js';
|
|
15
|
+
export const name = 'telegram-bot';
|
|
16
|
+
export const inject = ['workspaceRegistry', 'sessionController', 'credentials', 'commands'];
|
|
17
|
+
/**
|
|
18
|
+
* Loader/settings schema. Only `adminUserId` is volatile: it is the one field
|
|
19
|
+
* the Telegram settings page reads back. The bot token lives in credentials and
|
|
20
|
+
* never rides a settings response.
|
|
21
|
+
*/
|
|
22
|
+
export const Config = z.object({
|
|
23
|
+
adminUserId: z.number().step(1).min(1).volatile(),
|
|
24
|
+
allowedUserIds: z.array(z.number().step(1).min(1)).default([]),
|
|
25
|
+
botTokenRef: z.string().default('DSH_TELEGRAM_BOT_TOKEN'),
|
|
26
|
+
botToken: z.string().role('secret'),
|
|
27
|
+
apiRoot: z.string(),
|
|
28
|
+
lowBalanceUsd: z.number().min(0).default(1),
|
|
29
|
+
rich: z.boolean().default(true),
|
|
30
|
+
});
|
|
31
|
+
const STRINGS = {
|
|
32
|
+
ru: {
|
|
33
|
+
choose: 'Выбери рабочее пространство:',
|
|
34
|
+
active: 'Активное',
|
|
35
|
+
none: 'Пространств пока нет. Создай его в DSH Web.',
|
|
36
|
+
write: 'Потом просто напиши текст.',
|
|
37
|
+
refresh: '🔄 Обновить',
|
|
38
|
+
notFound: 'Пространство не найдено',
|
|
39
|
+
selected: 'Открыто',
|
|
40
|
+
thinking: '💭 Думает…',
|
|
41
|
+
writing: '✍️ Пишет ответ…',
|
|
42
|
+
done: '✅ Готово',
|
|
43
|
+
error: '⚠️ Ошибка',
|
|
44
|
+
stopped: '⏹ Остановлено',
|
|
45
|
+
maxTokens: '⚠️ Лимит вывода',
|
|
46
|
+
interrupted: '⚠️ Прервано',
|
|
47
|
+
blocked: '⛔ Заблокировано',
|
|
48
|
+
logsEmpty: 'Логов пока нет.',
|
|
49
|
+
busy: 'Сессия занята другим процессом.',
|
|
50
|
+
sessionMissing: 'Сессия не найдена. Выбери пространство заново.',
|
|
51
|
+
workspaceMissing: 'Пространство не найдено. Выбери заново.',
|
|
52
|
+
noWorkspace: 'Сначала выбери рабочее пространство: /menu',
|
|
53
|
+
selectSession: 'Выбери сессию:',
|
|
54
|
+
noSessions: 'В этом пространстве пока нет сессий. Напиши текст — создам новую.',
|
|
55
|
+
sessions: '🔄 Сессии',
|
|
56
|
+
backToWorkspaces: '◀️ Пространства',
|
|
57
|
+
newSession: '➕ Новая сессия',
|
|
58
|
+
newSessionTitle: 'Новая сессия',
|
|
59
|
+
session: 'Сессия',
|
|
60
|
+
opened: 'Открыто',
|
|
61
|
+
pendingText: 'Выбери сессию — текст отправится после выбора.',
|
|
62
|
+
createFailed: 'Не удалось создать сессию.',
|
|
63
|
+
sessionNotFound: 'Сессия не найдена',
|
|
64
|
+
menu: 'Меню',
|
|
65
|
+
balance: 'Баланс',
|
|
66
|
+
context: 'Контекст',
|
|
67
|
+
soundOn: '🔔 Звук: вкл',
|
|
68
|
+
soundOff: '🔕 Звук: выкл',
|
|
69
|
+
workspaces: '📂 Пространства',
|
|
70
|
+
compact: '🗜 Сжать',
|
|
71
|
+
compactHistory: 'Сжать историю?',
|
|
72
|
+
compactUnavailable: 'Сжатие недоступно в этой сессии.',
|
|
73
|
+
compactRunning: 'Идёт работа; сжать можно после завершения.',
|
|
74
|
+
compactNoHistory: 'Нечего сжимать.',
|
|
75
|
+
compactConfirm: 'Старая история будет заменена кратким резюме.',
|
|
76
|
+
compactDone: 'История сжата.',
|
|
77
|
+
stop: '⏹ Стоп',
|
|
78
|
+
stopDone: 'Остановлено.',
|
|
79
|
+
stopIdle: 'Нечего останавливать.',
|
|
80
|
+
status: 'ℹ️ Статус',
|
|
81
|
+
notAvailable: 'н/д',
|
|
82
|
+
noActiveSession: 'Сессия не выбрана.',
|
|
83
|
+
lowBalanceTitle: '⚠️ Низкий баланс',
|
|
84
|
+
lowBalanceText: 'Пополните счёт.',
|
|
85
|
+
home: '🏠 Меню',
|
|
86
|
+
back: '◀️ Назад',
|
|
87
|
+
notSelected: 'не выбрано',
|
|
88
|
+
notSelectedSession: 'не выбрана',
|
|
89
|
+
compactBusy: 'Сжатие уже идёт или агент занят.',
|
|
90
|
+
compactCancelled: 'Сжатие отменено.',
|
|
91
|
+
compactChanged: 'История изменилась; попробуйте ещё раз.',
|
|
92
|
+
compactSummary: 'Не удалось получить резюме.',
|
|
93
|
+
compactCommit: 'Сжатие завершилось не полностью.',
|
|
94
|
+
compactPersistence: 'Не удалось сохранить сессию.',
|
|
95
|
+
statusTitle: 'Статус',
|
|
96
|
+
agent: 'Агент',
|
|
97
|
+
running: 'работает',
|
|
98
|
+
idle: 'ожидает',
|
|
99
|
+
approvalTitle: '🔐 Требуется подтверждение',
|
|
100
|
+
approvalAllow: '✅ Разрешить',
|
|
101
|
+
approvalDeny: '❌ Отклонить',
|
|
102
|
+
approvalAllowed: '✅ Разрешено',
|
|
103
|
+
approvalRejected: '❌ Отклонено',
|
|
104
|
+
approvalTimeout: '⌛ Подтверждение не получено',
|
|
105
|
+
questionTitle: '❓ Вопрос агента',
|
|
106
|
+
questionTimeout: '⌛ Вопрос без ответа',
|
|
107
|
+
questionSelected: 'Выбрано',
|
|
108
|
+
cancel: 'Отмена',
|
|
109
|
+
stopConfirmTitle: '⏹ Остановить работу?',
|
|
110
|
+
stopConfirmText: 'Текущий ход агента будет прерван.',
|
|
111
|
+
stopYes: 'Да, остановить',
|
|
112
|
+
adminTitle: 'Админ-меню',
|
|
113
|
+
adminLogs: '📄 Логи',
|
|
114
|
+
adminRestart: '🔄 Перезапустить Harness',
|
|
115
|
+
restartConfirmTitle: '🔄 Перезапустить Harness?',
|
|
116
|
+
restartConfirmText: 'Текущая работа агента прервётся. Продолжить?',
|
|
117
|
+
restartYes: 'Да, перезапустить',
|
|
118
|
+
restarting: 'Перезапускаю Harness…',
|
|
119
|
+
restartDone: 'Harness перезапускается. Бот вернётся через несколько секунд.',
|
|
120
|
+
accessDenied: 'Нет доступа.',
|
|
121
|
+
logsFailed: 'Не удалось отправить лог.',
|
|
122
|
+
onlineTitle: 'Harness на связи',
|
|
123
|
+
onlineText: 'Бот запущен и готов к работе.',
|
|
124
|
+
openMenu: 'Меню',
|
|
125
|
+
},
|
|
126
|
+
en: {
|
|
127
|
+
choose: 'Choose a workspace:',
|
|
128
|
+
active: 'Active',
|
|
129
|
+
none: 'No workspaces yet. Create one in DSH Web.',
|
|
130
|
+
write: 'Then just send text.',
|
|
131
|
+
refresh: '🔄 Refresh',
|
|
132
|
+
notFound: 'Workspace not found',
|
|
133
|
+
selected: 'Opened',
|
|
134
|
+
thinking: '💭 Thinking…',
|
|
135
|
+
writing: '✍️ Writing…',
|
|
136
|
+
done: '✅ Done',
|
|
137
|
+
error: '⚠️ Error',
|
|
138
|
+
stopped: '⏹ Stopped',
|
|
139
|
+
maxTokens: '⚠️ Output limit',
|
|
140
|
+
interrupted: '⚠️ Interrupted',
|
|
141
|
+
blocked: '⛔ Blocked',
|
|
142
|
+
logsEmpty: 'No logs yet.',
|
|
143
|
+
busy: 'The Session is busy in another process.',
|
|
144
|
+
sessionMissing: 'Session not found. Choose the workspace again.',
|
|
145
|
+
workspaceMissing: 'Workspace not found. Choose it again.',
|
|
146
|
+
noWorkspace: 'Choose a workspace first: /menu',
|
|
147
|
+
selectSession: 'Choose a session:',
|
|
148
|
+
noSessions: 'No sessions in this workspace yet. Send text — I will create one.',
|
|
149
|
+
sessions: '🔄 Sessions',
|
|
150
|
+
backToWorkspaces: '◀️ Workspaces',
|
|
151
|
+
newSession: '➕ New session',
|
|
152
|
+
newSessionTitle: 'New session',
|
|
153
|
+
session: 'Session',
|
|
154
|
+
opened: 'Opened',
|
|
155
|
+
pendingText: 'Choose a session — the text will be sent after selection.',
|
|
156
|
+
createFailed: 'Could not create a session.',
|
|
157
|
+
sessionNotFound: 'Session not found',
|
|
158
|
+
menu: 'Menu',
|
|
159
|
+
balance: 'Balance',
|
|
160
|
+
context: 'Context',
|
|
161
|
+
soundOn: '🔔 Sound: on',
|
|
162
|
+
soundOff: '🔕 Sound: off',
|
|
163
|
+
workspaces: '📂 Workspaces',
|
|
164
|
+
compact: '🗜 Compact',
|
|
165
|
+
compactHistory: 'Compact history?',
|
|
166
|
+
compactUnavailable: 'Compaction is unavailable in this session.',
|
|
167
|
+
compactRunning: 'Work is running; compact after it finishes.',
|
|
168
|
+
compactNoHistory: 'No compactable history.',
|
|
169
|
+
compactConfirm: 'Older history will be replaced by a short summary.',
|
|
170
|
+
compactDone: 'History compacted.',
|
|
171
|
+
stop: '⏹ Stop',
|
|
172
|
+
stopDone: 'Stopped.',
|
|
173
|
+
stopIdle: 'Nothing to stop.',
|
|
174
|
+
status: 'ℹ️ Status',
|
|
175
|
+
notAvailable: 'n/a',
|
|
176
|
+
noActiveSession: 'No session selected.',
|
|
177
|
+
lowBalanceTitle: '⚠️ Low balance',
|
|
178
|
+
lowBalanceText: 'Please top up.',
|
|
179
|
+
home: '🏠 Menu',
|
|
180
|
+
back: '◀️ Back',
|
|
181
|
+
notSelected: 'not selected',
|
|
182
|
+
notSelectedSession: 'not selected',
|
|
183
|
+
compactBusy: 'Compaction is already running or the agent is busy.',
|
|
184
|
+
compactCancelled: 'Compaction cancelled.',
|
|
185
|
+
compactChanged: 'History changed; please retry.',
|
|
186
|
+
compactSummary: 'Could not produce a summary.',
|
|
187
|
+
compactCommit: 'Compaction did not finish cleanly.',
|
|
188
|
+
compactPersistence: 'Could not save the Session.',
|
|
189
|
+
statusTitle: 'Status',
|
|
190
|
+
agent: 'Agent',
|
|
191
|
+
running: 'running',
|
|
192
|
+
idle: 'idle',
|
|
193
|
+
approvalTitle: '🔐 Approval required',
|
|
194
|
+
approvalAllow: '✅ Allow',
|
|
195
|
+
approvalDeny: '❌ Reject',
|
|
196
|
+
approvalAllowed: '✅ Allowed',
|
|
197
|
+
approvalRejected: '❌ Rejected',
|
|
198
|
+
approvalTimeout: '⌛ Approval timed out',
|
|
199
|
+
questionTitle: '❓ Agent question',
|
|
200
|
+
questionTimeout: '⌛ Question timed out',
|
|
201
|
+
questionSelected: 'Selected',
|
|
202
|
+
cancel: 'Cancel',
|
|
203
|
+
stopConfirmTitle: '⏹ Stop the work?',
|
|
204
|
+
stopConfirmText: 'The current agent turn will be interrupted.',
|
|
205
|
+
stopYes: 'Yes, stop',
|
|
206
|
+
adminTitle: 'Admin menu',
|
|
207
|
+
adminLogs: '📄 Logs',
|
|
208
|
+
adminRestart: '🔄 Restart Harness',
|
|
209
|
+
restartConfirmTitle: '🔄 Restart Harness?',
|
|
210
|
+
restartConfirmText: 'The current agent work will be interrupted. Continue?',
|
|
211
|
+
restartYes: 'Yes, restart',
|
|
212
|
+
restarting: 'Restarting Harness…',
|
|
213
|
+
restartDone: 'Harness is restarting. The bot will be back in a few seconds.',
|
|
214
|
+
accessDenied: 'Access denied.',
|
|
215
|
+
logsFailed: 'Could not send the log.',
|
|
216
|
+
onlineTitle: 'Harness is online',
|
|
217
|
+
onlineText: 'The bot is running and ready.',
|
|
218
|
+
openMenu: 'Menu',
|
|
219
|
+
},
|
|
220
|
+
};
|
|
221
|
+
function t(locale, key) {
|
|
222
|
+
return STRINGS[locale][key];
|
|
223
|
+
}
|
|
224
|
+
function localeOf(languageCode) {
|
|
225
|
+
return languageCode?.toLowerCase().startsWith('ru') === true ? 'ru' : 'en';
|
|
226
|
+
}
|
|
227
|
+
function messageOf(error) {
|
|
228
|
+
return error instanceof Error ? error.message : String(error);
|
|
229
|
+
}
|
|
230
|
+
function codeOf(error) {
|
|
231
|
+
if (typeof error !== 'object' || error === null)
|
|
232
|
+
return undefined;
|
|
233
|
+
const code = error.code;
|
|
234
|
+
return typeof code === 'string' ? code : undefined;
|
|
235
|
+
}
|
|
236
|
+
function telegramErrorOf(error) {
|
|
237
|
+
return typeof error === 'object' && error !== null ? error : {};
|
|
238
|
+
}
|
|
239
|
+
function asRecord(value) {
|
|
240
|
+
return typeof value === 'object' && value !== null ? value : undefined;
|
|
241
|
+
}
|
|
242
|
+
function stringField(value) {
|
|
243
|
+
const record = asRecord(value);
|
|
244
|
+
for (const key of ['command', 'cmd', 'script', 'pattern', 'path', 'query']) {
|
|
245
|
+
const candidate = record?.[key];
|
|
246
|
+
if (typeof candidate === 'string' && candidate.length > 0)
|
|
247
|
+
return candidate;
|
|
248
|
+
}
|
|
249
|
+
return undefined;
|
|
250
|
+
}
|
|
251
|
+
function toolDetail(raw) {
|
|
252
|
+
if (typeof raw !== 'string' || raw.length === 0)
|
|
253
|
+
return undefined;
|
|
254
|
+
try {
|
|
255
|
+
return stringField(JSON.parse(raw));
|
|
256
|
+
}
|
|
257
|
+
catch {
|
|
258
|
+
return undefined;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
function truncate(value, max) {
|
|
262
|
+
return value.length <= max ? value : `${value.slice(0, max - 1)}…`;
|
|
263
|
+
}
|
|
264
|
+
function splitText(text, max) {
|
|
265
|
+
if (text.length <= max)
|
|
266
|
+
return [text];
|
|
267
|
+
const parts = [];
|
|
268
|
+
let rest = text;
|
|
269
|
+
while (rest.length > max) {
|
|
270
|
+
let cut = rest.lastIndexOf('\n\n', max);
|
|
271
|
+
if (cut < max * 0.5)
|
|
272
|
+
cut = rest.lastIndexOf('\n', max);
|
|
273
|
+
if (cut < max * 0.5)
|
|
274
|
+
cut = rest.lastIndexOf(' ', max);
|
|
275
|
+
if (cut <= 0)
|
|
276
|
+
cut = max;
|
|
277
|
+
parts.push(rest.slice(0, cut).trimEnd());
|
|
278
|
+
rest = rest.slice(cut).trimStart();
|
|
279
|
+
}
|
|
280
|
+
if (rest.length > 0)
|
|
281
|
+
parts.push(rest);
|
|
282
|
+
return parts;
|
|
283
|
+
}
|
|
284
|
+
function sleep(ms, signal) {
|
|
285
|
+
return new Promise(resolve => {
|
|
286
|
+
if (signal.aborted) {
|
|
287
|
+
resolve();
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
const timer = setTimeout(() => {
|
|
291
|
+
signal.removeEventListener('abort', onAbort);
|
|
292
|
+
resolve();
|
|
293
|
+
}, ms);
|
|
294
|
+
const onAbort = () => {
|
|
295
|
+
clearTimeout(timer);
|
|
296
|
+
resolve();
|
|
297
|
+
};
|
|
298
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
function optionalString(value, field) {
|
|
302
|
+
if (value === undefined)
|
|
303
|
+
return undefined;
|
|
304
|
+
if (typeof value !== 'string' || value.length === 0) {
|
|
305
|
+
throw new TypeError(`telegram-bot: config.${field} must be a non-empty string`);
|
|
306
|
+
}
|
|
307
|
+
return value;
|
|
308
|
+
}
|
|
309
|
+
function optionalNumber(value, field) {
|
|
310
|
+
if (value === undefined)
|
|
311
|
+
return undefined;
|
|
312
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
|
|
313
|
+
throw new TypeError(`telegram-bot: config.${field} must be a non-negative number`);
|
|
314
|
+
}
|
|
315
|
+
return value;
|
|
316
|
+
}
|
|
317
|
+
function optionalBoolean(value, field) {
|
|
318
|
+
if (value === undefined)
|
|
319
|
+
return undefined;
|
|
320
|
+
if (typeof value !== 'boolean') {
|
|
321
|
+
throw new TypeError(`telegram-bot: config.${field} must be a boolean`);
|
|
322
|
+
}
|
|
323
|
+
return value;
|
|
324
|
+
}
|
|
325
|
+
function unwrapVolatile(value) {
|
|
326
|
+
if (value === null || value === undefined)
|
|
327
|
+
return undefined;
|
|
328
|
+
if (typeof value === 'object') {
|
|
329
|
+
const get = value.get;
|
|
330
|
+
if (typeof get === 'function')
|
|
331
|
+
return get.call(value);
|
|
332
|
+
}
|
|
333
|
+
return value;
|
|
334
|
+
}
|
|
335
|
+
function parseConfig(raw) {
|
|
336
|
+
if (raw === undefined || raw === null)
|
|
337
|
+
raw = {};
|
|
338
|
+
if (typeof raw !== 'object' || Array.isArray(raw)) {
|
|
339
|
+
throw new TypeError('telegram-bot: config must be an object');
|
|
340
|
+
}
|
|
341
|
+
const value = raw;
|
|
342
|
+
const allowed = value.allowedUserIds;
|
|
343
|
+
if (allowed !== undefined
|
|
344
|
+
&& (!Array.isArray(allowed)
|
|
345
|
+
|| !allowed.every(id => typeof id === 'number' && Number.isSafeInteger(id) && id > 0))) {
|
|
346
|
+
throw new TypeError('telegram-bot: config.allowedUserIds must be an array of Telegram user IDs');
|
|
347
|
+
}
|
|
348
|
+
const botTokenRef = optionalString(value.botTokenRef, 'botTokenRef');
|
|
349
|
+
const botToken = optionalString(value.botToken, 'botToken');
|
|
350
|
+
const apiRoot = optionalString(value.apiRoot, 'apiRoot');
|
|
351
|
+
const adminCandidate = optionalNumber(unwrapVolatile(value.adminUserId), 'adminUserId');
|
|
352
|
+
if (adminCandidate !== undefined && (!Number.isSafeInteger(adminCandidate) || adminCandidate <= 0)) {
|
|
353
|
+
throw new TypeError('telegram-bot: config.adminUserId must be a positive Telegram user ID');
|
|
354
|
+
}
|
|
355
|
+
const lowBalanceValue = unwrapVolatile(value.lowBalanceUsd);
|
|
356
|
+
const richValue = unwrapVolatile(value.rich);
|
|
357
|
+
const lowBalanceUsd = lowBalanceValue === undefined ? undefined : optionalNumber(lowBalanceValue, 'lowBalanceUsd');
|
|
358
|
+
const rich = richValue === undefined ? undefined : optionalBoolean(richValue, 'rich');
|
|
359
|
+
return {
|
|
360
|
+
allowedUserIds: allowed ?? [],
|
|
361
|
+
...(adminCandidate === undefined ? {} : { adminUserId: adminCandidate }),
|
|
362
|
+
...(botTokenRef === undefined ? {} : { botTokenRef }),
|
|
363
|
+
...(botToken === undefined ? {} : { botToken }),
|
|
364
|
+
...(apiRoot === undefined ? {} : { apiRoot }),
|
|
365
|
+
...(lowBalanceUsd === undefined ? {} : { lowBalanceUsd }),
|
|
366
|
+
...(rich === undefined ? {} : { rich }),
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
async function resolveToken(config, credentials) {
|
|
370
|
+
if (config.botToken !== undefined)
|
|
371
|
+
return config.botToken;
|
|
372
|
+
if (credentials === undefined)
|
|
373
|
+
return undefined;
|
|
374
|
+
const ref = config.botTokenRef ?? 'DSH_TELEGRAM_BOT_TOKEN';
|
|
375
|
+
const resolved = await credentials.resolve(ref);
|
|
376
|
+
return resolved?.value;
|
|
377
|
+
}
|
|
378
|
+
async function resolveBotToken(ctx, config, credentials, signal) {
|
|
379
|
+
// HMR can briefly reload us before the credentials service is addressable.
|
|
380
|
+
// Retry instead of entering a permanent token-missing state.
|
|
381
|
+
for (let attempt = 0; attempt < 10; attempt += 1) {
|
|
382
|
+
const active = ctx.get('credentials') ?? credentials;
|
|
383
|
+
const token = await resolveToken(config, active);
|
|
384
|
+
if (token !== undefined)
|
|
385
|
+
return token;
|
|
386
|
+
if (signal.aborted)
|
|
387
|
+
return undefined;
|
|
388
|
+
await sleep(300, signal);
|
|
389
|
+
}
|
|
390
|
+
return undefined;
|
|
391
|
+
}
|
|
392
|
+
function commandsFor(locale) {
|
|
393
|
+
return [{
|
|
394
|
+
command: 'start',
|
|
395
|
+
description: locale === 'ru' ? 'Меню и баланс' : 'Menu and balance',
|
|
396
|
+
}];
|
|
397
|
+
}
|
|
398
|
+
function adminCommandsFor(locale) {
|
|
399
|
+
return [
|
|
400
|
+
...commandsFor(locale),
|
|
401
|
+
{
|
|
402
|
+
command: 'admin',
|
|
403
|
+
description: locale === 'ru' ? 'Админ-меню' : 'Admin menu',
|
|
404
|
+
},
|
|
405
|
+
];
|
|
406
|
+
}
|
|
407
|
+
async function installCommands(bot, logger, adminUserId) {
|
|
408
|
+
try {
|
|
409
|
+
await bot.api.setMyCommands(commandsFor('ru'), { language_code: 'ru' });
|
|
410
|
+
await bot.api.setMyCommands(commandsFor('en'), { language_code: 'en' });
|
|
411
|
+
if (adminUserId === undefined)
|
|
412
|
+
return;
|
|
413
|
+
// Only the admin sees /admin in the Telegram command list.
|
|
414
|
+
await bot.api.setMyCommands(adminCommandsFor('ru'), {
|
|
415
|
+
scope: { type: 'chat', chat_id: adminUserId },
|
|
416
|
+
language_code: 'ru',
|
|
417
|
+
});
|
|
418
|
+
await bot.api.setMyCommands(adminCommandsFor('en'), {
|
|
419
|
+
scope: { type: 'chat', chat_id: adminUserId },
|
|
420
|
+
language_code: 'en',
|
|
421
|
+
});
|
|
422
|
+
}
|
|
423
|
+
catch (error) {
|
|
424
|
+
logger.warn('commands-failed', `could not set bot commands: ${messageOf(error)}`);
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
function escapeHtml(value) {
|
|
428
|
+
return value
|
|
429
|
+
.replaceAll('&', '&')
|
|
430
|
+
.replaceAll('<', '<')
|
|
431
|
+
.replaceAll('>', '>')
|
|
432
|
+
.replaceAll('"', '"');
|
|
433
|
+
}
|
|
434
|
+
function formatWallet(wallet) {
|
|
435
|
+
const symbol = wallet.currency === 'USD' ? '$' : wallet.currency === 'CNY' ? '¥' : `${wallet.currency} `;
|
|
436
|
+
const amount = Number.parseFloat(wallet.balance);
|
|
437
|
+
return `${symbol}${Number.isFinite(amount) ? amount.toFixed(2) : wallet.balance}`;
|
|
438
|
+
}
|
|
439
|
+
async function getBalance(runtime, locale, force = false) {
|
|
440
|
+
if (runtime.account === undefined)
|
|
441
|
+
return {};
|
|
442
|
+
const cache = runtime.balanceCache;
|
|
443
|
+
if (!force && cache.value !== undefined && Date.now() - cache.at < 60_000) {
|
|
444
|
+
return { display: cache.value, amount: cache.amount, currency: cache.currency };
|
|
445
|
+
}
|
|
446
|
+
try {
|
|
447
|
+
const result = await runtime.account.getBalance({
|
|
448
|
+
version: '@shliamb/dsh-telegram-bot/0.2.0',
|
|
449
|
+
locale,
|
|
450
|
+
timezoneOffsetSeconds: -new Date().getTimezoneOffset() * 60,
|
|
451
|
+
});
|
|
452
|
+
if (result === null || result.status !== 'ready') {
|
|
453
|
+
cache.value = undefined;
|
|
454
|
+
cache.amount = undefined;
|
|
455
|
+
cache.currency = undefined;
|
|
456
|
+
cache.at = Date.now();
|
|
457
|
+
return {};
|
|
458
|
+
}
|
|
459
|
+
const wallet = result.value.find(item => item.currency === 'USD') ?? result.value[0];
|
|
460
|
+
if (wallet === undefined) {
|
|
461
|
+
cache.value = undefined;
|
|
462
|
+
cache.amount = undefined;
|
|
463
|
+
cache.currency = undefined;
|
|
464
|
+
cache.at = Date.now();
|
|
465
|
+
return {};
|
|
466
|
+
}
|
|
467
|
+
const amount = Number.parseFloat(wallet.balance);
|
|
468
|
+
const display = formatWallet(wallet);
|
|
469
|
+
cache.value = display;
|
|
470
|
+
cache.amount = Number.isFinite(amount) ? amount : undefined;
|
|
471
|
+
cache.currency = wallet.currency;
|
|
472
|
+
cache.at = Date.now();
|
|
473
|
+
return { display, amount: cache.amount, currency: wallet.currency };
|
|
474
|
+
}
|
|
475
|
+
catch (error) {
|
|
476
|
+
runtime.logger.warn('balance-failed', messageOf(error));
|
|
477
|
+
return cache.value === undefined ? {} : { display: cache.value, amount: cache.amount, currency: cache.currency };
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
async function getContextLabel(runtime, binding) {
|
|
481
|
+
if (runtime.tokenMeter === undefined || binding?.activeSessionId === undefined)
|
|
482
|
+
return undefined;
|
|
483
|
+
const sessionId = binding.activeSessionId;
|
|
484
|
+
const cached = runtime.contextCache.get(sessionId);
|
|
485
|
+
if (cached !== undefined && Date.now() - cached.at < 15_000) {
|
|
486
|
+
return cached.percent === undefined ? undefined : `${cached.percent}%`;
|
|
487
|
+
}
|
|
488
|
+
try {
|
|
489
|
+
const result = await runtime.sessions.resolveAgent(sessionId);
|
|
490
|
+
if (result.agent === undefined)
|
|
491
|
+
return undefined;
|
|
492
|
+
const pressure = runtime.tokenMeter.contextPressure(result.agent.session);
|
|
493
|
+
const percent = pressure.pressureTokens !== undefined
|
|
494
|
+
&& pressure.contextWindow !== undefined
|
|
495
|
+
&& pressure.contextWindow > 0
|
|
496
|
+
? Math.round(100 * pressure.pressureTokens / pressure.contextWindow)
|
|
497
|
+
: undefined;
|
|
498
|
+
runtime.contextCache.set(sessionId, { percent, at: Date.now() });
|
|
499
|
+
return percent === undefined ? undefined : `${percent}%`;
|
|
500
|
+
}
|
|
501
|
+
catch (error) {
|
|
502
|
+
runtime.logger.warn('context-failed', messageOf(error), { sessionId });
|
|
503
|
+
return undefined;
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
async function getMenuState(runtime, chatId, locale) {
|
|
507
|
+
const binding = runtime.store.get(chatId);
|
|
508
|
+
const [balance, context] = await Promise.all([
|
|
509
|
+
getBalance(runtime, locale),
|
|
510
|
+
getContextLabel(runtime, binding),
|
|
511
|
+
]);
|
|
512
|
+
return {
|
|
513
|
+
binding,
|
|
514
|
+
balance: balance.display,
|
|
515
|
+
context,
|
|
516
|
+
sound: binding?.sound !== false,
|
|
517
|
+
};
|
|
518
|
+
}
|
|
519
|
+
async function maybeWarnLowBalance(runtime, chatId, locale, silent) {
|
|
520
|
+
if (runtime.account === undefined)
|
|
521
|
+
return;
|
|
522
|
+
const balance = await getBalance(runtime, locale);
|
|
523
|
+
if (balance.amount === undefined || balance.currency !== 'USD' || balance.amount > runtime.lowBalanceUsd) {
|
|
524
|
+
runtime.lowBalanceWarnedAt.delete(chatId);
|
|
525
|
+
return;
|
|
526
|
+
}
|
|
527
|
+
const last = runtime.lowBalanceWarnedAt.get(chatId) ?? 0;
|
|
528
|
+
if (Date.now() - last < 6 * 60 * 60 * 1_000)
|
|
529
|
+
return;
|
|
530
|
+
runtime.lowBalanceWarnedAt.set(chatId, Date.now());
|
|
531
|
+
const text = `${t(locale, 'lowBalanceTitle')}: ${balance.display ?? '—'}\n${t(locale, 'lowBalanceText')}`;
|
|
532
|
+
await sendPlain(runtime, chatId, text, silent);
|
|
533
|
+
}
|
|
534
|
+
function compactErrorText(locale, error) {
|
|
535
|
+
switch (codeOf(error)) {
|
|
536
|
+
case 'busy': return t(locale, 'compactBusy');
|
|
537
|
+
case 'cancelled': return t(locale, 'compactCancelled');
|
|
538
|
+
case 'changed': return t(locale, 'compactChanged');
|
|
539
|
+
case 'summary': return t(locale, 'compactSummary');
|
|
540
|
+
case 'commit': return t(locale, 'compactCommit');
|
|
541
|
+
case 'persistence': return t(locale, 'compactPersistence');
|
|
542
|
+
default: return messageOf(error);
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
async function stopActive(runtime, chatId, locale) {
|
|
546
|
+
const binding = runtime.store.get(chatId);
|
|
547
|
+
if (binding?.activeSessionId === undefined)
|
|
548
|
+
return t(locale, 'noActiveSession');
|
|
549
|
+
const result = await runtime.sessions.resolveAgent(binding.activeSessionId);
|
|
550
|
+
if (result.agent === undefined)
|
|
551
|
+
return result.error?.message ?? t(locale, 'sessionMissing');
|
|
552
|
+
if (result.agent.status !== 'running')
|
|
553
|
+
return t(locale, 'stopIdle');
|
|
554
|
+
try {
|
|
555
|
+
result.agent.cancel({ kind: 'user' });
|
|
556
|
+
return t(locale, 'stopDone');
|
|
557
|
+
}
|
|
558
|
+
catch (error) {
|
|
559
|
+
runtime.logger.error('stop-failed', messageOf(error), { chatId });
|
|
560
|
+
return messageOf(error);
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
function compactResultText(locale, text) {
|
|
564
|
+
if (text === undefined)
|
|
565
|
+
return t(locale, 'compactDone');
|
|
566
|
+
if (text.includes('No compactable history'))
|
|
567
|
+
return t(locale, 'compactNoHistory');
|
|
568
|
+
if (text.includes('active compaction, or the agent is not idle'))
|
|
569
|
+
return t(locale, 'compactRunning');
|
|
570
|
+
if (text.includes('Compaction cancelled'))
|
|
571
|
+
return t(locale, 'compactCancelled');
|
|
572
|
+
if (text.includes('history selected for compaction changed'))
|
|
573
|
+
return t(locale, 'compactChanged');
|
|
574
|
+
if (text.includes('useful summary'))
|
|
575
|
+
return t(locale, 'compactSummary');
|
|
576
|
+
if (text.includes('did not finish cleanly'))
|
|
577
|
+
return t(locale, 'compactCommit');
|
|
578
|
+
if (text.includes('could not be saved'))
|
|
579
|
+
return t(locale, 'compactPersistence');
|
|
580
|
+
const counts = /Compacted (\d+) history items \(~(\d+) tokens\)/.exec(text);
|
|
581
|
+
return counts === null ? text : `${t(locale, 'compactDone')} ${counts[1]} / ~${counts[2]} tokens`;
|
|
582
|
+
}
|
|
583
|
+
async function runCompact(runtime, chatId, locale, sessionId) {
|
|
584
|
+
const result = await runtime.sessions.resolveAgent(sessionId);
|
|
585
|
+
if (result.agent === undefined)
|
|
586
|
+
return result.error?.message ?? t(locale, 'sessionMissing');
|
|
587
|
+
if (result.agent.status !== 'idle')
|
|
588
|
+
return t(locale, 'compactRunning');
|
|
589
|
+
const commands = runtime.commands;
|
|
590
|
+
if (commands === undefined)
|
|
591
|
+
return t(locale, 'compactUnavailable');
|
|
592
|
+
try {
|
|
593
|
+
// The preset that owns the session registers /compact together with its
|
|
594
|
+
// isolated compaction backend; calling the command uses the same path as Web.
|
|
595
|
+
const execution = await commands.execute(result.agent, '/compact', [], AbortSignal.timeout(300_000));
|
|
596
|
+
runtime.contextCache.delete(sessionId);
|
|
597
|
+
if (execution === undefined)
|
|
598
|
+
return t(locale, 'compactUnavailable');
|
|
599
|
+
runtime.logger.info('compact-result', 'manual compaction finished', {
|
|
600
|
+
chatId,
|
|
601
|
+
sessionId,
|
|
602
|
+
kind: execution.result.kind,
|
|
603
|
+
});
|
|
604
|
+
return compactResultText(locale, execution.result.text);
|
|
605
|
+
}
|
|
606
|
+
catch (error) {
|
|
607
|
+
runtime.logger.error('compact-failed', messageOf(error), {
|
|
608
|
+
chatId,
|
|
609
|
+
sessionId,
|
|
610
|
+
...(codeOf(error) === undefined ? {} : { code: codeOf(error) }),
|
|
611
|
+
});
|
|
612
|
+
return compactErrorText(locale, error);
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
async function statusText(runtime, chatId, locale) {
|
|
616
|
+
const binding = runtime.store.get(chatId);
|
|
617
|
+
const workspace = binding?.activeWorkspaceId === undefined ? undefined : runtime.workspaces.get(binding.activeWorkspaceId);
|
|
618
|
+
const balance = await getBalance(runtime, locale);
|
|
619
|
+
const context = await getContextLabel(runtime, binding);
|
|
620
|
+
let agentStatus = '—';
|
|
621
|
+
if (binding?.activeSessionId !== undefined) {
|
|
622
|
+
const result = await runtime.sessions.resolveAgent(binding.activeSessionId);
|
|
623
|
+
agentStatus = result.agent?.status ?? '—';
|
|
624
|
+
}
|
|
625
|
+
return [
|
|
626
|
+
t(locale, 'statusTitle'),
|
|
627
|
+
`${t(locale, 'balance')}: ${balance.display ?? '—'}`,
|
|
628
|
+
`${locale === 'ru' ? 'Пространство' : 'Workspace'}: ${workspace?.title ?? t(locale, 'notSelected')}`,
|
|
629
|
+
`${t(locale, 'session')}: ${binding?.activeSessionId?.slice(0, 8) ?? t(locale, 'notSelectedSession')}`,
|
|
630
|
+
`${t(locale, 'agent')}: ${agentStatus === 'running' ? t(locale, 'running') : agentStatus === 'idle' ? t(locale, 'idle') : agentStatus}`,
|
|
631
|
+
`${t(locale, 'context')}: ${context ?? '—'}`,
|
|
632
|
+
binding?.sound !== false ? t(locale, 'soundOn') : t(locale, 'soundOff'),
|
|
633
|
+
].join('\n');
|
|
634
|
+
}
|
|
635
|
+
function homeOnlyView(text, locale) {
|
|
636
|
+
return {
|
|
637
|
+
html: `<p>${escapeHtml(text)}</p><tg-button-row align="left"><tg-button type="callback_data" style="primary" data="menu:home">${escapeHtml(t(locale, 'home'))}</tg-button></tg-button-row>`,
|
|
638
|
+
text,
|
|
639
|
+
keyboard: new InlineKeyboard().text(t(locale, 'home'), 'menu:home'),
|
|
640
|
+
};
|
|
641
|
+
}
|
|
642
|
+
function buildAdminView(locale) {
|
|
643
|
+
const html = [
|
|
644
|
+
`<h2>${escapeHtml(t(locale, 'adminTitle'))}</h2>`,
|
|
645
|
+
`<tg-button-row align="left"><tg-button type="callback_data" style="primary" data="admin:logs">${escapeHtml(t(locale, 'adminLogs'))}</tg-button></tg-button-row>`,
|
|
646
|
+
`<tg-button-row align="left"><tg-button type="callback_data" style="danger" data="admin:restart">${escapeHtml(t(locale, 'adminRestart'))}</tg-button></tg-button-row>`,
|
|
647
|
+
`<tg-button-row align="left"><tg-button type="callback_data" style="link" data="menu:home">${escapeHtml(t(locale, 'home'))}</tg-button></tg-button-row>`,
|
|
648
|
+
].join('\n');
|
|
649
|
+
const text = [t(locale, 'adminTitle'), t(locale, 'adminLogs'), t(locale, 'adminRestart')].join('\n');
|
|
650
|
+
const keyboard = new InlineKeyboard()
|
|
651
|
+
.text(t(locale, 'adminLogs'), 'admin:logs').row()
|
|
652
|
+
.text(t(locale, 'adminRestart'), 'admin:restart').row()
|
|
653
|
+
.text(t(locale, 'home'), 'menu:home');
|
|
654
|
+
return { html, text, keyboard };
|
|
655
|
+
}
|
|
656
|
+
function buildRestartView(locale) {
|
|
657
|
+
const html = [
|
|
658
|
+
`<h2>${escapeHtml(t(locale, 'restartConfirmTitle'))}</h2>`,
|
|
659
|
+
`<p>${escapeHtml(t(locale, 'restartConfirmText'))}</p>`,
|
|
660
|
+
`<tg-button-row align="left"><tg-button type="callback_data" style="danger" data="admin:restart:yes">${escapeHtml(t(locale, 'restartYes'))}</tg-button><tg-button type="callback_data" style="link" data="admin:home">${escapeHtml(t(locale, 'back'))}</tg-button></tg-button-row>`,
|
|
661
|
+
].join('\n');
|
|
662
|
+
const text = [t(locale, 'restartConfirmTitle'), t(locale, 'restartConfirmText')].join('\n');
|
|
663
|
+
const keyboard = new InlineKeyboard()
|
|
664
|
+
.text(t(locale, 'restartYes'), 'admin:restart:yes')
|
|
665
|
+
.text(t(locale, 'back'), 'admin:home');
|
|
666
|
+
return { html, text, keyboard };
|
|
667
|
+
}
|
|
668
|
+
async function sendLogs(grammyCtx, locale, logger) {
|
|
669
|
+
const text = logger.tail(500);
|
|
670
|
+
if (text.length === 0) {
|
|
671
|
+
await grammyCtx.reply(t(locale, 'logsEmpty')).catch(() => undefined);
|
|
672
|
+
return;
|
|
673
|
+
}
|
|
674
|
+
const stamp = new Date().toISOString().replaceAll(':', '-');
|
|
675
|
+
try {
|
|
676
|
+
await grammyCtx.replyWithDocument(new InputFile(Buffer.from(`${text}\n`, 'utf8'), `telegram-bot-${stamp}.log`));
|
|
677
|
+
}
|
|
678
|
+
catch (error) {
|
|
679
|
+
logger.error('logs-failed', messageOf(error));
|
|
680
|
+
await grammyCtx.reply(t(locale, 'logsFailed')).catch(() => undefined);
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
function restartHarness(logger) {
|
|
684
|
+
try {
|
|
685
|
+
const restartLog = logger.path.replace(/telegram-bot\.log$/, 'harness-restart.log');
|
|
686
|
+
const fd = openSync(restartLog, 'a', 0o600);
|
|
687
|
+
// Re-enter through pnpm, exactly like the original `pnpm dsh web` launch.
|
|
688
|
+
// Running the raw Node entry skips pnpm's module-resolution setup and can
|
|
689
|
+
// load a different @deepseek-ai/cordis copy.
|
|
690
|
+
const pnpm = process.env.npm_execpath;
|
|
691
|
+
const command = pnpm === undefined
|
|
692
|
+
? ['pnpm', 'dsh', 'web', '--no-open']
|
|
693
|
+
: /\.(?:mjs|cjs|js)$/.test(pnpm)
|
|
694
|
+
? [process.execPath, pnpm, 'dsh', 'web', '--no-open']
|
|
695
|
+
: [pnpm, 'dsh', 'web', '--no-open'];
|
|
696
|
+
const child = spawn('/bin/bash', ['-c', 'sleep 2; exec "$@"', 'dsh-restart', ...command], {
|
|
697
|
+
cwd: process.cwd(),
|
|
698
|
+
env: process.env,
|
|
699
|
+
detached: true,
|
|
700
|
+
stdio: ['ignore', fd, fd],
|
|
701
|
+
});
|
|
702
|
+
child.unref();
|
|
703
|
+
logger.warn('restart', 'restarting the Harness process', {
|
|
704
|
+
pid: process.pid,
|
|
705
|
+
...(child.pid === undefined ? {} : { childPid: child.pid }),
|
|
706
|
+
});
|
|
707
|
+
setTimeout(() => process.exit(0), 1_000);
|
|
708
|
+
return true;
|
|
709
|
+
}
|
|
710
|
+
catch (error) {
|
|
711
|
+
logger.error('restart-failed', messageOf(error));
|
|
712
|
+
return false;
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
function buildApprovalView(request, token, locale) {
|
|
716
|
+
const reason = request.reason === undefined ? '' : `<p>${escapeHtml(request.reason)}</p>`;
|
|
717
|
+
const html = [
|
|
718
|
+
`<h2>${escapeHtml(t(locale, 'approvalTitle'))}</h2>`,
|
|
719
|
+
`<p><b>${escapeHtml(locale === 'ru' ? 'Инструмент' : 'Tool')}:</b> ${escapeHtml(request.toolName)}</p>`,
|
|
720
|
+
reason,
|
|
721
|
+
`<tg-button-row align="left"><tg-button type="callback_data" style="success" data="ap:${token}:a">${escapeHtml(t(locale, 'approvalAllow'))}</tg-button><tg-button type="callback_data" style="danger" data="ap:${token}:r">${escapeHtml(t(locale, 'approvalDeny'))}</tg-button></tg-button-row>`,
|
|
722
|
+
].join('\n');
|
|
723
|
+
const text = [
|
|
724
|
+
t(locale, 'approvalTitle'),
|
|
725
|
+
`${locale === 'ru' ? 'Инструмент' : 'Tool'}: ${request.toolName}`,
|
|
726
|
+
...(request.reason === undefined ? [] : [request.reason]),
|
|
727
|
+
].join('\n');
|
|
728
|
+
const keyboard = new InlineKeyboard()
|
|
729
|
+
.text(t(locale, 'approvalAllow'), `ap:${token}:a`)
|
|
730
|
+
.text(t(locale, 'approvalDeny'), `ap:${token}:r`);
|
|
731
|
+
return { html, text, keyboard };
|
|
732
|
+
}
|
|
733
|
+
function buildQuestionsView(request, token, locale, answers = new Map()) {
|
|
734
|
+
const html = [`<h2>${escapeHtml(t(locale, 'questionTitle'))}</h2>`];
|
|
735
|
+
const text = [t(locale, 'questionTitle')];
|
|
736
|
+
const keyboard = new InlineKeyboard();
|
|
737
|
+
request.questions.forEach((question, questionIndex) => {
|
|
738
|
+
html.push(`<h3>${escapeHtml(question.header ?? question.question)}</h3>`);
|
|
739
|
+
html.push(`<p>${escapeHtml(question.question)}</p>`);
|
|
740
|
+
if (question.detail !== undefined)
|
|
741
|
+
html.push(`<p>${escapeHtml(question.detail)}</p>`);
|
|
742
|
+
text.push('', question.question);
|
|
743
|
+
if (question.detail !== undefined)
|
|
744
|
+
text.push(question.detail);
|
|
745
|
+
const buttons = [];
|
|
746
|
+
question.options?.forEach((option, optionIndex) => {
|
|
747
|
+
const selected = answers.get(questionIndex) === option.label;
|
|
748
|
+
const label = `${selected ? '✓ ' : ''}${option.label}`;
|
|
749
|
+
const data = `q:${token}:${questionIndex}:${optionIndex}`;
|
|
750
|
+
buttons.push(`<tg-button type="callback_data" style="${selected ? 'success' : 'primary'}" data="${data}">${escapeHtml(label)}</tg-button>`);
|
|
751
|
+
keyboard.text(label, data).row();
|
|
752
|
+
});
|
|
753
|
+
if (buttons.length > 0) {
|
|
754
|
+
for (let index = 0; index < buttons.length; index += 3) {
|
|
755
|
+
html.push(`<tg-button-row align="left">${buttons.slice(index, index + 3).join('')}</tg-button-row>`);
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
question.options?.forEach(option => text.push(`• ${option.label}`));
|
|
759
|
+
});
|
|
760
|
+
return { html: html.join('\n'), text: text.join('\n'), keyboard };
|
|
761
|
+
}
|
|
762
|
+
async function handleApproval(runtime, request, next) {
|
|
763
|
+
if (request.signal?.aborted === true)
|
|
764
|
+
return 'cancelled';
|
|
765
|
+
const chatIdRaw = chatForSession(runtime, request.agent.session.id);
|
|
766
|
+
if (chatIdRaw === undefined)
|
|
767
|
+
return next();
|
|
768
|
+
const chatId = Number(chatIdRaw);
|
|
769
|
+
if (!Number.isSafeInteger(chatId))
|
|
770
|
+
return next();
|
|
771
|
+
const binding = runtime.store.get(chatIdRaw);
|
|
772
|
+
const locale = binding?.locale ?? 'ru';
|
|
773
|
+
const token = randomUUID().slice(0, 8);
|
|
774
|
+
const messageId = await sendRich(runtime, chatId, buildApprovalView(request, token, locale), binding?.sound === false);
|
|
775
|
+
if (messageId === undefined)
|
|
776
|
+
return next();
|
|
777
|
+
return await new Promise((resolve) => {
|
|
778
|
+
let settled = false;
|
|
779
|
+
let timer;
|
|
780
|
+
const finish = (outcome) => {
|
|
781
|
+
if (settled)
|
|
782
|
+
return;
|
|
783
|
+
settled = true;
|
|
784
|
+
clearTimeout(timer);
|
|
785
|
+
runtime.pendingApprovals.delete(token);
|
|
786
|
+
resolve(outcome);
|
|
787
|
+
};
|
|
788
|
+
timer = setTimeout(() => {
|
|
789
|
+
if (settled)
|
|
790
|
+
return;
|
|
791
|
+
const timeout = homeOnlyView(t(locale, 'approvalTimeout'), locale);
|
|
792
|
+
runtime.pendingApprovals.delete(token);
|
|
793
|
+
void editRich(runtime, chatId, messageId, timeout);
|
|
794
|
+
finish('unavailable');
|
|
795
|
+
}, 10 * 60 * 1_000);
|
|
796
|
+
runtime.pendingApprovals.set(token, { chatId, messageId, locale, finish });
|
|
797
|
+
request.signal?.addEventListener('abort', () => {
|
|
798
|
+
runtime.pendingApprovals.get(token)?.finish('cancelled');
|
|
799
|
+
}, { once: true });
|
|
800
|
+
});
|
|
801
|
+
}
|
|
802
|
+
async function handleQuestion(runtime, request, next) {
|
|
803
|
+
if (request.agent === undefined)
|
|
804
|
+
return next();
|
|
805
|
+
if (request.questions.length === 0)
|
|
806
|
+
return next();
|
|
807
|
+
if (request.questions.some(question => question.multiSelect === true
|
|
808
|
+
|| question.options === undefined
|
|
809
|
+
|| question.options.length === 0))
|
|
810
|
+
return next();
|
|
811
|
+
if (request.signal?.aborted === true) {
|
|
812
|
+
return { answers: request.questions.map(question => ({ id: question.id, selected: [] })) };
|
|
813
|
+
}
|
|
814
|
+
const chatIdRaw = chatForSession(runtime, request.agent.session.id);
|
|
815
|
+
if (chatIdRaw === undefined)
|
|
816
|
+
return next();
|
|
817
|
+
const chatId = Number(chatIdRaw);
|
|
818
|
+
if (!Number.isSafeInteger(chatId))
|
|
819
|
+
return next();
|
|
820
|
+
const binding = runtime.store.get(chatIdRaw);
|
|
821
|
+
const locale = binding?.locale ?? 'ru';
|
|
822
|
+
const token = randomUUID().slice(0, 8);
|
|
823
|
+
const answers = new Map();
|
|
824
|
+
const messageId = await sendRich(runtime, chatId, buildQuestionsView(request, token, locale), binding?.sound === false);
|
|
825
|
+
if (messageId === undefined)
|
|
826
|
+
return next();
|
|
827
|
+
return await new Promise((resolve) => {
|
|
828
|
+
let settled = false;
|
|
829
|
+
let timer;
|
|
830
|
+
const skipped = () => ({
|
|
831
|
+
answers: request.questions.map(question => ({ id: question.id, selected: [] })),
|
|
832
|
+
});
|
|
833
|
+
const finish = (answer) => {
|
|
834
|
+
if (settled)
|
|
835
|
+
return;
|
|
836
|
+
settled = true;
|
|
837
|
+
clearTimeout(timer);
|
|
838
|
+
runtime.pendingQuestions.delete(token);
|
|
839
|
+
resolve(answer);
|
|
840
|
+
};
|
|
841
|
+
timer = setTimeout(() => {
|
|
842
|
+
if (settled)
|
|
843
|
+
return;
|
|
844
|
+
const timeout = homeOnlyView(t(locale, 'questionTimeout'), locale);
|
|
845
|
+
runtime.pendingQuestions.delete(token);
|
|
846
|
+
void editRich(runtime, chatId, messageId, timeout);
|
|
847
|
+
finish(skipped());
|
|
848
|
+
}, 10 * 60 * 1_000);
|
|
849
|
+
runtime.pendingQuestions.set(token, { questions: request.questions, answers, chatId, messageId, locale, finish });
|
|
850
|
+
request.signal?.addEventListener('abort', () => {
|
|
851
|
+
runtime.pendingQuestions.get(token)?.finish(skipped());
|
|
852
|
+
}, { once: true });
|
|
853
|
+
});
|
|
854
|
+
}
|
|
855
|
+
function buildWorkspaceView(workspaces, binding, locale) {
|
|
856
|
+
const list = workspaces.slice(0, 10);
|
|
857
|
+
const keyboard = new InlineKeyboard();
|
|
858
|
+
for (const workspace of list) {
|
|
859
|
+
const mark = binding?.activeWorkspaceId === workspace.id ? '✓ ' : '';
|
|
860
|
+
keyboard.text(`${mark}${truncate(workspace.title, 38)}`, `ws:${workspace.id}`).row();
|
|
861
|
+
}
|
|
862
|
+
keyboard.text(t(locale, 'refresh'), 'menu:refresh').row();
|
|
863
|
+
keyboard.text(t(locale, 'home'), 'menu:home');
|
|
864
|
+
const active = list.find(workspace => workspace.id === binding?.activeWorkspaceId);
|
|
865
|
+
const lines = [
|
|
866
|
+
`${locale === 'ru' ? 'Рабочих пространств' : 'Workspaces'}: ${workspaces.length}`,
|
|
867
|
+
...(active === undefined ? [t(locale, 'choose')] : [`${t(locale, 'active')}: ${active.title}`]),
|
|
868
|
+
'',
|
|
869
|
+
t(locale, 'write'),
|
|
870
|
+
];
|
|
871
|
+
return { text: lines.join('\n'), keyboard };
|
|
872
|
+
}
|
|
873
|
+
async function sendWorkspaceView(grammyCtx, workspaces, store, locale) {
|
|
874
|
+
const chatId = grammyCtx.chat?.id;
|
|
875
|
+
if (chatId === undefined)
|
|
876
|
+
return;
|
|
877
|
+
const view = buildWorkspaceView(workspaces, store.get(chatId), locale);
|
|
878
|
+
await grammyCtx.reply(view.text, { reply_markup: view.keyboard });
|
|
879
|
+
}
|
|
880
|
+
function buildMainMenu(workspaces, state, locale) {
|
|
881
|
+
const binding = state.binding;
|
|
882
|
+
const active = workspaces.find(workspace => workspace.id === binding?.activeWorkspaceId);
|
|
883
|
+
const hasWorkspace = active !== undefined;
|
|
884
|
+
const hasSession = binding?.activeSessionId !== undefined;
|
|
885
|
+
const balance = state.balance ?? '—';
|
|
886
|
+
const context = state.context ?? '—';
|
|
887
|
+
const workspaceLabel = active?.title ?? t(locale, 'notSelected');
|
|
888
|
+
const sessionLabel = hasSession
|
|
889
|
+
? `${t(locale, 'session')} ${binding.activeSessionId.slice(0, 8)}`
|
|
890
|
+
: t(locale, 'notSelectedSession');
|
|
891
|
+
const soundLabel = state.sound ? t(locale, 'soundOn') : t(locale, 'soundOff');
|
|
892
|
+
const compactLabel = `${t(locale, 'compact')}${state.context === undefined ? '' : ` — ${state.context}`}`;
|
|
893
|
+
const button = (label, data, style, enabled) => enabled
|
|
894
|
+
? `<tg-button type="callback_data" style="${style}" data="${data}">${escapeHtml(label)}</tg-button>`
|
|
895
|
+
: `<tg-button type="disabled" style="${style}">${escapeHtml(label)}</tg-button>`;
|
|
896
|
+
const html = [
|
|
897
|
+
`<h1>${escapeHtml(balance)}</h1>`,
|
|
898
|
+
`<p><b>${escapeHtml(locale === 'ru' ? 'Пространство' : 'Workspace')}:</b> ${escapeHtml(workspaceLabel)}</p>`,
|
|
899
|
+
`<p><b>${escapeHtml(t(locale, 'session'))}:</b> ${escapeHtml(sessionLabel)}</p>`,
|
|
900
|
+
`<p><b>${escapeHtml(t(locale, 'context'))}:</b> ${escapeHtml(context)}</p>`,
|
|
901
|
+
`<tg-button-row align="left">${button(t(locale, 'workspaces'), 'menu:workspaces', 'primary', true)}${button(t(locale, 'sessions'), 'menu:sessions', 'primary', hasWorkspace)}</tg-button-row>`,
|
|
902
|
+
`<tg-button-row align="left">${button(t(locale, 'newSession'), 'new', 'success', true)}${button(compactLabel, 'menu:compact', 'danger', hasSession)}</tg-button-row>`,
|
|
903
|
+
`<tg-button-row align="left">${button(soundLabel, 'menu:sound', state.sound ? 'success' : 'link', true)}${button(t(locale, 'stop'), 'menu:stop', 'danger', hasSession)}</tg-button-row>`,
|
|
904
|
+
].join('\n');
|
|
905
|
+
const text = [
|
|
906
|
+
balance,
|
|
907
|
+
`${locale === 'ru' ? 'Пространство' : 'Workspace'}: ${workspaceLabel}`,
|
|
908
|
+
`${t(locale, 'session')}: ${sessionLabel}`,
|
|
909
|
+
`${t(locale, 'context')}: ${context}`,
|
|
910
|
+
'',
|
|
911
|
+
].join('\n');
|
|
912
|
+
const keyboard = new InlineKeyboard()
|
|
913
|
+
.text(t(locale, 'workspaces'), 'menu:workspaces')
|
|
914
|
+
.text(t(locale, 'sessions'), 'menu:sessions').row()
|
|
915
|
+
.text(t(locale, 'newSession'), 'new')
|
|
916
|
+
.text(compactLabel, 'menu:compact').row()
|
|
917
|
+
.text(soundLabel, 'menu:sound')
|
|
918
|
+
.text(t(locale, 'stop'), 'menu:stop');
|
|
919
|
+
return { html, text, keyboard };
|
|
920
|
+
}
|
|
921
|
+
async function sendRich(runtime, chatId, view, silent = false) {
|
|
922
|
+
if (runtime.rich) {
|
|
923
|
+
try {
|
|
924
|
+
const message = await runtime.bot.api.sendRichMessage(chatId, { html: view.html }, { disable_notification: silent });
|
|
925
|
+
return message.message_id;
|
|
926
|
+
}
|
|
927
|
+
catch (error) {
|
|
928
|
+
runtime.logger.warn('rich-send-failed', messageOf(error), { chatId });
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
try {
|
|
932
|
+
const message = await runtime.bot.api.sendMessage(chatId, view.text, {
|
|
933
|
+
reply_markup: view.keyboard,
|
|
934
|
+
disable_notification: silent,
|
|
935
|
+
});
|
|
936
|
+
return message.message_id;
|
|
937
|
+
}
|
|
938
|
+
catch (error) {
|
|
939
|
+
runtime.logger.error('send-failed', messageOf(error), { chatId });
|
|
940
|
+
}
|
|
941
|
+
try {
|
|
942
|
+
const message = await runtime.bot.api.sendMessage(chatId, view.text, { disable_notification: silent });
|
|
943
|
+
return message.message_id;
|
|
944
|
+
}
|
|
945
|
+
catch (error) {
|
|
946
|
+
runtime.logger.error('send-failed', messageOf(error), { chatId });
|
|
947
|
+
return undefined;
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
async function editRich(runtime, chatId, messageId, view) {
|
|
951
|
+
if (runtime.rich) {
|
|
952
|
+
try {
|
|
953
|
+
await runtime.bot.api.editMessageText(chatId, messageId, { html: view.html });
|
|
954
|
+
return;
|
|
955
|
+
}
|
|
956
|
+
catch (error) {
|
|
957
|
+
runtime.logger.warn('rich-edit-failed', messageOf(error), { chatId });
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
try {
|
|
961
|
+
await runtime.bot.api.editMessageText(chatId, messageId, view.text, { reply_markup: view.keyboard });
|
|
962
|
+
return;
|
|
963
|
+
}
|
|
964
|
+
catch (error) {
|
|
965
|
+
runtime.logger.warn('menu-edit-failed', messageOf(error), { chatId });
|
|
966
|
+
}
|
|
967
|
+
await sendRich(runtime, chatId, view);
|
|
968
|
+
}
|
|
969
|
+
async function sendPlain(runtime, chatId, text, silent = false) {
|
|
970
|
+
try {
|
|
971
|
+
await runtime.bot.api.sendMessage(chatId, text, { disable_notification: silent });
|
|
972
|
+
}
|
|
973
|
+
catch (error) {
|
|
974
|
+
runtime.logger.error('send-failed', messageOf(error), { chatId });
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
async function sendMainMenu(runtime, chatId, locale, editMessageId) {
|
|
978
|
+
const state = await getMenuState(runtime, chatId, locale);
|
|
979
|
+
const view = buildMainMenu(runtime.workspaces.list(), state, locale);
|
|
980
|
+
if (editMessageId !== undefined)
|
|
981
|
+
await editRich(runtime, chatId, editMessageId, view);
|
|
982
|
+
else
|
|
983
|
+
await sendRich(runtime, chatId, view);
|
|
984
|
+
}
|
|
985
|
+
async function sendBootGreeting(runtime) {
|
|
986
|
+
// The greeting marks a fresh Host start, not an HMR reload of this plugin.
|
|
987
|
+
if (process.uptime() > 180)
|
|
988
|
+
return;
|
|
989
|
+
const adminUserId = runtime.adminUserId;
|
|
990
|
+
if (adminUserId === undefined)
|
|
991
|
+
return;
|
|
992
|
+
const binding = runtime.store.get(adminUserId);
|
|
993
|
+
const locale = binding?.locale ?? 'ru';
|
|
994
|
+
const view = {
|
|
995
|
+
html: [
|
|
996
|
+
`<h2>${escapeHtml(t(locale, 'onlineTitle'))}</h2>`,
|
|
997
|
+
`<p>${escapeHtml(t(locale, 'onlineText'))}</p>`,
|
|
998
|
+
`<tg-button-row align="left"><tg-button type="callback_data" style="primary" data="menu:home">${escapeHtml(t(locale, 'openMenu'))}</tg-button></tg-button-row>`,
|
|
999
|
+
].join('\n'),
|
|
1000
|
+
text: `${t(locale, 'onlineTitle')}\n${t(locale, 'onlineText')}`,
|
|
1001
|
+
keyboard: new InlineKeyboard().text(t(locale, 'openMenu'), 'menu:home'),
|
|
1002
|
+
};
|
|
1003
|
+
await sendRich(runtime, adminUserId, view, binding?.sound === false);
|
|
1004
|
+
}
|
|
1005
|
+
function buildStopView(locale) {
|
|
1006
|
+
const html = [
|
|
1007
|
+
`<h2>${escapeHtml(t(locale, 'stopConfirmTitle'))}</h2>`,
|
|
1008
|
+
`<p>${escapeHtml(t(locale, 'stopConfirmText'))}</p>`,
|
|
1009
|
+
`<tg-button-row align="left"><tg-button type="callback_data" style="danger" data="stop:yes">${escapeHtml(t(locale, 'stopYes'))}</tg-button><tg-button type="callback_data" style="link" data="menu:home">${escapeHtml(t(locale, 'back'))}</tg-button></tg-button-row>`,
|
|
1010
|
+
].join('\n');
|
|
1011
|
+
const text = [t(locale, 'stopConfirmTitle'), t(locale, 'stopConfirmText')].join('\n');
|
|
1012
|
+
const keyboard = new InlineKeyboard()
|
|
1013
|
+
.text(t(locale, 'stopYes'), 'stop:yes')
|
|
1014
|
+
.text(t(locale, 'back'), 'menu:home');
|
|
1015
|
+
return { html, text, keyboard };
|
|
1016
|
+
}
|
|
1017
|
+
function buildCompactView(state, locale) {
|
|
1018
|
+
const context = state.context ?? '—';
|
|
1019
|
+
const html = [
|
|
1020
|
+
`<h2>${escapeHtml(t(locale, 'compactHistory'))}</h2>`,
|
|
1021
|
+
`<p><b>${escapeHtml(t(locale, 'context'))}:</b> ${escapeHtml(context)}</p>`,
|
|
1022
|
+
`<p>${escapeHtml(t(locale, 'compactConfirm'))}</p>`,
|
|
1023
|
+
`<tg-button-row align="left"><tg-button type="callback_data" style="danger" data="compact:yes">${escapeHtml(t(locale, 'compact'))}</tg-button><tg-button type="callback_data" style="link" data="menu:home">${escapeHtml(t(locale, 'back'))}</tg-button></tg-button-row>`,
|
|
1024
|
+
].join('\n');
|
|
1025
|
+
const text = [
|
|
1026
|
+
t(locale, 'compactHistory'),
|
|
1027
|
+
`${t(locale, 'context')}: ${context}`,
|
|
1028
|
+
t(locale, 'compactConfirm'),
|
|
1029
|
+
].join('\n');
|
|
1030
|
+
const keyboard = new InlineKeyboard().text(t(locale, 'compact'), 'compact:yes').text(t(locale, 'back'), 'menu:home');
|
|
1031
|
+
return { html, text, keyboard };
|
|
1032
|
+
}
|
|
1033
|
+
function sessionTitle(session, locale) {
|
|
1034
|
+
if (session.blank)
|
|
1035
|
+
return t(locale, 'newSessionTitle');
|
|
1036
|
+
const title = session.projections?.values?.title;
|
|
1037
|
+
if (typeof title === 'string' && title.trim().length > 0)
|
|
1038
|
+
return truncate(title.trim(), 48);
|
|
1039
|
+
return `${t(locale, 'session')} ${session.sessionId.slice(0, 8)}`;
|
|
1040
|
+
}
|
|
1041
|
+
async function listSessions(runtime, workspace) {
|
|
1042
|
+
const archived = new Set(runtime.workspaces.archivedSessionIds);
|
|
1043
|
+
const fallback = () => workspace.sessionIds
|
|
1044
|
+
.filter(id => !archived.has(id))
|
|
1045
|
+
.map(id => ({ sessionId: id, updatedAt: 0, running: false, blank: false }));
|
|
1046
|
+
try {
|
|
1047
|
+
const value = await runtime.sessions.list({}, AbortSignal.timeout(10_000));
|
|
1048
|
+
const items = value.items
|
|
1049
|
+
.filter(item => item.origin !== 'subagent' && !archived.has(item.sessionId) && workspace.sessionIds.includes(item.sessionId))
|
|
1050
|
+
.sort((a, b) => b.updatedAt - a.updatedAt);
|
|
1051
|
+
return items.length > 0 ? items : fallback();
|
|
1052
|
+
}
|
|
1053
|
+
catch (error) {
|
|
1054
|
+
runtime.logger.warn('session-list-failed', messageOf(error), { workspaceId: workspace.id });
|
|
1055
|
+
return fallback();
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
function buildSessionsView(workspace, sessions, locale) {
|
|
1059
|
+
const keyboard = new InlineKeyboard();
|
|
1060
|
+
for (const session of sessions.slice(0, 8)) {
|
|
1061
|
+
const mark = session.running ? '🟢' : '⚪';
|
|
1062
|
+
keyboard.text(`${mark} ${truncate(sessionTitle(session, locale), 34)}`, `s:${session.sessionId}`).row();
|
|
1063
|
+
}
|
|
1064
|
+
keyboard.text(t(locale, 'newSession'), 'new').row();
|
|
1065
|
+
keyboard.text(t(locale, 'backToWorkspaces'), 'menu:workspaces');
|
|
1066
|
+
return {
|
|
1067
|
+
text: `${workspace.title}\n${sessions.length === 0 ? t(locale, 'noSessions') : t(locale, 'selectSession')}`,
|
|
1068
|
+
keyboard,
|
|
1069
|
+
};
|
|
1070
|
+
}
|
|
1071
|
+
function buildOpenedView(workspace, title, locale) {
|
|
1072
|
+
const keyboard = new InlineKeyboard()
|
|
1073
|
+
.text(t(locale, 'sessions'), 'menu:sessions').row()
|
|
1074
|
+
.text(t(locale, 'newSession'), 'new').row()
|
|
1075
|
+
.text(t(locale, 'backToWorkspaces'), 'menu:workspaces');
|
|
1076
|
+
return {
|
|
1077
|
+
text: `${t(locale, 'opened')}: ${workspace.title}\n${title}\n\n${t(locale, 'write')}`,
|
|
1078
|
+
keyboard,
|
|
1079
|
+
};
|
|
1080
|
+
}
|
|
1081
|
+
async function submitPrompt(runtime, chatId, sessionId, prompt, locale) {
|
|
1082
|
+
runtime.sessionChats.set(sessionId, chatId);
|
|
1083
|
+
runtime.logger.info('session-tracked', 'session routed to chat', { chatId, sessionId });
|
|
1084
|
+
await ensureProgress(runtime, chatId, sessionId, t(locale, 'thinking'));
|
|
1085
|
+
const requestId = `telegram:${chatId}:${prompt.messageId}`;
|
|
1086
|
+
try {
|
|
1087
|
+
await runtime.sessions.prompt({ requestId, sessionId, mode: 'queue', content: [{ type: 'text', text: prompt.text }] }, AbortSignal.timeout(20_000));
|
|
1088
|
+
runtime.logger.info('prompt-accepted', 'prompt accepted', {
|
|
1089
|
+
chatId,
|
|
1090
|
+
sessionId,
|
|
1091
|
+
textLength: prompt.text.length,
|
|
1092
|
+
});
|
|
1093
|
+
}
|
|
1094
|
+
catch (error) {
|
|
1095
|
+
runtime.logger.error('prompt-failed', messageOf(error), {
|
|
1096
|
+
chatId,
|
|
1097
|
+
sessionId,
|
|
1098
|
+
...(codeOf(error) === undefined ? {} : { code: codeOf(error) }),
|
|
1099
|
+
});
|
|
1100
|
+
const line = `⚠️ ${errorText(locale, error)}`;
|
|
1101
|
+
if (runtime.progress.has(sessionId))
|
|
1102
|
+
await editProgress(runtime, sessionId, line, true);
|
|
1103
|
+
else
|
|
1104
|
+
await runtime.bot.api.sendMessage(chatId, line).catch(() => undefined);
|
|
1105
|
+
clearProgress(runtime, sessionId);
|
|
1106
|
+
runtime.sessionChats.delete(sessionId);
|
|
1107
|
+
}
|
|
1108
|
+
}
|
|
1109
|
+
async function activateSession(runtime, chatId, userId, workspace, sessionId, title, locale, prompt) {
|
|
1110
|
+
await runtime.store.set({
|
|
1111
|
+
chatId: String(chatId),
|
|
1112
|
+
userId,
|
|
1113
|
+
activeWorkspaceId: workspace.id,
|
|
1114
|
+
activeSessionId: sessionId,
|
|
1115
|
+
locale,
|
|
1116
|
+
updatedAt: Date.now(),
|
|
1117
|
+
});
|
|
1118
|
+
runtime.pendingPrompt.delete(chatId);
|
|
1119
|
+
const view = buildOpenedView(workspace, title, locale);
|
|
1120
|
+
if (prompt !== undefined)
|
|
1121
|
+
await submitPrompt(runtime, chatId, sessionId, prompt, locale);
|
|
1122
|
+
return view;
|
|
1123
|
+
}
|
|
1124
|
+
async function chooseWorkspace(runtime, chatId, userId, workspace, locale) {
|
|
1125
|
+
const sessions = await listSessions(runtime, workspace);
|
|
1126
|
+
if (sessions.length === 1) {
|
|
1127
|
+
const only = sessions[0];
|
|
1128
|
+
return activateSession(runtime, chatId, userId, workspace, only.sessionId, sessionTitle(only, locale), locale);
|
|
1129
|
+
}
|
|
1130
|
+
await runtime.store.set({
|
|
1131
|
+
chatId: String(chatId),
|
|
1132
|
+
userId,
|
|
1133
|
+
activeWorkspaceId: workspace.id,
|
|
1134
|
+
locale,
|
|
1135
|
+
updatedAt: Date.now(),
|
|
1136
|
+
});
|
|
1137
|
+
runtime.pendingPrompt.delete(chatId);
|
|
1138
|
+
return buildSessionsView(workspace, sessions, locale);
|
|
1139
|
+
}
|
|
1140
|
+
async function createSessionForWorkspace(runtime, chatId, userId, workspace, locale, prompt) {
|
|
1141
|
+
const created = await runtime.sessions.create({ workspaceId: workspace.id });
|
|
1142
|
+
return activateSession(runtime, chatId, userId, workspace, created.sessionId, t(locale, 'newSessionTitle'), locale, prompt);
|
|
1143
|
+
}
|
|
1144
|
+
async function editOrReply(grammyCtx, text, keyboard) {
|
|
1145
|
+
try {
|
|
1146
|
+
await grammyCtx.editMessageText(text, { reply_markup: keyboard });
|
|
1147
|
+
}
|
|
1148
|
+
catch {
|
|
1149
|
+
await grammyCtx.reply(text, { reply_markup: keyboard }).catch(() => undefined);
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
async function ensureProgress(runtime, chatId, sessionId, text) {
|
|
1153
|
+
if (runtime.progress.has(sessionId))
|
|
1154
|
+
return;
|
|
1155
|
+
const silent = runtime.store.get(String(chatId))?.sound === false;
|
|
1156
|
+
try {
|
|
1157
|
+
const message = await runtime.bot.api.sendMessage(chatId, text, { disable_notification: silent });
|
|
1158
|
+
runtime.progress.set(sessionId, { chatId, messageId: message.message_id, lastEditAt: Date.now() });
|
|
1159
|
+
}
|
|
1160
|
+
catch (error) {
|
|
1161
|
+
runtime.logger.warn('progress-send-failed', messageOf(error), { chatId, sessionId });
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
1164
|
+
async function editProgress(runtime, sessionId, text, force) {
|
|
1165
|
+
const state = runtime.progress.get(sessionId);
|
|
1166
|
+
if (state === undefined)
|
|
1167
|
+
return;
|
|
1168
|
+
const now = Date.now();
|
|
1169
|
+
if (state.timer !== undefined) {
|
|
1170
|
+
clearTimeout(state.timer);
|
|
1171
|
+
state.timer = undefined;
|
|
1172
|
+
}
|
|
1173
|
+
if (!force && now - state.lastEditAt < 1_500) {
|
|
1174
|
+
// Keep the newest stage instead of dropping it; the timer applies it once
|
|
1175
|
+
// the edit throttle has elapsed.
|
|
1176
|
+
state.pendingText = text;
|
|
1177
|
+
state.timer = setTimeout(() => {
|
|
1178
|
+
state.timer = undefined;
|
|
1179
|
+
const pending = state.pendingText;
|
|
1180
|
+
state.pendingText = undefined;
|
|
1181
|
+
if (pending !== undefined)
|
|
1182
|
+
void editProgress(runtime, sessionId, pending, true);
|
|
1183
|
+
}, 1_500 - (now - state.lastEditAt));
|
|
1184
|
+
return;
|
|
1185
|
+
}
|
|
1186
|
+
state.lastEditAt = now;
|
|
1187
|
+
state.pendingText = undefined;
|
|
1188
|
+
try {
|
|
1189
|
+
await runtime.bot.api.editMessageText(state.chatId, state.messageId, text);
|
|
1190
|
+
}
|
|
1191
|
+
catch (error) {
|
|
1192
|
+
const telegram = telegramErrorOf(error);
|
|
1193
|
+
if (telegram.description?.includes('message is not modified') === true)
|
|
1194
|
+
return;
|
|
1195
|
+
runtime.logger.warn('progress-edit-failed', messageOf(error), { sessionId });
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
function clearProgress(runtime, sessionId) {
|
|
1199
|
+
const state = runtime.progress.get(sessionId);
|
|
1200
|
+
if (state?.timer !== undefined)
|
|
1201
|
+
clearTimeout(state.timer);
|
|
1202
|
+
runtime.progress.delete(sessionId);
|
|
1203
|
+
}
|
|
1204
|
+
async function sendText(runtime, chatId, text, silent = false) {
|
|
1205
|
+
for (const part of splitText(text, 15_000)) {
|
|
1206
|
+
if (runtime.rich) {
|
|
1207
|
+
try {
|
|
1208
|
+
await runtime.bot.api.sendRichMessage(chatId, { markdown: part }, { disable_notification: silent });
|
|
1209
|
+
continue;
|
|
1210
|
+
}
|
|
1211
|
+
catch (error) {
|
|
1212
|
+
runtime.logger.warn('rich-send-failed', messageOf(error), { chatId, chars: part.length });
|
|
1213
|
+
}
|
|
1214
|
+
try {
|
|
1215
|
+
const html = `<p>${escapeHtml(part).replaceAll('\n', '<br>')}</p>`;
|
|
1216
|
+
await runtime.bot.api.sendRichMessage(chatId, { html }, { disable_notification: silent });
|
|
1217
|
+
continue;
|
|
1218
|
+
}
|
|
1219
|
+
catch (error) {
|
|
1220
|
+
runtime.logger.warn('rich-html-send-failed', messageOf(error), { chatId, chars: part.length });
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
for (const plain of splitText(part, 3_800)) {
|
|
1224
|
+
try {
|
|
1225
|
+
await runtime.bot.api.sendMessage(chatId, plain, { disable_notification: silent });
|
|
1226
|
+
}
|
|
1227
|
+
catch (error) {
|
|
1228
|
+
runtime.logger.error('send-failed', messageOf(error), { chatId, chars: plain.length });
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
}
|
|
1232
|
+
}
|
|
1233
|
+
function assistantText(event) {
|
|
1234
|
+
const data = asRecord(event.data);
|
|
1235
|
+
const message = asRecord(data?.['message']);
|
|
1236
|
+
const content = message?.['content'];
|
|
1237
|
+
if (!Array.isArray(content))
|
|
1238
|
+
return '';
|
|
1239
|
+
return content
|
|
1240
|
+
.map(block => asRecord(block))
|
|
1241
|
+
.filter((block) => block !== undefined)
|
|
1242
|
+
.filter(block => block['type'] === 'text' && typeof block['text'] === 'string')
|
|
1243
|
+
.map(block => block['text'])
|
|
1244
|
+
.join('\n\n')
|
|
1245
|
+
.trim();
|
|
1246
|
+
}
|
|
1247
|
+
function turnEndText(event, locale) {
|
|
1248
|
+
const data = asRecord(event.data);
|
|
1249
|
+
const reason = asRecord(data?.['reason']);
|
|
1250
|
+
const kind = typeof reason?.['kind'] === 'string' ? reason['kind'] : 'error';
|
|
1251
|
+
switch (kind) {
|
|
1252
|
+
case 'completed': return t(locale, 'done');
|
|
1253
|
+
case 'aborted': return t(locale, 'stopped');
|
|
1254
|
+
case 'max-tokens': return t(locale, 'maxTokens');
|
|
1255
|
+
case 'interrupted': return t(locale, 'interrupted');
|
|
1256
|
+
case 'blocked': return t(locale, 'blocked');
|
|
1257
|
+
default: return t(locale, 'error');
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
/**
|
|
1261
|
+
* Resolve the Telegram chat that should see a Session's events. The active
|
|
1262
|
+
* binding is authoritative, but a Session prompted from Telegram stays routed
|
|
1263
|
+
* after the user switches to another workspace or session, so its progress and
|
|
1264
|
+
* final answer keep arriving in parallel.
|
|
1265
|
+
*/
|
|
1266
|
+
function chatForSession(runtime, sessionId) {
|
|
1267
|
+
const tracked = runtime.sessionChats.get(sessionId);
|
|
1268
|
+
if (tracked !== undefined)
|
|
1269
|
+
return String(tracked);
|
|
1270
|
+
return runtime.store.sessionChat(sessionId);
|
|
1271
|
+
}
|
|
1272
|
+
async function handleSessionEvent(runtime, session, event) {
|
|
1273
|
+
if (session.header.origin === 'subagent')
|
|
1274
|
+
return;
|
|
1275
|
+
const chatIdRaw = chatForSession(runtime, session.id);
|
|
1276
|
+
if (chatIdRaw === undefined)
|
|
1277
|
+
return;
|
|
1278
|
+
const chatId = Number(chatIdRaw);
|
|
1279
|
+
if (!Number.isSafeInteger(chatId))
|
|
1280
|
+
return;
|
|
1281
|
+
const binding = runtime.store.get(chatIdRaw);
|
|
1282
|
+
const locale = binding?.locale ?? 'ru';
|
|
1283
|
+
const silent = binding?.sound === false;
|
|
1284
|
+
switch (event.type) {
|
|
1285
|
+
case 'turn/start':
|
|
1286
|
+
runtime.logger.info('turn-start', 'session turn started', {
|
|
1287
|
+
chatId,
|
|
1288
|
+
sessionId: session.id,
|
|
1289
|
+
active: binding?.activeSessionId === session.id,
|
|
1290
|
+
});
|
|
1291
|
+
await ensureProgress(runtime, chatId, session.id, t(locale, 'thinking'));
|
|
1292
|
+
break;
|
|
1293
|
+
case 'tool/call': {
|
|
1294
|
+
const data = asRecord(event.data);
|
|
1295
|
+
const name = typeof data?.['name'] === 'string' ? data['name'] : 'tool';
|
|
1296
|
+
const detail = toolDetail(data?.['arguments']);
|
|
1297
|
+
const label = detail === undefined ? `🔧 ${name}` : `🔧 ${name}: ${truncate(detail.split('\n')[0] ?? detail, 60)}`;
|
|
1298
|
+
await editProgress(runtime, session.id, label, false);
|
|
1299
|
+
break;
|
|
1300
|
+
}
|
|
1301
|
+
case 'assistant/message': {
|
|
1302
|
+
const text = assistantText(event);
|
|
1303
|
+
if (text.length === 0)
|
|
1304
|
+
break;
|
|
1305
|
+
await editProgress(runtime, session.id, t(locale, 'writing'), false);
|
|
1306
|
+
await sendText(runtime, chatId, text, silent);
|
|
1307
|
+
break;
|
|
1308
|
+
}
|
|
1309
|
+
case 'turn/end': {
|
|
1310
|
+
await editProgress(runtime, session.id, turnEndText(event, locale), true);
|
|
1311
|
+
clearProgress(runtime, session.id);
|
|
1312
|
+
runtime.sessionChats.delete(session.id);
|
|
1313
|
+
void maybeWarnLowBalance(runtime, chatId, locale, silent);
|
|
1314
|
+
break;
|
|
1315
|
+
}
|
|
1316
|
+
default:
|
|
1317
|
+
break;
|
|
1318
|
+
}
|
|
1319
|
+
}
|
|
1320
|
+
function errorText(locale, error) {
|
|
1321
|
+
const code = codeOf(error);
|
|
1322
|
+
if (code === 'session/writer-held')
|
|
1323
|
+
return t(locale, 'busy');
|
|
1324
|
+
if (code === 'session/not-found')
|
|
1325
|
+
return t(locale, 'sessionMissing');
|
|
1326
|
+
if (code === 'workspace/not-found')
|
|
1327
|
+
return t(locale, 'workspaceMissing');
|
|
1328
|
+
return messageOf(error);
|
|
1329
|
+
}
|
|
1330
|
+
async function startPolling(bot, logger, signal) {
|
|
1331
|
+
let attempt = 0;
|
|
1332
|
+
while (!signal.aborted) {
|
|
1333
|
+
try {
|
|
1334
|
+
await bot.start({
|
|
1335
|
+
allowed_updates: ['message', 'callback_query'],
|
|
1336
|
+
drop_pending_updates: true,
|
|
1337
|
+
onStart: info => logger.info('polling', `polling as @${info.username}`, { attempt: attempt + 1 }),
|
|
1338
|
+
});
|
|
1339
|
+
return;
|
|
1340
|
+
}
|
|
1341
|
+
catch (error) {
|
|
1342
|
+
if (signal.aborted)
|
|
1343
|
+
return;
|
|
1344
|
+
const telegram = telegramErrorOf(error);
|
|
1345
|
+
if (telegram.error_code === 401) {
|
|
1346
|
+
logger.error('polling-unauthorized', 'Telegram rejected the bot token; update credentials and restart the Host');
|
|
1347
|
+
return;
|
|
1348
|
+
}
|
|
1349
|
+
attempt += 1;
|
|
1350
|
+
const delay = Math.min(60_000, 1_000 * 2 ** Math.min(attempt, 6));
|
|
1351
|
+
logger.error('polling-failed', messageOf(error), {
|
|
1352
|
+
attempt,
|
|
1353
|
+
retryInMs: delay,
|
|
1354
|
+
...(telegram.error_code === undefined ? {} : { telegramCode: telegram.error_code }),
|
|
1355
|
+
});
|
|
1356
|
+
await sleep(delay, signal);
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
async function runBot(ctx, config, workspaces, sessions, credentials, logger, signal, publish) {
|
|
1361
|
+
logger.info('starting', 'resolving bot token');
|
|
1362
|
+
const token = await resolveBotToken(ctx, config, credentials, signal);
|
|
1363
|
+
if (signal.aborted)
|
|
1364
|
+
return;
|
|
1365
|
+
if (token === undefined) {
|
|
1366
|
+
logger.warn('token-missing', 'Telegram bot token is not configured; open Plugins -> @shliamb/dsh-telegram-bot to set it');
|
|
1367
|
+
return;
|
|
1368
|
+
}
|
|
1369
|
+
const adminUserId = config.adminUserId ?? config.allowedUserIds?.[0];
|
|
1370
|
+
const allowedUserIds = new Set(config.allowedUserIds ?? []);
|
|
1371
|
+
if (adminUserId !== undefined)
|
|
1372
|
+
allowedUserIds.add(adminUserId);
|
|
1373
|
+
const bot = new Bot(token, config.apiRoot === undefined ? undefined : { client: { apiRoot: config.apiRoot } });
|
|
1374
|
+
publish(bot);
|
|
1375
|
+
const store = await BindingStore.open(ctx.get('storageDomain'), logger);
|
|
1376
|
+
if (signal.aborted) {
|
|
1377
|
+
await store.close();
|
|
1378
|
+
return;
|
|
1379
|
+
}
|
|
1380
|
+
const account = ctx.get('accountController');
|
|
1381
|
+
const tokenMeter = ctx.get('tokenMeter');
|
|
1382
|
+
const commands = ctx.get('commands');
|
|
1383
|
+
const runtime = {
|
|
1384
|
+
bot,
|
|
1385
|
+
store,
|
|
1386
|
+
workspaces,
|
|
1387
|
+
sessions,
|
|
1388
|
+
account,
|
|
1389
|
+
tokenMeter,
|
|
1390
|
+
commands,
|
|
1391
|
+
adminUserId,
|
|
1392
|
+
allowedUserIds: [...allowedUserIds],
|
|
1393
|
+
logger,
|
|
1394
|
+
progress: new Map(),
|
|
1395
|
+
sessionChats: new Map(),
|
|
1396
|
+
queues: new Map(),
|
|
1397
|
+
pendingPrompt: new Map(),
|
|
1398
|
+
pendingApprovals: new Map(),
|
|
1399
|
+
pendingQuestions: new Map(),
|
|
1400
|
+
balanceCache: { at: 0 },
|
|
1401
|
+
contextCache: new Map(),
|
|
1402
|
+
lowBalanceWarnedAt: new Map(),
|
|
1403
|
+
rich: config.rich !== false,
|
|
1404
|
+
lowBalanceUsd: config.lowBalanceUsd ?? 1,
|
|
1405
|
+
};
|
|
1406
|
+
logger.info('bot-created', 'Telegram client created');
|
|
1407
|
+
const disposers = [];
|
|
1408
|
+
disposers.push(ctx.on('session/event', (session, event) => {
|
|
1409
|
+
void handleSessionEvent(runtime, session, event).catch((error) => {
|
|
1410
|
+
logger.error('event-failed', messageOf(error), { sessionId: session.id, event: event.type });
|
|
1411
|
+
});
|
|
1412
|
+
}));
|
|
1413
|
+
disposers.push(ctx.on('approval/request', (request, next) => handleApproval(runtime, request, next)));
|
|
1414
|
+
disposers.push(ctx.on('user-questions/request', (request, next) => handleQuestion(runtime, request, next)));
|
|
1415
|
+
// Log Telegram API failures once per method per 30 seconds; polling can
|
|
1416
|
+
// otherwise flood the file during a network outage.
|
|
1417
|
+
const lastApiError = new Map();
|
|
1418
|
+
bot.api.config.use(async (prev, method, payload, callSignal) => {
|
|
1419
|
+
try {
|
|
1420
|
+
return await prev(method, payload, callSignal);
|
|
1421
|
+
}
|
|
1422
|
+
catch (error) {
|
|
1423
|
+
const now = Date.now();
|
|
1424
|
+
const last = lastApiError.get(method) ?? 0;
|
|
1425
|
+
if (now - last >= 30_000) {
|
|
1426
|
+
lastApiError.set(method, now);
|
|
1427
|
+
logger.error('telegram-api', messageOf(error), {
|
|
1428
|
+
method,
|
|
1429
|
+
...(telegramErrorOf(error).error_code === undefined ? {} : { telegramCode: telegramErrorOf(error).error_code }),
|
|
1430
|
+
});
|
|
1431
|
+
}
|
|
1432
|
+
throw error;
|
|
1433
|
+
}
|
|
1434
|
+
});
|
|
1435
|
+
const deniedUsers = new Set();
|
|
1436
|
+
bot.use(async (grammyCtx, next) => {
|
|
1437
|
+
const userId = grammyCtx.from?.id;
|
|
1438
|
+
if (userId === undefined || !runtime.allowedUserIds.includes(userId)) {
|
|
1439
|
+
if (userId !== undefined && !deniedUsers.has(userId)) {
|
|
1440
|
+
deniedUsers.add(userId);
|
|
1441
|
+
logger.warn('unauthorized', 'ignored an update from a user outside the allowlist', {
|
|
1442
|
+
userId,
|
|
1443
|
+
chatType: grammyCtx.chat?.type ?? 'unknown',
|
|
1444
|
+
});
|
|
1445
|
+
}
|
|
1446
|
+
return;
|
|
1447
|
+
}
|
|
1448
|
+
if (grammyCtx.chat?.type !== 'private') {
|
|
1449
|
+
logger.warn('non-private', 'ignored an update from a non-private chat', {
|
|
1450
|
+
userId,
|
|
1451
|
+
chatType: grammyCtx.chat?.type ?? 'unknown',
|
|
1452
|
+
});
|
|
1453
|
+
return;
|
|
1454
|
+
}
|
|
1455
|
+
await next();
|
|
1456
|
+
});
|
|
1457
|
+
bot.command('start', async (grammyCtx) => {
|
|
1458
|
+
const locale = localeOf(grammyCtx.from?.language_code);
|
|
1459
|
+
const chatId = grammyCtx.chat?.id;
|
|
1460
|
+
if (chatId === undefined)
|
|
1461
|
+
return;
|
|
1462
|
+
const binding = store.get(chatId);
|
|
1463
|
+
if (binding !== undefined) {
|
|
1464
|
+
await store.set({ ...binding, locale, updatedAt: Date.now() });
|
|
1465
|
+
}
|
|
1466
|
+
await sendMainMenu(runtime, chatId, locale);
|
|
1467
|
+
});
|
|
1468
|
+
bot.command('menu', async (grammyCtx) => {
|
|
1469
|
+
const chatId = grammyCtx.chat?.id;
|
|
1470
|
+
if (chatId === undefined)
|
|
1471
|
+
return;
|
|
1472
|
+
const locale = localeOf(grammyCtx.from?.language_code);
|
|
1473
|
+
await sendMainMenu(runtime, chatId, locale);
|
|
1474
|
+
});
|
|
1475
|
+
bot.command('new', async (grammyCtx) => {
|
|
1476
|
+
const chatId = grammyCtx.chat?.id;
|
|
1477
|
+
const userId = grammyCtx.from?.id;
|
|
1478
|
+
if (chatId === undefined || userId === undefined)
|
|
1479
|
+
return;
|
|
1480
|
+
const locale = localeOf(grammyCtx.from?.language_code);
|
|
1481
|
+
const binding = store.get(chatId);
|
|
1482
|
+
const workspace = binding?.activeWorkspaceId === undefined ? undefined : workspaces.get(binding.activeWorkspaceId);
|
|
1483
|
+
if (workspace === undefined) {
|
|
1484
|
+
await sendWorkspaceView(grammyCtx, workspaces.list(), store, locale);
|
|
1485
|
+
return;
|
|
1486
|
+
}
|
|
1487
|
+
try {
|
|
1488
|
+
const pending = runtime.pendingPrompt.get(chatId);
|
|
1489
|
+
const view = await createSessionForWorkspace(runtime, chatId, userId, workspace, locale, pending);
|
|
1490
|
+
await grammyCtx.reply(view.text, { reply_markup: view.keyboard });
|
|
1491
|
+
logger.info('session-created', 'created a Session for the workspace', {
|
|
1492
|
+
chatId,
|
|
1493
|
+
workspaceId: workspace.id,
|
|
1494
|
+
});
|
|
1495
|
+
}
|
|
1496
|
+
catch (error) {
|
|
1497
|
+
logger.error('session-create-failed', messageOf(error), { chatId, workspaceId: workspace.id });
|
|
1498
|
+
await grammyCtx.reply(`⚠️ ${t(locale, 'createFailed')} ${errorText(locale, error)}`);
|
|
1499
|
+
}
|
|
1500
|
+
});
|
|
1501
|
+
bot.command('stop', async (grammyCtx) => {
|
|
1502
|
+
const chatId = grammyCtx.chat?.id;
|
|
1503
|
+
if (chatId === undefined)
|
|
1504
|
+
return;
|
|
1505
|
+
const locale = localeOf(grammyCtx.from?.language_code);
|
|
1506
|
+
await grammyCtx.reply(await stopActive(runtime, chatId, locale));
|
|
1507
|
+
});
|
|
1508
|
+
bot.command('status', async (grammyCtx) => {
|
|
1509
|
+
const chatId = grammyCtx.chat?.id;
|
|
1510
|
+
if (chatId === undefined)
|
|
1511
|
+
return;
|
|
1512
|
+
const locale = localeOf(grammyCtx.from?.language_code);
|
|
1513
|
+
await grammyCtx.reply(await statusText(runtime, chatId, locale));
|
|
1514
|
+
});
|
|
1515
|
+
bot.command('compact', async (grammyCtx) => {
|
|
1516
|
+
const chatId = grammyCtx.chat?.id;
|
|
1517
|
+
if (chatId === undefined)
|
|
1518
|
+
return;
|
|
1519
|
+
const locale = localeOf(grammyCtx.from?.language_code);
|
|
1520
|
+
const binding = store.get(chatId);
|
|
1521
|
+
if (binding?.activeSessionId === undefined) {
|
|
1522
|
+
await grammyCtx.reply(t(locale, 'noActiveSession'));
|
|
1523
|
+
return;
|
|
1524
|
+
}
|
|
1525
|
+
await grammyCtx.reply(await runCompact(runtime, chatId, locale, binding.activeSessionId));
|
|
1526
|
+
await sendMainMenu(runtime, chatId, locale);
|
|
1527
|
+
});
|
|
1528
|
+
bot.callbackQuery(/^ws:(.+)$/, async (grammyCtx) => {
|
|
1529
|
+
const workspaceId = grammyCtx.match[1];
|
|
1530
|
+
const chatId = grammyCtx.chat?.id;
|
|
1531
|
+
const userId = grammyCtx.from?.id;
|
|
1532
|
+
if (chatId === undefined || userId === undefined)
|
|
1533
|
+
return;
|
|
1534
|
+
const locale = localeOf(grammyCtx.from?.language_code);
|
|
1535
|
+
const workspace = workspaces.get(workspaceId);
|
|
1536
|
+
if (workspace === undefined) {
|
|
1537
|
+
await grammyCtx.answerCallbackQuery({ text: t(locale, 'notFound') });
|
|
1538
|
+
return;
|
|
1539
|
+
}
|
|
1540
|
+
await grammyCtx.answerCallbackQuery({ text: t(locale, 'selected') }).catch(() => undefined);
|
|
1541
|
+
logger.info('workspace-selected', 'workspace selected', { chatId, workspaceId: workspace.id });
|
|
1542
|
+
const view = await chooseWorkspace(runtime, chatId, userId, workspace, locale);
|
|
1543
|
+
await editOrReply(grammyCtx, view.text, view.keyboard);
|
|
1544
|
+
});
|
|
1545
|
+
bot.callbackQuery(/^s:(.+)$/, async (grammyCtx) => {
|
|
1546
|
+
const sessionId = grammyCtx.match[1];
|
|
1547
|
+
const chatId = grammyCtx.chat?.id;
|
|
1548
|
+
const userId = grammyCtx.from?.id;
|
|
1549
|
+
if (chatId === undefined || userId === undefined)
|
|
1550
|
+
return;
|
|
1551
|
+
const locale = localeOf(grammyCtx.from?.language_code);
|
|
1552
|
+
const binding = store.get(chatId);
|
|
1553
|
+
const workspace = binding?.activeWorkspaceId === undefined ? undefined : workspaces.get(binding.activeWorkspaceId);
|
|
1554
|
+
if (workspace === undefined) {
|
|
1555
|
+
await grammyCtx.answerCallbackQuery({ text: t(locale, 'workspaceMissing') });
|
|
1556
|
+
return;
|
|
1557
|
+
}
|
|
1558
|
+
const sessionsForWorkspace = await listSessions(runtime, workspace);
|
|
1559
|
+
const session = sessionsForWorkspace.find(item => item.sessionId === sessionId);
|
|
1560
|
+
if (session === undefined) {
|
|
1561
|
+
await grammyCtx.answerCallbackQuery({ text: t(locale, 'sessionNotFound') });
|
|
1562
|
+
return;
|
|
1563
|
+
}
|
|
1564
|
+
const pending = runtime.pendingPrompt.get(chatId);
|
|
1565
|
+
runtime.pendingPrompt.delete(chatId);
|
|
1566
|
+
await grammyCtx.answerCallbackQuery({ text: t(locale, 'selected') }).catch(() => undefined);
|
|
1567
|
+
const view = await activateSession(runtime, chatId, userId, workspace, session.sessionId, sessionTitle(session, locale), locale, pending);
|
|
1568
|
+
await editOrReply(grammyCtx, view.text, view.keyboard);
|
|
1569
|
+
logger.info('session-selected', 'session selected', {
|
|
1570
|
+
chatId,
|
|
1571
|
+
workspaceId: workspace.id,
|
|
1572
|
+
sessionId: session.sessionId,
|
|
1573
|
+
});
|
|
1574
|
+
});
|
|
1575
|
+
bot.callbackQuery('new', async (grammyCtx) => {
|
|
1576
|
+
const chatId = grammyCtx.chat?.id;
|
|
1577
|
+
const userId = grammyCtx.from?.id;
|
|
1578
|
+
if (chatId === undefined || userId === undefined)
|
|
1579
|
+
return;
|
|
1580
|
+
const locale = localeOf(grammyCtx.from?.language_code);
|
|
1581
|
+
const binding = store.get(chatId);
|
|
1582
|
+
const workspace = binding?.activeWorkspaceId === undefined ? undefined : workspaces.get(binding.activeWorkspaceId);
|
|
1583
|
+
if (workspace === undefined) {
|
|
1584
|
+
await grammyCtx.answerCallbackQuery({ text: t(locale, 'choose') }).catch(() => undefined);
|
|
1585
|
+
const view = buildWorkspaceView(workspaces.list(), store.get(chatId), locale);
|
|
1586
|
+
await editOrReply(grammyCtx, view.text, view.keyboard);
|
|
1587
|
+
return;
|
|
1588
|
+
}
|
|
1589
|
+
await grammyCtx.answerCallbackQuery({ text: t(locale, 'selected') }).catch(() => undefined);
|
|
1590
|
+
try {
|
|
1591
|
+
const pending = runtime.pendingPrompt.get(chatId);
|
|
1592
|
+
const view = await createSessionForWorkspace(runtime, chatId, userId, workspace, locale, pending);
|
|
1593
|
+
await editOrReply(grammyCtx, view.text, view.keyboard);
|
|
1594
|
+
logger.info('session-created', 'created a Session for the workspace', {
|
|
1595
|
+
chatId,
|
|
1596
|
+
workspaceId: workspace.id,
|
|
1597
|
+
});
|
|
1598
|
+
}
|
|
1599
|
+
catch (error) {
|
|
1600
|
+
logger.error('session-create-failed', messageOf(error), { chatId, workspaceId: workspace.id });
|
|
1601
|
+
await grammyCtx.reply(`⚠️ ${t(locale, 'createFailed')} ${errorText(locale, error)}`).catch(() => undefined);
|
|
1602
|
+
}
|
|
1603
|
+
});
|
|
1604
|
+
bot.callbackQuery('menu:workspaces', async (grammyCtx) => {
|
|
1605
|
+
const chatId = grammyCtx.chat?.id;
|
|
1606
|
+
if (chatId === undefined)
|
|
1607
|
+
return;
|
|
1608
|
+
const locale = localeOf(grammyCtx.from?.language_code);
|
|
1609
|
+
await grammyCtx.answerCallbackQuery().catch(() => undefined);
|
|
1610
|
+
const view = buildWorkspaceView(workspaces.list(), store.get(chatId), locale);
|
|
1611
|
+
await editOrReply(grammyCtx, view.text, view.keyboard);
|
|
1612
|
+
});
|
|
1613
|
+
bot.callbackQuery('menu:sessions', async (grammyCtx) => {
|
|
1614
|
+
const chatId = grammyCtx.chat?.id;
|
|
1615
|
+
if (chatId === undefined)
|
|
1616
|
+
return;
|
|
1617
|
+
const locale = localeOf(grammyCtx.from?.language_code);
|
|
1618
|
+
const binding = store.get(chatId);
|
|
1619
|
+
const workspace = binding?.activeWorkspaceId === undefined ? undefined : workspaces.get(binding.activeWorkspaceId);
|
|
1620
|
+
await grammyCtx.answerCallbackQuery().catch(() => undefined);
|
|
1621
|
+
if (workspace === undefined) {
|
|
1622
|
+
const view = buildWorkspaceView(workspaces.list(), store.get(chatId), locale);
|
|
1623
|
+
await editOrReply(grammyCtx, view.text, view.keyboard);
|
|
1624
|
+
return;
|
|
1625
|
+
}
|
|
1626
|
+
const sessionsForWorkspace = await listSessions(runtime, workspace);
|
|
1627
|
+
const view = buildSessionsView(workspace, sessionsForWorkspace, locale);
|
|
1628
|
+
await editOrReply(grammyCtx, view.text, view.keyboard);
|
|
1629
|
+
});
|
|
1630
|
+
bot.callbackQuery('menu:refresh', async (grammyCtx) => {
|
|
1631
|
+
const chatId = grammyCtx.chat?.id;
|
|
1632
|
+
if (chatId === undefined)
|
|
1633
|
+
return;
|
|
1634
|
+
const locale = localeOf(grammyCtx.from?.language_code);
|
|
1635
|
+
await grammyCtx.answerCallbackQuery().catch(() => undefined);
|
|
1636
|
+
const view = buildWorkspaceView(workspaces.list(), store.get(chatId), locale);
|
|
1637
|
+
await editOrReply(grammyCtx, view.text, view.keyboard);
|
|
1638
|
+
});
|
|
1639
|
+
bot.callbackQuery('menu:home', async (grammyCtx) => {
|
|
1640
|
+
const chatId = grammyCtx.chat?.id;
|
|
1641
|
+
if (chatId === undefined)
|
|
1642
|
+
return;
|
|
1643
|
+
const locale = localeOf(grammyCtx.from?.language_code);
|
|
1644
|
+
await grammyCtx.answerCallbackQuery().catch(() => undefined);
|
|
1645
|
+
await sendMainMenu(runtime, chatId, locale, grammyCtx.callbackQuery?.message?.message_id);
|
|
1646
|
+
});
|
|
1647
|
+
bot.callbackQuery('menu:sound', async (grammyCtx) => {
|
|
1648
|
+
const chatId = grammyCtx.chat?.id;
|
|
1649
|
+
const userId = grammyCtx.from?.id;
|
|
1650
|
+
if (chatId === undefined || userId === undefined)
|
|
1651
|
+
return;
|
|
1652
|
+
const locale = localeOf(grammyCtx.from?.language_code);
|
|
1653
|
+
const binding = store.get(chatId);
|
|
1654
|
+
const sound = binding?.sound === false;
|
|
1655
|
+
const next = binding === undefined
|
|
1656
|
+
? { chatId: String(chatId), userId, sound, updatedAt: Date.now() }
|
|
1657
|
+
: { ...binding, sound, updatedAt: Date.now() };
|
|
1658
|
+
await store.set(next);
|
|
1659
|
+
await grammyCtx.answerCallbackQuery({ text: sound ? t(locale, 'soundOn') : t(locale, 'soundOff') }).catch(() => undefined);
|
|
1660
|
+
await sendMainMenu(runtime, chatId, locale, grammyCtx.callbackQuery?.message?.message_id);
|
|
1661
|
+
});
|
|
1662
|
+
bot.callbackQuery('menu:stop', async (grammyCtx) => {
|
|
1663
|
+
const chatId = grammyCtx.chat?.id;
|
|
1664
|
+
if (chatId === undefined)
|
|
1665
|
+
return;
|
|
1666
|
+
const locale = localeOf(grammyCtx.from?.language_code);
|
|
1667
|
+
await grammyCtx.answerCallbackQuery().catch(() => undefined);
|
|
1668
|
+
const view = buildStopView(locale);
|
|
1669
|
+
const messageId = grammyCtx.callbackQuery?.message?.message_id;
|
|
1670
|
+
if (messageId !== undefined)
|
|
1671
|
+
await editRich(runtime, chatId, messageId, view);
|
|
1672
|
+
else
|
|
1673
|
+
await sendRich(runtime, chatId, view);
|
|
1674
|
+
});
|
|
1675
|
+
bot.callbackQuery('stop:yes', async (grammyCtx) => {
|
|
1676
|
+
const chatId = grammyCtx.chat?.id;
|
|
1677
|
+
if (chatId === undefined)
|
|
1678
|
+
return;
|
|
1679
|
+
const locale = localeOf(grammyCtx.from?.language_code);
|
|
1680
|
+
const text = await stopActive(runtime, chatId, locale);
|
|
1681
|
+
await grammyCtx.answerCallbackQuery({ text: truncate(text, 180) }).catch(() => undefined);
|
|
1682
|
+
await sendMainMenu(runtime, chatId, locale, grammyCtx.callbackQuery?.message?.message_id);
|
|
1683
|
+
});
|
|
1684
|
+
bot.callbackQuery('menu:compact', async (grammyCtx) => {
|
|
1685
|
+
const chatId = grammyCtx.chat?.id;
|
|
1686
|
+
if (chatId === undefined)
|
|
1687
|
+
return;
|
|
1688
|
+
const locale = localeOf(grammyCtx.from?.language_code);
|
|
1689
|
+
const binding = store.get(chatId);
|
|
1690
|
+
if (binding?.activeSessionId === undefined) {
|
|
1691
|
+
await grammyCtx.answerCallbackQuery({ text: t(locale, 'noActiveSession') }).catch(() => undefined);
|
|
1692
|
+
return;
|
|
1693
|
+
}
|
|
1694
|
+
await grammyCtx.answerCallbackQuery().catch(() => undefined);
|
|
1695
|
+
const state = await getMenuState(runtime, chatId, locale);
|
|
1696
|
+
const view = buildCompactView(state, locale);
|
|
1697
|
+
const messageId = grammyCtx.callbackQuery?.message?.message_id;
|
|
1698
|
+
if (messageId !== undefined)
|
|
1699
|
+
await editRich(runtime, chatId, messageId, view);
|
|
1700
|
+
else
|
|
1701
|
+
await sendRich(runtime, chatId, view);
|
|
1702
|
+
});
|
|
1703
|
+
bot.callbackQuery('compact:yes', async (grammyCtx) => {
|
|
1704
|
+
const chatId = grammyCtx.chat?.id;
|
|
1705
|
+
if (chatId === undefined)
|
|
1706
|
+
return;
|
|
1707
|
+
const locale = localeOf(grammyCtx.from?.language_code);
|
|
1708
|
+
const binding = store.get(chatId);
|
|
1709
|
+
if (binding?.activeSessionId === undefined) {
|
|
1710
|
+
await grammyCtx.answerCallbackQuery({ text: t(locale, 'noActiveSession') }).catch(() => undefined);
|
|
1711
|
+
return;
|
|
1712
|
+
}
|
|
1713
|
+
await grammyCtx.answerCallbackQuery({ text: t(locale, 'compact') }).catch(() => undefined);
|
|
1714
|
+
const text = await runCompact(runtime, chatId, locale, binding.activeSessionId);
|
|
1715
|
+
const view = {
|
|
1716
|
+
html: `<h2>${escapeHtml(t(locale, 'compactHistory'))}</h2><p>${escapeHtml(text)}</p><tg-button-row align="left"><tg-button type="callback_data" style="primary" data="menu:home">${escapeHtml(t(locale, 'home'))}</tg-button></tg-button-row>`,
|
|
1717
|
+
text,
|
|
1718
|
+
keyboard: new InlineKeyboard().text(t(locale, 'home'), 'menu:home'),
|
|
1719
|
+
};
|
|
1720
|
+
const messageId = grammyCtx.callbackQuery?.message?.message_id;
|
|
1721
|
+
if (messageId !== undefined)
|
|
1722
|
+
await editRich(runtime, chatId, messageId, view);
|
|
1723
|
+
else
|
|
1724
|
+
await sendRich(runtime, chatId, view);
|
|
1725
|
+
});
|
|
1726
|
+
bot.callbackQuery('admin:home', async (grammyCtx) => {
|
|
1727
|
+
const chatId = grammyCtx.chat?.id;
|
|
1728
|
+
if (chatId === undefined)
|
|
1729
|
+
return;
|
|
1730
|
+
const locale = localeOf(grammyCtx.from?.language_code);
|
|
1731
|
+
if (runtime.adminUserId === undefined || grammyCtx.from?.id !== runtime.adminUserId) {
|
|
1732
|
+
await grammyCtx.answerCallbackQuery({ text: t(locale, 'accessDenied') }).catch(() => undefined);
|
|
1733
|
+
return;
|
|
1734
|
+
}
|
|
1735
|
+
await grammyCtx.answerCallbackQuery().catch(() => undefined);
|
|
1736
|
+
const messageId = grammyCtx.callbackQuery?.message?.message_id;
|
|
1737
|
+
if (messageId !== undefined)
|
|
1738
|
+
await editRich(runtime, chatId, messageId, buildAdminView(locale));
|
|
1739
|
+
else
|
|
1740
|
+
await sendRich(runtime, chatId, buildAdminView(locale));
|
|
1741
|
+
});
|
|
1742
|
+
bot.callbackQuery('admin:logs', async (grammyCtx) => {
|
|
1743
|
+
const locale = localeOf(grammyCtx.from?.language_code);
|
|
1744
|
+
if (runtime.adminUserId === undefined || grammyCtx.from?.id !== runtime.adminUserId) {
|
|
1745
|
+
await grammyCtx.answerCallbackQuery({ text: t(locale, 'accessDenied') }).catch(() => undefined);
|
|
1746
|
+
return;
|
|
1747
|
+
}
|
|
1748
|
+
await grammyCtx.answerCallbackQuery().catch(() => undefined);
|
|
1749
|
+
await sendLogs(grammyCtx, locale, logger);
|
|
1750
|
+
});
|
|
1751
|
+
bot.callbackQuery('admin:restart', async (grammyCtx) => {
|
|
1752
|
+
const chatId = grammyCtx.chat?.id;
|
|
1753
|
+
if (chatId === undefined)
|
|
1754
|
+
return;
|
|
1755
|
+
const locale = localeOf(grammyCtx.from?.language_code);
|
|
1756
|
+
if (runtime.adminUserId === undefined || grammyCtx.from?.id !== runtime.adminUserId) {
|
|
1757
|
+
await grammyCtx.answerCallbackQuery({ text: t(locale, 'accessDenied') }).catch(() => undefined);
|
|
1758
|
+
return;
|
|
1759
|
+
}
|
|
1760
|
+
await grammyCtx.answerCallbackQuery().catch(() => undefined);
|
|
1761
|
+
const messageId = grammyCtx.callbackQuery?.message?.message_id;
|
|
1762
|
+
if (messageId !== undefined)
|
|
1763
|
+
await editRich(runtime, chatId, messageId, buildRestartView(locale));
|
|
1764
|
+
else
|
|
1765
|
+
await sendRich(runtime, chatId, buildRestartView(locale));
|
|
1766
|
+
});
|
|
1767
|
+
bot.callbackQuery('admin:restart:yes', async (grammyCtx) => {
|
|
1768
|
+
const chatId = grammyCtx.chat?.id;
|
|
1769
|
+
if (chatId === undefined)
|
|
1770
|
+
return;
|
|
1771
|
+
const locale = localeOf(grammyCtx.from?.language_code);
|
|
1772
|
+
if (runtime.adminUserId === undefined || grammyCtx.from?.id !== runtime.adminUserId) {
|
|
1773
|
+
await grammyCtx.answerCallbackQuery({ text: t(locale, 'accessDenied') }).catch(() => undefined);
|
|
1774
|
+
return;
|
|
1775
|
+
}
|
|
1776
|
+
await grammyCtx.answerCallbackQuery({ text: t(locale, 'restarting') }).catch(() => undefined);
|
|
1777
|
+
const messageId = grammyCtx.callbackQuery?.message?.message_id;
|
|
1778
|
+
const view = homeOnlyView(t(locale, 'restartDone'), locale);
|
|
1779
|
+
if (messageId !== undefined)
|
|
1780
|
+
await editRich(runtime, chatId, messageId, view);
|
|
1781
|
+
else
|
|
1782
|
+
await sendRich(runtime, chatId, view);
|
|
1783
|
+
if (!restartHarness(logger)) {
|
|
1784
|
+
await sendPlain(runtime, chatId, `⚠️ ${t(locale, 'error')}`);
|
|
1785
|
+
}
|
|
1786
|
+
});
|
|
1787
|
+
bot.callbackQuery(/^ap:([^:]+):(a|r)$/, async (grammyCtx) => {
|
|
1788
|
+
const token = grammyCtx.match[1];
|
|
1789
|
+
const decision = grammyCtx.match[2];
|
|
1790
|
+
const pending = runtime.pendingApprovals.get(token);
|
|
1791
|
+
const locale = pending?.locale ?? localeOf(grammyCtx.from?.language_code);
|
|
1792
|
+
if (pending === undefined) {
|
|
1793
|
+
await grammyCtx.answerCallbackQuery({ text: t(locale, 'notFound') }).catch(() => undefined);
|
|
1794
|
+
return;
|
|
1795
|
+
}
|
|
1796
|
+
const text = decision === 'a' ? t(locale, 'approvalAllowed') : t(locale, 'approvalRejected');
|
|
1797
|
+
await grammyCtx.answerCallbackQuery({ text }).catch(() => undefined);
|
|
1798
|
+
pending.finish(decision === 'a' ? 'allowed-once' : 'rejected');
|
|
1799
|
+
await editRich(runtime, pending.chatId, pending.messageId, homeOnlyView(text, locale));
|
|
1800
|
+
});
|
|
1801
|
+
bot.callbackQuery(/^q:([^:]+):(\d+):(\d+)$/, async (grammyCtx) => {
|
|
1802
|
+
const token = grammyCtx.match[1];
|
|
1803
|
+
const questionIndex = Number(grammyCtx.match[2]);
|
|
1804
|
+
const optionIndex = Number(grammyCtx.match[3]);
|
|
1805
|
+
const pending = runtime.pendingQuestions.get(token);
|
|
1806
|
+
const locale = pending?.locale ?? localeOf(grammyCtx.from?.language_code);
|
|
1807
|
+
if (pending === undefined) {
|
|
1808
|
+
await grammyCtx.answerCallbackQuery({ text: t(locale, 'notFound') }).catch(() => undefined);
|
|
1809
|
+
return;
|
|
1810
|
+
}
|
|
1811
|
+
const question = pending.questions[questionIndex];
|
|
1812
|
+
const option = question?.options?.[optionIndex];
|
|
1813
|
+
if (question === undefined || option === undefined) {
|
|
1814
|
+
await grammyCtx.answerCallbackQuery({ text: t(locale, 'notFound') }).catch(() => undefined);
|
|
1815
|
+
return;
|
|
1816
|
+
}
|
|
1817
|
+
pending.answers.set(questionIndex, option.label);
|
|
1818
|
+
await grammyCtx.answerCallbackQuery({
|
|
1819
|
+
text: truncate(`${t(locale, 'questionSelected')}: ${option.label}`, 180),
|
|
1820
|
+
}).catch(() => undefined);
|
|
1821
|
+
const allAnswered = pending.questions.every((_, index) => pending.answers.has(index));
|
|
1822
|
+
if (allAnswered) {
|
|
1823
|
+
const answer = {
|
|
1824
|
+
answers: pending.questions.map((item, index) => ({
|
|
1825
|
+
id: item.id,
|
|
1826
|
+
selected: [pending.answers.get(index)],
|
|
1827
|
+
})),
|
|
1828
|
+
};
|
|
1829
|
+
pending.finish(answer);
|
|
1830
|
+
const text = pending.questions
|
|
1831
|
+
.map((item, index) => `${item.question}: ${pending.answers.get(index) ?? ''}`)
|
|
1832
|
+
.join('\n');
|
|
1833
|
+
await editRich(runtime, pending.chatId, pending.messageId, homeOnlyView(text, locale));
|
|
1834
|
+
return;
|
|
1835
|
+
}
|
|
1836
|
+
const view = buildQuestionsView({ questions: pending.questions }, token, locale, pending.answers);
|
|
1837
|
+
await editRich(runtime, pending.chatId, pending.messageId, view);
|
|
1838
|
+
});
|
|
1839
|
+
bot.command('admin', async (grammyCtx) => {
|
|
1840
|
+
const chatId = grammyCtx.chat?.id;
|
|
1841
|
+
if (chatId === undefined)
|
|
1842
|
+
return;
|
|
1843
|
+
const locale = localeOf(grammyCtx.from?.language_code);
|
|
1844
|
+
if (runtime.adminUserId === undefined || grammyCtx.from?.id !== runtime.adminUserId) {
|
|
1845
|
+
await grammyCtx.reply(t(locale, 'accessDenied')).catch(() => undefined);
|
|
1846
|
+
return;
|
|
1847
|
+
}
|
|
1848
|
+
await sendRich(runtime, chatId, buildAdminView(locale));
|
|
1849
|
+
});
|
|
1850
|
+
bot.command('logs', async (grammyCtx) => {
|
|
1851
|
+
const locale = localeOf(grammyCtx.from?.language_code);
|
|
1852
|
+
if (runtime.adminUserId === undefined || grammyCtx.from?.id !== runtime.adminUserId) {
|
|
1853
|
+
await grammyCtx.reply(t(locale, 'accessDenied')).catch(() => undefined);
|
|
1854
|
+
return;
|
|
1855
|
+
}
|
|
1856
|
+
await sendLogs(grammyCtx, locale, logger);
|
|
1857
|
+
});
|
|
1858
|
+
bot.on('message:text', async (grammyCtx) => {
|
|
1859
|
+
const text = grammyCtx.message.text;
|
|
1860
|
+
if (text.startsWith('/'))
|
|
1861
|
+
return;
|
|
1862
|
+
const chatId = grammyCtx.chat.id;
|
|
1863
|
+
const userId = grammyCtx.from.id;
|
|
1864
|
+
const locale = localeOf(grammyCtx.from.language_code);
|
|
1865
|
+
const messageId = grammyCtx.message.message_id;
|
|
1866
|
+
const binding = store.get(chatId);
|
|
1867
|
+
const workspace = binding?.activeWorkspaceId === undefined ? undefined : workspaces.get(binding.activeWorkspaceId);
|
|
1868
|
+
if (workspace === undefined) {
|
|
1869
|
+
await sendWorkspaceView(grammyCtx, workspaces.list(), store, locale);
|
|
1870
|
+
return;
|
|
1871
|
+
}
|
|
1872
|
+
const archived = new Set(workspaces.archivedSessionIds);
|
|
1873
|
+
if (binding?.activeSessionId !== undefined
|
|
1874
|
+
&& workspace.sessionIds.includes(binding.activeSessionId)
|
|
1875
|
+
&& !archived.has(binding.activeSessionId)) {
|
|
1876
|
+
await submitPrompt(runtime, chatId, binding.activeSessionId, { text, messageId }, locale);
|
|
1877
|
+
return;
|
|
1878
|
+
}
|
|
1879
|
+
const sessionsForWorkspace = await listSessions(runtime, workspace);
|
|
1880
|
+
if (sessionsForWorkspace.length === 0) {
|
|
1881
|
+
try {
|
|
1882
|
+
const view = await createSessionForWorkspace(runtime, chatId, userId, workspace, locale, { text, messageId });
|
|
1883
|
+
await grammyCtx.reply(view.text, { reply_markup: view.keyboard });
|
|
1884
|
+
logger.info('session-created', 'created a Session for the workspace', {
|
|
1885
|
+
chatId,
|
|
1886
|
+
workspaceId: workspace.id,
|
|
1887
|
+
});
|
|
1888
|
+
}
|
|
1889
|
+
catch (error) {
|
|
1890
|
+
logger.error('session-create-failed', messageOf(error), { chatId, workspaceId: workspace.id });
|
|
1891
|
+
await grammyCtx.reply(`⚠️ ${t(locale, 'createFailed')} ${errorText(locale, error)}`);
|
|
1892
|
+
}
|
|
1893
|
+
return;
|
|
1894
|
+
}
|
|
1895
|
+
if (sessionsForWorkspace.length === 1) {
|
|
1896
|
+
const only = sessionsForWorkspace[0];
|
|
1897
|
+
const view = await activateSession(runtime, chatId, userId, workspace, only.sessionId, sessionTitle(only, locale), locale, { text, messageId });
|
|
1898
|
+
await grammyCtx.reply(view.text, { reply_markup: view.keyboard });
|
|
1899
|
+
return;
|
|
1900
|
+
}
|
|
1901
|
+
runtime.pendingPrompt.set(chatId, { text, messageId });
|
|
1902
|
+
const view = buildSessionsView(workspace, sessionsForWorkspace, locale);
|
|
1903
|
+
await grammyCtx.reply(`${view.text}\n\n${t(locale, 'pendingText')}`, { reply_markup: view.keyboard });
|
|
1904
|
+
});
|
|
1905
|
+
bot.catch((error) => {
|
|
1906
|
+
logger.error('update-failed', messageOf(error.error), {
|
|
1907
|
+
updateId: error.ctx.update.update_id,
|
|
1908
|
+
...(error.ctx.chat?.id === undefined ? {} : { chatId: error.ctx.chat.id }),
|
|
1909
|
+
...(error.ctx.from?.id === undefined ? {} : { userId: error.ctx.from.id }),
|
|
1910
|
+
});
|
|
1911
|
+
});
|
|
1912
|
+
try {
|
|
1913
|
+
void sendBootGreeting(runtime).catch((error) => {
|
|
1914
|
+
logger.warn('greeting-failed', messageOf(error));
|
|
1915
|
+
});
|
|
1916
|
+
await installCommands(bot, logger, adminUserId);
|
|
1917
|
+
await startPolling(bot, logger, signal);
|
|
1918
|
+
}
|
|
1919
|
+
finally {
|
|
1920
|
+
for (const dispose of disposers)
|
|
1921
|
+
dispose();
|
|
1922
|
+
await store.close();
|
|
1923
|
+
}
|
|
1924
|
+
}
|
|
1925
|
+
export function apply(ctx, rawConfig) {
|
|
1926
|
+
const logger = createPluginLogger(ctx);
|
|
1927
|
+
let config;
|
|
1928
|
+
try {
|
|
1929
|
+
config = parseConfig(rawConfig);
|
|
1930
|
+
}
|
|
1931
|
+
catch (error) {
|
|
1932
|
+
logger.error('config-invalid', messageOf(error));
|
|
1933
|
+
throw error;
|
|
1934
|
+
}
|
|
1935
|
+
const workspaces = ctx.get('workspaceRegistry');
|
|
1936
|
+
if (workspaces === undefined) {
|
|
1937
|
+
logger.error('service-missing', 'workspaceRegistry service is unavailable');
|
|
1938
|
+
throw new Error('telegram-bot: workspaceRegistry service is unavailable');
|
|
1939
|
+
}
|
|
1940
|
+
const sessions = ctx.get('sessionController');
|
|
1941
|
+
if (sessions === undefined) {
|
|
1942
|
+
logger.error('service-missing', 'sessionController service is unavailable');
|
|
1943
|
+
throw new Error('telegram-bot: sessionController service is unavailable');
|
|
1944
|
+
}
|
|
1945
|
+
const credentials = ctx.get('credentials');
|
|
1946
|
+
if (credentials === undefined && config.botToken === undefined) {
|
|
1947
|
+
logger.warn('credentials-missing', 'credentials service is unavailable; set config.botToken or restore credentials');
|
|
1948
|
+
}
|
|
1949
|
+
let bot;
|
|
1950
|
+
let controller;
|
|
1951
|
+
let running;
|
|
1952
|
+
let restarting;
|
|
1953
|
+
let starting = false;
|
|
1954
|
+
let activeConfig = config;
|
|
1955
|
+
const start = () => {
|
|
1956
|
+
if (controller !== undefined)
|
|
1957
|
+
return;
|
|
1958
|
+
starting = true;
|
|
1959
|
+
try {
|
|
1960
|
+
// Volatile fields (`adminUserId`) are references: re-read them on every
|
|
1961
|
+
// start so a settings save reaches the new runtime without a Host restart.
|
|
1962
|
+
activeConfig = parseConfig(rawConfig);
|
|
1963
|
+
}
|
|
1964
|
+
catch (error) {
|
|
1965
|
+
logger.error('config-invalid', messageOf(error));
|
|
1966
|
+
}
|
|
1967
|
+
const next = new AbortController();
|
|
1968
|
+
controller = next;
|
|
1969
|
+
running = runBot(ctx, activeConfig, workspaces, sessions, credentials, logger, next.signal, value => {
|
|
1970
|
+
bot = value;
|
|
1971
|
+
}).catch((error) => {
|
|
1972
|
+
if (!next.signal.aborted) {
|
|
1973
|
+
logger.error('fatal', messageOf(error));
|
|
1974
|
+
}
|
|
1975
|
+
}).finally(() => {
|
|
1976
|
+
if (controller === next) {
|
|
1977
|
+
controller = undefined;
|
|
1978
|
+
running = undefined;
|
|
1979
|
+
}
|
|
1980
|
+
starting = false;
|
|
1981
|
+
});
|
|
1982
|
+
};
|
|
1983
|
+
const stop = async () => {
|
|
1984
|
+
const current = controller;
|
|
1985
|
+
if (current === undefined)
|
|
1986
|
+
return;
|
|
1987
|
+
current.abort();
|
|
1988
|
+
void bot?.stop().catch(() => undefined);
|
|
1989
|
+
await running?.catch(() => undefined);
|
|
1990
|
+
};
|
|
1991
|
+
const restart = () => {
|
|
1992
|
+
if (restarting !== undefined)
|
|
1993
|
+
return;
|
|
1994
|
+
restarting = (async () => {
|
|
1995
|
+
await stop();
|
|
1996
|
+
start();
|
|
1997
|
+
})().finally(() => {
|
|
1998
|
+
restarting = undefined;
|
|
1999
|
+
});
|
|
2000
|
+
};
|
|
2001
|
+
ctx.effect(() => {
|
|
2002
|
+
start();
|
|
2003
|
+
const tokenRef = activeConfig.botTokenRef ?? 'DSH_TELEGRAM_BOT_TOKEN';
|
|
2004
|
+
const offCredentials = ctx.on('credentials/reference-updated', ref => {
|
|
2005
|
+
if (ref === tokenRef)
|
|
2006
|
+
restart();
|
|
2007
|
+
});
|
|
2008
|
+
const offSettings = ctx.on('settings/document-updated', namespace => {
|
|
2009
|
+
if (namespace === 'telegram-bot' && !starting)
|
|
2010
|
+
restart();
|
|
2011
|
+
});
|
|
2012
|
+
return async () => {
|
|
2013
|
+
offCredentials();
|
|
2014
|
+
offSettings();
|
|
2015
|
+
logger.info('stopped', 'plugin disposed');
|
|
2016
|
+
await stop();
|
|
2017
|
+
logger.close();
|
|
2018
|
+
};
|
|
2019
|
+
});
|
|
2020
|
+
}
|