@shliamb/dsh-telegram-bot 0.2.1 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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.2.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.2.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.2.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.2.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.2.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.2.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.',
@@ -445,7 +471,7 @@ async function getBalance(runtime, locale, force = false) {
445
471
  }
446
472
  try {
447
473
  const result = await runtime.account.getBalance({
448
- version: '@shliamb/dsh-telegram-bot/0.2.1',
474
+ version: '@shliamb/dsh-telegram-bot/0.2.2',
449
475
  locale,
450
476
  timezoneOffsetSeconds: -new Date().getTimezoneOffset() * 60,
451
477
  });
@@ -730,35 +756,92 @@ function buildApprovalView(request, token, locale) {
730
756
  .text(t(locale, 'approvalDeny'), `ap:${token}:r`);
731
757
  return { html, text, keyboard };
732
758
  }
733
- function buildQuestionsView(request, token, locale, answers = new Map()) {
734
- const html = [`<h2>${escapeHtml(t(locale, 'questionTitle'))}</h2>`];
735
- const text = [t(locale, 'questionTitle')];
759
+ function questionOptionLabel(option, selected) {
760
+ return truncate(`${selected ? '✓ ' : ''}${option.label}`, 60);
761
+ }
762
+ function buildQuestionView(pending, locale) {
763
+ const question = pending.question;
764
+ const counter = pending.questionTotal > 1 ? ` ${pending.questionIndex + 1}/${pending.questionTotal}` : '';
765
+ const html = [`<h2>${escapeHtml(t(locale, 'questionTitle'))}${counter}</h2>`];
766
+ const text = [`${t(locale, 'questionTitle')}${counter}`];
767
+ if (question.header !== undefined && question.header.length > 0) {
768
+ html.push(`<h3>${escapeHtml(question.header)}</h3>`);
769
+ text.push('', question.header);
770
+ }
771
+ html.push(`<p>${escapeHtml(question.question)}</p>`);
772
+ text.push('', question.question);
773
+ if (question.detail !== undefined && question.detail.length > 0) {
774
+ html.push(`<p>${escapeHtml(question.detail)}</p>`);
775
+ text.push(question.detail);
776
+ }
777
+ const options = question.options ?? [];
778
+ const hint = pending.awaitingText
779
+ ? t(locale, 'questionCustomPrompt')
780
+ : options.length === 0
781
+ ? t(locale, 'questionTextOnly')
782
+ : pending.multi
783
+ ? t(locale, 'questionMultiHint')
784
+ : t(locale, 'questionHint');
785
+ html.push(`<p><i>${escapeHtml(hint)}</i></p>`);
786
+ text.push('', hint);
736
787
  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}`));
788
+ const optionButtons = [];
789
+ options.forEach((option, index) => {
790
+ const selected = pending.selected.has(option.label);
791
+ const label = questionOptionLabel(option, selected);
792
+ const data = `q:${pending.token}:o:${index}`;
793
+ keyboard.text(label, data).row();
794
+ optionButtons.push(`<tg-button type="callback_data" style="${selected ? 'success' : 'primary'}" data="${data}">${escapeHtml(label)}</tg-button>`);
759
795
  });
796
+ for (let index = 0; index < optionButtons.length; index += 2) {
797
+ html.push(`<tg-button-row align="left">${optionButtons.slice(index, index + 2).join('')}</tg-button-row>`);
798
+ }
799
+ const extraButtons = [];
800
+ if (pending.multi && options.length > 0) {
801
+ const data = `q:${pending.token}:d`;
802
+ keyboard.text(t(locale, 'questionDone'), data);
803
+ extraButtons.push(`<tg-button type="callback_data" style="success" data="${data}">${escapeHtml(t(locale, 'questionDone'))}</tg-button>`);
804
+ }
805
+ if (options.length > 0) {
806
+ const data = `q:${pending.token}:c`;
807
+ keyboard.text(t(locale, 'questionCustom'), data);
808
+ extraButtons.push(`<tg-button type="callback_data" style="primary" data="${data}">${escapeHtml(t(locale, 'questionCustom'))}</tg-button>`);
809
+ }
810
+ const skipData = `q:${pending.token}:s`;
811
+ keyboard.text(t(locale, 'questionSkip'), skipData);
812
+ extraButtons.push(`<tg-button type="callback_data" style="link" data="${skipData}">${escapeHtml(t(locale, 'questionSkip'))}</tg-button>`);
813
+ if (extraButtons.length > 0)
814
+ html.push(`<tg-button-row align="left">${extraButtons.join('')}</tg-button-row>`);
760
815
  return { html: html.join('\n'), text: text.join('\n'), keyboard };
761
816
  }
817
+ function buildQuestionResultView(question, answer, outcome, locale) {
818
+ const label = outcome === 'answered'
819
+ ? t(locale, 'questionAnswered')
820
+ : outcome === 'skipped'
821
+ ? t(locale, 'questionSkipped')
822
+ : outcome === 'timeout'
823
+ ? t(locale, 'questionTimeout')
824
+ : t(locale, 'questionCancelled');
825
+ const detailParts = [...answer.selected];
826
+ if (answer.custom !== undefined && answer.custom.length > 0)
827
+ detailParts.push(answer.custom);
828
+ const detail = detailParts.join(' · ');
829
+ const html = [`<p><b>${escapeHtml(label)}</b></p>`, `<p>${escapeHtml(question.question)}</p>`];
830
+ const text = [label, question.question];
831
+ if (detail.length > 0) {
832
+ html.push(`<p>${escapeHtml(detail)}</p>`);
833
+ text.push(detail);
834
+ }
835
+ return { html: html.join('\n'), text: text.join('\n'), keyboard: new InlineKeyboard() };
836
+ }
837
+ async function clearQuestionKeyboard(runtime, chatId, messageId) {
838
+ try {
839
+ await runtime.bot.api.editMessageReplyMarkup(chatId, messageId, { reply_markup: new InlineKeyboard() });
840
+ }
841
+ catch (error) {
842
+ runtime.logger.warn('question-keyboard-clear-failed', messageOf(error), { chatId });
843
+ }
844
+ }
762
845
  async function handleApproval(runtime, request, next) {
763
846
  if (request.signal?.aborted === true)
764
847
  return 'cancelled';
@@ -783,34 +866,131 @@ async function handleApproval(runtime, request, next) {
783
866
  settled = true;
784
867
  clearTimeout(timer);
785
868
  runtime.pendingApprovals.delete(token);
869
+ if (runtime.pendingApprovalChats.get(chatId) === token)
870
+ runtime.pendingApprovalChats.delete(chatId);
786
871
  resolve(outcome);
787
872
  };
788
873
  timer = setTimeout(() => {
789
874
  if (settled)
790
875
  return;
791
876
  const timeout = homeOnlyView(t(locale, 'approvalTimeout'), locale);
792
- runtime.pendingApprovals.delete(token);
793
877
  void editRich(runtime, chatId, messageId, timeout);
794
878
  finish('unavailable');
795
879
  }, 10 * 60 * 1_000);
796
880
  runtime.pendingApprovals.set(token, { chatId, messageId, locale, finish });
881
+ runtime.pendingApprovalChats.set(chatId, token);
797
882
  request.signal?.addEventListener('abort', () => {
798
883
  runtime.pendingApprovals.get(token)?.finish('cancelled');
799
884
  }, { once: true });
800
885
  });
801
886
  }
887
+ async function askQuestion(runtime, chatId, sessionId, locale, question, questionIndex, questionTotal, silent, signal, deadline) {
888
+ const skip = () => ({ id: question.id, selected: [] });
889
+ const isAborted = () => signal?.aborted === true;
890
+ if (isAborted() || Date.now() >= deadline)
891
+ return skip();
892
+ // A chat has one visible question. A question for another parallel Session
893
+ // waits for the visible one instead of cancelling it; text and callbacks
894
+ // always belong to the question currently on screen.
895
+ const previousToken = runtime.pendingQuestionChats.get(chatId);
896
+ const previous = previousToken === undefined ? undefined : runtime.pendingQuestions.get(previousToken);
897
+ if (previous !== undefined) {
898
+ runtime.logger.info('question-queued', 'waiting for the visible question to close', {
899
+ chatId,
900
+ sessionId,
901
+ questionId: question.id,
902
+ previousSessionId: previous.sessionId,
903
+ });
904
+ await previous.done;
905
+ }
906
+ else if (previousToken !== undefined) {
907
+ runtime.pendingQuestionChats.delete(chatId);
908
+ }
909
+ if (isAborted() || Date.now() >= deadline)
910
+ return skip();
911
+ const token = randomUUID().slice(0, 8);
912
+ let finishStep;
913
+ let markDone = () => { };
914
+ const done = new Promise(resolve => { markDone = resolve; });
915
+ const pending = {
916
+ token,
917
+ question,
918
+ questionIndex,
919
+ questionTotal,
920
+ chatId,
921
+ sessionId,
922
+ locale,
923
+ multi: question.multiSelect === true,
924
+ selected: new Set(),
925
+ messageId: 0,
926
+ awaitingText: false,
927
+ finish: (answer, outcome) => finishStep?.(answer, outcome),
928
+ done,
929
+ };
930
+ const messageId = await sendRich(runtime, chatId, buildQuestionView(pending, locale), silent);
931
+ if (messageId === undefined) {
932
+ runtime.logger.error('question-send-failed', 'could not send a question to Telegram', {
933
+ chatId,
934
+ sessionId,
935
+ questionId: question.id,
936
+ });
937
+ return undefined;
938
+ }
939
+ pending.messageId = messageId;
940
+ runtime.pendingQuestions.set(token, pending);
941
+ runtime.pendingQuestionChats.set(chatId, token);
942
+ if (runtime.progress.has(sessionId)) {
943
+ await editProgress(runtime, sessionId, t(locale, 'questionWaiting'), false);
944
+ }
945
+ runtime.logger.info('question-shown', 'agent question sent to Telegram', {
946
+ chatId,
947
+ sessionId,
948
+ questionId: question.id,
949
+ index: questionIndex,
950
+ total: questionTotal,
951
+ multi: pending.multi,
952
+ });
953
+ return await new Promise(resolve => {
954
+ let settled = false;
955
+ let timer;
956
+ const finish = (answer, outcome) => {
957
+ if (settled)
958
+ return;
959
+ settled = true;
960
+ clearTimeout(timer);
961
+ runtime.pendingQuestions.delete(token);
962
+ if (runtime.pendingQuestionChats.get(chatId) === token)
963
+ runtime.pendingQuestionChats.delete(chatId);
964
+ const result = buildQuestionResultView(question, answer, outcome, locale);
965
+ void (async () => {
966
+ await editRich(runtime, chatId, messageId, result);
967
+ await clearQuestionKeyboard(runtime, chatId, messageId);
968
+ })();
969
+ runtime.logger.info('question-closed', 'agent question closed', {
970
+ chatId,
971
+ sessionId,
972
+ questionId: question.id,
973
+ outcome,
974
+ });
975
+ markDone();
976
+ resolve(answer);
977
+ };
978
+ finishStep = finish;
979
+ timer = setTimeout(() => finish(skip(), 'timeout'), Math.max(0, deadline - Date.now()));
980
+ signal?.addEventListener('abort', () => finish(skip(), 'cancelled'), { once: true });
981
+ });
982
+ }
802
983
  async function handleQuestion(runtime, request, next) {
803
984
  if (request.agent === undefined)
804
985
  return next();
805
986
  if (request.questions.length === 0)
806
987
  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
- }
988
+ const aborted = () => request.signal?.aborted === true;
989
+ const skippedAll = () => ({
990
+ answers: request.questions.map(question => ({ id: question.id, selected: [] })),
991
+ });
992
+ if (aborted())
993
+ return skippedAll();
814
994
  const chatIdRaw = chatForSession(runtime, request.agent.session.id);
815
995
  if (chatIdRaw === undefined)
816
996
  return next();
@@ -819,38 +999,70 @@ async function handleQuestion(runtime, request, next) {
819
999
  return next();
820
1000
  const binding = runtime.store.get(chatIdRaw);
821
1001
  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: [] })),
1002
+ const silent = binding?.sound === false;
1003
+ // Serialize whole question batches per chat. A second Session can ask while
1004
+ // the first batch is between questions; let it wait for the visible batch
1005
+ // instead of overtaking or cancelling it.
1006
+ const previousBatch = runtime.questionQueues.get(chatId);
1007
+ if (previousBatch !== undefined) {
1008
+ runtime.logger.info('question-batch-queued', 'waiting for the visible question batch', {
1009
+ chatId,
1010
+ sessionId: request.agent.session.id,
832
1011
  });
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 });
1012
+ await previousBatch;
1013
+ if (aborted())
1014
+ return skippedAll();
1015
+ }
1016
+ let releaseBatch = () => { };
1017
+ const batch = new Promise(resolve => { releaseBatch = resolve; });
1018
+ runtime.questionQueues.set(chatId, batch);
1019
+ try {
1020
+ const deadline = Date.now() + 10 * 60 * 1_000;
1021
+ const answers = [];
1022
+ for (let index = 0; index < request.questions.length; index += 1) {
1023
+ const question = request.questions[index];
1024
+ if (aborted() || Date.now() >= deadline) {
1025
+ answers.push({ id: question.id, selected: [] });
1026
+ continue;
1027
+ }
1028
+ try {
1029
+ const item = await askQuestion(runtime, chatId, request.agent.session.id, locale, question, index, request.questions.length, silent, request.signal, deadline);
1030
+ if (item === undefined) {
1031
+ if (answers.length === 0)
1032
+ return next();
1033
+ answers.push({ id: question.id, selected: [] });
1034
+ }
1035
+ else {
1036
+ answers.push(item);
1037
+ }
1038
+ }
1039
+ catch (error) {
1040
+ runtime.logger.error('question-failed', messageOf(error), {
1041
+ chatId,
1042
+ sessionId: request.agent.session.id,
1043
+ questionId: question.id,
1044
+ });
1045
+ answers.push({ id: question.id, selected: [] });
1046
+ }
1047
+ }
1048
+ return { answers };
1049
+ }
1050
+ finally {
1051
+ releaseBatch();
1052
+ if (runtime.questionQueues.get(chatId) === batch)
1053
+ runtime.questionQueues.delete(chatId);
1054
+ }
1055
+ }
1056
+ function answerQuestionWithText(runtime, pending, text) {
1057
+ const selected = pending.multi ? [...pending.selected] : [];
1058
+ runtime.logger.info('question-answered', 'agent question answered with text', {
1059
+ chatId: pending.chatId,
1060
+ sessionId: pending.sessionId,
1061
+ questionId: pending.question.id,
1062
+ customLength: text.length,
1063
+ selectedCount: selected.length,
853
1064
  });
1065
+ pending.finish({ id: pending.question.id, selected, custom: text }, 'answered');
854
1066
  }
855
1067
  function buildWorkspaceView(workspaces, binding, locale) {
856
1068
  const list = workspaces.slice(0, 10);
@@ -1396,7 +1608,10 @@ async function runBot(ctx, config, workspaces, sessions, credentials, logger, si
1396
1608
  queues: new Map(),
1397
1609
  pendingPrompt: new Map(),
1398
1610
  pendingApprovals: new Map(),
1611
+ pendingApprovalChats: new Map(),
1399
1612
  pendingQuestions: new Map(),
1613
+ pendingQuestionChats: new Map(),
1614
+ questionQueues: new Map(),
1400
1615
  balanceCache: { at: 0 },
1401
1616
  contextCache: new Map(),
1402
1617
  lowBalanceWarnedAt: new Map(),
@@ -1798,43 +2013,59 @@ async function runBot(ctx, config, workspaces, sessions, credentials, logger, si
1798
2013
  pending.finish(decision === 'a' ? 'allowed-once' : 'rejected');
1799
2014
  await editRich(runtime, pending.chatId, pending.messageId, homeOnlyView(text, locale));
1800
2015
  });
1801
- bot.callbackQuery(/^q:([^:]+):(\d+):(\d+)$/, async (grammyCtx) => {
2016
+ bot.callbackQuery(/^q:([^:]+):(o|d|c|s)(?::(\d+))?$/, async (grammyCtx) => {
1802
2017
  const token = grammyCtx.match[1];
1803
- const questionIndex = Number(grammyCtx.match[2]);
1804
- const optionIndex = Number(grammyCtx.match[3]);
2018
+ const action = grammyCtx.match[2];
2019
+ const optionIndex = grammyCtx.match[3] === undefined ? undefined : Number(grammyCtx.match[3]);
1805
2020
  const pending = runtime.pendingQuestions.get(token);
1806
2021
  const locale = pending?.locale ?? localeOf(grammyCtx.from?.language_code);
1807
- if (pending === undefined) {
2022
+ if (pending === undefined || grammyCtx.chat?.id !== pending.chatId) {
1808
2023
  await grammyCtx.answerCallbackQuery({ text: t(locale, 'notFound') }).catch(() => undefined);
1809
2024
  return;
1810
2025
  }
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);
2026
+ if (action === 'o') {
2027
+ const option = optionIndex === undefined ? undefined : pending.question.options?.[optionIndex];
2028
+ if (option === undefined) {
2029
+ await grammyCtx.answerCallbackQuery({ text: t(locale, 'notFound') }).catch(() => undefined);
2030
+ return;
2031
+ }
2032
+ if (pending.multi) {
2033
+ if (pending.selected.has(option.label))
2034
+ pending.selected.delete(option.label);
2035
+ else
2036
+ pending.selected.add(option.label);
2037
+ await grammyCtx.answerCallbackQuery({
2038
+ text: truncate(`${t(locale, 'questionSelected')}: ${option.label}`, 180),
2039
+ }).catch(() => undefined);
2040
+ await editRich(runtime, pending.chatId, pending.messageId, buildQuestionView(pending, locale));
2041
+ return;
2042
+ }
2043
+ await grammyCtx.answerCallbackQuery({
2044
+ text: truncate(`${t(locale, 'questionSelected')}: ${option.label}`, 180),
2045
+ }).catch(() => undefined);
2046
+ pending.finish({ id: pending.question.id, selected: [option.label] }, 'answered');
2047
+ return;
2048
+ }
2049
+ if (action === 'd') {
2050
+ if (pending.selected.size === 0) {
2051
+ await grammyCtx.answerCallbackQuery({
2052
+ text: t(locale, 'questionNeedOption'),
2053
+ show_alert: true,
2054
+ }).catch(() => undefined);
2055
+ return;
2056
+ }
2057
+ await grammyCtx.answerCallbackQuery({ text: t(locale, 'questionAnswered') }).catch(() => undefined);
2058
+ pending.finish({ id: pending.question.id, selected: [...pending.selected] }, 'answered');
1815
2059
  return;
1816
2060
  }
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));
2061
+ if (action === 'c') {
2062
+ pending.awaitingText = true;
2063
+ await grammyCtx.answerCallbackQuery({ text: t(locale, 'questionCustomPrompt') }).catch(() => undefined);
2064
+ await editRich(runtime, pending.chatId, pending.messageId, buildQuestionView(pending, locale));
1834
2065
  return;
1835
2066
  }
1836
- const view = buildQuestionsView({ questions: pending.questions }, token, locale, pending.answers);
1837
- await editRich(runtime, pending.chatId, pending.messageId, view);
2067
+ await grammyCtx.answerCallbackQuery({ text: t(locale, 'questionSkipped') }).catch(() => undefined);
2068
+ pending.finish({ id: pending.question.id, selected: [] }, 'skipped');
1838
2069
  });
1839
2070
  bot.command('admin', async (grammyCtx) => {
1840
2071
  const chatId = grammyCtx.chat?.id;
@@ -1863,6 +2094,21 @@ async function runBot(ctx, config, workspaces, sessions, credentials, logger, si
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
+ if (questionToken !== undefined) {
2099
+ const pending = runtime.pendingQuestions.get(questionToken);
2100
+ if (pending !== undefined) {
2101
+ answerQuestionWithText(runtime, pending, text);
2102
+ return;
2103
+ }
2104
+ runtime.pendingQuestionChats.delete(chatId);
2105
+ }
2106
+ const approvalToken = runtime.pendingApprovalChats.get(chatId);
2107
+ if (approvalToken !== undefined) {
2108
+ logger.info('approval-text-blocked', 'text ignored while an approval is pending', { chatId });
2109
+ await grammyCtx.reply(t(locale, 'approvalTextOnly')).catch(() => undefined);
2110
+ return;
2111
+ }
1866
2112
  const binding = store.get(chatId);
1867
2113
  const workspace = binding?.activeWorkspaceId === undefined ? undefined : workspaces.get(binding.activeWorkspaceId);
1868
2114
  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.2",
4
4
  "description": "Telegram bridge for DeepSeek Harness",
5
5
  "keywords": [
6
6
  "deepseek-harness",