dsh-tg-bridge 1.48.0 → 1.49.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.
@@ -0,0 +1,47 @@
1
+ // The 🌿 picker's router half. Kept out of the callback router because the
2
+ // router sits at the size ceiling, and because the picker is one idea: a
3
+ // press names a turn, the plan is rebuilt from the live session, and the
4
+ // action types the very command that does the work — `/fork` and
5
+ // `/branch new` stay the only implementations of a branch.
6
+ import { answerBranchPress, isBranchPress } from '../work/branch-buttons.mjs';
7
+ import { t } from '../core/i18n.mjs';
8
+ import { DSH_HOME } from '../core/paths.mjs';
9
+ import { state } from '../core/state.mjs';
10
+ import { tg } from './telegram.mjs';
11
+ import { sessionFile } from './thoughts.mjs';
12
+ import { activeTurns } from '../turn/turn.mjs';
13
+ import { join } from 'node:path';
14
+
15
+ /**
16
+ * Handle one `bf:` press.
17
+ *
18
+ * @returns {Promise<boolean>} true when the press was this module's to answer.
19
+ */
20
+ export async function handleBranchPress({ data, key, lang, chatId, threadId, messageId, answer, clearKeyboard, runCommandFromButton, log }) {
21
+ if (!isBranchPress(data)) return false;
22
+ const sessionId = state.sessions[key] || '';
23
+ const sessionPath = sessionId ? sessionFile(join(DSH_HOME, 'sessions'), sessionId) : '';
24
+ const done = answerBranchPress(data, {
25
+ t: (k, vars) => t(lang, k, vars),
26
+ ctx: { sessionId, busy: activeTurns.has(key), file: sessionPath },
27
+ });
28
+ if (done.command) {
29
+ await clearKeyboard();
30
+ await answer(t(lang, 'bridge.cb.done'));
31
+ await runCommandFromButton(done.command, { chatId, threadId, key, lang });
32
+ } else {
33
+ // Either a confirm card replaces the picker, or one line replaces it —
34
+ // a refused press leaves nothing clickable behind.
35
+ const card = done.card || { text: done.line, keyboard: [] };
36
+ await tg('editMessageText', {
37
+ chat_id: chatId,
38
+ message_id: messageId,
39
+ text: card.text,
40
+ reply_markup: { inline_keyboard: card.keyboard },
41
+ ...(threadId > 0 ? { message_thread_id: threadId } : {}),
42
+ }).catch(() => {});
43
+ await answer(t(lang, 'bridge.cb.done'));
44
+ }
45
+ log(`branch press ${data} for ${key}`);
46
+ return true;
47
+ }
@@ -11,6 +11,7 @@ import { sessionKey } from '../core/keys.mjs';
11
11
  import { commandForName, isMenuPress, menuTarget, renderPanel, runsUnasked } from './menu-card.mjs';
12
12
  import { DSH_HOME, LOG } from '../core/paths.mjs';
13
13
  import { approvals, enqueue, lastPrompt, redeliver, rewindUsed } from '../turn/queue.mjs';
14
+ import { handleBranchPress } from './branch-press.mjs';
14
15
  import { answerRewindPress, cutSession, isRewindPress } from '../work/rewind-buttons.mjs';
15
16
  import { applyRewind, newestBackup, restoreBackup } from '../work/rewind.mjs';
16
17
  import { diffPressRouter } from '../control/cmd-diff.mjs';
@@ -177,6 +178,8 @@ export async function handleCallback(query) {
177
178
  return;
178
179
  }
179
180
 
181
+ if (await handleBranchPress({ data, key, lang, chatId, threadId, messageId, answer, clearKeyboard, runCommandFromButton, log })) return;
182
+
180
183
  // A search result's plus button. The name came from the registry and the
181
184
  // command is the one the hint under the list names, so a tap installs exactly
182
185
  // what was read — no hidden second path into pnpm.
