@shliamb/dsh-telegram-bot 0.2.4 → 0.2.6

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/README.md CHANGED
@@ -59,13 +59,13 @@ Adding a new bundle requires a Host restart. Chat sessions and bindings survive
59
59
  The repository also contains a ready-to-install archive:
60
60
 
61
61
  ```text
62
- dist/shliamb-dsh-telegram-bot-0.2.4.tgz
62
+ dist/shliamb-dsh-telegram-bot-0.2.6.tgz
63
63
  ```
64
64
 
65
65
  If the `dsh` CLI is on your `PATH`, run this from the repository root:
66
66
 
67
67
  ```bash
68
- dsh plugin --profile web add ./dist/shliamb-dsh-telegram-bot-0.2.4.tgz
68
+ dsh plugin --profile web add ./dist/shliamb-dsh-telegram-bot-0.2.6.tgz
69
69
  dsh web
70
70
  ```
71
71
 
@@ -73,7 +73,7 @@ If you run Harness from a source checkout, use `pnpm dsh` from that checkout and
73
73
 
74
74
  ```bash
75
75
  cd /path/to/deepseek-harness
76
- pnpm dsh plugin --profile web add /path/to/HarnessBot/dist/shliamb-dsh-telegram-bot-0.2.4.tgz
76
+ pnpm dsh plugin --profile web add /path/to/HarnessBot/dist/shliamb-dsh-telegram-bot-0.2.6.tgz
77
77
  pnpm dsh web
78
78
  ```
79
79
 
@@ -179,7 +179,8 @@ Final answers are sent as separate rich messages. Long text is split into parts
179
179
  After you choose a workspace:
180
180
 
181
181
  - if it has one session, that session is selected automatically;
182
- - if it has several, an inline picker with `🟢`/`⚪` and session titles appears;
182
+ - if it has several, an inline picker appears: `✅` is the current session, `🟢` is running and `⚪` is idle;
183
+ - empty draft sessions are hidden and reused by **New session**, so pressing it twice does not create duplicates;
183
184
  - if it has none, a session is created when you send the first message.
184
185
 
185
186
  Text sent before a session is selected is not lost: it waits in `pendingPrompt` and is submitted after the selection.
@@ -205,6 +206,8 @@ When the agent requests a tool approval, the bot sends an inline **Allow** / **D
205
206
 
206
207
  Approvals and questions are answered for the bound session. The bot asks one question at a time. For a single-select question, tapping an option answers immediately; for a multi-select question, toggle the options and tap **Done**. Typing text while a question is open sends it as the custom answer (for multi-select it supplements the selected options), and **Skip** leaves the question unanswered. While a question or approval is open, ordinary text is not queued as a new prompt.
207
208
 
209
+ Where the prompt appears is decided by the Telegram binding. If the request belongs to the Session currently open in the bot, Telegram claims it and shows the buttons. Any other Session keeps the prompt in Web; if Web has not settled it within 15 seconds, the bot sends a plain text notice naming the workspace and Session. This keeps Web as the primary surface while a deliberately opened Telegram Session takes over its own questions and approvals.
210
+
208
211
  ### Compaction, sound and stop
209
212
 
210
213
  - **Compact** shows the current context percentage and asks for confirmation. The plugin calls the preset-scoped `/compact` command through the `commands` service and reports the localized result and the new percentage. If the agent is busy, compaction is refused.
package/README.ru.md CHANGED
@@ -59,13 +59,13 @@ pnpm dsh web
59
59
  В репозитории также лежит готовый к установке архив:
60
60
 
61
61
  ```text
62
- dist/shliamb-dsh-telegram-bot-0.2.4.tgz
62
+ dist/shliamb-dsh-telegram-bot-0.2.6.tgz
63
63
  ```
64
64
 
65
65
  Если команда `dsh` доступна в `PATH`, выполните из корня репозитория:
66
66
 
67
67
  ```bash
68
- dsh plugin --profile web add ./dist/shliamb-dsh-telegram-bot-0.2.4.tgz
68
+ dsh plugin --profile web add ./dist/shliamb-dsh-telegram-bot-0.2.6.tgz
69
69
  dsh web
70
70
  ```
71
71
 
@@ -73,7 +73,7 @@ dsh web
73
73
 
74
74
  ```bash
75
75
  cd /path/to/deepseek-harness
76
- pnpm dsh plugin --profile web add /path/to/HarnessBot/dist/shliamb-dsh-telegram-bot-0.2.4.tgz
76
+ pnpm dsh plugin --profile web add /path/to/HarnessBot/dist/shliamb-dsh-telegram-bot-0.2.6.tgz
77
77
  pnpm dsh web
78
78
  ```
79
79
 
@@ -179,7 +179,8 @@ ID админа хранится в конфиге плагина. Если `all
179
179
  После выбора пространства:
180
180
 
181
181
  - если сессия одна — она выбирается автоматически;
182
- - если сессий несколько — появляется inline-список `🟢`/`⚪` с названиями;
182
+ - если сессий несколько — появляется inline-список: `✅` — текущая, `🟢` — работает, `⚪` — ожидает;
183
+ - пустые черновики сессий скрыты и переиспользуются кнопкой «Новая сессия», поэтому повторное нажатие не плодит дубли;
183
184
  - если сессий нет — новая создаётся при первом сообщении.
184
185
 
185
186
  Текст, отправленный до выбора сессии, не теряется: он ждёт в `pendingPrompt` и уходит после выбора.
@@ -205,6 +206,8 @@ ID админа хранится в конфиге плагина. Если `all
205
206
 
