@shliamb/dsh-telegram-bot 0.2.5 → 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.5.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.5.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.5.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
 
@@ -206,6 +206,8 @@ When the agent requests a tool approval, the bot sends an inline **Allow** / **D
206
206
 
207
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.
208
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
+
209
211
  ### Compaction, sound and stop
210
212
 
211
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.5.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.5.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.5.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
 
@@ -206,6 +206,8 @@ ID админа хранится в конфиге плагина. Если `all
206
206
 
207
207
  Подтверждения и вопросы отвечаются для привязанной сессии. Бот задаёт вопросы по одному. В single-select нажатие варианта сразу отправляет ответ; в multi-select отметь варианты и нажми **«Готово»**. Текст, отправленный при открытом вопросе, уходит как «свой ответ» (в multi-select дополняет выбранные варианты), а **«Пропустить»** оставляет вопрос без ответа. Пока вопрос или approval открыт, обычный текст не ставится в очередь как новая задача.
208
208
 
209
+ Куда придёт запрос, решает привязка Telegram. Если запрос относится к сессии, которая сейчас открыта в боте, Telegram забирает его и показывает кнопки. Любая другая сессия оставляет запрос в Web; если Web не ответил за 15 секунд, бот присылает обычное текстовое уведомление с названием пространства и сессии. Так Web остаётся основным экраном, а специально открытая сессия в Telegram забирает свои вопросы и подтверждения.
210
+
209
211
  ### Сжатие, звук и остановка
210
212
 
211
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
@@ -59,6 +59,9 @@ const STRINGS = {
59
59
  selectSession: 'Выбери сессию:',
60
60
  noSessions: 'В этом пространстве пока нет сессий. Нажми «Новая сессия» или просто напиши текст.',
61
61
  sessionLegend: '✅ — текущая, 🟢 — работает, ⚪ — ожидает',
62
+ webWaitingQuestion: '⏳ В Web ожидается ответ',
63
+ webWaitingApproval: '⏳ В Web ожидается подтверждение',
64
+ webWaitingHint: 'Открой Web, чтобы продолжить.',
62
65
  sessions: '🔄 Сессии',
63
66
  backToWorkspaces: '◀️ Пространства',
64
67
  newSession: '➕ Новая сессия',
@@ -173,6 +176,9 @@ const STRINGS = {
173
176
  selectSession: 'Choose a session:',
174
177
  noSessions: 'No sessions in this workspace yet. Tap New session or just send text.',
175
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.',
176
182
  sessions: '🔄 Sessions',
177
183
  backToWorkspaces: '◀️ Workspaces',
178
184
  newSession: '➕ New session',
@@ -877,18 +883,46 @@ async function clearQuestionKeyboard(runtime, chatId, messageId) {
877
883
  async function handleApproval(runtime, request, next) {
878
884
  if (request.signal?.aborted === true)
879
885
  return 'cancelled';
880
- const chatIdRaw = chatForSession(runtime, request.agent.session.id);
881
- if (chatIdRaw === undefined)
882
- return next();
883
- const chatId = Number(chatIdRaw);
884
- if (!Number.isSafeInteger(chatId))
885
- return next();
886
- 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;
887
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
+ });
888
916
  const token = randomUUID().slice(0, 8);
889
917
  const messageId = await sendRich(runtime, chatId, buildApprovalView(request, token, locale), binding?.sound === false);
890
- 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
+ });
891
924
  return next();
925
+ }
892
926
  return await new Promise((resolve) => {
893
927
  let settled = false;
894
928
  let timer;
@@ -1016,8 +1050,10 @@ async function askQuestion(runtime, chatId, sessionId, locale, question, questio
1016
1050
  return await answerPromise;
1017
1051
  }
1018
1052
  async function handleQuestion(runtime, request, next) {
1019
- if (request.agent === undefined)
1053
+ if (request.agent === undefined) {
1054
+ runtime.logger.info('question-delegated', 'question has no owning agent', { reason: 'no-agent' });
1020
1055
  return next();
1056
+ }
1021
1057
  if (request.questions.length === 0)
1022
1058
  return next();
1023
1059
  const aborted = () => request.signal?.aborted === true;
@@ -1026,15 +1062,36 @@ async function handleQuestion(runtime, request, next) {
1026
1062
  });
1027
1063
  if (aborted())
1028
1064
  return skippedAll();
1029
- const chatIdRaw = chatForSession(runtime, request.agent.session.id);
1030
- if (chatIdRaw === undefined)
1031
- return next();
1032
- const chatId = Number(chatIdRaw);
1033
- if (!Number.isSafeInteger(chatId))
1034
- return next();
1035
- 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;
1036
1077
  const locale = binding?.locale ?? 'ru';
1037
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
+ });
1038
1095
  // Serialize whole question batches per chat. A second Session can ask while
1039
1096
  // the first batch is between questions; let it wait for the visible batch
1040
1097
  // instead of overtaking or cancelling it.
@@ -1042,7 +1099,7 @@ async function handleQuestion(runtime, request, next) {
1042
1099
  if (previousBatch !== undefined) {
1043
1100
  runtime.logger.info('question-batch-queued', 'waiting for the visible question batch', {
1044
1101
  chatId,
1045
- sessionId: request.agent.session.id,
1102
+ sessionId,
1046
1103
  });
1047
1104
  await previousBatch;
1048
1105
  if (aborted())
@@ -1061,10 +1118,16 @@ async function handleQuestion(runtime, request, next) {
1061
1118
  continue;
1062
1119
  }
1063
1120
  try {
1064
- 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);
1065
1122
  if (item === undefined) {
1066
- 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
+ });
1067
1129
  return next();
1130
+ }
1068
1131
  answers.push({ id: question.id, selected: [] });
1069
1132
  }
1070
1133
  else {
@@ -1074,7 +1137,7 @@ async function handleQuestion(runtime, request, next) {
1074
1137
  catch (error) {
1075
1138
  runtime.logger.error('question-failed', messageOf(error), {
1076
1139
  chatId,
1077
- sessionId: request.agent.session.id,
1140
+ sessionId,
1078
1141
  questionId: question.id,
1079
1142
  });
1080
1143
  answers.push({ id: question.id, selected: [] });
@@ -1536,6 +1599,67 @@ function chatForSession(runtime, sessionId) {
1536
1599
  return String(tracked);
1537
1600
  return runtime.store.sessionChat(sessionId);
1538
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
+ }
1539
1663
  async function handleSessionEvent(runtime, session, event) {
1540
1664
  if (session.header.origin === 'subagent')
1541
1665
  return;
@@ -1685,8 +1809,11 @@ async function runBot(ctx, config, workspaces, sessions, credentials, logger, si
1685
1809
  logger.error('event-failed', messageOf(error), { sessionId: session.id, event: event.type });
1686
1810
  });
1687
1811
  }));
1688
- disposers.push(ctx.on('approval/request', (request, next) => handleApproval(runtime, request, next)));
1689
- 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 }));
1690
1817
  // Log Telegram API failures once per method per 30 seconds; polling can
1691
1818
  // otherwise flood the file during a network outage.
1692
1819
  const lastApiError = new Map();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shliamb/dsh-telegram-bot",
3
- "version": "0.2.5",
3
+ "version": "0.2.6",
4
4
  "description": "Telegram bridge for DeepSeek Harness",
5
5
  "keywords": [
6
6
  "deepseek-harness",