@@ -211,11 +211,14 @@ export async function handleSessionCommands(ctx) {
211
211
  if (!source) { say(t(lang, 'ctrl.fork.noSession')); return true; }
212
212
  if (target.kind === 'topic' && !ctx.openTopic) { say(t(lang, 'ctrl.branch.unsupported')); return true; }
213
213
  const file = sessionFile(join(DSH_HOME, 'sessions'), source);
214
- const plan = planFork(file, 0);
214
+ // `steps` is 0 for every form but `new <n>`: a branch into another topic
215
+ // copies the whole session unless the person named a turn to branch from.
216
+ const steps = target.steps || 0;
217
+ const plan = planFork(file, steps);
215
218
  if (plan.reason) {
216
219
  // The same refusals as a cut: a session being written is the one file this
217
220
  // must never copy, and the reason is the same sentence.
218
- say(t(lang, `ctrl.rewind.refused.${plan.reason}`, { total: plan.total, dropped: 0 }));
221
+ say(t(lang, `ctrl.rewind.refused.${plan.reason}`, { total: plan.total, dropped: steps }));
219
222
  return true;
220
223
  }
221
224
  let made;
package/docs/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # CHANGELOG — DSH Telegram bridge
2
2
 
3
+ ## 1.49.0
4
+
5
+ - **Branching from any turn, as a tap instead of a count.** The `/rewind`
6
+ card's buttons now carry a second row: 🌿 with a turn number for each of the
7
+ recent turns. One tap rewrites the card into a confirm — "branch from turn
8
+ N, the copy keeps the first N turns, the original stays whole" — with two
9
+ destinations: in this topic, or in a new topic of its own. The buttons
10
+ carry turn numbers, not steps, so a press stays honest however many turns
11
+ arrived since the card was drawn; the plan is rebuilt from the file at
12
+ press time, and a session that is being written, rewound or switched away
13
+ is refused with the same sentences a typed command gets. The actions
14
+ themselves type `/fork` and `/branch new` — the commands stay the only
15
+ implementations of a branch, and the buttons can never disagree with them.
16
+ `/branch new <n>` accepts the turn count in typed form too. Three locales,
17
+ 5 tests.
18
+
3
19
  ## 1.48.0
4
20
 
5
21
  - **`/remember` — long-term memory the person can read whole, kept in the one
package/docs/COMMANDS.md CHANGED
@@ -33,7 +33,7 @@ Built from the same code as `/help`: the list, the sections and the sentences ar
33
33
  - `/status` — Where this topic stands: session, model, effort, running turns. Read-only.
34
34
  - `/sessions` — The sessions of this topic. /sessions lists the last few with the id to copy; /sessions <id> continues an older one here. /new starts a fresh one and leaves the old on disk.
35
35
  - `/rewind` — Going back, one command with three words. /rewind 2 removes the last two turns so you can word the task differently: it shows a card of what will go and cuts only on the button; /rewind undo puts it back. /rewind fork [n] is a branch inside this topic: it copies the session as it stood n turns back and moves this topic onto the copy, cutting nothing. /rewind branches lists the copies, a press switches. A branch into another topic is /branch.
36
- - `/branch` — A branch into another topic, in two forms. /branch <id> brings a copy of that session here: this topic continues it, the original stays whole. /branch new carries a copy of this session into a new topic and leaves this one as it was. A copy inside this topic is /rewind fork. A branch is a snapshot of the conversation: from there the two live on their own.
36
+ - `/branch` — A branch into another topic, in two forms. /branch <id> brings a copy of that session here: this topic continues it, the original stays whole. /branch new [n] carries a copy of this session into a new topic — the whole thing, or from n turns back. The 🌿 buttons on the /rewind card offer the same for recent turns. A copy inside this topic is /rewind fork. A branch is a snapshot of the conversation: from there the two live on their own.
37
37
  - `/history` — Exports this topic’s whole history as one markdown file: turns and answers in order, no tool noise. Easy to read and keep on a phone.
38
38
  - `/profile` — The profile this topic runs on, and how to change it: /profile <name>, /profile new.
39
39
  - `/compact` — Where context compaction happens, the threshold this install runs with, and the one thing that works here instead: /new.
@@ -136,7 +136,7 @@ Inline: type @bot rew in any chat to see the commands that start with rew. Switc
136
136
  - `/status` — Где тема сейчас: сессия, модель, усилие, идущие ходы. Ничего не меняет.
137
137
  - `/sessions` — Сессии этой темы. /sessions показывает последние и id, который можно скопировать; /sessions <id> продолжает старую сессию здесь же. /new начинает новую, старая остаётся на диске.
138
138
  - `/rewind` — Откат — одна команда с тремя словами. /rewind 2 убирает два последних хода, чтобы сформулировать иначе: сначала карточка того, что уйдёт, режет только кнопка; /rewind undo возвращает. /rewind fork [n] — ветка внутри темы: копирует сессию в том виде, каким она была n ходов назад, и переводит тему на копию, ничего не отрезая. /rewind branches показывает копии, нажатие переключает. Ветка в другую тему — это /branch.
139
- - `/branch` — Ветка в другую тему — две формы. /branch <id> приносит копию той сессии сюда: эта тема продолжит её, исходная остаётся цела. /branch new уносит копию этой сессии в новую тему и оставляет эту как была. Копия внутри этой темы — /rewind fork. Ветка — снимок разговора: дальше обе живут сами.
139
+ - `/branch` — Ветка в другую тему — две формы. /branch <id> приносит копию той сессии сюда: эта тема продолжит её, исходная остаётся цела. /branch new [n] уносит копию этой сессии в новую тему — целиком или от n ходов назад. Кнопки 🌿 в карточке /rewind предлагают то же для последних ходов. Копия внутри этой темы — /rewind fork. Ветка — снимок разговора: дальше обе живут сами.
140
140
  - `/history` — Выгружает всю историю темы одним markdown-файлом: ходы и ответы по порядку, без шума инструментов. Удобно читать и хранить на телефоне.
141
141
  - `/profile` — Профиль, на котором идёт тема, и как его сменить: /profile <имя>, /profile new.
142
142
  - `/compact` — Где происходит сжатие контекста, с каким порогом работает эта установка и что здесь работает вместо него: /new.
@@ -239,7 +239,7 @@ Inline: type @bot rew in any chat to see the commands that start with rew. Switc
239
239
  - `/status` — 本话题的状态:会话、模型、力度、进行中的轮次。不改变任何东西。
240
240
  - `/sessions` — 本话题的会话。/sessions 列出最近几个和可复制的编号;/sessions <id> 就在这里继续较早的会话。/new 开始新的,旧的留在磁盘上。
241
241
  - `/rewind` — 回退只有一条命令、三种说法。/rewind 2 去掉最后两轮以便换种说法:先显示将移除内容的卡片,只有按按钮才裁切;/rewind undo 可恢复。/rewind fork [n] 是话题内部的分支:把会话复制成 n 轮前的样子并把本话题切到副本,不切断任何东西。/rewind branches 列出副本,按一下就切换。分支到另一个话题用 /branch。
242
- - `/branch` — 分支到另一个话题,两种形式。/branch <id> 把那个会话的副本带到这里:本话题接着它走,原会话完好。/branch new 把本会话的副本带到一个新话题,本话题保持原样。在本话题内部复制用 /rewind fork。分支是对话的快照:之后两者各自独立。
242
+ - `/branch` — 分支到另一个话题,两种形式。/branch <id> 把那个会话的副本带到这里:本话题接着它走,原会话完好。/branch new [n] 把本会话的副本带到一个新话题——整段,或从 n 轮之前。/rewind 卡片上的 🌿 按钮对最近的轮提供同样的操作。在本话题内部复制用 /rewind fork。分支是对话的快照:之后两者各自独立。
243
243
  - `/history` — 将本话题的全部历史导出为一个 markdown 文件:按顺序排列的回合与回答,不含工具噪音。适合在手机上阅读和保存。
244
244
  - `/profile` — 本话题使用的配置档,以及如何更换:/profile <名称>、/profile new。
245
245
  - `/compact` — 上下文压缩发生在哪里、本机用的阈值是多少,以及在这里真正有效的那件事:/new。
@@ -4,8 +4,11 @@
4
4
  // feature, one file, one diff. It also keeps `ctrl.mjs` under the 500-line
5
5
  // ceiling, which that table was sitting on.
6
6
  export default {
7
- 'ctrl.help.about.branch': "A branch into another topic, in two forms. /branch <id> brings a copy of that session here: this topic continues it, the original stays whole. /branch new carries a copy of this session into a new topic and leaves this one as it was. A copy inside this topic is /rewind fork. A branch is a snapshot of the conversation: from there the two live on their own.",
8
- 'ctrl.branch.usage': "A branch has two forms. /branch <id> — a copy of that session here, this topic continues it. /branch new — a copy of this session in a new topic. A copy inside this topic is /rewind fork.",
7
+ 'ctrl.help.about.branch': "A branch into another topic, in two forms. /branch <id> brings a copy of that session here: this topic continues it, the original stays whole. /branch new [n] carries a copy of this session into a new topic — the whole thing, or from n turns back. The 🌿 buttons on the /rewind card offer the same for recent turns. A copy inside this topic is /rewind fork. A branch is a snapshot of the conversation: from there the two live on their own.",
8
+ 'ctrl.branch.usage': "A branch has two forms. /branch <id> — a copy of that session here, this topic continues it. /branch new [n] — a copy of this session in a new topic, from n turns back (without a number, the whole thing). A copy inside this topic is /rewind fork.",
9
+ 'ctrl.branch.confirm': "Branch from turn {turn}: the copy keeps the first {kept} turn(s); the original session stays whole. Where should the copy go?",
10
+ 'ctrl.branch.here': "In this topic",
11
+ 'ctrl.branch.new': "New topic",
9
12
  'ctrl.branch.hereDone': "Branched: this topic now continues {id}, keeping {kept} turn(s). The original session is untouched.",
10
13
  'ctrl.branch.topicDone': "Opened the topic \"{name}\" with a copy of this session ({id}), {kept} turn(s). This topic is untouched.",
11
14
  'ctrl.branch.topicFailed': "Could not open the topic — no topic permission, or a Telegram limit. The copy was removed; nothing changed.",
@@ -4,8 +4,11 @@
4
4
  // feature, one file, one diff. It also keeps `ctrl.mjs` under the 500-line
5
5
  // ceiling, which that table was sitting on.
6
6
  export default {
7
- 'ctrl.help.about.branch': "Ветка в другую тему — две формы. /branch <id> приносит копию той сессии сюда: эта тема продолжит её, исходная остаётся цела. /branch new уносит копию этой сессии в новую тему и оставляет эту как была. Копия внутри этой темы — /rewind fork. Ветка — снимок разговора: дальше обе живут сами.",
8
- 'ctrl.branch.usage': "Ветка — две формы. /branch <id> — копия той сессии сюда, эта тема продолжит её. /branch new — копия этой сессии в новую тему. Копия внутри этой темы — /rewind fork.",
7
+ 'ctrl.help.about.branch': "Ветка в другую тему — две формы. /branch <id> приносит копию той сессии сюда: эта тема продолжит её, исходная остаётся цела. /branch new [n] уносит копию этой сессии в новую тему — целиком или от n ходов назад. Кнопки 🌿 в карточке /rewind предлагают то же для последних ходов. Копия внутри этой темы — /rewind fork. Ветка — снимок разговора: дальше обе живут сами.",
8
+ 'ctrl.branch.usage': "Ветка — две формы. /branch <id> — копия той сессии сюда, эта тема продолжит её. /branch new [n] — копия этой сессии в новую тему, от n ходов назад (без числа — целиком). Копия внутри этой темы — /rewind fork.",
9
+ 'ctrl.branch.confirm': "Ветка от хода {turn}: в копии первые {kept} ход(ов), исходная сессия останется целой. Куда унести копию?",
10
+ 'ctrl.branch.here': "В эту тему",
11
+ 'ctrl.branch.new': "В новую тему",
9
12
  'ctrl.branch.hereDone': "Ветка создана: тема продолжает {id}, сохранено {kept} ход(ов). Исходная сессия цела.",
10
13
  'ctrl.branch.topicDone': "Открыл тему «{name}» — там копия этой сессии ({id}), {kept} ход(ов). Эта тема не тронута.",
11
14
  'ctrl.branch.topicFailed': "Тему открыть не вышло — нет прав на темы или лимит Telegram. Копию убрал, ничего не изменилось.",
@@ -4,8 +4,11 @@
4
4
  // feature, one file, one diff. It also keeps `ctrl.mjs` under the 500-line
5
5
  // ceiling, which that table was sitting on.
6
6
  export default {
7
- 'ctrl.help.about.branch': "分支到另一个话题,两种形式。/branch <id> 把那个会话的副本带到这里:本话题接着它走,原会话完好。/branch new 把本会话的副本带到一个新话题,本话题保持原样。在本话题内部复制用 /rewind fork。分支是对话的快照:之后两者各自独立。",
8
- 'ctrl.branch.usage': "分支有两种形式。/branch <id> —— 把那个会话的副本带到这里,本话题接着它走。/branch new —— 把本会话的副本放到一个新话题。在本话题内部复制用 /rewind fork。",
7
+ 'ctrl.help.about.branch': "分支到另一个话题,两种形式。/branch <id> 把那个会话的副本带到这里:本话题接着它走,原会话完好。/branch new [n] 把本会话的副本带到一个新话题——整段,或从 n 轮之前。/rewind 卡片上的 🌿 按钮对最近的轮提供同样的操作。在本话题内部复制用 /rewind fork。分支是对话的快照:之后两者各自独立。",
8
+ 'ctrl.branch.usage': "分支有两种形式。/branch <id> —— 把那个会话的副本带到这里,本话题接着它走。/branch new [n] —— 把本会话的副本放到一个新话题,从 n 轮之前(不带数字则整段)。在本话题内部复制用 /rewind fork。",
9
+ 'ctrl.branch.confirm': "从第 {turn} 轮分支:副本保留前 {kept} 轮,原会话保持完好。副本放到哪里?",
10
+ 'ctrl.branch.here': "在本话题",
11
+ 'ctrl.branch.new': "新话题",
9
12
  'ctrl.branch.hereDone': "分支已建立:本话题继续 {id},保留 {kept} 轮。原会话完好。",
10
13
  'ctrl.branch.topicDone': "已打开话题「{name}」,其中是本会话的副本({id}),{kept} 轮。本话题未改动。",
11
14
  'ctrl.branch.topicFailed': "无法打开话题——没有话题权限,或 Telegram 限制。副本已删除,什么都没变。",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-tg-bridge",
3
- "version": "1.48.0",
3
+ "version": "1.49.0",
4
4
  "description": "Drive DeepSeek Harness from Telegram: one project, model and session per forum topic",
5
5
  "type": "module",
6
6
  "main": "plugin-bridge.mjs",
@@ -0,0 +1,65 @@
1
+ // The 🌿 picker on the rewind card: "branch from this turn" as a tap instead
2
+ // of a counted `/rewind fork`. A press never trusts the card it was drawn on —
3
+ // the session may have moved on — so the plan is rebuilt from the file at
4
+ // press time and the turn number in the callback becomes steps against the
5
+ // live total.
6
+ //
7
+ // The actions themselves do not fork from here: they type `/fork` and
8
+ // `/branch new`, so the buttons and the commands can never disagree about
9
+ // what a branch is.
10
+ import { planFork } from './rewind.mjs';
11
+
12
+ /** Callback data a 🌿 button carries: `bf:<verb>:<turn>:<last 8 of session>`. */
13
+ const BRANCH_CALLBACK = /^bf:([khnx]):(\d{1,6}):([0-9a-f]{8})$/;
14
+
15
+ export function isBranchPress(data) {
16
+ return String(data || '').startsWith('bf:');
17
+ }
18
+
19
+ /**
20
+ * What one 🌿 press means right now.
21
+ *
22
+ * `{ card }` — redraw the message into a confirm card. `{ command }` — the
23
+ * command the handler should run as if typed. `{ line }` — show this instead
24
+ * (refusal, stale button, cancel); nothing happened.
25
+ */
26
+ export function answerBranchPress(data, { t, ctx }) {
27
+ // Same rule as the rewind buttons: a caller's binding mistake must stay a
28
+ // visible key, never the word "undefined" in a chat.
29
+ const say = (k, vars) => {
30
+ const line = t(k, vars);
31
+ return typeof line === 'string' && line && line !== 'undefined' ? line : k;
32
+ };
33
+ const match = BRANCH_CALLBACK.exec(String(data || ''));
34
+ if (!match) return { line: say('ctrl.rewind.stale') };
35
+ const [, verb, rawTurn, tail] = match;
36
+ const turn = Number.parseInt(rawTurn, 10);
37
+ if (!ctx.sessionId || !ctx.sessionId.endsWith(tail)) return { line: say('ctrl.rewind.stale') };
38
+ if (ctx.busy) return { line: say('ctrl.rewind.busy') };
39
+ if (verb === 'x') return { line: say('ctrl.rewind.cancelled') };
40
+ // Turn numbers, not steps, ride in the callback: "branch from turn 42" must
41
+ // mean 42 however many turns arrived since the card was drawn.
42
+ const whole = planFork(ctx.file, 0);
43
+ if (whole.reason) {
44
+ return { line: say(`ctrl.rewind.refused.${whole.reason}`, { total: whole.total, dropped: 0 }) };
45
+ }
46
+ const steps = whole.total - turn;
47
+ // A turn beyond the live total means the session was rewound or switched
48
+ // after the card: the point the button named no longer exists.
49
+ if (steps < 0) return { line: say('ctrl.rewind.stale') };
50
+ if (verb === 'k') {
51
+ return {
52
+ card: {
53
+ text: say('ctrl.branch.confirm', { turn, kept: turn }),
54
+ keyboard: [
55
+ [
56
+ { text: say('ctrl.branch.here'), callback_data: `bf:h:${turn}:${tail}` },
57
+ { text: say('ctrl.branch.new'), callback_data: `bf:n:${turn}:${tail}` },
58
+ ],
59
+ [{ text: say('ctrl.rewind.cancel'), callback_data: `bf:x:${turn}:${tail}` }],
60
+ ],
61
+ },
62
+ };
63
+ }
64
+ return { command: verb === 'h' ? `/fork ${steps}` : `/branch new ${steps}` };
65
+ }
@@ -62,6 +62,14 @@ export function renderRewindUsage({ t: tr, file, sessionId }) {
62
62
  callback_data: `rw:n:${index + 1}:${sessionId.slice(-8)}`,
63
63
  }));
64
64
  rows.push(row);
65
+ // A cut is not the only way off a turn: 🌿 offers a branch from that turn —
66
+ // the same fork `/rewind fork` types, without counting turns by hand. The
67
+ // button carries the turn number (not steps), so it stays honest however
68
+ // many turns arrive before the press.
69
+ rows.push(turns.slice(0, 3).map((turn) => ({
70
+ text: `🌿${turn.turn}`,
71
+ callback_data: `bf:k:${turn.turn}:${sessionId.slice(-8)}`,
72
+ })));
65
73
  }
66
74
  return { text: lines.join('\n'), keyboard: rows };
67
75
  }