206
207
  Подтверждения и вопросы отвечаются для привязанной сессии. Бот задаёт вопросы по одному. В single-select нажатие варианта сразу отправляет ответ; в multi-select отметь варианты и нажми **«Готово»**. Текст, отправленный при открытом вопросе, уходит как «свой ответ» (в multi-select дополняет выбранные варианты), а **«Пропустить»** оставляет вопрос без ответа. Пока вопрос или approval открыт, обычный текст не ставится в очередь как новая задача.
207
208
 
209
+ Куда придёт запрос, решает привязка Telegram. Если запрос относится к сессии, которая сейчас открыта в боте, Telegram забирает его и показывает кнопки. Любая другая сессия оставляет запрос в Web; если Web не ответил за 15 секунд, бот присылает обычное текстовое уведомление с названием пространства и сессии. Так Web остаётся основным экраном, а специально открытая сессия в Telegram забирает свои вопросы и подтверждения.
210
+
208
211
  ### Сжатие, звук и остановка
209
212
 
210
213
  - **«Сжать»** показывает текущий процент контекста и просит подтверждение. Плагин вызывает preset-команду `/compact` через сервис `commands`, затем показывает локализованный результат и новый процент. Если агент занят, сжатие отклоняется.
package/lib/index.d.ts CHANGED
@@ -70,6 +70,10 @@ interface DshSessionEvent {
70
70
  readonly type: string;
71
71
  readonly data: Record<string, unknown>;
72
72
  }
