dsh-tg-bridge 1.7.0 → 1.7.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/bot-menu.mjs CHANGED
@@ -38,7 +38,7 @@ const COMMANDS = [
38
38
  { command: 'seed', description: 'Засеять пустую тему текстом и закрепить' },
39
39
  { command: 'goal', description: 'Цель темы: /goal <текст>, /goal done' },
40
40
  { command: 'task', description: 'Задачи: /task <текст>, /task done <n>' },
41
- { command: 'sessions', description: 'Список сессий темы' },
41
+ { command: 'sessions', description: 'Сессии темы — обычный текст продолжает последнюю' },
42
42
  { command: 'resume', description: 'Продолжить сессию: /resume <id>' },
43
43
  { command: 'model', description: 'Показать или сменить: /model, /model <id>' },
44
44
  { command: 'skills', description: 'Скиллы: список или текст одного' },
@@ -46,8 +46,8 @@ const COMMANDS = [
46
46
  { command: 'plugins', description: 'Список и управление: add/remove/disable/enable' },
47
47
  { command: 'app', description: 'Приложение DSH, не мост: /app restart confirm' },
48
48
  { command: 'restart', description: 'Перезапуск моста: /restart confirm' },
49
- { command: 'doctor', description: 'Диагностика: мост, сеть, диск, каталог, сессия' },
50
- { command: 'logs', description: 'Хвост лога моста: /logs 50 или /logs TG_NET' },
49
+ { command: 'doctor', description: 'Диагностика: мост, сеть, диск, плагины, сессия' },
50
+ { command: 'logs', description: 'Лог: /logs, /logs 100, /logs errors, /logs <текст>' },
51
51
  { command: 'help', description: 'Все команды и подсказки' },
52
52
  { command: 'lang', description: 'Язык интерфейса: en, ru, zh' },
53
53
  { command: 'reasoning', description: 'Заметки по ходу: /reasoning on|off' },
@@ -68,7 +68,7 @@ const COMMANDS_EN = [
68
68
  { command: 'seed', description: 'Seed an empty topic with text and pin it' },
69
69
  { command: 'goal', description: 'Topic goal: /goal <text>, /goal done' },
70
70
  { command: 'task', description: 'Checklist: /task <text>, /task done <n>' },
71
- { command: 'sessions', description: 'This topic\u2019s sessions' },
71
+ { command: 'sessions', description: 'Sessions of this topic — plain text continues the last one' },
72
72
  { command: 'resume', description: 'Continue a session: /resume <id>' },
73
73
  { command: 'model', description: 'Show or switch: /model, /model <id>' },
74
74
  { command: 'skills', description: 'Installed skills' },
@@ -76,8 +76,8 @@ const COMMANDS_EN = [
76
76
  { command: 'plugins', description: 'List and manage: add/remove/disable/enable' },
77
77
  { command: 'app', description: 'DSH desktop app (not the bridge)' },
78
78
  { command: 'restart', description: 'Restart the bridge: /restart confirm' },
79
- { command: 'doctor', description: 'Diagnostics: bridge, network, disk, directory, session' },
80
- { command: 'logs', description: 'Bridge log tail: /logs 50 or /logs TG_NET' },
79
+ { command: 'doctor', description: 'Diagnostics: bridge, network, disk, plugins, session' },
80
+ { command: 'logs', description: 'Log: /logs, /logs 100, /logs errors, /logs <text>' },
81
81
  { command: 'help', description: 'All commands and hints' },
82
82
  { command: 'lang', description: 'Interface language: en, ru, zh' },
83
83
  { command: 'reasoning', description: 'Working notes: /reasoning on|off' },
@@ -98,7 +98,7 @@ const COMMANDS_ZH = [
98
98
  { command: 'seed', description: '用文本初始化空话题并置顶' },
99
99
  { command: 'goal', description: '本话题目标:/goal <文本>、/goal done' },
100
100
  { command: 'task', description: '任务清单:/task <文本>、/task done <n>' },
101
- { command: 'sessions', description: '本主题的会话列表' },
101
+ { command: 'sessions', description: '本主题的会话 —— 直接发文字会延续最近一个' },
102
102
  { command: 'resume', description: '继续会话:/resume <id>' },
103
103
  { command: 'model', description: '查看或切换:/model, /model <id>' },
104
104
  { command: 'skills', description: '已安装的技能' },
@@ -106,8 +106,8 @@ const COMMANDS_ZH = [
106
106
  { command: 'plugins', description: '列表与管理:add/remove/disable/enable' },
107
107
  { command: 'app', description: 'DSH 桌面应用(不是桥接)' },
108
108
  { command: 'restart', description: '重启桥接:/restart confirm' },
109
- { command: 'doctor', description: '诊断:桥接、网络、磁盘、目录、会话' },
110
- { command: 'logs', description: '桥接日志:/logs 50 或 /logs TG_NET' },
109
+ { command: 'doctor', description: '诊断:桥接、网络、磁盘、插件、会话' },
110
+ { command: 'logs', description: '日志:/logs、/logs 100、/logs errors、/logs <文本>' },
111
111
  { command: 'help', description: '全部命令与提示' },
112
112
  { command: 'lang', description: '界面语言:en、ru、zh' },
113
113
  { command: 'reasoning', description: '工作记录:/reasoning on|off' },
package/bridge.mjs CHANGED
@@ -1229,8 +1229,11 @@ async function mediaPrompt(msgs, chatId, threadId, lang, opts = {}) {
1229
1229
  let text = parts.filter(Boolean).join('\n\n');
1230
1230
  // A steer cannot apply the vision overlay to a turn that is already running,
1231
1231
  // so the model gets a path and an honest line instead of a silently
1232
- // unreadable image.
1233
- if (text && photo && opts.steer) text += `\n\n${t(lang, 'prompt.photoMidTurn')}`;
1232
+ // unreadable image. If the turn died while the file was being fetched, the
1233
+ // text is about to become a turn of its own — and there the image *is*
1234
+ // readable, so the disclaimer would be a lie.
1235
+ const liveNow = opts.stillRunning ? opts.stillRunning() : true;
1236
+ if (text && photo && opts.steer && liveNow) text += `\n\n${t(lang, 'prompt.photoMidTurn')}`;
1234
1237
  if (text && caption) text += `\n\n${t(lang, 'prompt.note', { note: caption })}`;
1235
1238
  return { text, extraArgs, profile };
1236
1239
  }
@@ -1756,13 +1759,33 @@ function watchSteer(job, msg, text, thread, lang) {
1756
1759
  async function steerMediaMessage(msgs, sessionId, key, thread, lang) {
1757
1760
  const list = Array.isArray(msgs) ? msgs : [msgs];
1758
1761
  const first = list[0];
1759
- const built = await mediaPrompt(list, first.chat.id, thread, lang, { steer: true });
1762
+ const wasRunning = activeTurns.has(key);
1763
+ const built = await mediaPrompt(list, first.chat.id, thread, lang, {
1764
+ steer: true,
1765
+ stillRunning: () => activeTurns.has(key),
1766
+ });
1760
1767
  if (!built.text) {
1761
1768
  log('steer media produced no text; nothing injected');
1762
1769
  return;
1763
1770
  }
1764
- if (!activeTurns.has(key)) log(`steer media: turn ended during prep, job will re-queue (${key})`);
1765
- steerRunningTurn(first, built.text, sessionId, thread);
1771
+ if (activeTurns.has(key)) {
1772
+ steerRunningTurn(first, built.text, sessionId, thread);
1773
+ return;
1774
+ }
1775
+ // Transcribing and downloading take seconds; the turn this addition was meant
1776
+ // for may already be gone. Writing the job anyway left the addition in the
1777
+ // directory until `watchSteer` noticed — a minute of silence for a voice note
1778
+ // that arrived half a second too late. The prepared text (transcript, file
1779
+ // path, caption) is already the whole request, so run it as its own turn.
1780
+ log(`steer media: turn ended during prep (was ${wasRunning ? 'running' : 'gone'}), delivering as a turn (${key})`);
1781
+ enqueue(key, () => handleMessage({
1782
+ chat: first.chat,
1783
+ from: first.from,
1784
+ message_id: 0,
1785
+ message_thread_id: thread || undefined,
1786
+ is_topic_message: thread > 0,
1787
+ text: built.text,
1788
+ }));
1766
1789
  }
1767
1790
 
1768
1791
  // ------------------------------------------------------------------ albums
@@ -1797,7 +1820,11 @@ async function deliverAlbum(msgs) {
1797
1820
  const lang = resolveLang(state, key, first, config);
1798
1821
  const sessionId = liveSessions.get(key) || state.sessions[key];
1799
1822
  log(`album ${first.media_group_id}: ${msgs.length} item(s) in ${key}`);
1800
- if (config.steerDuringTurn !== false && steerAvailable(profileOf(key)) && activeTurns.has(key) && sessionId) {
1823
+ // Decide at flush time, not at send time: the buffer holds the photos for up
1824
+ // to four seconds, and a turn that ended in that window must still get an
1825
+ // answer rather than a silent drop. `steerMediaMessage` re-checks on its own
1826
+ // and quotes the built prompt into a turn when the steered turn is gone.
1827
+ if (config.steerDuringTurn !== false && steerAvailable(profileOf(key)) && sessionId) {
1801
1828
  try {
1802
1829
  await steerMediaMessage(msgs, sessionId, key, thread, lang);
1803
1830
  return;
@@ -2209,8 +2236,9 @@ async function main() {
2209
2236
  return;
2210
2237
  }
2211
2238
  // Transcription and downloads take seconds; the update loop must not
2212
- // wait for them, and the turn may even finish meanwhile — the steer
2213
- // watcher then turns the prepared text into a turn of its own.
2239
+ // wait for them. The turn may finish meanwhile, and `steerMediaMessage`
2240
+ // then runs the prepared text as a turn of its own instead of leaving
2241
+ // the voicemail in a directory nobody reads again.
2214
2242
  ack(update.update_id);
2215
2243
  const lang = resolveLang(state, queueKey, msg, config);
2216
2244
  void steerMediaMessage(msg, sessionId, queueKey, thread, lang).catch((error) => {
package/control.mjs CHANGED
@@ -11,7 +11,7 @@ import { join, basename } from 'node:path';
11
11
  import { fileURLToPath } from 'node:url';
12
12
  import { t, LANGS, normalizeLang } from './i18n.mjs';
13
13
  import { addTask, clearGoal, doneTask, finishGoal, goalOf, progressOf, removeTask, setGoal } from './goals.mjs';
14
- import { lastTurnReasoning, sessionFile } from './thoughts.mjs';
14
+ import { lastTurnReasoning, lastTurnText, sessionFile, sessionStats } from './thoughts.mjs';
15
15
 
16
16
  const HOME = homedir();
17
17
  const DSH_HOME = process.env.DSH_HOME || join(HOME, '.dsh');
@@ -296,9 +296,16 @@ function bareId(id) {
296
296
  return String(id).replace(/^session-/, '');
297
297
  }
298
298
 
299
+ /** `2026-10-25 17:11` in the machine's own zone, for the status card. */
300
+ function stamp(ms) {
301
+ const d = new Date(ms);
302
+ if (Number.isNaN(d.getTime())) return '—';
303
+ const pad = (n) => String(n).padStart(2, '0');
304
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
305
+ }
306
+
299
307
  /** Recent DSH sessions of this workspace, newest first, with their titles. */
300
- function recentSessions(cwd, limit, lang = 'ru') {
301
- const root = join(DSH_HOME, 'sessions');
308
+ function recentSessions(cwd, limit, lang = 'ru') { const root = join(DSH_HOME, 'sessions');
302
309
  const rows = [];
303
310
  let dirs = [];
304
311
  try {
@@ -455,21 +462,44 @@ export async function handleControl(ctx) {
455
462
  switch (effective) {
456
463
  case '/status': {
457
464
  const head = modelOf(activeProfile);
458
- const session = state.sessions[key] || t(lang, 'ctrl.session.none');
459
465
  const active = ctx.activeTurns ? ctx.activeTurns.size : 0;
460
- const lines = [
461
- t(lang, 'ctrl.status.profile', { name: activeProfile, route: `${head.provider}/${head.model}` }),
462
- t(lang, 'ctrl.status.thread', { name: ctx.threadId || t(lang, 'ctrl.status.threadDefault') }),
463
- t(lang, 'ctrl.status.session', { id: session }),
464
- t(lang, 'ctrl.status.turns', { n: active }),
465
- t(lang, 'ctrl.status.skills', { n: skillsOf().length }),
466
- `DSH_HOME: ${DSH_HOME}`,
467
- ];
466
+ // A card, not a key dump: the identity first, then what the session is
467
+ // doing, then the environment. Numbers are the ones a person asks for
468
+ // ("how much context is left", "how big is this session").
469
+ const sessionId = state.sessions[key] || '';
470
+ const stats = sessionId ? sessionStats(sessionFile(join(DSH_HOME, 'sessions'), sessionId)) : null;
471
+ const title = sessionId ? state.titles?.[key] : '';
472
+ const lines = [t(lang, 'ctrl.status.head')];
473
+ lines.push(t(lang, 'ctrl.status.session', { id: sessionId ? `${sessionId.slice(0, 8)}…` : t(lang, 'ctrl.session.none') }));
474
+ if (title) lines.push(t(lang, 'ctrl.status.title', { title }));
475
+ lines.push(t(lang, 'ctrl.status.profile', { name: activeProfile, route: `${head.provider}/${head.model}` }));
476
+ lines.push(t(lang, 'ctrl.status.thread', { name: ctx.threadId || t(lang, 'ctrl.status.threadDefault') }));
477
+ if (stats?.createdAt) lines.push(t(lang, 'ctrl.status.created', { when: stamp(stats.createdAt) }));
478
+ if (stats?.lastActivity) lines.push(t(lang, 'ctrl.status.activity', { when: stamp(stats.lastActivity) }));
479
+ if (stats?.contextTokens) {
480
+ const window = Number(config.contextWindow) || 0;
481
+ lines.push(window
482
+ ? t(lang, 'ctrl.status.context', {
483
+ now: stats.contextTokens.toLocaleString('en-US'),
484
+ max: window.toLocaleString('en-US'),
485
+ pct: Math.round((stats.contextTokens / window) * 100),
486
+ })
487
+ : t(lang, 'ctrl.status.contextNoWindow', { now: stats.contextTokens.toLocaleString('en-US') }));
488
+ }
489
+ if (stats?.lifetimeTokens) {
490
+ lines.push(t(lang, 'ctrl.status.lifetime', { n: stats.lifetimeTokens.toLocaleString('en-US') }));
491
+ }
492
+ if (stats?.turns) lines.push(t(lang, 'ctrl.status.steps', { n: stats.turns }));
493
+ lines.push(t(lang, 'ctrl.status.turns', { n: active }));
494
+ lines.push(t(lang, 'ctrl.status.notes', {
495
+ state: reasoningOf(state, config, key) ? t(lang, 'ctrl.status.on') : t(lang, 'ctrl.status.off'),
496
+ }));
497
+ lines.push(t(lang, 'ctrl.status.skills', { n: skillsOf().length }));
468
498
  // The desktop profile only matters when this install actually has one.
469
499
  if (existsSync(join(PROFILES, 'desktop', 'cordis.patch.yml'))) {
470
500
  const desk = modelOf('desktop');
471
501
  const deskPlugins = pluginsOf('desktop');
472
- lines.splice(1, 0, t(lang, 'ctrl.status.ui', {
502
+ lines.push(t(lang, 'ctrl.status.ui', {
473
503
  route: `${desk.provider}/${desk.model}`,
474
504
  n: deskPlugins.bundles.length,
475
505
  }));
@@ -481,6 +511,7 @@ export async function handleControl(ctx) {
481
511
  done, total, text: currentGoal.text.length > 60 ? `${currentGoal.text.slice(0, 59)}…` : currentGoal.text,
482
512
  }));
483
513
  }
514
+ lines.push(`DSH_HOME: ${DSH_HOME}`);
484
515
  say(lines.join('\n'));
485
516
  return true;
486
517
  }
@@ -823,10 +854,14 @@ export async function handleControl(ctx) {
823
854
  const wanted = (arg || '').trim().replace(/^"|"$/g, '');
824
855
  state.cwd = state.cwd || {};
825
856
  if (!wanted) {
826
- const current = state.cwd[key] || config.cwd;
857
+ // A topic without its own directory still has one: the bridge default.
858
+ // Printing an empty line there reads as "nothing is bound".
859
+ const current = state.cwd[key] || config.cwd || '';
827
860
  const lines = [
828
861
  t(lang, 'ctrl.cd.current'),
829
- current,
862
+ current
863
+ ? `${current}${state.cwd[key] ? '' : t(lang, 'ctrl.cd.defaultSuffix')}`
864
+ : t(lang, 'ctrl.cd.unset'),
830
865
  '',
831
866
  t(lang, 'ctrl.cd.bind'),
832
867
  t(lang, 'ctrl.cd.resetHint'),
@@ -1072,9 +1107,14 @@ export async function handleControl(ctx) {
1072
1107
  add(t(lang, 'ctrl.doctor.disk'), t(lang, 'ctrl.doctor.diskFree', { gb: (free / 1024 ** 3).toFixed(1) }));
1073
1108
  } catch {}
1074
1109
 
1075
- // Project directory bound to this topic and whether it exists.
1076
- const cwd = (state.cwd && state.cwd[key]) || config.cwd;
1077
- add(t(lang, 'ctrl.doctor.cwd'), `${cwd}${existsSync(cwd) ? '' : t(lang, 'ctrl.doctor.cwdMissing')}`);
1110
+ // Project directory bound to this topic and whether it exists. The bridge
1111
+ // default is a fact, not an accident: say when it is being used.
1112
+ const bound = state.cwd && state.cwd[key];
1113
+ const cwd = bound || config.cwd || '';
1114
+ const shown = cwd
1115
+ ? `${cwd}${bound ? '' : t(lang, 'ctrl.doctor.cwdDefault')}${existsSync(cwd) ? '' : t(lang, 'ctrl.doctor.cwdMissing')}`
1116
+ : t(lang, 'ctrl.doctor.cwdUnset');
1117
+ add(t(lang, 'ctrl.doctor.cwd'), shown);
1078
1118
 
1079
1119
  add(t(lang, 'ctrl.doctor.session'), state.sessions[key] || t(lang, 'ctrl.doctor.sessionNew'));
1080
1120
  say(`${t(lang, 'ctrl.doctor.title')}\n\n${rows.join('\n')}`);
@@ -1138,7 +1178,13 @@ export async function handleControl(ctx) {
1138
1178
  const file = sessionFile(join(DSH_HOME, 'sessions'), sessionId);
1139
1179
  const text = file ? lastTurnReasoning(file, { maxChars: 4000 }) : '';
1140
1180
  if (!text) {
1141
- say(t(lang, 'ctrl.thoughts.none'));
1181
+ // Not every turn plans: a one-word answer has no reasoning part at all.
1182
+ // Saying "here is what the last turn answered" beats a dead end that
1183
+ // looks like a broken command.
1184
+ const answered = file ? lastTurnText(file, { maxChars: 1200 }) : '';
1185
+ say(answered
1186
+ ? `${t(lang, 'ctrl.thoughts.none')}\n\n${t(lang, 'ctrl.thoughts.lastAnswer')}\n\n${answered}`
1187
+ : t(lang, 'ctrl.thoughts.none'));
1142
1188
  return true;
1143
1189
  }
1144
1190
  say(t(lang, 'ctrl.thoughts.title', { chars: text.length }) + '\n\n' + text);
package/i18n.mjs CHANGED
@@ -69,11 +69,22 @@ const DICT = {
69
69
  'cmd.cd.none': 'No such directory: {path}',
70
70
  'cmd.new.done': 'New session in this topic. Context cleared.',
71
71
  'ctrl.session.none': '(none yet)',
72
+ 'ctrl.status.head': '📊 Bridge status',
72
73
  'ctrl.status.profile': 'Profile: {name} ({route})',
73
74
  'ctrl.status.thread': 'Thread: {name}',
74
75
  'ctrl.status.threadDefault': 'general',
75
76
  'ctrl.status.session': 'Session: {id}',
77
+ 'ctrl.status.title': 'Title: {title}',
78
+ 'ctrl.status.created': 'Created: {when}',
79
+ 'ctrl.status.activity': 'Last activity: {when}',
80
+ 'ctrl.status.context': 'Context: {now} / {max} ({pct}%)',
81
+ 'ctrl.status.contextNoWindow': 'Context: {now} tokens (window unknown: set contextWindow in config.json)',
82
+ 'ctrl.status.lifetime': 'Session tokens billed: {n}',
83
+ 'ctrl.status.steps': 'Turns in the session: {n}',
76
84
  'ctrl.status.turns': 'Turns running: {n}',
85
+ 'ctrl.status.notes': 'Working notes (💭 in progress): {state}',
86
+ 'ctrl.status.on': 'on',
87
+ 'ctrl.status.off': 'off',
77
88
  'ctrl.status.skills': 'Skills: {n}',
78
89
  'ctrl.status.ui': 'UI: desktop ({route}) — bundled plugins: {n}',
79
90
  'ctrl.models.current': 'Current model: {model}',
@@ -144,6 +155,8 @@ const DICT = {
144
155
  'ctrl.send.unsupported': 'File sending is unavailable: the bridge is an old version.',
145
156
  'ctrl.send.failed': 'Could not send the file: {err}',
146
157
  'ctrl.cd.current': 'Current topic directory:',
158
+ 'ctrl.cd.defaultSuffix': ' (bridge default)',
159
+ 'ctrl.cd.unset': 'not set — the bridge default working directory is used',
147
160
  'ctrl.cd.bind': 'Bind: /cd <path>',
148
161
  'ctrl.cd.resetHint': 'Reset: /cd reset',
149
162
  'ctrl.cd.projects': 'Projects:',
@@ -173,6 +186,8 @@ const DICT = {
173
186
  'ctrl.doctor.diskFree': '{gb} GB free',
174
187
  'ctrl.doctor.cwd': 'Topic directory',
175
188
  'ctrl.doctor.cwdMissing': ' (NO SUCH DIRECTORY)',
189
+ 'ctrl.doctor.cwdDefault': ' (bridge default; bind this topic with /cd)',
190
+ 'ctrl.doctor.cwdUnset': 'not set anywhere — check cwd in config.json',
176
191
  'ctrl.doctor.session': 'Session',
177
192
  'ctrl.doctor.sessionNew': '(new)',
178
193
  'ctrl.logs.unreadable': 'Cannot read the log: {err}',
@@ -182,6 +197,7 @@ const DICT = {
182
197
  'ctrl.logs.title': 'Log ({shown} of {total})',
183
198
  'ctrl.thoughts.title': '🧠 Reasoning of the last turn ({chars} chars, kept for a few minutes):',
184
199
  'ctrl.thoughts.none': 'The last turn stored no reasoning plan.',
200
+ 'ctrl.thoughts.lastAnswer': 'What the last turn answered:',
185
201
  'ctrl.thoughts.noSession': 'This topic has no session yet: send a task first.',
186
202
  'goal.none': 'No goal in this topic. Set one: /goal <text>',
187
203
  'goal.set': 'Goal: {text}',
@@ -321,11 +337,22 @@ const DICT = {
321
337
  'cmd.cd.none': 'Нет такого каталога: {path}',
322
338
  'cmd.new.done': 'Новая сессия в этой ветке. Контекст очищен.',
323
339
  'ctrl.session.none': '(ещё нет)',
340
+ 'ctrl.status.head': '📊 Статус моста',
324
341
  'ctrl.status.profile': 'Профиль: {name} ({route})',
325
342
  'ctrl.status.thread': 'Ветка: {name}',
326
343
  'ctrl.status.threadDefault': 'общая',
327
344
  'ctrl.status.session': 'Сессия: {id}',
345
+ 'ctrl.status.title': 'Название: {title}',
346
+ 'ctrl.status.created': 'Создана: {when}',
347
+ 'ctrl.status.activity': 'Последняя активность: {when}',
348
+ 'ctrl.status.context': 'Контекст: {now} / {max} ({pct}%)',
349
+ 'ctrl.status.contextNoWindow': 'Контекст: {now} токенов (окно неизвестно: укажи contextWindow в config.json)',
350
+ 'ctrl.status.lifetime': 'Токенов за сессию: {n}',
351
+ 'ctrl.status.steps': 'Ходов в сессии: {n}',
328
352
  'ctrl.status.turns': 'Ходов в работе: {n}',
353
+ 'ctrl.status.notes': 'Заметки по ходу (💭 в прогрессе): {state}',
354
+ 'ctrl.status.on': 'включены',
355
+ 'ctrl.status.off': 'выключены',
329
356
  'ctrl.status.skills': 'Скиллы: {n}',
330
357
  'ctrl.status.ui': 'UI: desktop ({route}) — плагинов {n}',
331
358
  'ctrl.models.current': 'Модель сейчас: {model}',
@@ -396,6 +423,8 @@ const DICT = {
396
423
  'ctrl.send.unsupported': 'Отправка файлов недоступна: мост старой версии.',
397
424
  'ctrl.send.failed': 'Не смог отправить файл: {err}',
398
425
  'ctrl.cd.current': 'Текущий каталог темы:',
426
+ 'ctrl.cd.defaultSuffix': ' (по умолчанию моста)',
427
+ 'ctrl.cd.unset': 'не задан — используется рабочий каталог по умолчанию',
399
428
  'ctrl.cd.bind': 'Привязать: /cd <путь>',
400
429
  'ctrl.cd.resetHint': 'Сбросить: /cd reset',
401
430
  'ctrl.cd.projects': 'Проекты:',
@@ -425,6 +454,8 @@ const DICT = {
425
454
  'ctrl.doctor.diskFree': '{gb} ГБ свободно',
426
455
  'ctrl.doctor.cwd': 'Каталог темы',
427
456
  'ctrl.doctor.cwdMissing': ' (НЕТ ТАКОГО)',
457
+ 'ctrl.doctor.cwdDefault': ' (по умолчанию моста; привязать тему: /cd)',
458
+ 'ctrl.doctor.cwdUnset': 'не задан нигде — проверь cwd в config.json',
428
459
  'ctrl.doctor.session': 'Сессия',
429
460
  'ctrl.doctor.sessionNew': '(новая)',
430
461
  'ctrl.logs.unreadable': 'Не могу прочитать лог: {err}',
@@ -434,6 +465,7 @@ const DICT = {
434
465
  'ctrl.logs.title': 'Лог ({shown} из {total})',
435
466
  'ctrl.thoughts.title': '🧠 Рассуждения последнего хода ({chars} символов, повисят несколько минут):',
436
467
  'ctrl.thoughts.none': 'В последнем ходе не сохранилось плана рассуждений.',
468
+ 'ctrl.thoughts.lastAnswer': 'Последний ход ответил так:',
437
469
  'ctrl.thoughts.noSession': 'В этой теме ещё нет сессии: сначала отправь задачу.',
438
470
  'goal.none': 'В этой теме нет цели. Задать: /goal <текст>',
439
471
  'goal.set': 'Цель: {text}',
@@ -573,11 +605,22 @@ const DICT = {
573
605
  'cmd.cd.none': '目录不存在:{path}',
574
606
  'cmd.new.done': '已在本话题开始新会话,上下文已清空。',
575
607
  'ctrl.session.none': '(还没有)',
608
+ 'ctrl.status.head': '📊 桥接状态',
576
609
  'ctrl.status.profile': '配置档:{name}({route})',
577
610
  'ctrl.status.thread': '话题:{name}',
578
611
  'ctrl.status.threadDefault': '公共',
579
612
  'ctrl.status.session': '会话:{id}',
613
+ 'ctrl.status.title': '标题:{title}',
614
+ 'ctrl.status.created': '创建时间:{when}',
615
+ 'ctrl.status.activity': '最近活动:{when}',
616
+ 'ctrl.status.context': '上下文:{now} / {max}({pct}%)',
617
+ 'ctrl.status.contextNoWindow': '上下文:{now} 个 token(窗口未知:在 config.json 里设置 contextWindow)',
618
+ 'ctrl.status.lifetime': '本会话累计 token:{n}',
619
+ 'ctrl.status.steps': '会话中的轮次:{n}',
580
620
  'ctrl.status.turns': '进行中的任务:{n}',
621
+ 'ctrl.status.notes': '工作记录(进度中的 💭):{state}',
622
+ 'ctrl.status.on': '开',
623
+ 'ctrl.status.off': '关',
581
624
  'ctrl.status.skills': '技能:{n}',
582
625
  'ctrl.status.ui': 'UI:desktop({route})— 插件 {n} 个',
583
626
  'ctrl.models.current': '当前模型:{model}',
@@ -648,6 +691,8 @@ const DICT = {
648
691
  'ctrl.send.unsupported': '无法发送文件:桥是旧版本。',
649
692
  'ctrl.send.failed': '无法发送文件:{err}',
650
693
  'ctrl.cd.current': '话题的当前目录:',
694
+ 'ctrl.cd.defaultSuffix': '(桥接默认)',
695
+ 'ctrl.cd.unset': '未设置 —— 使用桥接的默认工作目录',
651
696
  'ctrl.cd.bind': '绑定:/cd <路径>',
652
697
  'ctrl.cd.resetHint': '重置:/cd reset',
653
698
  'ctrl.cd.projects': '项目:',
@@ -677,6 +722,8 @@ const DICT = {
677
722
  'ctrl.doctor.diskFree': '{gb} GB 可用',
678
723
  'ctrl.doctor.cwd': '话题目录',
679
724
  'ctrl.doctor.cwdMissing': '(没有这个目录)',
725
+ 'ctrl.doctor.cwdDefault': '(桥接默认;可用 /cd 绑定话题)',
726
+ 'ctrl.doctor.cwdUnset': '未设置 —— 检查 config.json 里的 cwd',
680
727
  'ctrl.doctor.session': '会话',
681
728
  'ctrl.doctor.sessionNew': '(新)',
682
729
  'ctrl.logs.unreadable': '无法读取日志:{err}',
@@ -686,6 +733,7 @@ const DICT = {
686
733
  'ctrl.logs.title': '日志({shown}/{total})',
687
734
  'ctrl.thoughts.title': '🧠 上一轮的推理({chars} 字符,几分钟后消失):',
688
735
  'ctrl.thoughts.none': '上一轮没有保存推理过程。',
736
+ 'ctrl.thoughts.lastAnswer': '上一轮的回答:',
689
737
  'ctrl.thoughts.noSession': '本话题还没有会话:先发一个任务。',
690
738
  'goal.none': '本话题还没有目标。设置:/goal <文本>',
691
739
  'goal.set': '目标:{text}',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-tg-bridge",
3
- "version": "1.7.0",
3
+ "version": "1.7.2",
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",
@@ -67,6 +67,7 @@
67
67
  "plugin/",
68
68
  "profiles.mjs",
69
69
  "cli-args.mjs",
70
- "thoughts.mjs"
70
+ "thoughts.mjs",
71
+ "sync-runtime.mjs"
71
72
  ]
72
73
  }
@@ -0,0 +1,44 @@
1
+ // Copy the runtime files of this checkout into the live bridge directory,
2
+ // keeping a timestamped backup of what it replaces.
3
+ //
4
+ // node sync-runtime.mjs # repo -> ~/.dsh/tg-bridge
5
+ // node sync-runtime.mjs --dir X # repo -> X
6
+ //
7
+ // Written in Node, not PowerShell: the files are UTF-8 with Cyrillic, and
8
+ // Set-Content would mangle them. The version in package.json comes along too —
9
+ // `/version` reads it, and a module-only sync would leave it describing the
10
+ // previous release.
11
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync } from 'node:fs';
12
+ import { homedir } from 'node:os';
13
+ import { dirname, join } from 'node:path';
14
+ import { fileURLToPath } from 'node:url';
15
+
16
+ const here = dirname(fileURLToPath(import.meta.url));
17
+ const flag = process.argv.indexOf('--dir');
18
+ const target = flag > -1 && process.argv[flag + 1]
19
+ ? process.argv[flag + 1]
20
+ : join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'tg-bridge');
21
+
22
+ if (!existsSync(target)) mkdirSync(target, { recursive: true });
23
+
24
+ const stamp = new Date().toISOString().replace(/[:.]/g, '').slice(0, 15);
25
+ const names = readdirSync(here).filter((name) => name.endsWith('.mjs') || name === 'package.json');
26
+ let copied = 0;
27
+
28
+ for (const name of names) {
29
+ if (name === 'sync-runtime.mjs') continue;
30
+ const to = join(target, name);
31
+ if (existsSync(to)) copyFileSync(to, `${to}.bak-${stamp}`);
32
+ copyFileSync(join(here, name), to);
33
+ copied += 1;
34
+ }
35
+
36
+ const version = (() => {
37
+ try {
38
+ return JSON.parse(readFileSync(join(target, 'package.json'), 'utf8')).version;
39
+ } catch {
40
+ return 'unknown';
41
+ }
42
+ })();
43
+ console.log(`synced ${copied} files into ${target} (version ${version}, backup stamp ${stamp})`);
44
+ console.log('restart the bridge to load them: /restart confirm in Telegram');
package/thoughts.mjs CHANGED
@@ -44,14 +44,25 @@ export function sessionFile(sessionsRoot, sessionId) {
44
44
  /**
45
45
  * Reasoning blocks of the last turn, oldest first. `maxChars` keeps the head of
46
46
  * the stream: that is where the plan and the first diagnosis are.
47
+ *
48
+ * Not every turn has reasoning to show: a one-word answer ("ok") carries a text
49
+ * part and nothing else, and some models are not given a reasoning budget at all.
50
+ * The caller distinguishes "no plan in this turn" from "no such session".
47
51
  */
48
52
  export function lastTurnReasoning(file, { maxChars = 4000 } = {}) {
49
- if (!file || !existsSync(file)) return '';
53
+ const blocks = lastTurnBlocks(file).filter((part) => part.type === 'reasoning' && part.text);
54
+ const text = blocks.map((part) => part.text.trim()).join('\n\n').trim();
55
+ return text.length > maxChars ? `${text.slice(0, maxChars)}…` : text;
56
+ }
57
+
58
+ /** Every part of every assistant message of the last turn, in order. */
59
+ function lastTurnBlocks(file) {
60
+ if (!file || !existsSync(file)) return [];
50
61
  let buf;
51
62
  try {
52
63
  buf = readFileSync(file);
53
64
  } catch {
54
- return '';
65
+ return [];
55
66
  }
56
67
  const starts = frameStarts(buf);
57
68
  const lines = [];
@@ -73,7 +84,7 @@ export function lastTurnReasoning(file, { maxChars = 4000 } = {}) {
73
84
  }
74
85
  }
75
86
  lines.reverse();
76
- const blocks = [];
87
+ const out = [];
77
88
  for (const line of lines) {
78
89
  let record;
79
90
  try {
@@ -82,12 +93,70 @@ export function lastTurnReasoning(file, { maxChars = 4000 } = {}) {
82
93
  continue;
83
94
  }
84
95
  if (record?.type !== 'assistant/message') continue;
85
- for (const part of record.data?.message?.content ?? []) {
86
- if (part?.type === 'reasoning' && part.text) blocks.push(part.text.trim());
87
- }
96
+ for (const part of record.data?.message?.content ?? []) out.push(part);
88
97
  }
89
- const text = blocks.join('\n\n').trim();
98
+ return out;
99
+ }
100
+
101
+ /** The last turn's own answer text — the fallback when it planned nothing. */
102
+ export function lastTurnText(file, { maxChars = 1500 } = {}) {
103
+ const text = lastTurnBlocks(file)
104
+ .filter((part) => part.type === 'text' && part.text)
105
+ .map((part) => part.text.trim())
106
+ .join('\n\n')
107
+ .trim();
90
108
  return text.length > maxChars ? `${text.slice(0, maxChars)}…` : text;
91
109
  }
92
110
 
111
+ /**
112
+ * What a `/status` card wants to know about a session: when it started, when it
113
+ * last did anything, which model answered, how big the context is now, and how
114
+ * many tokens were billed over the session's whole life.
115
+ *
116
+ * `totalTokens` on an assistant message is the size of the prompt that turn sent
117
+ * (input + cache read), i.e. the current context — not the lifetime total, which
118
+ * is the sum over every call.
119
+ */
120
+ export function sessionStats(file) {
121
+ const empty = { createdAt: 0, lastActivity: 0, model: '', contextTokens: 0, lifetimeTokens: 0, turns: 0 };
122
+ if (!file || !existsSync(file)) return empty;
123
+ let buf;
124
+ try {
125
+ buf = readFileSync(file);
126
+ } catch {
127
+ return empty;
128
+ }
129
+ const stats = { ...empty };
130
+ const starts = frameStarts(buf);
131
+ for (let i = 0; i < starts.length - 1; i++) {
132
+ let text = '';
133
+ try {
134
+ text = zstdDecompressSync(buf.subarray(starts[i], starts[i + 1])).toString('utf8');
135
+ } catch {
136
+ continue;
137
+ }
138
+ for (const line of text.split('\n')) {
139
+ if (!line) continue;
140
+ let record;
141
+ try {
142
+ record = JSON.parse(line);
143
+ } catch {
144
+ continue;
145
+ }
146
+ if (record.type === 'session' && record.createdAt) stats.createdAt = record.createdAt;
147
+ if (record.type === 'turn/start') stats.turns += 1;
148
+ if (record.time) stats.lastActivity = Math.max(stats.lastActivity, record.time);
149
+ if (record.type !== 'assistant/message') continue;
150
+ const usage = record.data?.usage;
151
+ if (usage) {
152
+ if (Number.isFinite(usage.totalTokens)) stats.contextTokens = usage.totalTokens;
153
+ const billed = (usage.inputTokens ?? 0) + (usage.outputTokens ?? 0) + (usage.cacheReadTokens ?? 0);
154
+ stats.lifetimeTokens += billed;
155
+ }
156
+ if (!stats.model && record.data?.message?.model) stats.model = record.data.message.model;
157
+ }
158
+ }
159
+ return stats;
160
+ }
161
+
93
162
  export { frameStarts };