@shliamb/dsh-telegram-bot 0.2.1 → 0.2.3

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
@@ -15,7 +15,7 @@ Telegram bridge for **DeepSeek Harness**. The plugin runs inside the Harness Hos
15
15
  - Rich final answers: Markdown with tables, headings, lists and code; falls back to rich HTML and then to plain text.
16
16
  - One editable progress message per turn (`💭 thinking`, `🔧 tool`, `✍️ writing`, `✅ done`) instead of a stream of bash output.
17
17
  - Parallel turns: switch to another workspace while an older turn keeps updating. Its final answer still arrives in the same chat.
18
- - Tool approvals and agent questions as inline buttons.
18
+ - Tool approvals and agent questions as inline buttons; typed text answers as custom, including multi-select.
19
19
  - Main menu with account balance, workspace, session, context usage and colored buttons.
20
20
  - Sound on/off per chat, history compaction via `/compact`, and a confirmed stop.
21
21
  - Admin screen with log download and remote Harness restart.
@@ -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.1.tgz
62
+ dist/shliamb-dsh-telegram-bot-0.2.3.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.1.tgz
68
+ dsh plugin --profile web add ./dist/shliamb-dsh-telegram-bot-0.2.3.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.1.tgz
76
+ pnpm dsh plugin --profile web add /path/to/HarnessBot/dist/shliamb-dsh-telegram-bot-0.2.3.tgz
77
77
  pnpm dsh web
78
78
  ```
79
79
 
@@ -203,7 +203,7 @@ Turn tracking lives in Host memory. If the Host is restarted in the middle of a
203
203
 
204
204
  When the agent requests a tool approval, the bot sends an inline **Allow** / **Deny** keyboard. When the agent asks a question with predefined options, the answers are inline buttons as well. Requests time out after 10 minutes.
205
205
 
206
- Approvals and questions are answered for the bound session. Questions that need multi-select or free-form text are left to the Web UI.
206
+ 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
207
 
208
208
  ### Compaction, sound and stop
209
209
 
@@ -298,7 +298,7 @@ dist/ Prebuilt install archive
298
298
  - Web settings expose only the token and the admin ID; `lowBalanceUsd`, `rich` and `apiRoot` are configured through `cordis.patch.yml`.
299
299
  - No voice or file handling: Telegram transcribes voice messages itself.
300
300
  - No proxy configuration.
301
- - Approvals and questions are tied to the bound session; multi-select and free-text questions continue in the Web UI.
301
+ - Approvals and questions are tied to the bound session. An unbound or unsupported question is answered in the Web UI; Telegram supports single-select, multi-select, custom text and skip.
302
302
  - Progress tracking is in memory, so a Host restart in the middle of a turn can leave a stale progress message.
303
303
 
304
304
  ## Roadmap
package/README.ru.md CHANGED
@@ -15,7 +15,7 @@ Telegram-мост для **DeepSeek Harness**. Плагин устанавлив
15
15
  - Rich-ответы: Markdown с таблицами, заголовками, списками и кодом; при ошибке — rich HTML, затем обычный текст.
16
16
  - Одно редактируемое progress-сообщение на ход (`💭 думает`, `🔧 инструмент`, `✍️ пишет`, `✅ готово`) вместо потока bash-вывода.
17
17
  - Параллельные ходы: можно переключиться в другое пространство, а старое progress-сообщение продолжит обновляться. Финальный ответ всё равно придёт в тот же чат.
18
- - Подтверждения инструментов и вопросы агента кнопками.
18
+ - Подтверждения инструментов и вопросы агента кнопками; текст принимается как «свой ответ», включая мультивыбор.
19
19
  - Главное меню с балансом, пространством, сессией, процентом контекста и цветными кнопками.
20
20
  - Звук on/off для чата, сжатие истории через `/compact`, остановка с подтверждением.
21
21
  - Админ-экран с логами документом и удалённым перезапуском Harness.
@@ -59,13 +59,13 @@ pnpm dsh web
59
59
  В репозитории также лежит готовый к установке архив:
60
60
 
61
61
  ```text