73
+ interface ListenerOptions {
74
+ /** Add this listener ahead of listeners registered earlier for the event. */
75
+ prepend?: boolean;
76
+ }
73
77
  interface HarnessContext {
74
78
  readonly logger: Logger;
75
79
  get(name: string): unknown;
@@ -77,8 +81,8 @@ interface HarnessContext {
77
81
  on(event: 'session/event', listener: (session: DshSession, event: DshSessionEvent) => void): () => void;
78
82
  on(event: 'credentials/reference-updated', listener: (ref: string) => void): () => void;
79
83
  on(event: 'settings/document-updated', listener: (namespace: string, revision: number) => void): () => void;
80
- on(event: 'approval/request', listener: (request: ApprovalRequest, next: () => Promise<ApprovalOutcome>) => Promise<ApprovalOutcome>): () => void;
81
- on(event: 'user-questions/request', listener: (request: AskQuestionRequest, next: () => Promise<AskQuestionAnswer>) => Promise<AskQuestionAnswer>): () => void;
84
+ on(event: 'approval/request', listener: (request: ApprovalRequest, next: () => Promise<ApprovalOutcome>) => Promise<ApprovalOutcome>, options?: ListenerOptions): () => void;
85
+ on(event: 'user-questions/request', listener: (request: AskQuestionRequest, next: () => Promise<AskQuestionAnswer>) => Promise<AskQuestionAnswer>, options?: ListenerOptions): () => void;
82
86
  }
83
87
  /**
84
88
  * Loader/settings schema. Only `adminUserId` is volatile: it is the one field
package/lib/index.js CHANGED
@@ -33,6 +33,12 @@ const STRINGS = {
33
33
  choose: 'Выбери рабочее пространство:',
34
34
  active: 'Активное',
35
35
  none: 'Пространств пока нет. Создай его в DSH Web.',
36
+ workspace: 'Пространство',
37
+ tool: 'Инструмент',
38
+ workspacesCount: 'Рабочих пространств',
39
+ tokens: 'токенов',
40
+ cmdStart: 'Меню и баланс',
41
+ cmdAdmin: 'Админ-меню',
36
42
  write: 'Потом просто напиши текст.',
37
43
  refresh: '🔄 Обновить',
38
44
  notFound: 'Пространство не найдено',
@@ -51,7 +57,11 @@ const STRINGS = {
51
57
  workspaceMissing: 'Пространство не найдено. Выбери заново.',
52
58
  noWorkspace: 'Сначала выбери рабочее пространство: /menu',
53
59
  selectSession: 'Выбери сессию:',
54
- noSessions: 'В этом пространстве пока нет сессий. Напиши текст — создам новую.',
60
+ noSessions: 'В этом пространстве пока нет сессий. Нажми «Новая сессия» или просто напиши текст.',
61
+ sessionLegend: '✅ — текущая, 🟢 — работает, ⚪ — ожидает',
62
+ webWaitingQuestion: '⏳ В Web ожидается ответ',
63
+ webWaitingApproval: '⏳ В Web ожидается подтверждение',
64
+ webWaitingHint: 'Открой Web, чтобы продолжить.',
55
65
  sessions: '🔄 Сессии',
56
66
  backToWorkspaces: '◀️ Пространства',
57
67
  newSession: '➕ Новая сессия',
@@ -140,6 +150,12 @@ const STRINGS = {
140
150
  choose: 'Choose a workspace:',
141
151
  active: 'Active',
142
152
  none: 'No workspaces yet. Create one in DSH Web.',
153
+ workspace: 'Workspace',
154
+ tool: 'Tool',
155
+ workspacesCount: 'Workspaces',
156
+ tokens: 'tokens',
157
+ cmdStart: 'Menu and balance',
158
+ cmdAdmin: 'Admin menu',
143
159
  write: 'Then just send text.',
144
160
  refresh: '🔄 Refresh',
145
161
  notFound: 'Workspace not found',
@@ -158,7 +174,11 @@ const STRINGS = {
158
174
  workspaceMissing: 'Workspace not found. Choose it again.',
159
175
  noWorkspace: 'Choose a workspace first: /menu',
160
176
  selectSession: 'Choose a session:',
161
- noSessions: 'No sessions in this workspace yet. Send text — I will create one.',
177
+ noSessions: 'No sessions in this workspace yet. Tap New session or just send text.',
178
+ sessionLegend: '✅ current, 🟢 running, ⚪ idle',
179
+ webWaitingQuestion: '⏳ Web is waiting for an answer',
180
+ webWaitingApproval: '⏳ Web is waiting for approval',
181
+ webWaitingHint: 'Open Web to continue.',
162
182
  sessions: '🔄 Sessions',
163
183
  backToWorkspaces: '◀️ Workspaces',
164
184
  newSession: '➕ New session',
@@ -420,7 +440,7 @@ async function resolveBotToken(ctx, config, credentials, signal) {
420
440
  function commandsFor(locale) {
421
441
  return [{
422
442
  command: 'start',
423
- description: locale === 'ru' ? 'Меню и баланс' : 'Menu and balance',
443
+ description: t(locale, 'cmdStart'),
424
444
  }];
425
445
  }
426
446
  function adminCommandsFor(locale) {
@@ -428,17 +448,23 @@ function adminCommandsFor(locale) {
428
448
  ...commandsFor(locale),
429
449
  {
430
450
  command: 'admin',
431
- description: locale === 'ru' ? 'Админ-меню' : 'Admin menu',
451
+ description: t(locale, 'cmdAdmin'),
432
452
  },
433
453
  ];
434
454
  }
435
455
  async function installCommands(bot, logger, adminUserId) {
436
456
  try {
457
+ // Every non-ru interface falls back to English, including languages that
458
+ // have no dedicated list. Telegram uses the default list for those.
459
+ await bot.api.setMyCommands(commandsFor('en'));
437
460
  await bot.api.setMyCommands(commandsFor('ru'), { language_code: 'ru' });
438
461
  await bot.api.setMyCommands(commandsFor('en'), { language_code: 'en' });
439
462
  if (adminUserId === undefined)
440
463
  return;
441
464
  // Only the admin sees /admin in the Telegram command list.
465
+ await bot.api.setMyCommands(adminCommandsFor('en'), {
466
+ scope: { type: 'chat', chat_id: adminUserId },
467
+ });
442
468
  await bot.api.setMyCommands(adminCommandsFor('ru'), {
443
469
  scope: { type: 'chat', chat_id: adminUserId },
444
470
  language_code: 'ru',
@@ -505,10 +531,9 @@ async function getBalance(runtime, locale, force = false) {
505
531
  return cache.value === undefined ? {} : { display: cache.value, amount: cache.amount, currency: cache.currency };
506
532
  }
507
533
  }
508
- async function getContextLabel(runtime, binding) {
509
- if (runtime.tokenMeter === undefined || binding?.activeSessionId === undefined)
534
+ async function getSessionContextLabel(runtime, sessionId) {
535
+ if (runtime.tokenMeter === undefined)
510
536
  return undefined;
511
- const sessionId = binding.activeSessionId;
512
537
  const cached = runtime.contextCache.get(sessionId);
513
538
  if (cached !== undefined && Date.now() - cached.at < 15_000) {
514
539
  return cached.percent === undefined ? undefined : `${cached.percent}%`;
@@ -518,10 +543,14 @@ async function getContextLabel(runtime, binding) {
518
543
  if (result.agent === undefined)
519
544
  return undefined;
520
545
  const pressure = runtime.tokenMeter.contextPressure(result.agent.session);
521
- const percent = pressure.pressureTokens !== undefined
546
+ // `pressureTokens` is the last request's prompt size and cannot see a
547
+ // compaction. `projectedTokens` applies the surface delta since that
548
+ // sample, matching the Web context meter.
549
+ const used = pressure.projectedTokens ?? pressure.pressureTokens;
550
+ const percent = used !== undefined
522
551
  && pressure.contextWindow !== undefined
523
552
  && pressure.contextWindow > 0
524
- ? Math.round(100 * pressure.pressureTokens / pressure.contextWindow)
553
+ ? Math.round(100 * used / pressure.contextWindow)
525
554
  : undefined;
526
555
  runtime.contextCache.set(sessionId, { percent, at: Date.now() });
527
556
  return percent === undefined ? undefined : `${percent}%`;
@@ -531,6 +560,11 @@ async function getContextLabel(runtime, binding) {
531
560
  return undefined;
532
561
  }
533
562
  }
563
+ async function getContextLabel(runtime, binding) {
564
+ if (binding?.activeSessionId === undefined)
565
+ return undefined;
566
+ return getSessionContextLabel(runtime, binding.activeSessionId);
567
+ }
534
568
  async function getMenuState(runtime, chatId, locale) {
535
569
  const binding = runtime.store.get(chatId);
536
570
  const [balance, context] = await Promise.all([
@@ -606,7 +640,7 @@ function compactResultText(locale, text) {
606
640
  if (text.includes('could not be saved'))
607
641
  return t(locale, 'compactPersistence');
608
642
  const counts = /Compacted (\d+) history items \(~(\d+) tokens\)/.exec(text);
609
- return counts === null ? text : `${t(locale, 'compactDone')} ${counts[1]} / ~${counts[2]} tokens`;
643
+ return counts === null ? text : `${t(locale, 'compactDone')} ${counts[1]} / ~${counts[2]} ${t(locale, 'tokens')}`;
610
644
  }
611
645
  async function runCompact(runtime, chatId, locale, sessionId) {
612
646
  const result = await runtime.sessions.resolveAgent(sessionId);
@@ -629,7 +663,9 @@ async function runCompact(runtime, chatId, locale, sessionId) {
629
663
  sessionId,
630
664
  kind: execution.result.kind,
631
665
  });
632
- return compactResultText(locale, execution.result.text);
666
+ const summary = compactResultText(locale, execution.result.text);
667
+ const context = await getSessionContextLabel(runtime, sessionId);
668
+ return context === undefined ? summary : `${summary}\n${t(locale, 'context')}: ${context}`;
633
669
  }
634
670
  catch (error) {
635
671
  runtime.logger.error('compact-failed', messageOf(error), {
@@ -653,7 +689,7 @@ async function statusText(runtime, chatId, locale) {
653
689
  return [
654
690
  t(locale, 'statusTitle'),
655
691
  `${t(locale, 'balance')}: ${balance.display ?? '—'}`,
656
- `${locale === 'ru' ? 'Пространство' : 'Workspace'}: ${workspace?.title ?? t(locale, 'notSelected')}`,
692
+ `${t(locale, 'workspace')}: ${workspace?.title ?? t(locale, 'notSelected')}`,
657
693
  `${t(locale, 'session')}: ${binding?.activeSessionId?.slice(0, 8) ?? t(locale, 'notSelectedSession')}`,
658
694
  `${t(locale, 'agent')}: ${agentStatus === 'running' ? t(locale, 'running') : agentStatus === 'idle' ? t(locale, 'idle') : agentStatus}`,
659
695
  `${t(locale, 'context')}: ${context ?? '—'}`,
@@ -744,13 +780,13 @@ function buildApprovalView(request, token, locale) {
744
780
  const reason = request.reason === undefined ? '' : `<p>${escapeHtml(request.reason)}</p>`;
745
781
  const html = [
746
782
  `<h2>${escapeHtml(t(locale, 'approvalTitle'))}</h2>`,
747
- `<p><b>${escapeHtml(locale === 'ru' ? 'Инструмент' : 'Tool')}:</b> ${escapeHtml(request.toolName)}</p>`,
783
+ `<p><b>${escapeHtml(t(locale, 'tool'))}:</b> ${escapeHtml(request.toolName)}</p>`,
748
784
  reason,
749
785
  `<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>`,
750
786
  ].join('\n');
751
787
  const text = [
752
788
  t(locale, 'approvalTitle'),
753
- `${locale === 'ru' ? 'Инструмент' : 'Tool'}: ${request.toolName}`,
789
+ `${t(locale, 'tool')}: ${request.toolName}`,
754
790
  ...(request.reason === undefined ? [] : [request.reason]),
755
791
  ].join('\n');
756
792
  const keyboard = new InlineKeyboard()
@@ -847,18 +883,46 @@ async function clearQuestionKeyboard(runtime, chatId, messageId) {
847
883
  async function handleApproval(runtime, request, next) {
848
884
  if (request.signal?.aborted === true)
849
885
  return 'cancelled';
850
- const chatIdRaw = chatForSession(runtime, request.agent.session.id);
851
- if (chatIdRaw === undefined)
852
- return next();
853
- const chatId = Number(chatIdRaw);
854
- if (!Number.isSafeInteger(chatId))
855
- return next();
856
- const binding = runtime.store.get(chatIdRaw);
886
+ const sessionId = request.agent.session.id;
887
+ const target = answerTargetForSession(runtime, sessionId);
888
+ if (target === undefined) {
889
+ runtime.logger.info('approval-delegated', 'session is not bound to a Telegram chat', {
890
+ sessionId,
891
+ toolName: request.toolName,
892
+ reason: 'unbound',
893
+ });
894
+ const answer = next();
895
+ scheduleWebWaitingNotice(runtime, undefined, sessionId, 'approval', answer, request.toolName);
896
+ return answer;
897
+ }
898
+ const { chatId, binding, active } = target;
857
899
  const locale = binding?.locale ?? 'ru';
900
+ if (!active) {
901
+ runtime.logger.info('approval-delegated', 'session is not active in Telegram', {
902
+ chatId,
903
+ sessionId,
904
+ toolName: request.toolName,
905
+ reason: 'not-active',
906
+ });
907
+ const answer = next();
908
+ scheduleWebWaitingNotice(runtime, target, sessionId, 'approval', answer, request.toolName);
909
+ return answer;
910
+ }
911
+ runtime.logger.info('approval-claimed', 'approval claimed for Telegram', {
912
+ chatId,
913
+ sessionId,
914
+ toolName: request.toolName,
915
+ });
858
916
  const token = randomUUID().slice(0, 8);
859
917
  const messageId = await sendRich(runtime, chatId, buildApprovalView(request, token, locale), binding?.sound === false);
860
- if (messageId === undefined)
918
+ if (messageId === undefined) {
919
+ runtime.logger.info('approval-delegated', 'could not send approval to Telegram', {
920
+ chatId,
921
+ sessionId,
922
+ reason: 'send-failed',
923
+ });
861
924
  return next();
925
+ }
862
926
  return await new Promise((resolve) => {
863
927
  let settled = false;
864
928
  let timer;
@@ -986,8 +1050,10 @@ async function askQuestion(runtime, chatId, sessionId, locale, question, questio
986
1050
  return await answerPromise;
987
1051
  }
988
1052
  async function handleQuestion(runtime, request, next) {
989
- if (request.agent === undefined)
1053
+ if (request.agent === undefined) {
1054
+ runtime.logger.info('question-delegated', 'question has no owning agent', { reason: 'no-agent' });
990
1055
  return next();
1056
+ }
991
1057
  if (request.questions.length === 0)
992
1058
  return next();
993
1059
  const aborted = () => request.signal?.aborted === true;
@@ -996,15 +1062,36 @@ async function handleQuestion(runtime, request, next) {
996
1062
  });
997
1063
  if (aborted())
998
1064
  return skippedAll();
999
- const chatIdRaw = chatForSession(runtime, request.agent.session.id);
1000
- if (chatIdRaw === undefined)
1001
- return next();
1002
- const chatId = Number(chatIdRaw);
1003
- if (!Number.isSafeInteger(chatId))
1004
- return next();
1005
- const binding = runtime.store.get(chatIdRaw);
1065
+ const sessionId = request.agent.session.id;
1066
+ const target = answerTargetForSession(runtime, sessionId);
1067
+ if (target === undefined) {
1068
+ runtime.logger.info('question-delegated', 'session is not bound to a Telegram chat', {
1069
+ sessionId,
1070
+ reason: 'unbound',
1071
+ });
1072
+ const answer = next();
1073
+ scheduleWebWaitingNotice(runtime, undefined, sessionId, 'question', answer);
1074
+ return answer;
1075
+ }
1076
+ const { chatId, binding, active } = target;
1006
1077
  const locale = binding?.locale ?? 'ru';
1007
1078
  const silent = binding?.sound === false;
1079
+ if (!active) {
1080
+ runtime.logger.info('question-delegated', 'session is not active in Telegram', {
1081
+ chatId,
1082
+ sessionId,
1083
+ reason: 'not-active',
1084
+ questions: request.questions.length,
1085
+ });
1086
+ const answer = next();
1087
+ scheduleWebWaitingNotice(runtime, target, sessionId, 'question', answer);
1088
+ return answer;
1089
+ }
1090
+ runtime.logger.info('question-claimed', 'question claimed for Telegram', {
1091
+ chatId,
1092
+ sessionId,
1093
+ questions: request.questions.length,
1094
+ });
1008
1095
  // Serialize whole question batches per chat. A second Session can ask while
1009
1096
  // the first batch is between questions; let it wait for the visible batch
1010
1097
  // instead of overtaking or cancelling it.
@@ -1012,7 +1099,7 @@ async function handleQuestion(runtime, request, next) {
1012
1099
  if (previousBatch !== undefined) {
1013
1100
  runtime.logger.info('question-batch-queued', 'waiting for the visible question batch', {
1014
1101
  chatId,
1015
- sessionId: request.agent.session.id,
1102
+ sessionId,
1016
1103
  });
1017
1104
  await previousBatch;
1018
1105
  if (aborted())
@@ -1031,10 +1118,16 @@ async function handleQuestion(runtime, request, next) {
1031
1118
  continue;
1032
1119
  }
1033
1120
  try {
1034
- const item = await askQuestion(runtime, chatId, request.agent.session.id, locale, question, index, request.questions.length, silent, request.signal, deadline);
1121
+ const item = await askQuestion(runtime, chatId, sessionId, locale, question, index, request.questions.length, silent, request.signal, deadline);
1035
1122
  if (item === undefined) {
1036
- if (answers.length === 0)
1123
+ if (answers.length === 0) {
1124
+ runtime.logger.info('question-delegated', 'could not send question to Telegram', {
1125
+ chatId,
1126
+ sessionId,
1127
+ reason: 'send-failed',
1128
+ });
1037
1129
  return next();
1130
+ }
1038
1131
  answers.push({ id: question.id, selected: [] });
1039
1132
  }
1040
1133
  else {
@@ -1044,7 +1137,7 @@ async function handleQuestion(runtime, request, next) {
1044
1137
  catch (error) {
1045
1138
  runtime.logger.error('question-failed', messageOf(error), {
1046
1139
  chatId,
1047
- sessionId: request.agent.session.id,
1140
+ sessionId,
1048
1141
  questionId: question.id,
1049
1142
  });
1050
1143
  answers.push({ id: question.id, selected: [] });
@@ -1080,7 +1173,7 @@ function buildWorkspaceView(workspaces, binding, locale) {
1080
1173
  keyboard.text(t(locale, 'home'), 'menu:home');
1081
1174
  const active = list.find(workspace => workspace.id === binding?.activeWorkspaceId);
1082
1175
  const lines = [
1083
- `${locale === 'ru' ? 'Рабочих пространств' : 'Workspaces'}: ${workspaces.length}`,
1176
+ `${t(locale, 'workspacesCount')}: ${workspaces.length}`,
1084
1177
  ...(active === undefined ? [t(locale, 'choose')] : [`${t(locale, 'active')}: ${active.title}`]),
1085
1178
  '',
1086
1179
  t(locale, 'write'),
@@ -1112,7 +1205,7 @@ function buildMainMenu(workspaces, state, locale) {
1112
1205
  : `<tg-button type="disabled" style="${style}">${escapeHtml(label)}</tg-button>`;
1113
1206
  const html = [
1114
1207
  `<h1>${escapeHtml(balance)}</h1>`,
1115
- `<p><b>${escapeHtml(locale === 'ru' ? 'Пространство' : 'Workspace')}:</b> ${escapeHtml(workspaceLabel)}</p>`,
1208
+ `<p><b>${escapeHtml(t(locale, 'workspace'))}:</b> ${escapeHtml(workspaceLabel)}</p>`,
1116
1209
  `<p><b>${escapeHtml(t(locale, 'session'))}:</b> ${escapeHtml(sessionLabel)}</p>`,
1117
1210
  `<p><b>${escapeHtml(t(locale, 'context'))}:</b> ${escapeHtml(context)}</p>`,
1118
1211
  `<tg-button-row align="left">${button(t(locale, 'workspaces'), 'menu:workspaces', 'primary', true)}${button(t(locale, 'sessions'), 'menu:sessions', 'primary', hasWorkspace)}</tg-button-row>`,
@@ -1121,7 +1214,7 @@ function buildMainMenu(workspaces, state, locale) {
1121
1214
  ].join('\n');
1122
1215
  const text = [
1123
1216
  balance,
1124
- `${locale === 'ru' ? 'Пространство' : 'Workspace'}: ${workspaceLabel}`,
1217
+ `${t(locale, 'workspace')}: ${workspaceLabel}`,
1125
1218
  `${t(locale, 'session')}: ${sessionLabel}`,
1126
1219
  `${t(locale, 'context')}: ${context}`,
1127
1220
  '',
@@ -1272,16 +1365,25 @@ async function listSessions(runtime, workspace) {
1272
1365
  return fallback();
1273
1366
  }
1274
1367
  }
1275
- function buildSessionsView(workspace, sessions, locale) {
1368
+ function visibleSessions(sessions) {
1369
+ // A blank Session is a draft, not a choice: "new session" is an action.
1370
+ return sessions.filter(session => !session.blank);
1371
+ }
1372
+ function buildSessionsView(workspace, sessions, locale, activeSessionId) {
1373
+ const visible = visibleSessions(sessions);
1276
1374
  const keyboard = new InlineKeyboard();
1277
- for (const session of sessions.slice(0, 8)) {
1375
+ for (const session of visible.slice(0, 8)) {
1278
1376
  const mark = session.running ? '🟢' : '⚪';
1279
- keyboard.text(`${mark} ${truncate(sessionTitle(session, locale), 34)}`, `s:${session.sessionId}`).row();
1377
+ const current = session.sessionId === activeSessionId ? '✅ ' : '';
1378
+ keyboard.text(`${current}${mark} ${truncate(sessionTitle(session, locale), 34)}`, `s:${session.sessionId}`).row();
1280
1379
  }
1281
1380
  keyboard.text(t(locale, 'newSession'), 'new').row();
1282
1381
  keyboard.text(t(locale, 'backToWorkspaces'), 'menu:workspaces');
1382
+ const lines = [workspace.title, visible.length === 0 ? t(locale, 'noSessions') : t(locale, 'selectSession')];
1383
+ if (visible.length > 0)
1384
+ lines.push('', t(locale, 'sessionLegend'));
1283
1385
  return {
1284
- text: `${workspace.title}\n${sessions.length === 0 ? t(locale, 'noSessions') : t(locale, 'selectSession')}`,
1386
+ text: lines.join('\n'),
1285
1387
  keyboard,
1286
1388
  };
1287
1389
  }
@@ -1340,8 +1442,9 @@ async function activateSession(runtime, chatId, userId, workspace, sessionId, ti
1340
1442
  }
1341
1443
  async function chooseWorkspace(runtime, chatId, userId, workspace, locale) {
1342
1444
  const sessions = await listSessions(runtime, workspace);
1343
- if (sessions.length === 1) {
1344
- const only = sessions[0];
1445
+ const visible = visibleSessions(sessions);
1446
+ const only = visible.length === 1 ? visible[0] : visible.length === 0 && sessions.length === 1 ? sessions[0] : undefined;
1447
+ if (only !== undefined) {
1345
1448
  return activateSession(runtime, chatId, userId, workspace, only.sessionId, sessionTitle(only, locale), locale);
1346
1449
  }
1347
1450
  await runtime.store.set({
@@ -1355,7 +1458,17 @@ async function chooseWorkspace(runtime, chatId, userId, workspace, locale) {
1355
1458
  return buildSessionsView(workspace, sessions, locale);
1356
1459
  }
1357
1460
  async function createSessionForWorkspace(runtime, chatId, userId, workspace, locale, prompt) {
1358
- const created = await runtime.sessions.create({ workspaceId: workspace.id });
1461
+ // Reuse an existing draft instead of minting another blank Session on every
1462
+ // press of "New session". The controller falls back to a new identity when
1463
+ // the named Session is no longer reusable.
1464
+ const binding = runtime.store.get(String(chatId));
1465
+ const sessions = await listSessions(runtime, workspace);
1466
+ const draft = sessions.find(session => session.blank && session.sessionId === binding?.activeSessionId)
1467
+ ?? sessions.find(session => session.blank);
1468
+ const created = await runtime.sessions.create({
1469
+ workspaceId: workspace.id,
1470
+ ...(draft === undefined ? {} : { sessionId: draft.sessionId }),
1471
+ });
1359
1472
  return activateSession(runtime, chatId, userId, workspace, created.sessionId, t(locale, 'newSessionTitle'), locale, prompt);
1360
1473
  }
1361
1474
  async function editOrReply(grammyCtx, text, keyboard) {
@@ -1486,6 +1599,67 @@ function chatForSession(runtime, sessionId) {
1486
1599
  return String(tracked);
1487
1600
  return runtime.store.sessionChat(sessionId);
1488
1601
  }
1602
+ function answerTargetForSession(runtime, sessionId) {
1603
+ const chatIdRaw = chatForSession(runtime, sessionId);
1604
+ if (chatIdRaw === undefined)
1605
+ return undefined;
1606
+ const chatId = Number(chatIdRaw);
1607
+ if (!Number.isSafeInteger(chatId))
1608
+ return undefined;
1609
+ const binding = runtime.store.get(chatIdRaw);
1610
+ return { chatId, binding, active: binding?.activeSessionId === sessionId };
1611
+ }
1612
+ function workspaceTitleFor(runtime, sessionId) {
1613
+ return runtime.workspaces.list().find(workspace => workspace.sessionIds.includes(sessionId))?.title;
1614
+ }
1615
+ /**
1616
+ * Tell the Telegram chat that a question or approval for another Session is
1617
+ * waiting in Web. This never claims the request: the Web answerer still gets it
1618
+ * through `next()`.
1619
+ */
1620
+ async function notifyWebWaiting(runtime, target, locale, sessionId, kind, toolName) {
1621
+ const workspace = workspaceTitleFor(runtime, sessionId) ?? '—';
1622
+ const place = `${workspace} / ${t(locale, 'session')} ${sessionId.slice(0, 8)}`;
1623
+ const head = kind === 'question' ? t(locale, 'webWaitingQuestion') : t(locale, 'webWaitingApproval');
1624
+ const subject = kind === 'approval' && toolName !== undefined ? ` (${toolName})` : '';
1625
+ const text = `${head}${subject}: ${place}\n${t(locale, 'webWaitingHint')}`;
1626
+ await sendPlain(runtime, target.chatId, text, target.binding?.sound === false);
1627
+ }
1628
+ /** Sessions without their own Telegram route still report to the admin chat. */
1629
+ function webNoticeTarget(runtime, target) {
1630
+ if (target !== undefined)
1631
+ return target;
1632
+ const admin = runtime.adminUserId;
1633
+ if (admin === undefined)
1634
+ return undefined;
1635
+ return { chatId: admin, binding: runtime.store.get(String(admin)), active: false };
1636
+ }
1637
+ const WEB_WAITING_NOTICE_MS = 15_000;
1638
+ /**
1639
+ * Ping the Telegram chat only when Web has not settled the request quickly.
1640
+ * If the user is already answering in Web, the notice is cancelled, so the
1641
+ * bot does not duplicate every Web card.
1642
+ */
1643
+ function scheduleWebWaitingNotice(runtime, target, sessionId, kind, answered, toolName, delayMs = WEB_WAITING_NOTICE_MS) {
1644
+ const noticeTarget = webNoticeTarget(runtime, target);
1645
+ if (noticeTarget === undefined)
1646
+ return;
1647
+ const locale = noticeTarget.binding?.locale ?? 'ru';
1648
+ let settled = false;
1649
+ const timer = setTimeout(() => {
1650
+ if (settled)
1651
+ return;
1652
+ runtime.logger.info('web-waiting-notice', 'notifying Telegram about a Web request', {
1653
+ chatId: noticeTarget.chatId,
1654
+ sessionId,
1655
+ kind,
1656
+ ...(toolName === undefined ? {} : { toolName }),
1657
+ });
1658
+ void notifyWebWaiting(runtime, noticeTarget, locale, sessionId, kind, toolName);
1659
+ }, delayMs);
1660
+ timer.unref?.();
1661
+ void answered.then(() => { settled = true; clearTimeout(timer); }, () => { settled = true; clearTimeout(timer); });
1662
+ }
1489
1663
  async function handleSessionEvent(runtime, session, event) {
1490
1664
  if (session.header.origin === 'subagent')
1491
1665
  return;
@@ -1530,6 +1704,11 @@ async function handleSessionEvent(runtime, session, event) {
1530
1704
  void maybeWarnLowBalance(runtime, chatId, locale, silent);
1531
1705
  break;
1532
1706
  }
1707
+ case 'compaction/end':
1708
+ // Compaction can also be started from Web; drop the cached percentage
1709
+ // so the next menu reads the updated projection immediately.
1710
+ runtime.contextCache.delete(session.id);
1711
+ break;
1533
1712
  default:
1534
1713
  break;
1535
1714
  }
@@ -1630,8 +1809,11 @@ async function runBot(ctx, config, workspaces, sessions, credentials, logger, si
1630
1809
  logger.error('event-failed', messageOf(error), { sessionId: session.id, event: event.type });
1631
1810
  });