package/work/rewind.mjs CHANGED
@@ -227,12 +227,16 @@ export function planFork(file, steps = 0) {
227
227
  * its own". A bare `/branch` explains both instead of guessing — opening a
228
228
  * Telegram topic is a visible side effect, and `/branches` (the list) is one
229
229
  * letter away from the name that would trigger it.
230
- * @returns {{kind: 'usage'|'topic'|'here', id: string}}
230
+ * @returns {{kind: 'usage'|'topic'|'here', id: string, steps?: number}}
231
231
  */
232
232
  export function branchTarget(arg) {
233
233
  const wanted = String(arg || '').trim().toLowerCase();
234
234
  if (!wanted) return { kind: 'usage', id: '' };
235
- if (wanted === 'new' || wanted === 'topic') return { kind: 'topic', id: '' };
235
+ // `new 3` names how far back the copy starts: the same branch the rewind
236
+ // card's 🌿 buttons type, available to fingers as well. No number keeps the
237
+ // whole session, exactly as before.
238
+ const fresh = /^(?:new|topic)(?:\s+(\d+))?$/.exec(wanted);
239
+ if (fresh) return { kind: 'topic', id: '', steps: fresh[1] ? Number.parseInt(fresh[1], 10) : 0 };
236
240
  const bare = wanted.replace(/^session-/, '');
237
241
  if (!/^[0-9a-f][0-9a-f-]{7,}$/.test(bare)) return { kind: 'usage', id: '' };
238
242
  return { kind: 'here', id: `session-${bare}` };