62
- dist/shliamb-dsh-telegram-bot-0.2.1.tgz
62
+ dist/shliamb-dsh-telegram-bot-0.2.3.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.1.tgz
68
+ dsh plugin --profile web add ./dist/shliamb-dsh-telegram-bot-0.2.3.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.1.tgz
76
+ pnpm dsh plugin --profile web add /path/to/HarnessBot/dist/shliamb-dsh-telegram-bot-0.2.3.tgz
77
77
  pnpm dsh web
78
78
  ```
79
79
 
@@ -203,7 +203,7 @@ ID админа хранится в конфиге плагина. Если `all
203
203
 
204
204
  Когда агент просит подтвердить инструмент, бот присылает inline-кнопки **«Разрешить»** / **«Запретить»**. Когда агент задаёт вопрос с готовыми вариантами, ответы тоже приходят кнопками. Таймаут запроса — 10 минут.
205
205
 
206
- Подтверждения и вопросы отвечаются для привязанной сессии. Вопросы, которым нужен multi-select или свободный текст, остаются в Web-интерфейсе.
206
+ Подтверждения и вопросы отвечаются для привязанной сессии. Бот задаёт вопросы по одному. В single-select нажатие варианта сразу отправляет ответ; в multi-select отметь варианты и нажми **«Готово»**. Текст, отправленный при открытом вопросе, уходит как «свой ответ» (в multi-select дополняет выбранные варианты), а **«Пропустить»** оставляет вопрос без ответа. Пока вопрос или approval открыт, обычный текст не ставится в очередь как новая задача.
207
207
 
208
208
  ### Сжатие, звук и остановка
209
209
 
@@ -298,7 +298,7 @@ dist/ Готовый установочный архив
298
298
  - В Web-настройках только токен и ID админа; `lowBalanceUsd`, `rich` и `apiRoot` задаются через `cordis.patch.yml`.
299
299
  - Нет голосовых и файлов: Telegram сам транскрибирует голос.
300
300
  - Нет настройки прокси.
301
- - Подтверждения и вопросы привязаны к выбранной сессии; multi-select и свободный текст продолжаются в Web.
301
+ - Подтверждения и вопросы привязаны к выбранной сессии. Непривязанный или неподдерживаемый вопрос отвечается в Web; в Telegram работают single-select, multi-select, свой текст и пропуск.
302
302
  - Отслеживание progress живёт в памяти, поэтому перезапуск Host посреди хода может оставить устаревшее progress-сообщение.
303
303
 
304
304
  ## Roadmap