1632
1811
  }));
1633
- disposers.push(ctx.on('approval/request', (request, next) => handleApproval(runtime, request, next)));
1634
- disposers.push(ctx.on('user-questions/request', (request, next) => handleQuestion(runtime, request, next)));
1812
+ // Answerers run as a waterfall, and the Web bridge is registered earlier.
1813
+ // Prepending lets the bot decide first: it claims questions for the active
1814
+ // Telegram Session and delegates everything else to Web.
1815
+ disposers.push(ctx.on('approval/request', (request, next) => handleApproval(runtime, request, next), { prepend: true }));
1816
+ disposers.push(ctx.on('user-questions/request', (request, next) => handleQuestion(runtime, request, next), { prepend: true }));
1635
1817
  // Log Telegram API failures once per method per 30 seconds; polling can
1636
1818
  // otherwise flood the file during a network outage.
1637
1819
  const lastApiError = new Map();
@@ -1672,6 +1854,14 @@ async function runBot(ctx, config, workspaces, sessions, credentials, logger, si
1672
1854
  });
1673
1855
  return;
1674
1856
  }
1857
+ // Event-driven messages (progress, final answer, questions) read the
1858
+ // binding locale, while handlers read the update. Keep the binding in sync
1859
+ // so changing the Telegram interface language takes effect immediately.
1860
+ const locale = localeOf(grammyCtx.from?.language_code);
1861
+ const binding = store.get(grammyCtx.chat.id);
1862
+ if (binding !== undefined && binding.locale !== locale) {
1863
+ await store.set({ ...binding, locale, updatedAt: Date.now() });
1864
+ }
1675
1865
  await next();
