dsh-tg-bridge 1.15.0 → 1.16.0

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
@@ -42,17 +42,19 @@ const COMMANDS = [
42
42
  { command: 'sessions', description: 'Сессии темы — обычный текст продолжает последнюю' },
43
43
  { command: 'resume', description: 'Продолжить сессию: /resume <id>' },
44
44
  { command: 'model', description: 'Показать или сменить: /model, /model <id>' },
45
- { command: 'models', description: 'Все модели профиля и цены' },
45
+ { command: 'models', description: 'Все модели профиля и цены' },
46
46
  { command: 'skills', description: 'Скиллы: список или текст одного' },
47
47
  { command: 'soul', description: 'Персона: показать или задать' },
48
- { command: 'plugins', description: 'Список и включение: disable/enable (add/remove — /plugin)' },
49
- { command: 'plugin', description: 'Один плагин: /plugin disable <id>' },
48
+ { command: 'plugins', description: 'Список, add, remove, disable, enable — всё здесь' },
49
+ { command: 'plugin', description: 'Старая форма /plugins — то же самое' },
50
50
  { command: 'app', description: 'Приложение DSH, не мост: /app restart confirm' },
51
51
  { command: 'restart', description: 'Перезапуск моста: /restart confirm' },
52
52
  { command: 'doctor', description: 'Диагностика: мост, сеть, диск, плагины, сессия' },
53
53
  { command: 'logs', description: 'Лог: /logs, /logs 100, /logs errors, /logs file' },
54
54
  { command: 'help', description: 'Все команды и подсказки' },
55
- { command: 'settings', description: 'Настройки кнопками, по разделам' },
55
+ { command: 'settings', description: 'Настройки кнопками, по разделам' },
56
+ { command: 'menu', description: 'Панель: всё кнопками, исчезает после нажатия' },
57
+ { command: 'rewind', description: 'Откатить ход и сформулировать иначе: /rewind 2' },
56
58
  { command: 'lang', description: 'Язык интерфейса: en, ru, zh' },
57
59
  { command: 'reasoning', description: 'Заметки по ходу: /reasoning on|off' },
58
60
  { command: 'profile', description: 'Профиль темы: /profile <имя>, /profile new' },
@@ -84,17 +86,19 @@ const COMMANDS_EN = [
84
86
  { command: 'sessions', description: 'Sessions of this topic — plain text continues the last one' },
85
87
  { command: 'resume', description: 'Continue a session: /resume <id>' },
86
88
  { command: 'model', description: 'Show or switch: /model, /model <id>' },
87
- { command: 'models', description: 'All models of this profile with prices' },
89
+ { command: 'models', description: 'All models of this profile with prices' },
88
90
  { command: 'skills', description: 'Installed skills' },
89
91
  { command: 'soul', description: 'Agent persona' },
90
- { command: 'plugins', description: 'List and toggle: disable/enable (add/remove is /plugin)' },
91
- { command: 'plugin', description: 'One plugin: /plugin disable <id>' },
92
+ { command: 'plugins', description: 'List, add, remove, disable, enable — all here' },
93
+ { command: 'plugin', description: 'Старая форма /plugins — то же самое' },
92
94
  { command: 'app', description: 'DSH desktop app (not the bridge)' },
93
95
  { command: 'restart', description: 'Restart the bridge: /restart confirm' },
94
96
  { command: 'doctor', description: 'Diagnostics: bridge, network, disk, plugins, session' },
95
97
  { command: 'logs', description: 'Log: /logs, /logs 100, /logs errors, /logs file' },
96
98
  { command: 'help', description: 'All commands and hints' },
97
- { command: 'settings', description: 'Settings as buttons, grouped by topic' },
99
+ { command: 'settings', description: 'Settings as buttons, grouped by topic' },
100
+ { command: 'menu', description: 'Panel: everything as buttons, gone after a press' },
101
+ { command: 'rewind', description: 'Go back a turn and rephrase: /rewind 2' },
98
102
  { command: 'lang', description: 'Interface language: en, ru, zh' },
99
103
  { command: 'reasoning', description: 'Working notes: /reasoning on|off' },
100
104
  { command: 'profile', description: 'Topic profile: /profile <name>, /profile new' },
@@ -126,17 +130,19 @@ const COMMANDS_ZH = [
126
130
  { command: 'sessions', description: '本主题的会话 —— 直接发文字会延续最近一个' },
127
131
  { command: 'resume', description: '继续会话:/resume <id>' },
128
132
  { command: 'model', description: '查看或切换:/model, /model <id>' },
129
- { command: 'models', description: '本配置档的全部模型与价格' },
133
+ { command: 'models', description: '本配置档的全部模型与价格' },
130
134
  { command: 'skills', description: '已安装的技能' },
131
135
  { command: 'soul', description: '代理人格设定' },
132
- { command: 'plugins', description: '列表与开关:disable/enable(add/remove 用 /plugin)' },
133
- { command: 'plugin', description: '单个插件:/plugin disable <id>' },
136
+ { command: 'plugins', description: '列表、add、remove、disable、enable 都在这里' },
137
+ { command: 'plugin', description: 'Старая форма /plugins — то же самое' },
134
138
  { command: 'app', description: 'DSH 桌面应用(不是桥接)' },
135
139
  { command: 'restart', description: '重启桥接:/restart confirm' },
136
140
  { command: 'doctor', description: '诊断:桥接、网络、磁盘、插件、会话' },
137
141
  { command: 'logs', description: '日志:/logs、/logs 100、/logs errors、/logs file' },
138
142
  { command: 'help', description: '全部命令与提示' },
139
- { command: 'settings', description: '用按钮调设置,按主题分组' },
143
+ { command: 'settings', description: '用按钮调设置,按主题分组' },
144
+ { command: 'menu', description: '面板:全部做成按钮,按一下就消失' },
145
+ { command: 'rewind', description: '回退一轮并换种说法:/rewind 2' },
140
146
  { command: 'lang', description: '界面语言:en、ru、zh' },
141
147
  { command: 'reasoning', description: '工作记录:/reasoning on|off' },
142
148
  { command: 'profile', description: '话题配置档:/profile <名称>,/profile new' },
package/bridge.mjs CHANGED
@@ -44,6 +44,10 @@ import { drainAsetJobs } from './aset-jobs.mjs';
44
44
  import { materialiseProfile, pruneDerived } from './aset-profile.mjs';
45
45
  import { parseCallback } from './aset-schema.mjs';
46
46
  import { commandFor, renderSettingsCard, settingsCurrent } from './settings-card.mjs';
47
+ import { answerRewindPress, cutSession, isRewindPress } from './rewind-buttons.mjs';
48
+ import { applyRewind, newestBackup, restoreBackup } from './rewind.mjs';
49
+ import { sessionFile } from './thoughts.mjs';
50
+ import { MENU_PREFIX, commandForName, isMenuPress, renderPanel } from './menu-card.mjs';
47
51
 
48
52
  const HOME = homedir();
49
53
  const DSH_HOME = process.env.DSH_HOME || join(HOME, '.dsh');
@@ -790,6 +794,65 @@ function topicName(chatId, threadId) {
790
794
  return '';
791
795
  }
792
796
 
797
+ /**
798
+ * Run a command that a button stands for, exactly as if it had been typed.
799
+ *
800
+ * The panel has no second implementation of anything: a press calls this, and
801
+ * this calls `handleControl` with the same context a typed command gets. What
802
+ * a button cannot do is money or state the person did not mean — so a press
803
+ * never falls through to an AI turn.
804
+ */
805
+ async function runCommandFromButton(typed, { chatId, threadId, key }) {
806
+ const lang = langFor(chatId, threadId);
807
+ const [head, ...rest] = typed.trim().split(/\s+/);
808
+ const arg = rest.join(' ');
809
+ const handled = await handleControl({
810
+ command: head,
811
+ arg,
812
+ text: typed,
813
+ lang,
814
+ chatId,
815
+ threadId,
816
+ key,
817
+ state,
818
+ config,
819
+ activeTurns,
820
+ saveState,
821
+ log,
822
+ send,
823
+ jobs: () => ({
824
+ active: [...activeTurns.keys()].map((topic) => ({ key: topic, startedAt: turnStartedAt.get(topic) || 0 })),
825
+ queued: [...queues.keys()].filter((topic) => !activeTurns.has(topic)).length,
826
+ max: MAX_PARALLEL,
827
+ }),
828
+ api: tg,
829
+ sendFile: (p, caption = '') => sendFile(chatId, threadId, p, caption),
830
+ seedTopic: ensureTopicSeed,
831
+ profile: profileOf(key),
832
+ reply: (out, extra = {}) => (extra.keyboard
833
+ ? tg('sendMessage', {
834
+ chat_id: chatId,
835
+ text: out,
836
+ disable_web_page_preview: true,
837
+ reply_markup: { inline_keyboard: extra.keyboard },
838
+ ...(threadId > 0 ? { message_thread_id: threadId } : {}),
839
+ }).catch(() => {})
840
+ : send(chatId, out, threadId)),
841
+ stopTurn: (k) => {
842
+ const child = activeTurns.get(k);
843
+ if (!child) return false;
844
+ try {
845
+ child.kill();
846
+ activeTurns.delete(k);
847
+ return true;
848
+ } catch {
849
+ return false;
850
+ }
851
+ },
852
+ });
853
+ if (!handled) await send(chatId, t(lang, 'bridge.cb.unknown'), threadId);
854
+ }
855
+
793
856
  async function send(chatId, text, threadId = 0, replyTo = 0) {
794
857
  // Who is reading: the topic's language decides even the fallback line, so an
795
858
  // English or Chinese topic never sees a Russian placeholder.
@@ -2090,6 +2153,8 @@ const lastPrompt = new Map();
2090
2153
 
2091
2154
  /** Pending approval requests: id -> { key, chatId, threadId, resolve, timer. */
2092
2155
  const approvals = new Map();
2156
+ // A rewind card is used once - a fast double tap must not cut twice.
2157
+ const rewindUsed = new Set();
2093
2158
  let approvalSeq = 0;
2094
2159
 
2095
2160
  function errorKeyboard(key, lang = 'ru') {
@@ -2196,6 +2261,76 @@ async function handleCallback(query) {
2196
2261
  return;
2197
2262
  }
2198
2263
 
2264
+ if (isRewindPress(data)) {
2265
+ // A rewind button. What it acts on is read here, not taken from the card:
2266
+ // between drawing "go back 2" and the press, the session may have moved on,
2267
+ // and the answer says so instead of cutting the wrong turns.
2268
+ const sessionId = state.sessions[key] || '';
2269
+ const sessionPath = sessionId ? sessionFile(join(DSH_HOME, 'sessions'), sessionId) : '';
2270
+ const line = answerRewindPress(data, {
2271
+ used: rewindUsed,
2272
+ lang,
2273
+ t,
2274
+ ctx: {
2275
+ sessionId,
2276
+ busy: activeTurns.has(key),
2277
+ file: sessionPath,
2278
+ cut: (steps) => cutSession(sessionPath, steps, applyRewind),
2279
+ undo: () => {
2280
+ const backup = newestBackup(sessionPath);
2281
+ if (!backup) return { error: 'nothing' };
2282
+ try {
2283
+ restoreBackup(backup, sessionPath);
2284
+ return { backup };
2285
+ } catch (error) {
2286
+ return { error: error.message };
2287
+ }
2288
+ },
2289
+ },
2290
+ });
2291
+ // The card becomes the one line answering the press, and keeps no buttons.
2292
+ await tg('editMessageText', {
2293
+ chat_id: chatId,
2294
+ message_id: messageId,
2295
+ text: line,
2296
+ reply_markup: { inline_keyboard: [] },
2297
+ ...(threadId > 0 ? { message_thread_id: threadId } : {}),
2298
+ }).catch(() => {});
2299
+ await answer(t(lang, 'bridge.cb.done'));
2300
+ log(`rewind press ${data} for ${key}`);
2301
+ return;
2302
+ }
2303
+
2304
+ if (isMenuPress(data)) {
2305
+ // The panel. A press is exactly a typed command, so it goes through the same
2306
+ // `handleControl`; the card is replaced by whatever that command answers, and
2307
+ // if it draws a card of its own (settings, rewind) this one is simply gone.
2308
+ // `mn:g:<group>` switches tabs in place — that is the only press that does
2309
+ // not run a command.
2310
+ const [verb, name] = data.slice(MENU_PREFIX.length).split(':');
2311
+ if (verb === 'g') {
2312
+ const card = renderPanel({ t: (k, v) => t(lang, k, v), page: name });
2313
+ if (card) {
2314
+ await tg('editMessageText', {
2315
+ chat_id: chatId,
2316
+ message_id: messageId,
2317
+ text: card.text,
2318
+ reply_markup: { inline_keyboard: card.keyboard },
2319
+ ...(threadId > 0 ? { message_thread_id: threadId } : {}),
2320
+ }).catch(() => {});
2321
+ await answer(t(lang, 'bridge.cb.done'));
2322
+ return;
2323
+ }
2324
+ }
2325
+ await clearKeyboard();
2326
+ const typed = commandForName(name, { t: (k, v) => t(lang, k, v) });
2327
+ await answer(typed || t(lang, 'bridge.cb.unknown'));
2328
+ if (!typed) return;
2329
+ log(`menu press /${name} for ${key}`);
2330
+ await runCommandFromButton(typed, { chatId, threadId, key, lang });
2331
+ return;
2332
+ }
2333
+
2199
2334
  if (data === 'stop') {
2200
2335
  const killed = killTurn(key);
2201
2336
  await clearKeyboard();
package/control.mjs CHANGED
@@ -17,6 +17,11 @@ import { setRowConfig, unsetRowConfig } from './profile-edit.mjs';
17
17
  import { parseReminder, stampAt, upcoming } from './reminders.mjs';
18
18
  import { AgentsetStore, emptySet, slugId } from './agentsets.mjs';
19
19
  import { SETTINGS_PAGES, renderSettingsCard, settingsCurrent } from './settings-card.mjs';
20
+ import { planRewind } from './rewind.mjs';
21
+ import { cutSession, isRewindPress } from './rewind-buttons.mjs';
22
+ import { renderRewindCard, renderRewindUsage } from './rewind-card.mjs';
23
+ import { MENU_GROUPS, commandForName, renderPanel } from './menu-card.mjs';
24
+ import { explainCommand } from './help-explain.mjs';
20
25
  import { profileValues, resolveSettings } from './settings.mjs';
21
26
  import { UPDATE_DEFAULTS, describeUpdate, modeChange, updateState } from './update-policy.mjs';
22
27
 
@@ -668,7 +673,8 @@ export const CONTROL_COMMANDS = [
668
673
  'jobs', 'remind', 'sessions', 'resume', 'plugins', 'plugin',
669
674
  'skills', 'soul', 'restart', 'app', 'stop', 'new', 'seed', 'send', 'cd',
670
675
  'prices', 'help', 'doctor', 'logs', 'lang', 'reasoning', 'goal', 'task', 'tasks',
671
- 'thoughts', 'version', 'update', 'agentset', 'subscribe',
676
+ 'thoughts', 'version', 'update', 'agentset', 'subscribe', 'settings',
677
+ 'rewind', 'menu',
672
678
  ];
673
679
 
674
680
  /**
@@ -1714,6 +1720,55 @@ export async function handleControl(ctx) {
1714
1720
  return true;
1715
1721
  }
1716
1722
 
1723
+ case '/menu': {
1724
+ // The panel: a few buttons, one per job, and each of them runs the command
1725
+ // a person would otherwise have to spell. It replaces itself on a press,
1726
+ // which is why nothing here tries to stay in the chat.
1727
+ const page = String(arg || '').trim().toLowerCase();
1728
+ const card = renderPanel({ t: (k, vars) => t(lang, k, vars), page: MENU_GROUPS.includes(page) ? page : MENU_GROUPS[0] });
1729
+ await reply(card.text, { keyboard: card.keyboard });
1730
+ return true;
1731
+ }
1732
+
1733
+ case '/rewind': {
1734
+ // Going back the way the desktop app's branch-from-here does. The file is
1735
+ // cut only where a turn begins, a copy of it is kept, and a turn that is
1736
+ // still running refuses the whole thing: a session being written is the
1737
+ // one file this must never touch.
1738
+ const sessionId = state.sessions[key] || '';
1739
+ if (!sessionId) { say(t(lang, 'ctrl.rewind.noSession')); return true; }
1740
+ const file = sessionFile(join(DSH_HOME, 'sessions'), sessionId);
1741
+ const wanted = String(arg || '').trim().toLowerCase();
1742
+ if (ctx.activeTurns && ctx.activeTurns.has(key)) { say(t(lang, 'ctrl.rewind.busy')); return true; }
1743
+
1744
+ // Undo is its own verb: it restores the newest backup and says so.
1745
+ if (wanted === 'undo' || wanted === 'назад' || wanted === 'отмена') {
1746
+ const done = ctx.undoRewind ? ctx.undoRewind(file) : { error: 'no undo here' };
1747
+ if (done.error === 'nothing') { say(t(lang, 'ctrl.rewind.nothing')); return true; }
1748
+ say(done.error ? t(lang, 'ctrl.rewind.failed', { error: done.error }) : t(lang, 'ctrl.rewind.undone'));
1749
+ return true;
1750
+ }
1751
+
1752
+ const steps = Number.parseInt(wanted, 10);
1753
+ if (!wanted || !Number.isInteger(steps) || steps < 1) {
1754
+ const card = renderRewindUsage({ t: (k, vars) => t(lang, k, vars), file, sessionId });
1755
+ await reply(card.text, card.keyboard.length ? { keyboard: card.keyboard } : undefined);
1756
+ return true;
1757
+ }
1758
+
1759
+ // Say the number twice: the card already asks "back 2?" and this is the
1760
+ // proof that two is what will be cut.
1761
+ const plan = planRewind(file, steps);
1762
+ if (plan.reason) {
1763
+ const key2 = plan.reason === 'too-many-steps' ? 'ctrl.rewind.refused.too-many-steps' : `ctrl.rewind.refused.${plan.reason}`;
1764
+ say(t(lang, key2, { total: plan.total, dropped: steps }));
1765
+ return true;
1766
+ }
1767
+ const card = renderRewindCard({ t: (k, vars) => t(lang, k, vars), file, sessionId, steps, lang });
1768
+ await reply(card.text, { keyboard: card.keyboard });
1769
+ return true;
1770
+ }
1771
+
1717
1772
  case '/new': {
1718
1773
  delete state.sessions[key];
1719
1774
  ctx.saveState();
@@ -1781,6 +1836,19 @@ export async function handleControl(ctx) {
1781
1836
  // One translated body keeps the help in step with the menu; the Russian
1782
1837
  // text stays as the fallback when a key is missing.
1783
1838
  const helpLang = normalizeLang(state.lang?.[key] || config.lang) || 'ru';
1839
+ // `/help <command>` answers about one command: the list alone forced a
1840
+ // reader to guess which of /task and /tasks they wanted, and the pairs
1841
+ // that look alike are exactly the ones worth a sentence each.
1842
+ const about = String(arg || '').trim().toLowerCase().replace(/^\//, '');
1843
+ if (about) {
1844
+ const lines = explainCommand(about, helpLang, t);
1845
+ if (lines) {
1846
+ say(lines);
1847
+ return true;
1848
+ }
1849
+ say(t(helpLang, 'ctrl.help.unknown', { name: about }));
1850
+ return true;
1851
+ }
1784
1852
  say(t(helpLang, 'help.body'));
1785
1853
  return true;
1786
1854
  }
@@ -0,0 +1,36 @@
1
+ // Which commands need a sentence each, and which only need their line from
2
+ // /help. The pairs are the whole reason this exists: /task and /tasks, /model
3
+ // and /models, /plugin and /plugins are one letter apart and do different jobs,
4
+ // so a lookup must say which is which before it says anything else.
5
+ import { CONTROL_COMMANDS } from './control.mjs';
6
+ import { t } from './i18n.mjs';
7
+
8
+ /** The /help group each command is listed under. */
9
+ const SECTION = {
10
+ cd: 'Work', new: 'Work', stop: 'Work', send: 'Work', seed: 'Work',
11
+ goal: 'Goals', task: 'Goals', tasks: 'Goals',
12
+ status: 'Sessions', sessions: 'Sessions', resume: 'Sessions', rewind: 'Sessions', profile: 'Sessions',
13
+ agents: 'Agents', model: 'Models', models: 'Models', prices: 'Models', thoughts: 'Models',
14
+ effort: 'Tuning', permissions: 'Tuning', preset: 'Tuning', agentset: 'Tuning', plan: 'Tuning', jobs: 'Tuning', remind: 'Tuning',
15
+ skills: 'Extensions', plugins: 'Extensions', plugin: 'Extensions', soul: 'Extensions',
16
+ version: 'Versions', update: 'Versions', subscribe: 'Versions',
17
+ settings: 'Other', lang: 'Other', reasoning: 'Other', doctor: 'Other', logs: 'Other',
18
+ app: 'Other', restart: 'Other', help: 'Other', menu: 'Panels',
19
+ };
20
+
21
+ /**
22
+ * The explanation for one command, or '' when there is no such command.
23
+ * A command with a sentence of its own gets it; the rest get the line from
24
+ * /help that lists them, so a reader still sees the command in context.
25
+ */
26
+ export function explainCommand(name, lang, t) {
27
+ const clean = String(name || '').trim().toLowerCase().replace(/^\//, '');
28
+ if (!CONTROL_COMMANDS.includes(clean)) return '';
29
+ const about = t(lang, `ctrl.help.about.${clean}`);
30
+ if (about && !about.startsWith('ctrl.help.about.')) return about;
31
+ const body = String(t(lang, 'help.body'));
32
+ const want = SECTION[clean];
33
+ const line = want ? (body.split('\n').find((row) => row.startsWith(`${want}:`)) || '') : '';
34
+ const head = t(lang, 'ctrl.help.versus', { name: clean });
35
+ return line ? `${head}\n\n${line}` : head;
36
+ }