package/lib/index.js CHANGED
@@ -105,6 +105,19 @@ const STRINGS = {
105
105
  questionTitle: '❓ Вопрос агента',
106
106
  questionTimeout: '⌛ Вопрос без ответа',
107
107
  questionSelected: 'Выбрано',
108
+ questionHint: 'Нажми вариант или напиши свой ответ текстом.',
109
+ questionMultiHint: 'Отметь варианты и нажми «Готово» — или напиши свой ответ текстом.',
110
+ questionTextOnly: 'Напиши ответ текстом.',
111
+ questionCustom: '✍️ Свой ответ',
112
+ questionCustomPrompt: 'Напиши свой ответ одним сообщением.',
113
+ questionDone: '✅ Готово',
114
+ questionSkip: '⏭ Пропустить',
115
+ questionAnswered: '✅ Ответ отправлен',
116
+ questionSkipped: '⏭ Пропущено',
117
+ questionCancelled: '⌛ Вопрос снят',
118
+ questionNeedOption: 'Выбери хотя бы один вариант.',
119
+ questionWaiting: '❓ Жду ответа',
120
+ approvalTextOnly: 'Сейчас жду подтверждения. Нажми «Разрешить» или «Отклонить».',
108
121
  cancel: 'Отмена',
109
122
  stopConfirmTitle: '⏹ Остановить работу?',
110
123
  stopConfirmText: 'Текущий ход агента будет прерван.',
@@ -199,6 +212,19 @@ const STRINGS = {
199
212
  questionTitle: '❓ Agent question',
200
213
  questionTimeout: '⌛ Question timed out',
201
214
  questionSelected: 'Selected',
215
+ questionHint: 'Tap an option or reply with your own text.',
216
+ questionMultiHint: 'Select options and tap Done — or reply with your own text.',
217
+ questionTextOnly: 'Reply with text.',
218
+ questionCustom: '✍️ Write my answer',
219
+ questionCustomPrompt: 'Send your answer in one message.',
220
+ questionDone: '✅ Done',
221
+ questionSkip: '⏭ Skip',
222
+ questionAnswered: '✅ Answer sent',
223
+ questionSkipped: '⏭ Skipped',
224
+ questionCancelled: '⌛ Question dismissed',
225
+ questionNeedOption: 'Select at least one option.',
226
+ questionWaiting: '❓ Waiting for your answer',
227
+ approvalTextOnly: 'Approval is pending. Tap Allow or Reject.',
202
228
  cancel: 'Cancel',
203
229
  stopConfirmTitle: '⏹ Stop the work?',
204
230
  stopConfirmText: 'The current agent turn will be interrupted.',
@@ -218,6 +244,8 @@ const STRINGS = {
218
244
  openMenu: 'Menu',
219
245
  },
220
246
  };
247
+ /** Commands handled by dedicated grammY handlers; text starting with one is not a question answer. */
248
+ const BOT_TEXT_COMMANDS = new Set(['start', 'menu', 'admin', 'new', 'compact', 'stop', 'status', 'logs']);
221
249
  function t(locale, key) {
222
250
  return STRINGS[locale][key];
223
251
  }
@@ -445,7 +473,7 @@ async function getBalance(runtime, locale, force = false) {
445
473
  }
446
474
  try {
447
475
  const result = await runtime.account.getBalance({
448
- version: '@shliamb/dsh-telegram-bot/0.2.1',
476
+ version: '@shliamb/dsh-telegram-bot/0.2.3',
449
477
  locale,
450
478
  timezoneOffsetSeconds: -new Date().getTimezoneOffset() * 60,
451
479
  });
@@ -730,35 +758,92 @@ function buildApprovalView(request, token, locale) {
730
758
  .text(t(locale, 'approvalDeny'), `ap:${token}:r`);
731
759
  return { html, text, keyboard };
732
760
  }
733
- function buildQuestionsView(request, token, locale, answers = new Map()) {
734
- const html = [`<h2>${escapeHtml(t(locale, 'questionTitle'))}</h2>`];
735
- const text = [t(locale, 'questionTitle')];
761
+ function questionOptionLabel(option, selected) {
762
+ return truncate(`${selected ? '✓ ' : ''}${option.label}`, 60);
763
+ }
764
+ function buildQuestionView(pending, locale) {
765
+ const question = pending.question;
766
+ const counter = pending.questionTotal > 1 ? ` ${pending.questionIndex + 1}/${pending.questionTotal}` : '';
767
+ const html = [`<h2>${escapeHtml(t(locale, 'questionTitle'))}${counter}</h2>`];
768
+ const text = [`${t(locale, 'questionTitle')}${counter}`];
769
+ if (question.header !== undefined && question.header.length > 0) {
770
+ html.push(`<h3>${escapeHtml(question.header)}</h3>`);
771
+ text.push('', question.header);
772
+ }
773
+ html.push(`<p>${escapeHtml(question.question)}</p>`);
774
+ text.push('', question.question);
775
+ if (question.detail !== undefined && question.detail.length > 0) {
776
+ html.push(`<p>${escapeHtml(question.detail)}</p>`);
777
+ text.push(question.detail);
778
+ }
779
+ const options = question.options ?? [];
780
+ const hint = pending.awaitingText
781
+ ? t(locale, 'questionCustomPrompt')
782
+ : options.length === 0
783
+ ? t(locale, 'questionTextOnly')
784
+ : pending.multi
785
+ ? t(locale, 'questionMultiHint')
786
+ : t(locale, 'questionHint');
787
+ html.push(`<p><i>${escapeHtml(hint)}</i></p>`);
788
+ text.push('', hint);
736
789
  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}`));
790
+ const optionButtons = [];
791
+ options.forEach((option, index) => {
792
+ const selected = pending.selected.has(option.label);
793
+ const label = questionOptionLabel(option, selected);
794
+ const data = `q:${pending.token}:o:${index}`;
795
+ keyboard.text(label, data).row();
796
+ optionButtons.push(`<tg-button type="callback_data" style="${selected ? 'success' : 'primary'}" data="${data}">${escapeHtml(label)}</tg-button>`);
759
797
  });
798
+ for (let index = 0; index < optionButtons.length; index += 2) {
799
+ html.push(`<tg-button-row align="left">${optionButtons.slice(index, index + 2).join('')}</tg-button-row>`);
800
+ }
801
+ const extraButtons = [];
802
+ if (pending.multi && options.length > 0) {
803
+ const data = `q:${pending.token}:d`;
804
+ keyboard.text(t(locale, 'questionDone'), data);
805
+ extraButtons.push(`<tg-button type="callback_data" style="success" data="${data}">${escapeHtml(t(locale, 'questionDone'))}</tg-button>`);
806
+ }
807
+ if (options.length > 0) {
808
+ const data = `q:${pending.token}:c`;
809
+ keyboard.text(t(locale, 'questionCustom'), data);
810
+ extraButtons.push(`<tg-button type="callback_data" style="primary" data="${data}">${escapeHtml(t(locale, 'questionCustom'))}</tg-button>`);
811
+ }
812
+ const skipData = `q:${pending.token}:s`;
813
+ keyboard.text(t(locale, 'questionSkip'), skipData);
814
+ extraButtons.push(`<tg-button type="callback_data" style="link" data="${skipData}">${escapeHtml(t(locale, 'questionSkip'))}</tg-button>`);
815
+ if (extraButtons.length > 0)
816
+ html.push(`<tg-button-row align="left">${extraButtons.join('')}</tg-button-row>`);
760
817
  return { html: html.join('\n'), text: text.join('\n'), keyboard };
761
818
  }
819
+ function buildQuestionResultView(question, answer, outcome, locale) {
820
+ const label = outcome === 'answered'
821
+ ? t(locale, 'questionAnswered')
822
+ : outcome === 'skipped'
823
+ ? t(locale, 'questionSkipped')
824
+ : outcome === 'timeout'
825
+ ? t(locale, 'questionTimeout')
826
+ : t(locale, 'questionCancelled');
827
+ const detailParts = [...answer.selected];
828
+ if (answer.custom !== undefined && answer.custom.length > 0)
829
+ detailParts.push(answer.custom);
830
+ const detail = detailParts.join(' · ');
831
+ const html = [`<p><b>${escapeHtml(label)}</b></p>`, `<p>${escapeHtml(question.question)}</p>`];
832
+ const text = [label, question.question];
833
+ if (detail.length > 0) {
834
+ html.push(`<p>${escapeHtml(detail)}</p>`);
835
+ text.push(detail);
836
+ }
837
+ return { html: html.join('\n'), text: text.join('\n'), keyboard: new InlineKeyboard() };
838
+ }
839
+ async function clearQuestionKeyboard(runtime, chatId, messageId) {
840
+ try {
841
+ await runtime.bot.api.editMessageReplyMarkup(chatId, messageId, { reply_markup: new InlineKeyboard() });
842
+ }
843
+ catch (error) {
844
+ runtime.logger.warn('question-keyboard-clear-failed', messageOf(error), { chatId });
845
+ }
846
+ }
762
847
  async function handleApproval(runtime, request, next) {
763
848
  if (request.signal?.aborted === true)
764
849
  return 'cancelled';
@@ -783,34 +868,131 @@ async function handleApproval(runtime, request, next) {
783
868
  settled = true;
784
869
  clearTimeout(timer);
785
870
  runtime.pendingApprovals.delete(token);
871
+ if (runtime.pendingApprovalChats.get(chatId) === token)
872
+ runtime.pendingApprovalChats.delete(chatId);
786
873
  resolve(outcome);
787
874
  };
788
875
  timer = setTimeout(() => {
789
876
  if (settled)
790
877
  return;
791
878
  const timeout = homeOnlyView(t(locale, 'approvalTimeout'), locale);
792
- runtime.pendingApprovals.delete(token);
793
879
  void editRich(runtime, chatId, messageId, timeout);
794
880
  finish('unavailable');
795
881
  }, 10 * 60 * 1_000);
796
882
  runtime.pendingApprovals.set(token, { chatId, messageId, locale, finish });
883
+ runtime.pendingApprovalChats.set(chatId, token);
797
884
  request.signal?.addEventListener('abort', () => {
798
885
  runtime.pendingApprovals.get(token)?.finish('cancelled');
799
886
  }, { once: true });
800
887
  });
801
888
  }
889
+ async function askQuestion(runtime, chatId, sessionId, locale, question, questionIndex, questionTotal, silent, signal, deadline) {
890
+ const skip = () => ({ id: question.id, selected: [] });
891
+ const isAborted = () => signal?.aborted === true;
892
+ if (isAborted() || Date.now() >= deadline)
893
+ return skip();
894
+ // A chat has one visible question. A question for another parallel Session
895
+ // waits for the visible one instead of cancelling it; text and callbacks
896
+ // always belong to the question currently on screen.
897
+ const previousToken = runtime.pendingQuestionChats.get(chatId);
898
+ const previous = previousToken === undefined ? undefined : runtime.pendingQuestions.get(previousToken);
899
+ if (previous !== undefined) {
900
+ runtime.logger.info('question-queued', 'waiting for the visible question to close', {
901
+ chatId,
902
+ sessionId,
903
+ questionId: question.id,
904
+ previousSessionId: previous.sessionId,
905
+ });
906
+ await previous.done;
907
+ }
908
+ else if (previousToken !== undefined) {
909
+ runtime.pendingQuestionChats.delete(chatId);
910
+ }
911
+ if (isAborted() || Date.now() >= deadline)
912
+ return skip();
913
+ const token = randomUUID().slice(0, 8);
914
+ let finishStep;
915
+ let markDone = () => { };
916
+ const done = new Promise(resolve => { markDone = resolve; });
917
+ const pending = {
918
+ token,
919
+ question,
920
+ questionIndex,
921
+ questionTotal,
922
+ chatId,
923
+ sessionId,
924
+ locale,
925
+ multi: question.multiSelect === true,
926
+ selected: new Set(),
927
+ messageId: 0,
928
+ awaitingText: false,
929
+ finish: (answer, outcome) => finishStep?.(answer, outcome),
930
+ done,
931
+ };
932
+ const messageId = await sendRich(runtime, chatId, buildQuestionView(pending, locale), silent);
933
+ if (messageId === undefined) {
934
+ runtime.logger.error('question-send-failed', 'could not send a question to Telegram', {
935
+ chatId,
936
+ sessionId,
937
+ questionId: question.id,
938
+ });
939
+ return undefined;
940
+ }
941
+ pending.messageId = messageId;
942
+ runtime.pendingQuestions.set(token, pending);
943
+ runtime.pendingQuestionChats.set(chatId, token);
944
+ if (runtime.progress.has(sessionId)) {
945
+ await editProgress(runtime, sessionId, t(locale, 'questionWaiting'), false);
946
+ }
947
+ runtime.logger.info('question-shown', 'agent question sent to Telegram', {
948
+ chatId,
949
+ sessionId,
950
+ questionId: question.id,
951
+ index: questionIndex,
952
+ total: questionTotal,
953
+ multi: pending.multi,
954
+ });
955
+ return await new Promise(resolve => {
956
+ let settled = false;
957
+ let timer;
958
+ const finish = (answer, outcome) => {
959
+ if (settled)
960
+ return;
961
+ settled = true;
962
+ clearTimeout(timer);
963
+ runtime.pendingQuestions.delete(token);
964
+ if (runtime.pendingQuestionChats.get(chatId) === token)
965
+ runtime.pendingQuestionChats.delete(chatId);
966
+ const result = buildQuestionResultView(question, answer, outcome, locale);
967
+ void (async () => {
968
+ await editRich(runtime, chatId, messageId, result);
969
+ await clearQuestionKeyboard(runtime, chatId, messageId);
970
+ })();
971
+ runtime.logger.info('question-closed', 'agent question closed', {
972
+ chatId,
973
+ sessionId,
974
+ questionId: question.id,
975
+ outcome,
976
+ });
977
+ markDone();
978
+ resolve(answer);
979
+ };
980
+ finishStep = finish;
981
+ timer = setTimeout(() => finish(skip(), 'timeout'), Math.max(0, deadline - Date.now()));
982
+ signal?.addEventListener('abort', () => finish(skip(), 'cancelled'), { once: true });
983
+ });
984
+ }
802
985
  async function handleQuestion(runtime, request, next) {
803
986
  if (request.agent === undefined)
804
987
  return next();
805
988
  if (request.questions.length === 0)
806
989
  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
- }
990
+ const aborted = () => request.signal?.aborted === true;
991
+ const skippedAll = () => ({
992
+ answers: request.questions.map(question => ({ id: question.id, selected: [] })),
993
+ });
994
+ if (aborted())
995
+ return skippedAll();
814
996
  const chatIdRaw = chatForSession(runtime, request.agent.session.id);
815
997
  if (chatIdRaw === undefined)
816
998
  return next();
@@ -819,38 +1001,70 @@ async function handleQuestion(runtime, request, next) {
819
1001
  return next();
820
1002
  const binding = runtime.store.get(chatIdRaw);
821
1003
  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: [] })),
1004
+ const silent = binding?.sound === false;
1005
+ // Serialize whole question batches per chat. A second Session can ask while
1006
+ // the first batch is between questions; let it wait for the visible batch
1007
+ // instead of overtaking or cancelling it.
1008
+ const previousBatch = runtime.questionQueues.get(chatId);
1009
+ if (previousBatch !== undefined) {
1010
+ runtime.logger.info('question-batch-queued', 'waiting for the visible question batch', {
1011
+ chatId,
1012
+ sessionId: request.agent.session.id,
832
1013
  });
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 });
1014
+ await previousBatch;
1015
+ if (aborted())
1016
+ return skippedAll();
1017
+ }
1018
+ let releaseBatch = () => { };
1019
+ const batch = new Promise(resolve => { releaseBatch = resolve; });
1020
+ runtime.questionQueues.set(chatId, batch);
1021
+ try {
1022
+ const deadline = Date.now() + 10 * 60 * 1_000;
1023
+ const answers = [];
1024
+ for (let index = 0; index < request.questions.length; index += 1) {
1025
+ const question = request.questions[index];
1026
+ if (aborted() || Date.now() >= deadline) {
1027
+ answers.push({ id: question.id, selected: [] });
1028
+ continue;
1029
+ }
1030
+ try {
1031
+ const item = await askQuestion(runtime, chatId, request.agent.session.id, locale, question, index, request.questions.length, silent, request.signal, deadline);
1032
+ if (item === undefined) {
1033
+ if (answers.length === 0)
1034
+ return next();
1035
+ answers.push({ id: question.id, selected: [] });
1036
+ }
1037
+ else {
1038
+ answers.push(item);
1039
+ }
1040
+ }
1041
+ catch (error) {
1042
+ runtime.logger.error('question-failed', messageOf(error), {
1043
+ chatId,
1044
+ sessionId: request.agent.session.id,
1045
+ questionId: question.id,
1046
+ });
1047
+ answers.push({ id: question.id, selected: [] });
1048
+ }
1049
+ }
1050
+ return { answers };
1051
+ }
1052
+ finally {
1053
+ releaseBatch();
1054
+ if (runtime.questionQueues.get(chatId) === batch)
1055
+ runtime.questionQueues.delete(chatId);
1056
+ }
1057
+ }
1058
+ function answerQuestionWithText(runtime, pending, text) {
1059
+ const selected = pending.multi ? [...pending.selected] : [];
1060
+ runtime.logger.info('question-answered', 'agent question answered with text', {
1061
+ chatId: pending.chatId,
1062
+ sessionId: pending.sessionId,
1063
+ questionId: pending.question.id,
1064
+ customLength: text.length,
1065
+ selectedCount: selected.length,
853
1066
  });
1067
+ pending.finish({ id: pending.question.id, selected, custom: text }, 'answered');
854
1068
  }
855
1069
  function buildWorkspaceView(workspaces, binding, locale) {
856
1070
  const list = workspaces.slice(0, 10);
@@ -1396,7 +1610,10 @@ async function runBot(ctx, config, workspaces, sessions, credentials, logger, si
1396
1610
  queues: new Map(),
1397
1611
  pendingPrompt: new Map(),
1398
1612
  pendingApprovals: new Map(),
1613
+ pendingApprovalChats: new Map(),
1399
1614
  pendingQuestions: new Map(),
1615
+ pendingQuestionChats: new Map(),
1616
+ questionQueues: new Map(),
1400
1617
  balanceCache: { at: 0 },
1401
1618
  contextCache: new Map(),
1402
1619
  lowBalanceWarnedAt: new Map(),
@@ -1798,43 +2015,59 @@ async function runBot(ctx, config, workspaces, sessions, credentials, logger, si
1798
2015
  pending.finish(decision === 'a' ? 'allowed-once' : 'rejected');
1799
2016
  await editRich(runtime, pending.chatId, pending.messageId, homeOnlyView(text, locale));
1800
2017
  });
1801
- bot.callbackQuery(/^q:([^:]+):(\d+):(\d+)$/, async (grammyCtx) => {
2018
+ bot.callbackQuery(/^q:([^:]+):(o|d|c|s)(?::(\d+))?$/, async (grammyCtx) => {
1802
2019
  const token = grammyCtx.match[1];
1803
- const questionIndex = Number(grammyCtx.match[2]);
1804
- const optionIndex = Number(grammyCtx.match[3]);
2020
+ const action = grammyCtx.match[2];
2021
+ const optionIndex = grammyCtx.match[3] === undefined ? undefined : Number(grammyCtx.match[3]);
1805
2022
  const pending = runtime.pendingQuestions.get(token);
1806
2023
  const locale = pending?.locale ?? localeOf(grammyCtx.from?.language_code);
1807
- if (pending === undefined) {
2024
+ if (pending === undefined || grammyCtx.chat?.id !== pending.chatId) {
1808
2025
  await grammyCtx.answerCallbackQuery({ text: t(locale, 'notFound') }).catch(() => undefined);
1809
2026
  return;
1810
2027
  }
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);
2028
+ if (action === 'o') {
2029
+ const option = optionIndex === undefined ? undefined : pending.question.options?.[optionIndex];
2030
+ if (option === undefined) {
2031
+ await grammyCtx.answerCallbackQuery({ text: t(locale, 'notFound') }).catch(() => undefined);
2032
+ return;
2033
+ }
2034
+ if (pending.multi) {
2035
+ if (pending.selected.has(option.label))
2036
+ pending.selected.delete(option.label);
2037
+ else
2038
+ pending.selected.add(option.label);
2039
+ await grammyCtx.answerCallbackQuery({
2040
+ text: truncate(`${t(locale, 'questionSelected')}: ${option.label}`, 180),
2041
+ }).catch(() => undefined);
2042
+ await editRich(runtime, pending.chatId, pending.messageId, buildQuestionView(pending, locale));
2043
+ return;
2044
+ }
2045
+ await grammyCtx.answerCallbackQuery({
2046
+ text: truncate(`${t(locale, 'questionSelected')}: ${option.label}`, 180),
2047
+ }).catch(() => undefined);
2048
+ pending.finish({ id: pending.question.id, selected: [option.label] }, 'answered');
1815
2049
  return;
1816
2050
  }
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));
2051
+ if (action === 'd') {
2052
+ if (pending.selected.size === 0) {
2053
+ await grammyCtx.answerCallbackQuery({
2054
+ text: t(locale, 'questionNeedOption'),
2055
+ show_alert: true,
2056
+ }).catch(() => undefined);
2057
+ return;
2058
+ }
2059
+ await grammyCtx.answerCallbackQuery({ text: t(locale, 'questionAnswered') }).catch(() => undefined);
2060
+ pending.finish({ id: pending.question.id, selected: [...pending.selected] }, 'answered');
2061
+ return;
2062
+ }
2063
+ if (action === 'c') {
2064
+ pending.awaitingText = true;
2065
+ await grammyCtx.answerCallbackQuery({ text: t(locale, 'questionCustomPrompt') }).catch(() => undefined);
2066
+ await editRich(runtime, pending.chatId, pending.messageId, buildQuestionView(pending, locale));
1834
2067
  return;
1835
2068
  }
1836
- const view = buildQuestionsView({ questions: pending.questions }, token, locale, pending.answers);
1837
- await editRich(runtime, pending.chatId, pending.messageId, view);
2069
+ await grammyCtx.answerCallbackQuery({ text: t(locale, 'questionSkipped') }).catch(() => undefined);
2070
+ pending.finish({ id: pending.question.id, selected: [] }, 'skipped');
1838
2071
  });
1839
2072
  bot.command('admin', async (grammyCtx) => {
1840
2073
  const chatId = grammyCtx.chat?.id;
@@ -1857,12 +2090,33 @@ async function runBot(ctx, config, workspaces, sessions, credentials, logger, si
1857
2090
  });
1858
2091
  bot.on('message:text', async (grammyCtx) => {
1859
2092
  const text = grammyCtx.message.text;
1860
- if (text.startsWith('/'))
1861
- return;
1862
2093
  const chatId = grammyCtx.chat.id;
1863
2094
  const userId = grammyCtx.from.id;
1864
2095
  const locale = localeOf(grammyCtx.from.language_code);
1865
2096
  const messageId = grammyCtx.message.message_id;
2097
+ const questionToken = runtime.pendingQuestionChats.get(chatId);
2098
+ const pendingQuestion = questionToken === undefined ? undefined : runtime.pendingQuestions.get(questionToken);
2099
+ if (questionToken !== undefined && pendingQuestion === undefined)
2100
+ runtime.pendingQuestionChats.delete(chatId);
2101
+ const approvalToken = runtime.pendingApprovalChats.get(chatId);
2102
+ if (text.startsWith('/')) {
2103
+ const command = text.slice(1).split(/[ @]/, 1)[0]?.toLowerCase();
2104
+ if (command !== undefined && BOT_TEXT_COMMANDS.has(command))
2105
+ return;
2106
+ // A slash-prefixed custom answer is valid while a question is open (for
2107
+ // example a path); only commands are reserved.
2108
+ if (pendingQuestion === undefined && approvalToken === undefined)
2109
+ return;
2110
+ }
2111
+ if (pendingQuestion !== undefined) {
2112
+ answerQuestionWithText(runtime, pendingQuestion, text);
2113
+ return;
2114
+ }
2115
+ if (approvalToken !== undefined) {
2116
+ logger.info('approval-text-blocked', 'text ignored while an approval is pending', { chatId });
2117
+ await grammyCtx.reply(t(locale, 'approvalTextOnly')).catch(() => undefined);
2118
+ return;
2119
+ }
1866
2120
  const binding = store.get(chatId);
1867
2121
  const workspace = binding?.activeWorkspaceId === undefined ? undefined : workspaces.get(binding.activeWorkspaceId);
1868
2122
  if (workspace === undefined) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shliamb/dsh-telegram-bot",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "description": "Telegram bridge for DeepSeek Harness",
5
5
  "keywords": [
6
6
  "deepseek-harness",