1676
1866
  });
1677
1867
  bot.command('start', async (grammyCtx) => {
@@ -1844,7 +2034,7 @@ async function runBot(ctx, config, workspaces, sessions, credentials, logger, si
1844
2034
  return;
1845
2035
  }
1846
2036
  const sessionsForWorkspace = await listSessions(runtime, workspace);
1847
- const view = buildSessionsView(workspace, sessionsForWorkspace, locale);
2037
+ const view = buildSessionsView(workspace, sessionsForWorkspace, locale, binding?.activeSessionId);
1848
2038
  await editOrReply(grammyCtx, view.text, view.keyboard);
1849
2039
  });
1850
2040
  bot.callbackQuery('menu:refresh', async (grammyCtx) => {
@@ -2134,7 +2324,8 @@ async function runBot(ctx, config, workspaces, sessions, credentials, logger, si
2134
2324
  return;
2135
2325
  }
2136
2326
  const sessionsForWorkspace = await listSessions(runtime, workspace);
2137
- if (sessionsForWorkspace.length === 0) {
2327
+ const visibleForWorkspace = visibleSessions(sessionsForWorkspace);
2328
+ if (visibleForWorkspace.length === 0) {
2138
2329
  try {
2139
2330
  const view = await createSessionForWorkspace(runtime, chatId, userId, workspace, locale, { text, messageId });
2140
2331
  await grammyCtx.reply(view.text, { reply_markup: view.keyboard });
@@ -2149,14 +2340,14 @@ async function runBot(ctx, config, workspaces, sessions, credentials, logger, si
2149
2340
  }
2150
2341
  return;
2151
2342
  }
2152
- if (sessionsForWorkspace.length === 1) {
2153
- const only = sessionsForWorkspace[0];
2343
+ if (visibleForWorkspace.length === 1) {
2344
+ const only = visibleForWorkspace[0];
2154
2345
  const view = await activateSession(runtime, chatId, userId, workspace, only.sessionId, sessionTitle(only, locale), locale, { text, messageId });
2155
2346
  await grammyCtx.reply(view.text, { reply_markup: view.keyboard });
2156
2347
  return;
2157
2348
  }
2158
2349
  runtime.pendingPrompt.set(chatId, { text, messageId });
2159
- const view = buildSessionsView(workspace, sessionsForWorkspace, locale);
2350
+ const view = buildSessionsView(workspace, sessionsForWorkspace, locale, binding?.activeSessionId);
2160
2351
  await grammyCtx.reply(`${view.text}\n\n${t(locale, 'pendingText')}`, { reply_markup: view.keyboard });
2161
2352
  });
2162
2353
  bot.catch((error) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shliamb/dsh-telegram-bot",
3
- "version": "0.2.4",
3
+ "version": "0.2.6",
4
4
  "description": "Telegram bridge for DeepSeek Harness",
5
5
  "keywords": [
6
6
  "deepseek-harness",