dsh-tg-bridge 1.19.4 → 1.19.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
@@ -186,7 +186,7 @@ Send the bot:
186
186
 
187
187
  ```
188
188
  Work: /cd · /new · /stop · /send · /seed
189
- Goals: /goal · /goal reopen · /task · /task done|rm|edit <n>
189
+ Goals: /goal (plan + checklist) · /goal reopen · /task (checklist only) · /task done|rm|edit <n>
190
190
  Sessions: /status · /sessions · /resume
191
191
  Agents: /agents · /agents <id> · /agents set model|depth|filter
192
192
  Models: /model · /model <id> · /prices
@@ -370,7 +370,7 @@ so a chatty research topic and a terse deploy topic can differ.
370
370
 
371
371
  The reasoning block itself is model output; `/thoughts` is what reads it back:
372
372
 
373
- - `/thoughts` — the last turn as a message, in parts, deleted after a few minutes;
373
+ - `/thoughts` — the last turn as a message, in parts, deleted after three minutes;
374
374
  - `/thoughts file` — the **whole** last turn as `reasoning-<date>-file.md`, sent as a document
375
375
  (a five-hour turn is tens of thousands of characters, which no chat message can hold);
376
376
  - `/thoughts all` — every turn of the session in one file (a long session is a couple of MB);
package/allowlist.mjs ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Whether an update is from someone the bot serves.
3
+ *
4
+ * Small and separate on purpose: `bridge.mjs` starts polling the moment it is
5
+ * imported, so the one rule that decides who may talk to the agent has to be
6
+ * testable without booting the bot. An empty allowlist refuses everything — a
7
+ * bot that answers strangers shows them the owner's work, and the steer path
8
+ * reads like an ordinary message once it reaches the agent.
9
+ */
10
+ export function allowedSender(msg, config) {
11
+ const ids = config?.allowedUserIds || [];
12
+ const from = msg?.from?.id;
13
+ const chat = msg?.chat?.id;
14
+ return ids.includes(from) || ids.includes(chat);
15
+ }
package/bridge.mjs CHANGED
@@ -25,6 +25,7 @@ net.setDefaultAutoSelectFamily(false);
25
25
  import { noticeIsObsolete } from './queue-notice.mjs';
26
26
  import { immediateKind } from './immediate.mjs';
27
27
  import { writeSteerJob } from './steer-queue.mjs';
28
+ import { allowedSender } from './allowlist.mjs';
28
29
  import { inlineText } from './media-text.mjs';
29
30
  import { createAlbumBuffer } from './albums.mjs';
30
31
  import { turnArgs } from './cli-args.mjs';
@@ -865,6 +866,10 @@ async function runCommandFromButton(typed, { chatId, threadId, key }) {
865
866
  }),
866
867
  api: tg,
867
868
  sendFile: (p, caption = '') => sendFile(chatId, threadId, p, caption),
869
+ // A report meant to be read once (/thoughts) can ask for a message that
870
+ // removes itself. Without this the chat is told it will disappear while the
871
+ // message is a normal one — a promise nothing was keeping.
872
+ ephemeral: (out) => sendEphemeral(chatId, out, threadId),
868
873
  seedTopic: ensureTopicSeed,
869
874
  profile: profileOf(key),
870
875
  reply: (out, extra = {}) => sendWithMarkup(chatId, threadId, out, extra),
@@ -1063,6 +1068,18 @@ function runTurn(task, sessionId, key = '', onEvent = null, extraArgs = [], cwd
1063
1068
  stderr += buf;
1064
1069
  if (onEvent) { try { onEvent({ type: 'activity' }); } catch {} }
1065
1070
  });
1071
+ // A missing or moved DSH app used to emit `error` with no listener, which
1072
+ // kills the process — every turn, forever. The turn now fails with a line
1073
+ // that says which path was expected and how to point the bridge elsewhere.
1074
+ child.on('error', (error) => {
1075
+ clearTimeout(timer);
1076
+ if (key) activeTurns.delete(key);
1077
+ const hint = error?.code === 'ENOENT'
1078
+ ? t(lang, 'bridge.error.noApp', { path: EXE })
1079
+ : t(lang, 'bridge.error.spawn', { msg: error?.message || String(error) });
1080
+ log(`turn spawn failed: ${error?.message || error}`);
1081
+ resolve({ sessionId: sid, text: '', error: hint });
1082
+ });
1066
1083
  child.on('close', (code) => {
1067
1084
  clearTimeout(timer);
1068
1085
  if (key) activeTurns.delete(key);
@@ -2805,6 +2822,15 @@ async function main() {
2805
2822
  ack(update.update_id);
2806
2823
  return;
2807
2824
  }
2825
+ // The allowlist has to be the first thing every update meets, not a step
2826
+ // inside handleMessage: the steer branch below reaches the running agent
2827
+ // without going through handleMessage, so a stranger the bot can see used
2828
+ // to be able to inject text into the owner's live turn.
2829
+ if (!allowedSender(msg)) {
2830
+ log(`ignored update from ${msg.from?.id} (chat ${msg.chat?.id}${msg.message_thread_id ? ` topic=${msg.message_thread_id}` : ''})`);
2831
+ ack(update.update_id);
2832
+ return;
2833
+ }
2808
2834
  const queueKey = sessionKey(msg.chat.id, threadOf(msg));
2809
2835
  const thread = threadOf(msg);
2810
2836
  // `/stop` behind the turn it should kill is a no-op; run the few commands
package/control.mjs CHANGED
@@ -5,7 +5,7 @@
5
5
  // Everything works on the same files DSH itself reads, so a running desktop app
6
6
  // and a headless turn see the same state; commands that need a reload say so.
7
7
  import { execFileSync, spawn, spawnSync } from 'node:child_process';
8
- import { existsSync, copyFileSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
8
+ import { cpSync, existsSync, copyFileSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
9
9
  import { homedir, tmpdir } from 'node:os';
10
10
  import { join, basename } from 'node:path';
11
11
  import { fileURLToPath } from 'node:url';
@@ -666,9 +666,22 @@ function goalView(goal, lang) {
666
666
  }
667
667
 
668
668
  /**
669
- * Handle one control command. Returns true when the message was a control
670
- * command and the caller must not run a turn.
669
+ * The checklist on its own, without the goal's wording.
670
+ *
671
+ * `/goal` and `/task` used to print the same card, so typing either one told a
672
+ * person nothing about which command owns what. `/goal` is the plan (objective,
673
+ * checklist, progress); `/task` is the list you tick — the thing you read five
674
+ * times a day while the objective stays the same.
671
675
  */
676
+ function taskView(goal, lang) {
677
+ const { done, total } = progressOf(goal);
678
+ if (goal.tasks.length === 0) return t(lang, 'task.empty');
679
+ const lines = [t(lang, 'task.listTitle', { done, total })];
680
+ goal.tasks.forEach((task, i) => lines.push(`${task.done ? '✅' : '⬜'} ${i + 1}. ${task.text}`));
681
+ return lines.join('\n');
682
+ }
683
+
684
+
672
685
  export const CONTROL_COMMANDS = [
673
686
  'status', 'models', 'model', 'effort', 'profile', 'agents', 'preset', 'permissions', 'plan',
674
687
  'jobs', 'remind', 'sessions', 'resume', 'plugins', 'plugin',
@@ -1851,7 +1864,7 @@ export async function handleControl(ctx) {
1851
1864
  const body = (arg || '').trim();
1852
1865
  const current = goalOf(state, key);
1853
1866
  if (!body) {
1854
- say(current ? goalView(current, L) : t(L, 'task.none'));
1867
+ say(current ? taskView(current, L) : t(L, 'task.none'));
1855
1868
  return true;
1856
1869
  }
1857
1870
  if (body.toLowerCase() === 'help' || body.toLowerCase() === '?') {
@@ -2297,13 +2310,14 @@ export async function handleControl(ctx) {
2297
2310
  }
2298
2311
  }
2299
2312
 
2313
+ const brief = ctx.ephemeral || ((out) => say(out));
2300
2314
  const text = file ? lastTurnReasoning(file, { maxChars: 20000 }) : '';
2301
2315
  if (!text) {
2302
2316
  // Not every turn plans: a one-word answer has no reasoning part at all.
2303
2317
  // Saying "here is what the last turn answered" beats a dead end that
2304
2318
  // looks like a broken command.
2305
2319
  const answered = file ? lastTurnText(file, { maxChars: 1200 }) : '';
2306
- say(answered
2320
+ brief(answered
2307
2321
  ? `${t(lang, 'ctrl.thoughts.none')}\n\n${t(lang, 'ctrl.thoughts.lastAnswer')}\n\n${answered}\n\n${t(lang, 'ctrl.thoughts.hint')}`
2308
2322
  : `${t(lang, 'ctrl.thoughts.none')}\n\n${t(lang, 'ctrl.thoughts.hint')}`);
2309
2323
  return true;
@@ -2316,7 +2330,7 @@ export async function handleControl(ctx) {
2316
2330
  parts.forEach((part, index) => {
2317
2331
  const last = index === parts.length - 1;
2318
2332
  const head = parts.length > 1 ? `${title} (${index + 1}/${parts.length})` : title;
2319
- say(`${head}\n\n${part}${last ? `\n\n${t(lang, 'ctrl.thoughts.hint')}` : ''}`);
2333
+ brief(`${head}\n\n${part}${last ? `\n\n${t(lang, 'ctrl.thoughts.hint')}` : ''}`);
2320
2334
  });
2321
2335
  return true;
2322
2336
  }
@@ -2603,6 +2617,28 @@ function bridgeRoot() {
2603
2617
  * Everything else in the directory (config, state, logs, backups) is left where
2604
2618
  * it is. Returns the directory name the old files were saved under.
2605
2619
  */
2620
+ /**
2621
+ * Copy a fetched release over this install, keeping the old files under `backup`.
2622
+ *
2623
+ * Split from the npm call so it can be tested at all: the path inside the temp
2624
+ * dir and the directory entries (`plugin/`, `skills/`) are exactly what broke
2625
+ * `/update confirm` when it was written — it read `<work>/package`, a path npm
2626
+ * never creates, and copied entries as if they were all files.
2627
+ */
2628
+ export function copyRelease(fromDir, root, backup) {
2629
+ const backupDir = join(root, backup);
2630
+ mkdirSync(backupDir, { recursive: true });
2631
+ const copied = [];
2632
+ for (const name of readdirSync(fromDir)) {
2633
+ const from = join(fromDir, name);
2634
+ const to = join(root, name);
2635
+ if (existsSync(to)) cpSync(to, join(backupDir, name), { recursive: true });
2636
+ cpSync(from, to, { recursive: true });
2637
+ copied.push(name);
2638
+ }
2639
+ return copied;
2640
+ }
2641
+
2606
2642
  function installRelease(version) {
2607
2643
  const root = bridgeRoot();
2608
2644
  const stamp = new Date().toISOString().replace(/[:.]/g, '-');
@@ -2619,13 +2655,9 @@ function installRelease(version) {
2619
2655
  const tail = `${r.stdout || ''}${r.stderr || ''}`.trim().split(/\r?\n/).slice(-6).join('\n');
2620
2656
  throw new Error(`npm exited ${r.status ?? '?'}${tail ? `\n${tail}` : ''}`);
2621
2657
  }
2622
- mkdirSync(join(root, backup), { recursive: true });
2623
- for (const name of readdirSync(join(work, 'package'))) {
2624
- const from = join(work, 'package', name);
2625
- const to = join(root, name);
2626
- if (existsSync(to)) copyFileSync(to, join(backup, name));
2627
- copyFileSync(from, to);
2628
- }
2658
+ // `--prefix` puts the package in node_modules; the flat `package` name npm
2659
+ // used before v5 has not existed for years.
2660
+ copyRelease(join(work, 'node_modules', 'dsh-tg-bridge'), root, backup);
2629
2661
  return backup;
2630
2662
  } finally {
2631
2663
  try {
package/i18n.mjs CHANGED
@@ -447,7 +447,7 @@ const DICT = {
447
447
  'ctrl.logs.title': 'Log ({shown} of {total})',
448
448
  'ctrl.logs.fileCaption': 'bridge.log, {mb} MB — the whole file',
449
449
  'ctrl.logs.noFileChannel': 'This bridge build cannot send files; use /logs 200.',
450
- 'ctrl.thoughts.title': '🧠 Reasoning of the last turn ({chars} chars, kept for a few minutes):',
450
+ 'ctrl.thoughts.title': '🧠 Reasoning of the last turn ({chars} chars, this message disappears in 3 minutes):',
451
451
  'ctrl.thoughts.none': 'The last turn stored no reasoning plan.',
452
452
  'ctrl.thoughts.lastAnswer': 'What the last turn answered:',
453
453
  'ctrl.thoughts.noSession': 'This topic has no session yet: send a task first.',
@@ -478,6 +478,7 @@ const DICT = {
478
478
  'task.removed': 'Task {n} removed.',
479
479
  'task.bad': 'No task {n}.',
480
480
  'task.empty': 'No tasks yet — /task <text>.',
481
+ 'task.listTitle': 'Tasks ({done}/{total}):',
481
482
  'task.tapHint': 'Tap a number to mark it done, tap it again to undo.',
482
483
  'task.usage': 'Usage: /task <text> | /task done <n> | /task edit <n> <text> | /task rm <n>',
483
484
  'status.goal': 'Goal: {done}/{total} · {text}',
@@ -514,6 +515,8 @@ const DICT = {
514
515
  'bridge.progress.emptyReply': '(empty reply)',
515
516
  'bridge.error.inline': 'error: {msg}',
516
517
  'bridge.error.cliDied': 'the CLI exited with code {code} and printed nothing',
518
+ 'bridge.error.noApp': 'DeepSeek Harness is not at {path} — the bridge cannot start a turn. Install the app or point `dshApp` in config.json at it.',
519
+ 'bridge.error.spawn': 'could not start the DSH turn: {msg}',
517
520
  'bridge.fallback.quota': 'quota/balance exhausted',
518
521
  'bridge.fallback.noAnswer': 'the model did not answer',
519
522
  'bridge.fallback.switched': '↻ {reason} — running on {model}{free}',
@@ -1086,7 +1089,7 @@ const DICT = {
1086
1089
  'ctrl.logs.title': 'Лог ({shown} из {total})',
1087
1090
  'ctrl.logs.fileCaption': 'bridge.log, {mb} МБ — файл целиком',
1088
1091
  'ctrl.logs.noFileChannel': 'Эта сборка моста не умеет отправлять файлы; используй /logs 200.',
1089
- 'ctrl.thoughts.title': '🧠 Рассуждения последнего хода ({chars} символов, повисят несколько минут):',
1092
+ 'ctrl.thoughts.title': '🧠 Рассуждения последнего хода ({chars} символов, сообщение исчезнет через 3 минуты):',
1090
1093
  'ctrl.thoughts.none': 'В последнем ходе не сохранилось плана рассуждений.',
1091
1094
  'ctrl.thoughts.lastAnswer': 'Последний ход ответил так:',
1092
1095
  'ctrl.thoughts.noSession': 'В этой теме ещё нет сессии: сначала отправь задачу.',
@@ -1117,6 +1120,7 @@ const DICT = {
1117
1120
  'task.removed': 'Задача {n} удалена.',
1118
1121
  'task.bad': 'Нет задачи {n}.',
1119
1122
  'task.empty': 'Задач ещё нет — /task <текст>.',
1123
+ 'task.listTitle': 'Задачи ({done}/{total}):',
1120
1124
  'task.tapHint': 'Нажми номер — задача закрыта, нажми ещё раз — вернуть.',
1121
1125
  'task.usage': 'Использование: /task <текст> | /task done <n> | /task edit <n> <текст> | /task rm <n>',
1122
1126
  'status.goal': 'Цель: {done}/{total} · {text}',
@@ -1153,6 +1157,8 @@ const DICT = {
1153
1157
  'bridge.progress.emptyReply': '(пустой ответ)',
1154
1158
  'bridge.error.inline': 'ошибка: {msg}',
1155
1159
  'bridge.error.cliDied': 'CLI завершился с кодом {code} без вывода',
1160
+ 'bridge.error.noApp': 'DeepSeek Harness не найден по пути {path} — ход запустить нечем. Установите приложение или укажите путь в `dshApp` в config.json.',
1161
+ 'bridge.error.spawn': 'не удалось запустить ход DSH: {msg}',
1156
1162
  'bridge.fallback.quota': 'квота/баланс исчерпаны',
1157
1163
  'bridge.fallback.noAnswer': 'модель не ответила',
1158
1164
  'bridge.fallback.switched': '↻ {reason} — работаю на {model}{free}',
@@ -1725,7 +1731,7 @@ const DICT = {
1725
1731
  'ctrl.logs.title': '日志({shown}/{total})',
1726
1732
  'ctrl.logs.fileCaption': 'bridge.log,{mb} MB —— 完整文件',
1727
1733
  'ctrl.logs.noFileChannel': '这个桥接版本无法发送文件;请用 /logs 200。',
1728
- 'ctrl.thoughts.title': '🧠 上一轮的推理({chars} 字符,几分钟后消失):',
1734
+ 'ctrl.thoughts.title': '🧠 上一轮的推理({chars} 字符,本消息 3 分钟后自动消失):',
1729
1735
  'ctrl.thoughts.none': '上一轮没有保存推理过程。',
1730
1736
  'ctrl.thoughts.lastAnswer': '上一轮的回答:',
1731
1737
  'ctrl.thoughts.noSession': '本话题还没有会话:先发一个任务。',
@@ -1756,6 +1762,7 @@ const DICT = {
1756
1762
  'task.removed': '已删除任务 {n}。',
1757
1763
  'task.bad': '没有任务 {n}。',
1758
1764
  'task.empty': '还没有任务——/task <文本>。',
1765
+ 'task.listTitle': '任务({done}/{total}):',
1759
1766
  'task.tapHint': '点数字标记完成,再点一次撤销。',
1760
1767
  'task.usage': '用法:/task <文本> | /task done <n> | /task edit <n> <文本> | /task rm <n>',
1761
1768
  'status.goal': '目标:{done}/{total} · {text}',
@@ -1792,6 +1799,8 @@ const DICT = {
1792
1799
  'bridge.progress.emptyReply': '(空回复)',
1793
1800
  'bridge.error.inline': '错误:{msg}',
1794
1801
  'bridge.error.cliDied': 'CLI 以代码 {code} 退出且没有输出',
1802
+ 'bridge.error.noApp': '未在 {path} 找到 DeepSeek Harness,无法启动回合。请安装应用,或在 config.json 中用 `dshApp` 指定路径。',
1803
+ 'bridge.error.spawn': '无法启动 DSH 回合:{msg}',
1795
1804
  'bridge.fallback.quota': '配额/余额已用尽',
1796
1805
  'bridge.fallback.noAnswer': '模型没有回应',
1797
1806
  'bridge.fallback.switched': '↻ {reason} —— 正在使用 {model}{free}',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-tg-bridge",
3
- "version": "1.19.4",
3
+ "version": "1.19.6",
4
4
  "description": "Telegram bridge for DeepSeek Harness: text, voice, photos and project-per-topic sessions without opening the desktop app",
5
5
  "type": "module",
6
6
  "main": "plugin-bridge.mjs",
@@ -62,6 +62,7 @@
62
62
  "settings-card.mjs",
63
63
  "media-text.mjs",
64
64
  "albums.mjs",
65
+ "allowlist.mjs",
65
66
  "prices.mjs",
66
67
  "setup.mjs",
67
68
  "bot-menu.mjs",