dsh-tg-bridge 1.6.0 → 1.7.1
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 +3 -0
- package/bot-menu.mjs +18 -9
- package/bridge.mjs +40 -1
- package/control.mjs +192 -20
- package/i18n.mjs +102 -3
- package/immediate.mjs +14 -36
- package/package.json +4 -2
- package/sync-runtime.mjs +20 -0
- package/thoughts.mjs +162 -0
package/README.md
CHANGED
|
@@ -163,6 +163,9 @@ Send the bot:
|
|
|
163
163
|
| Command | Expected |
|
|
164
164
|
|---|---|
|
|
165
165
|
| `/doctor` | report: pid, Telegram, disk, directory, session |
|
|
166
|
+
| `/version` | bridge version, the latest on npm, bridge directory |
|
|
167
|
+
| `/update` | says whether a newer release exists (`/update confirm` installs it) |
|
|
168
|
+
| `/thoughts` | the last turn's reasoning, deleted after a few minutes |
|
|
166
169
|
| `/help` | commands grouped by category |
|
|
167
170
|
| `/cd my-app` | topic bound to the project |
|
|
168
171
|
| `/prices` | model prices and the cost of the current one |
|
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,12 +46,15 @@ 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: '
|
|
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' },
|
|
54
54
|
{ command: 'profile', description: 'Профиль темы: /profile <имя>, /profile new' },
|
|
55
|
+
{ command: 'thoughts', description: 'Рассуждения последнего хода (исчезает)' },
|
|
56
|
+
{ command: 'version', description: 'Версия моста и последняя на npm' },
|
|
57
|
+
{ command: 'update', description: 'Обновить мост из npm: /update confirm' },
|
|
55
58
|
];
|
|
56
59
|
|
|
57
60
|
/** English menu (language_code: en). Same commands, translated descriptions. */
|
|
@@ -65,7 +68,7 @@ const COMMANDS_EN = [
|
|
|
65
68
|
{ command: 'seed', description: 'Seed an empty topic with text and pin it' },
|
|
66
69
|
{ command: 'goal', description: 'Topic goal: /goal <text>, /goal done' },
|
|
67
70
|
{ command: 'task', description: 'Checklist: /task <text>, /task done <n>' },
|
|
68
|
-
{ command: 'sessions', description: '
|
|
71
|
+
{ command: 'sessions', description: 'Sessions of this topic — plain text continues the last one' },
|
|
69
72
|
{ command: 'resume', description: 'Continue a session: /resume <id>' },
|
|
70
73
|
{ command: 'model', description: 'Show or switch: /model, /model <id>' },
|
|
71
74
|
{ command: 'skills', description: 'Installed skills' },
|
|
@@ -73,12 +76,15 @@ const COMMANDS_EN = [
|
|
|
73
76
|
{ command: 'plugins', description: 'List and manage: add/remove/disable/enable' },
|
|
74
77
|
{ command: 'app', description: 'DSH desktop app (not the bridge)' },
|
|
75
78
|
{ command: 'restart', description: 'Restart the bridge: /restart confirm' },
|
|
76
|
-
{ command: 'doctor', description: 'Diagnostics: bridge, network, disk,
|
|
77
|
-
{ command: 'logs', description: '
|
|
79
|
+
{ command: 'doctor', description: 'Diagnostics: bridge, network, disk, plugins, session' },
|
|
80
|
+
{ command: 'logs', description: 'Log: /logs, /logs 100, /logs errors, /logs <text>' },
|
|
78
81
|
{ command: 'help', description: 'All commands and hints' },
|
|
79
82
|
{ command: 'lang', description: 'Interface language: en, ru, zh' },
|
|
80
83
|
{ command: 'reasoning', description: 'Working notes: /reasoning on|off' },
|
|
81
84
|
{ command: 'profile', description: 'Topic profile: /profile <name>, /profile new' },
|
|
85
|
+
{ command: 'thoughts', description: 'Reasoning of the last turn (self-deleting)' },
|
|
86
|
+
{ command: 'version', description: 'Bridge version and the latest on npm' },
|
|
87
|
+
{ command: 'update', description: 'Update the bridge from npm: /update confirm' },
|
|
82
88
|
];
|
|
83
89
|
|
|
84
90
|
/** Chinese menu (language_code: zh-hans). */
|
|
@@ -92,7 +98,7 @@ const COMMANDS_ZH = [
|
|
|
92
98
|
{ command: 'seed', description: '用文本初始化空话题并置顶' },
|
|
93
99
|
{ command: 'goal', description: '本话题目标:/goal <文本>、/goal done' },
|
|
94
100
|
{ command: 'task', description: '任务清单:/task <文本>、/task done <n>' },
|
|
95
|
-
{ command: 'sessions', description: '
|
|
101
|
+
{ command: 'sessions', description: '本主题的会话 —— 直接发文字会延续最近一个' },
|
|
96
102
|
{ command: 'resume', description: '继续会话:/resume <id>' },
|
|
97
103
|
{ command: 'model', description: '查看或切换:/model, /model <id>' },
|
|
98
104
|
{ command: 'skills', description: '已安装的技能' },
|
|
@@ -100,12 +106,15 @@ const COMMANDS_ZH = [
|
|
|
100
106
|
{ command: 'plugins', description: '列表与管理:add/remove/disable/enable' },
|
|
101
107
|
{ command: 'app', description: 'DSH 桌面应用(不是桥接)' },
|
|
102
108
|
{ command: 'restart', description: '重启桥接:/restart confirm' },
|
|
103
|
-
{ command: 'doctor', description: '
|
|
104
|
-
{ command: 'logs', description: '
|
|
109
|
+
{ command: 'doctor', description: '诊断:桥接、网络、磁盘、插件、会话' },
|
|
110
|
+
{ command: 'logs', description: '日志:/logs、/logs 100、/logs errors、/logs <文本>' },
|
|
105
111
|
{ command: 'help', description: '全部命令与提示' },
|
|
106
112
|
{ command: 'lang', description: '界面语言:en、ru、zh' },
|
|
107
113
|
{ command: 'reasoning', description: '工作记录:/reasoning on|off' },
|
|
108
114
|
{ command: 'profile', description: '话题配置档:/profile <名称>,/profile new' },
|
|
115
|
+
{ command: 'thoughts', description: '上一轮的推理(稍后自动消失)' },
|
|
116
|
+
{ command: 'version', description: '桥接版本与 npm 上的最新版本' },
|
|
117
|
+
{ command: 'update', description: '从 npm 更新桥接:/update confirm' },
|
|
109
118
|
];
|
|
110
119
|
|
|
111
120
|
async function api(method, body) {
|
package/bridge.mjs
CHANGED
|
@@ -710,6 +710,25 @@ async function send(chatId, text, threadId = 0, replyTo = 0) {
|
|
|
710
710
|
return lastId;
|
|
711
711
|
}
|
|
712
712
|
|
|
713
|
+
/**
|
|
714
|
+
* Send a message that deletes itself after `ttlMs`.
|
|
715
|
+
*
|
|
716
|
+
* Reports read once and forgotten (`/thoughts`, an unknown command showing the
|
|
717
|
+
* menu) should not stay in the scrollback forever. The API cannot edit plain
|
|
718
|
+
* text into a spoiler, so the choice is between two kinds of litter: a long
|
|
719
|
+
* reply or a "gone" tombstone. A tombstone wins.
|
|
720
|
+
*/
|
|
721
|
+
async function sendEphemeral(chatId, text, threadId = 0, replyTo = 0, ttlMs = 180000) {
|
|
722
|
+
const id = await send(chatId, text, threadId, replyTo);
|
|
723
|
+
if (!id) return id;
|
|
724
|
+
const timer = setTimeout(() => {
|
|
725
|
+
tg('deleteMessage', { chat_id: chatId, message_id: id })
|
|
726
|
+
.catch((error) => log(`ephemeral delete failed msg=${id}: ${String(error.message).slice(0, 80)}`));
|
|
727
|
+
}, ttlMs);
|
|
728
|
+
timer.unref?.();
|
|
729
|
+
return id;
|
|
730
|
+
}
|
|
731
|
+
|
|
713
732
|
/** Remember which topics already got their seed message, so it happens once. */
|
|
714
733
|
function topicSeeded(threadId) {
|
|
715
734
|
return Boolean(state.seededTopics?.[String(threadId)]);
|
|
@@ -1336,7 +1355,9 @@ async function handleMessage(msg, album = null) {
|
|
|
1336
1355
|
// answers something the person did not ask. Answer with the menu instead.
|
|
1337
1356
|
if (command && !effective) {
|
|
1338
1357
|
log(`unknown command ${head} from ${from}`);
|
|
1339
|
-
|
|
1358
|
+
// Ephemeral: a mistyped command is usually a typo of a real one, so the menu
|
|
1359
|
+
// appears long enough to pick from it and then clears itself.
|
|
1360
|
+
await sendEphemeral(
|
|
1340
1361
|
chatId,
|
|
1341
1362
|
`${t(lang, 'msg.unknownCommand', { cmd: head })}
|
|
1342
1363
|
|
|
@@ -2090,6 +2111,24 @@ function runTurnLive(task, sessionId, key, options = {}) {
|
|
|
2090
2111
|
|
|
2091
2112
|
async function main() {
|
|
2092
2113
|
log('bridge started');
|
|
2114
|
+
// Downloaded photos live in the runtime directory and every album leaves a
|
|
2115
|
+
// few behind. A week is long enough for "look at that picture again" in a
|
|
2116
|
+
// session, short enough that the directory does not grow without a bound.
|
|
2117
|
+
try {
|
|
2118
|
+
const cutoff = Date.now() - 7 * 24 * 60 * 60 * 1000;
|
|
2119
|
+
let pruned = 0;
|
|
2120
|
+
for (const name of readdirSync(DIR)) {
|
|
2121
|
+
if (!/^photo-\d+-\d+\.jpg$/.test(name)) continue;
|
|
2122
|
+
const path = join(DIR, name);
|
|
2123
|
+
if (statSync(path).mtimeMs < cutoff) {
|
|
2124
|
+
unlinkSync(path);
|
|
2125
|
+
pruned++;
|
|
2126
|
+
}
|
|
2127
|
+
}
|
|
2128
|
+
if (pruned) log(`pruned ${pruned} old photo(s)`);
|
|
2129
|
+
} catch (error) {
|
|
2130
|
+
log(`photo prune failed: ${error.message}`);
|
|
2131
|
+
}
|
|
2093
2132
|
try {
|
|
2094
2133
|
const me = await tg('getMe');
|
|
2095
2134
|
botUsername = me.username || '';
|
package/control.mjs
CHANGED
|
@@ -5,12 +5,13 @@
|
|
|
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, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
|
|
9
|
-
import { homedir } from 'node:os';
|
|
8
|
+
import { existsSync, copyFileSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
9
|
+
import { homedir, tmpdir } from 'node:os';
|
|
10
10
|
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, lastTurnText, sessionFile, sessionStats } from './thoughts.mjs';
|
|
14
15
|
|
|
15
16
|
const HOME = homedir();
|
|
16
17
|
const DSH_HOME = process.env.DSH_HOME || join(HOME, '.dsh');
|
|
@@ -295,9 +296,16 @@ function bareId(id) {
|
|
|
295
296
|
return String(id).replace(/^session-/, '');
|
|
296
297
|
}
|
|
297
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
|
+
|
|
298
307
|
/** Recent DSH sessions of this workspace, newest first, with their titles. */
|
|
299
|
-
function recentSessions(cwd, limit, lang = 'ru') {
|
|
300
|
-
const root = join(DSH_HOME, 'sessions');
|
|
308
|
+
function recentSessions(cwd, limit, lang = 'ru') { const root = join(DSH_HOME, 'sessions');
|
|
301
309
|
const rows = [];
|
|
302
310
|
let dirs = [];
|
|
303
311
|
try {
|
|
@@ -416,6 +424,7 @@ export const CONTROL_COMMANDS = [
|
|
|
416
424
|
'status', 'models', 'model', 'profile', 'sessions', 'resume', 'plugins', 'plugin',
|
|
417
425
|
'skills', 'soul', 'restart', 'app', 'stop', 'new', 'seed', 'send', 'cd',
|
|
418
426
|
'prices', 'help', 'doctor', 'logs', 'lang', 'reasoning', 'goal', 'task',
|
|
427
|
+
'thoughts', 'version', 'update',
|
|
419
428
|
];
|
|
420
429
|
|
|
421
430
|
/**
|
|
@@ -453,21 +462,44 @@ export async function handleControl(ctx) {
|
|
|
453
462
|
switch (effective) {
|
|
454
463
|
case '/status': {
|
|
455
464
|
const head = modelOf(activeProfile);
|
|
456
|
-
const session = state.sessions[key] || t(lang, 'ctrl.session.none');
|
|
457
465
|
const active = ctx.activeTurns ? ctx.activeTurns.size : 0;
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
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 }));
|
|
466
498
|
// The desktop profile only matters when this install actually has one.
|
|
467
499
|
if (existsSync(join(PROFILES, 'desktop', 'cordis.patch.yml'))) {
|
|
468
500
|
const desk = modelOf('desktop');
|
|
469
501
|
const deskPlugins = pluginsOf('desktop');
|
|
470
|
-
lines.
|
|
502
|
+
lines.push(t(lang, 'ctrl.status.ui', {
|
|
471
503
|
route: `${desk.provider}/${desk.model}`,
|
|
472
504
|
n: deskPlugins.bundles.length,
|
|
473
505
|
}));
|
|
@@ -479,6 +511,7 @@ export async function handleControl(ctx) {
|
|
|
479
511
|
done, total, text: currentGoal.text.length > 60 ? `${currentGoal.text.slice(0, 59)}…` : currentGoal.text,
|
|
480
512
|
}));
|
|
481
513
|
}
|
|
514
|
+
lines.push(`DSH_HOME: ${DSH_HOME}`);
|
|
482
515
|
say(lines.join('\n'));
|
|
483
516
|
return true;
|
|
484
517
|
}
|
|
@@ -821,10 +854,14 @@ export async function handleControl(ctx) {
|
|
|
821
854
|
const wanted = (arg || '').trim().replace(/^"|"$/g, '');
|
|
822
855
|
state.cwd = state.cwd || {};
|
|
823
856
|
if (!wanted) {
|
|
824
|
-
|
|
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 || '';
|
|
825
860
|
const lines = [
|
|
826
861
|
t(lang, 'ctrl.cd.current'),
|
|
827
|
-
current
|
|
862
|
+
current
|
|
863
|
+
? `${current}${state.cwd[key] ? '' : t(lang, 'ctrl.cd.defaultSuffix')}`
|
|
864
|
+
: t(lang, 'ctrl.cd.unset'),
|
|
828
865
|
'',
|
|
829
866
|
t(lang, 'ctrl.cd.bind'),
|
|
830
867
|
t(lang, 'ctrl.cd.resetHint'),
|
|
@@ -1070,9 +1107,14 @@ export async function handleControl(ctx) {
|
|
|
1070
1107
|
add(t(lang, 'ctrl.doctor.disk'), t(lang, 'ctrl.doctor.diskFree', { gb: (free / 1024 ** 3).toFixed(1) }));
|
|
1071
1108
|
} catch {}
|
|
1072
1109
|
|
|
1073
|
-
// Project directory bound to this topic and whether it exists.
|
|
1074
|
-
|
|
1075
|
-
|
|
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);
|
|
1076
1118
|
|
|
1077
1119
|
add(t(lang, 'ctrl.doctor.session'), state.sessions[key] || t(lang, 'ctrl.doctor.sessionNew'));
|
|
1078
1120
|
say(`${t(lang, 'ctrl.doctor.title')}\n\n${rows.join('\n')}`);
|
|
@@ -1124,9 +1166,139 @@ export async function handleControl(ctx) {
|
|
|
1124
1166
|
return true;
|
|
1125
1167
|
}
|
|
1126
1168
|
|
|
1169
|
+
case '/thoughts': {
|
|
1170
|
+
// The reasoning of the last turn, pulled from the session log itself. It
|
|
1171
|
+
// is ephemeral: the reply lives a few minutes and then deletes itself, so
|
|
1172
|
+
// a long plan never turns into chat clutter.
|
|
1173
|
+
const sessionId = ctx.state.sessions?.[key];
|
|
1174
|
+
if (!sessionId) {
|
|
1175
|
+
say(t(lang, 'ctrl.thoughts.noSession'));
|
|
1176
|
+
return true;
|
|
1177
|
+
}
|
|
1178
|
+
const file = sessionFile(join(DSH_HOME, 'sessions'), sessionId);
|
|
1179
|
+
const text = file ? lastTurnReasoning(file, { maxChars: 4000 }) : '';
|
|
1180
|
+
if (!text) {
|
|
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'));
|
|
1188
|
+
return true;
|
|
1189
|
+
}
|
|
1190
|
+
say(t(lang, 'ctrl.thoughts.title', { chars: text.length }) + '\n\n' + text);
|
|
1191
|
+
return true;
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
case '/version': {
|
|
1195
|
+
// Which bridge is running, which one npm has, and whether this install can
|
|
1196
|
+
// update itself. A report, so it answers even in the middle of a turn.
|
|
1197
|
+
const installed = bridgeVersion();
|
|
1198
|
+
const latest = npmLatest('dsh-tg-bridge');
|
|
1199
|
+
const where = process.env.DSH_BRIDGE_ROOT || join(DSH_HOME, 'tg-bridge');
|
|
1200
|
+
const lines = [t(lang, 'ctrl.version.title')];
|
|
1201
|
+
lines.push(t(lang, 'ctrl.version.installed', { v: installed || t(lang, 'ctrl.version.unknown') }));
|
|
1202
|
+
lines.push(t(lang, 'ctrl.version.latest', { v: latest || t(lang, 'ctrl.version.offline') }));
|
|
1203
|
+
if (installed && latest && installed !== latest) lines.push(t(lang, 'ctrl.version.update', { v: latest }));
|
|
1204
|
+
lines.push(t(lang, 'ctrl.version.root', { path: where }));
|
|
1205
|
+
lines.push(t(lang, 'ctrl.version.hint'));
|
|
1206
|
+
say(lines.join('\n'));
|
|
1207
|
+
return true;
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
case '/update': {
|
|
1211
|
+
// The person's own copy of the bridge, updated from npm. Nothing is
|
|
1212
|
+
// touched unless the release is newer, and the running process keeps its
|
|
1213
|
+
// old modules until the next `/restart confirm` — so a bad release never
|
|
1214
|
+
// takes the chat down by itself.
|
|
1215
|
+
if (String(arg).trim() === 'confirm') {
|
|
1216
|
+
const installed = bridgeVersion();
|
|
1217
|
+
const latest = npmLatest('dsh-tg-bridge');
|
|
1218
|
+
if (!latest) {
|
|
1219
|
+
say(t(lang, 'ctrl.update.offline'));
|
|
1220
|
+
return true;
|
|
1221
|
+
}
|
|
1222
|
+
if (installed && installed === latest) {
|
|
1223
|
+
say(t(lang, 'ctrl.update.current', { v: installed }));
|
|
1224
|
+
return true;
|
|
1225
|
+
}
|
|
1226
|
+
const root = process.env.DSH_BRIDGE_ROOT || join(DSH_HOME, 'tg-bridge');
|
|
1227
|
+
say(t(lang, 'ctrl.update.running', { v: latest }));
|
|
1228
|
+
// `npm install dsh-tg-bridge@x` inside the bridge's own directory would
|
|
1229
|
+
// drop a nested node_modules/dsh-tg-bridge and leave the running files
|
|
1230
|
+
// alone, so the release is fetched into a temp dir and its files are
|
|
1231
|
+
// copied over the top. Config, state and logs stay untouched.
|
|
1232
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
1233
|
+
const backup = join(root, `update-backup-${stamp}`);
|
|
1234
|
+
const work = join(tmpdir(), `dsh-tg-bridge-${stamp}`);
|
|
1235
|
+
const r = spawnSync(
|
|
1236
|
+
'npm',
|
|
1237
|
+
['install', '--no-save', '--no-audit', '--no-fund', '--prefix', work, `dsh-tg-bridge@${latest}`],
|
|
1238
|
+
{ encoding: 'utf8', shell: true, timeout: 240000, windowsHide: true },
|
|
1239
|
+
);
|
|
1240
|
+
const tail = `${r.stdout || ''}${r.stderr || ''}`.trim().split(/\r?\n/).slice(-6).join('\n');
|
|
1241
|
+
if (r.status !== 0) {
|
|
1242
|
+
say(t(lang, 'ctrl.update.failed', { code: r.status ?? '?' }) + (tail ? `\n\n${tail}` : ''));
|
|
1243
|
+
return true;
|
|
1244
|
+
}
|
|
1245
|
+
try {
|
|
1246
|
+
mkdirSync(backup, { recursive: true });
|
|
1247
|
+
for (const name of readdirSync(join(work, 'package'))) {
|
|
1248
|
+
const from = join(work, 'package', name);
|
|
1249
|
+
const to = join(root, name);
|
|
1250
|
+
if (existsSync(to)) copyFileSync(to, join(backup, name));
|
|
1251
|
+
copyFileSync(from, to);
|
|
1252
|
+
}
|
|
1253
|
+
} catch (error) {
|
|
1254
|
+
say(t(lang, 'ctrl.update.failed', { code: 'copy' }) + `\n\n${error.message}`);
|
|
1255
|
+
return true;
|
|
1256
|
+
} finally {
|
|
1257
|
+
try {
|
|
1258
|
+
rmSync(work, { recursive: true, force: true });
|
|
1259
|
+
} catch {}
|
|
1260
|
+
}
|
|
1261
|
+
say(t(lang, 'ctrl.update.done', { v: latest }));
|
|
1262
|
+
return true;
|
|
1263
|
+
}
|
|
1264
|
+
const installed = bridgeVersion();
|
|
1265
|
+
const latest = npmLatest('dsh-tg-bridge');
|
|
1266
|
+
if (!latest) {
|
|
1267
|
+
say(t(lang, 'ctrl.update.offline'));
|
|
1268
|
+
return true;
|
|
1269
|
+
}
|
|
1270
|
+
if (installed && installed === latest) {
|
|
1271
|
+
say(t(lang, 'ctrl.update.current', { v: installed }));
|
|
1272
|
+
return true;
|
|
1273
|
+
}
|
|
1274
|
+
say(t(lang, 'ctrl.update.available', { from: installed || '?', to: latest }));
|
|
1275
|
+
return true;
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1127
1278
|
default:
|
|
1128
1279
|
return false;
|
|
1129
1280
|
}
|
|
1130
1281
|
}
|
|
1131
1282
|
|
|
1132
|
-
|
|
1283
|
+
/** Version of the bridge this process runs, read from its own package.json. */
|
|
1284
|
+
function bridgeVersion() {
|
|
1285
|
+
const root = process.env.DSH_BRIDGE_ROOT || join(DSH_HOME, 'tg-bridge');
|
|
1286
|
+
try {
|
|
1287
|
+
return JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')).version || '';
|
|
1288
|
+
} catch {
|
|
1289
|
+
return '';
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
|
|
1293
|
+
/** Latest published version of an npm package, or '' when npm is unreachable. */
|
|
1294
|
+
function npmLatest(name) {
|
|
1295
|
+
try {
|
|
1296
|
+
const r = spawnSync('npm', ['view', name, 'version'], { encoding: 'utf8', shell: true, timeout: 45000, windowsHide: true });
|
|
1297
|
+
const out = String(r.stdout || '').trim().split(/\s+/).pop() || '';
|
|
1298
|
+
return r.status === 0 && /^\d/.test(out) ? out : '';
|
|
1299
|
+
} catch {
|
|
1300
|
+
return '';
|
|
1301
|
+
}
|
|
1302
|
+
}
|
|
1303
|
+
|
|
1304
|
+
export { DSH_HOME, modelOf, modelsOf, pluginsOf, recentSessions, skillsOf, soulOf, bridgeVersion, npmLatest };
|
package/i18n.mjs
CHANGED
|
@@ -19,7 +19,7 @@ const DICT = {
|
|
|
19
19
|
'status.failed': 'Turn failed',
|
|
20
20
|
'status.queued': 'queued',
|
|
21
21
|
'status.stop': 'Stop',
|
|
22
|
-
'help.body': "Write the task as plain text. Each forum topic is its own session:\n\nWork: /cd \u003cproject\u003e · /new · /stop · /send \u003cfile\u003e · /seed \u003ctext\u003e\nGoals: /goal · /task\nSessions: /status · /sessions [n] · /resume \u003cid\u003e\nModels: /model · /model \u003cid\u003e · /prices\nExtensions: /skills · /plugins · /plugin add|remove · /soul\nOther: /lang · /reasoning · /doctor · /logs [errors|N] · /app · /restart · /help",
|
|
22
|
+
'help.body': "Write the task as plain text. Each forum topic is its own session:\n\nWork: /cd \u003cproject\u003e · /new · /stop · /send \u003cfile\u003e · /seed \u003ctext\u003e\nGoals: /goal · /task\nSessions: /status · /sessions [n] · /resume \u003cid\u003e\nModels: /model · /model \u003cid\u003e · /prices · /thoughts\nExtensions: /skills · /plugins · /plugin add|remove · /soul\nVersions: /version · /update · /update confirm\nOther: /lang · /reasoning · /doctor · /logs [errors|N] · /app · /restart · /help",
|
|
23
23
|
'btn.stop': 'Stop',
|
|
24
24
|
'btn.logs': 'Logs',
|
|
25
25
|
'btn.retry': 'Retry',
|
|
@@ -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}',
|
|
@@ -116,6 +127,20 @@ const DICT = {
|
|
|
116
127
|
'ctrl.soul.title': 'Persona ({path}):\n\n{text}',
|
|
117
128
|
'ctrl.soul.empty': 'Persona is empty. Set it: /soul <text>\nFile: {path}',
|
|
118
129
|
'ctrl.soul.saved': 'Persona updated in ~/.dsh/AGENTS.md. Applies to new sessions.',
|
|
130
|
+
'ctrl.version.title': 'Versions',
|
|
131
|
+
'ctrl.version.installed': 'Installed here: {v}',
|
|
132
|
+
'ctrl.version.latest': 'Latest on npm: {v}',
|
|
133
|
+
'ctrl.version.unknown': 'unknown',
|
|
134
|
+
'ctrl.version.offline': 'unreachable',
|
|
135
|
+
'ctrl.version.update': 'Update available: /update, then /update confirm',
|
|
136
|
+
'ctrl.version.root': 'Bridge directory: {path}',
|
|
137
|
+
'ctrl.version.hint': 'The new code loads after /restart confirm; the current chat keeps running until then.',
|
|
138
|
+
'ctrl.update.available': 'Version {from} is running, {to} is on npm.\nInstall it: /update confirm.\nEverything keeps working on the old code until /restart confirm.',
|
|
139
|
+
'ctrl.update.current': 'Already on {v} — the latest published version.',
|
|
140
|
+
'ctrl.update.offline': 'npm is unreachable, so no version check is possible. Try again in a minute.',
|
|
141
|
+
'ctrl.update.running': 'Installing {v} into the bridge directory…',
|
|
142
|
+
'ctrl.update.done': 'Installed {v}. Load it: /restart confirm',
|
|
143
|
+
'ctrl.update.failed': 'The install failed (exit {code}). Nothing was changed; the bridge still runs the old code.',
|
|
119
144
|
'ctrl.app.usage': 'Usage: /app restart confirm — restart the DSH app.',
|
|
120
145
|
'ctrl.app.confirm': 'Restarting the app ends this chat. Repeat: /app restart confirm',
|
|
121
146
|
'ctrl.app.notRunning': 'DSH is not running — starting it.',
|
|
@@ -130,6 +155,8 @@ const DICT = {
|
|
|
130
155
|
'ctrl.send.unsupported': 'File sending is unavailable: the bridge is an old version.',
|
|
131
156
|
'ctrl.send.failed': 'Could not send the file: {err}',
|
|
132
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',
|
|
133
160
|
'ctrl.cd.bind': 'Bind: /cd <path>',
|
|
134
161
|
'ctrl.cd.resetHint': 'Reset: /cd reset',
|
|
135
162
|
'ctrl.cd.projects': 'Projects:',
|
|
@@ -159,6 +186,8 @@ const DICT = {
|
|
|
159
186
|
'ctrl.doctor.diskFree': '{gb} GB free',
|
|
160
187
|
'ctrl.doctor.cwd': 'Topic directory',
|
|
161
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',
|
|
162
191
|
'ctrl.doctor.session': 'Session',
|
|
163
192
|
'ctrl.doctor.sessionNew': '(new)',
|
|
164
193
|
'ctrl.logs.unreadable': 'Cannot read the log: {err}',
|
|
@@ -166,6 +195,10 @@ const DICT = {
|
|
|
166
195
|
'ctrl.logs.empty': 'The log is empty.',
|
|
167
196
|
'ctrl.logs.errors': 'Errors ({shown} of {total})',
|
|
168
197
|
'ctrl.logs.title': 'Log ({shown} of {total})',
|
|
198
|
+
'ctrl.thoughts.title': '🧠 Reasoning of the last turn ({chars} chars, kept for a few minutes):',
|
|
199
|
+
'ctrl.thoughts.none': 'The last turn stored no reasoning plan.',
|
|
200
|
+
'ctrl.thoughts.lastAnswer': 'What the last turn answered:',
|
|
201
|
+
'ctrl.thoughts.noSession': 'This topic has no session yet: send a task first.',
|
|
169
202
|
'goal.none': 'No goal in this topic. Set one: /goal <text>',
|
|
170
203
|
'goal.set': 'Goal: {text}',
|
|
171
204
|
'goal.default': 'Tasks',
|
|
@@ -254,7 +287,7 @@ const DICT = {
|
|
|
254
287
|
'status.failed': 'Ход не удался',
|
|
255
288
|
'status.queued': 'в очереди',
|
|
256
289
|
'status.stop': 'Стоп',
|
|
257
|
-
'help.body': "Задачу можно писать обычным текстом. Каждая ветка форума — отдельная сессия:\n\nРабота: /cd \u003cпроект\u003e · /new · /stop · /send \u003cфайл\u003e · /seed \u003cтекст\u003e\nЦели: /goal · /task\nСессии: /status · /sessions [n] · /resume \u003cid\u003e\nМодели: /model · /model \u003cid\u003e · /prices\nРасширения: /skills · /plugins · /plugin add|remove · /soul\nПрочее: /lang · /reasoning · /doctor · /logs [errors|N] · /app · /restart · /help",
|
|
290
|
+
'help.body': "Задачу можно писать обычным текстом. Каждая ветка форума — отдельная сессия:\n\nРабота: /cd \u003cпроект\u003e · /new · /stop · /send \u003cфайл\u003e · /seed \u003cтекст\u003e\nЦели: /goal · /task\nСессии: /status · /sessions [n] · /resume \u003cid\u003e\nМодели: /model · /model \u003cid\u003e · /prices · /thoughts\nРасширения: /skills · /plugins · /plugin add|remove · /soul\nВерсии: /version · /update · /update confirm\nПрочее: /lang · /reasoning · /doctor · /logs [errors|N] · /app · /restart · /help",
|
|
258
291
|
'btn.stop': 'Стоп',
|
|
259
292
|
'btn.logs': 'Логи',
|
|
260
293
|
'btn.retry': 'Повторить',
|
|
@@ -304,11 +337,22 @@ const DICT = {
|
|
|
304
337
|
'cmd.cd.none': 'Нет такого каталога: {path}',
|
|
305
338
|
'cmd.new.done': 'Новая сессия в этой ветке. Контекст очищен.',
|
|
306
339
|
'ctrl.session.none': '(ещё нет)',
|
|
340
|
+
'ctrl.status.head': '📊 Статус моста',
|
|
307
341
|
'ctrl.status.profile': 'Профиль: {name} ({route})',
|
|
308
342
|
'ctrl.status.thread': 'Ветка: {name}',
|
|
309
343
|
'ctrl.status.threadDefault': 'общая',
|
|
310
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}',
|
|
311
352
|
'ctrl.status.turns': 'Ходов в работе: {n}',
|
|
353
|
+
'ctrl.status.notes': 'Заметки по ходу (💭 в прогрессе): {state}',
|
|
354
|
+
'ctrl.status.on': 'включены',
|
|
355
|
+
'ctrl.status.off': 'выключены',
|
|
312
356
|
'ctrl.status.skills': 'Скиллы: {n}',
|
|
313
357
|
'ctrl.status.ui': 'UI: desktop ({route}) — плагинов {n}',
|
|
314
358
|
'ctrl.models.current': 'Модель сейчас: {model}',
|
|
@@ -351,6 +395,20 @@ const DICT = {
|
|
|
351
395
|
'ctrl.soul.title': 'Персона ({path}):\n\n{text}',
|
|
352
396
|
'ctrl.soul.empty': 'Персона пуста. Задать: /soul <text>\nФайл: {path}',
|
|
353
397
|
'ctrl.soul.saved': 'Персона обновлена в ~/.dsh/AGENTS.md. Применяется в новых сессиях.',
|
|
398
|
+
'ctrl.version.title': 'Версии',
|
|
399
|
+
'ctrl.version.installed': 'Установлено здесь: {v}',
|
|
400
|
+
'ctrl.version.latest': 'Последняя на npm: {v}',
|
|
401
|
+
'ctrl.version.unknown': 'неизвестно',
|
|
402
|
+
'ctrl.version.offline': 'недоступен',
|
|
403
|
+
'ctrl.version.update': 'Есть обновление: /update, затем /update confirm',
|
|
404
|
+
'ctrl.version.root': 'Каталог моста: {path}',
|
|
405
|
+
'ctrl.version.hint': 'Новый код включится после /restart confirm — до этого чат работает как есть.',
|
|
406
|
+
'ctrl.update.available': 'Работает {from}, на npm уже {to}.\nПоставить: /update confirm.\nДо /restart confirm всё работает на старом коде.',
|
|
407
|
+
'ctrl.update.current': 'Уже стоит {v} — это последняя опубликованная версия.',
|
|
408
|
+
'ctrl.update.offline': 'npm недоступен, проверить версию не могу. Попробуй через минуту.',
|
|
409
|
+
'ctrl.update.running': 'Ставлю {v} в каталог моста…',
|
|
410
|
+
'ctrl.update.done': 'Установлено {v}. Включить: /restart confirm',
|
|
411
|
+
'ctrl.update.failed': 'Установка не удалась (код {code}). Ничего не изменено, мост работает на старом коде.',
|
|
354
412
|
'ctrl.app.usage': 'Использование: /app restart confirm — перезапустить приложение DSH.',
|
|
355
413
|
'ctrl.app.confirm': 'Перезапуск приложения оборвёт этот чат. Повтори: /app restart confirm',
|
|
356
414
|
'ctrl.app.notRunning': 'DSH сейчас не запущен — поднимаю.',
|
|
@@ -365,6 +423,8 @@ const DICT = {
|
|
|
365
423
|
'ctrl.send.unsupported': 'Отправка файлов недоступна: мост старой версии.',
|
|
366
424
|
'ctrl.send.failed': 'Не смог отправить файл: {err}',
|
|
367
425
|
'ctrl.cd.current': 'Текущий каталог темы:',
|
|
426
|
+
'ctrl.cd.defaultSuffix': ' (по умолчанию моста)',
|
|
427
|
+
'ctrl.cd.unset': 'не задан — используется рабочий каталог по умолчанию',
|
|
368
428
|
'ctrl.cd.bind': 'Привязать: /cd <путь>',
|
|
369
429
|
'ctrl.cd.resetHint': 'Сбросить: /cd reset',
|
|
370
430
|
'ctrl.cd.projects': 'Проекты:',
|
|
@@ -394,6 +454,8 @@ const DICT = {
|
|
|
394
454
|
'ctrl.doctor.diskFree': '{gb} ГБ свободно',
|
|
395
455
|
'ctrl.doctor.cwd': 'Каталог темы',
|
|
396
456
|
'ctrl.doctor.cwdMissing': ' (НЕТ ТАКОГО)',
|
|
457
|
+
'ctrl.doctor.cwdDefault': ' (по умолчанию моста; привязать тему: /cd)',
|
|
458
|
+
'ctrl.doctor.cwdUnset': 'не задан нигде — проверь cwd в config.json',
|
|
397
459
|
'ctrl.doctor.session': 'Сессия',
|
|
398
460
|
'ctrl.doctor.sessionNew': '(новая)',
|
|
399
461
|
'ctrl.logs.unreadable': 'Не могу прочитать лог: {err}',
|
|
@@ -401,6 +463,10 @@ const DICT = {
|
|
|
401
463
|
'ctrl.logs.empty': 'Лог пуст.',
|
|
402
464
|
'ctrl.logs.errors': 'Ошибки ({shown} из {total})',
|
|
403
465
|
'ctrl.logs.title': 'Лог ({shown} из {total})',
|
|
466
|
+
'ctrl.thoughts.title': '🧠 Рассуждения последнего хода ({chars} символов, повисят несколько минут):',
|
|
467
|
+
'ctrl.thoughts.none': 'В последнем ходе не сохранилось плана рассуждений.',
|
|
468
|
+
'ctrl.thoughts.lastAnswer': 'Последний ход ответил так:',
|
|
469
|
+
'ctrl.thoughts.noSession': 'В этой теме ещё нет сессии: сначала отправь задачу.',
|
|
404
470
|
'goal.none': 'В этой теме нет цели. Задать: /goal <текст>',
|
|
405
471
|
'goal.set': 'Цель: {text}',
|
|
406
472
|
'goal.default': 'Задачи',
|
|
@@ -489,7 +555,7 @@ const DICT = {
|
|
|
489
555
|
'status.failed': '运行失败',
|
|
490
556
|
'status.queued': '排队中',
|
|
491
557
|
'status.stop': '停止',
|
|
492
|
-
'help.body': "任务直接以文本发送。每个论坛话题是一个独立会话:\n\n工作: /cd \u003c项目\u003e · /new · /stop · /send \u003c文件\u003e · /seed \u003c文本\u003e\n目标: /goal · /task\n会话: /status · /sessions [n] · /resume \u003cid\u003e\n模型: /model · /model \u003cid\u003e · /prices\n扩展: /skills · /plugins · /plugin add|remove · /soul\n其他: /lang · /reasoning · /doctor · /logs [errors|N] · /app · /restart · /help",
|
|
558
|
+
'help.body': "任务直接以文本发送。每个论坛话题是一个独立会话:\n\n工作: /cd \u003c项目\u003e · /new · /stop · /send \u003c文件\u003e · /seed \u003c文本\u003e\n目标: /goal · /task\n会话: /status · /sessions [n] · /resume \u003cid\u003e\n模型: /model · /model \u003cid\u003e · /prices · /thoughts\n扩展: /skills · /plugins · /plugin add|remove · /soul\n版本: /version · /update · /update confirm\n其他: /lang · /reasoning · /doctor · /logs [errors|N] · /app · /restart · /help",
|
|
493
559
|
'btn.stop': '停止',
|
|
494
560
|
'btn.logs': '日志',
|
|
495
561
|
'btn.retry': '重试',
|
|
@@ -539,11 +605,22 @@ const DICT = {
|
|
|
539
605
|
'cmd.cd.none': '目录不存在:{path}',
|
|
540
606
|
'cmd.new.done': '已在本话题开始新会话,上下文已清空。',
|
|
541
607
|
'ctrl.session.none': '(还没有)',
|
|
608
|
+
'ctrl.status.head': '📊 桥接状态',
|
|
542
609
|
'ctrl.status.profile': '配置档:{name}({route})',
|
|
543
610
|
'ctrl.status.thread': '话题:{name}',
|
|
544
611
|
'ctrl.status.threadDefault': '公共',
|
|
545
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}',
|
|
546
620
|
'ctrl.status.turns': '进行中的任务:{n}',
|
|
621
|
+
'ctrl.status.notes': '工作记录(进度中的 💭):{state}',
|
|
622
|
+
'ctrl.status.on': '开',
|
|
623
|
+
'ctrl.status.off': '关',
|
|
547
624
|
'ctrl.status.skills': '技能:{n}',
|
|
548
625
|
'ctrl.status.ui': 'UI:desktop({route})— 插件 {n} 个',
|
|
549
626
|
'ctrl.models.current': '当前模型:{model}',
|
|
@@ -586,6 +663,20 @@ const DICT = {
|
|
|
586
663
|
'ctrl.soul.title': '人格({path}):\n\n{text}',
|
|
587
664
|
'ctrl.soul.empty': '人格为空。设置:/soul <文本>\n文件:{path}',
|
|
588
665
|
'ctrl.soul.saved': '人格已更新到 ~/.dsh/AGENTS.md。对新会话生效。',
|
|
666
|
+
'ctrl.version.title': '版本',
|
|
667
|
+
'ctrl.version.installed': '本地版本:{v}',
|
|
668
|
+
'ctrl.version.latest': 'npm 最新:{v}',
|
|
669
|
+
'ctrl.version.unknown': '未知',
|
|
670
|
+
'ctrl.version.offline': '不可达',
|
|
671
|
+
'ctrl.version.update': '有更新:/update,然后 /update confirm',
|
|
672
|
+
'ctrl.version.root': '桥接目录:{path}',
|
|
673
|
+
'ctrl.version.hint': '新代码在 /restart confirm 之后生效;在此之前聊天照常运行。',
|
|
674
|
+
'ctrl.update.available': '当前 {from},npm 上已是 {to}。\n安装:/update confirm。\n在 /restart confirm 之前一切仍用旧代码。',
|
|
675
|
+
'ctrl.update.current': '已经是 {v} —— 最新发布版本。',
|
|
676
|
+
'ctrl.update.offline': 'npm 不可达,无法检查版本。请稍后再试。',
|
|
677
|
+
'ctrl.update.running': '正在把 {v} 安装到桥接目录…',
|
|
678
|
+
'ctrl.update.done': '已安装 {v}。加载它:/restart confirm',
|
|
679
|
+
'ctrl.update.failed': '安装失败(退出码 {code})。没有做任何更改,桥接仍运行旧代码。',
|
|
589
680
|
'ctrl.app.usage': '用法:/app restart confirm —— 重启 DSH 应用。',
|
|
590
681
|
'ctrl.app.confirm': '重启应用会中断这个聊天。请重发:/app restart confirm',
|
|
591
682
|
'ctrl.app.notRunning': 'DSH 当前没有运行 —— 正在启动。',
|
|
@@ -600,6 +691,8 @@ const DICT = {
|
|
|
600
691
|
'ctrl.send.unsupported': '无法发送文件:桥是旧版本。',
|
|
601
692
|
'ctrl.send.failed': '无法发送文件:{err}',
|
|
602
693
|
'ctrl.cd.current': '话题的当前目录:',
|
|
694
|
+
'ctrl.cd.defaultSuffix': '(桥接默认)',
|
|
695
|
+
'ctrl.cd.unset': '未设置 —— 使用桥接的默认工作目录',
|
|
603
696
|
'ctrl.cd.bind': '绑定:/cd <路径>',
|
|
604
697
|
'ctrl.cd.resetHint': '重置:/cd reset',
|
|
605
698
|
'ctrl.cd.projects': '项目:',
|
|
@@ -629,6 +722,8 @@ const DICT = {
|
|
|
629
722
|
'ctrl.doctor.diskFree': '{gb} GB 可用',
|
|
630
723
|
'ctrl.doctor.cwd': '话题目录',
|
|
631
724
|
'ctrl.doctor.cwdMissing': '(没有这个目录)',
|
|
725
|
+
'ctrl.doctor.cwdDefault': '(桥接默认;可用 /cd 绑定话题)',
|
|
726
|
+
'ctrl.doctor.cwdUnset': '未设置 —— 检查 config.json 里的 cwd',
|
|
632
727
|
'ctrl.doctor.session': '会话',
|
|
633
728
|
'ctrl.doctor.sessionNew': '(新)',
|
|
634
729
|
'ctrl.logs.unreadable': '无法读取日志:{err}',
|
|
@@ -636,6 +731,10 @@ const DICT = {
|
|
|
636
731
|
'ctrl.logs.empty': '日志为空。',
|
|
637
732
|
'ctrl.logs.errors': '错误({shown}/{total})',
|
|
638
733
|
'ctrl.logs.title': '日志({shown}/{total})',
|
|
734
|
+
'ctrl.thoughts.title': '🧠 上一轮的推理({chars} 字符,几分钟后消失):',
|
|
735
|
+
'ctrl.thoughts.none': '上一轮没有保存推理过程。',
|
|
736
|
+
'ctrl.thoughts.lastAnswer': '上一轮的回答:',
|
|
737
|
+
'ctrl.thoughts.noSession': '本话题还没有会话:先发一个任务。',
|
|
639
738
|
'goal.none': '本话题还没有目标。设置:/goal <文本>',
|
|
640
739
|
'goal.set': '目标:{text}',
|
|
641
740
|
'goal.default': '任务',
|
package/immediate.mjs
CHANGED
|
@@ -1,41 +1,20 @@
|
|
|
1
1
|
// Which control commands may run while a turn is still working?
|
|
2
2
|
//
|
|
3
3
|
// Everything in a topic used to be queued, so `/stop` waited for the very turn
|
|
4
|
-
// it was supposed to kill
|
|
5
|
-
//
|
|
4
|
+
// it was supposed to kill, and a report typed during a long turn was answered
|
|
5
|
+
// only when that turn ended — which looks exactly like silence. The rule is not
|
|
6
|
+
// "important commands" but "commands that do not touch the turn's session":
|
|
6
7
|
//
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
//
|
|
13
|
-
// * everything else queues, because it changes the session the turn is using
|
|
14
|
-
// (`/model`, `/new`, `/resume`, `/cd`, `/send`, `/seed`, `/plugin`).
|
|
8
|
+
// * always immediate — reports, turn control, and settings that only affect
|
|
9
|
+
// the next turn (`/model`, `/lang`, `/goal`, `/thoughts`, unknown commands
|
|
10
|
+
// that deserve an instant "no such command");
|
|
11
|
+
// * queued — `/new`, `/resume`, `/seed`, `/send` (they replace or feed the
|
|
12
|
+
// session the running turn is writing) and plugin mutations (pnpm install
|
|
13
|
+
// must not race a turn).
|
|
15
14
|
|
|
15
|
+
const QUEUED = new Set(['new', 'resume', 'seed', 'send']);
|
|
16
16
|
const PLUGIN_ACTIONS = new Set(['add', 'remove', 'disable', 'enable']);
|
|
17
17
|
|
|
18
|
-
const ALWAYS = new Set([
|
|
19
|
-
// Turn control.
|
|
20
|
-
'stop',
|
|
21
|
-
'restart',
|
|
22
|
-
// Reports: they read profiles, sessions, skills and the price table, but
|
|
23
|
-
// touch neither the queue nor the session of the running turn.
|
|
24
|
-
'status',
|
|
25
|
-
'logs',
|
|
26
|
-
'help',
|
|
27
|
-
'doctor',
|
|
28
|
-
'models',
|
|
29
|
-
'sessions',
|
|
30
|
-
'skills',
|
|
31
|
-
'prices',
|
|
32
|
-
]);
|
|
33
|
-
|
|
34
|
-
const BARE_ONLY = new Set([
|
|
35
|
-
'soul', // `/soul` reads AGENTS.md, `/soul <text>` rewrites it
|
|
36
|
-
'lang', // `/lang` reports the current language, `/lang en` switches it
|
|
37
|
-
]);
|
|
38
|
-
|
|
39
18
|
/**
|
|
40
19
|
* Canonical immediate command name, or '' when the message must queue.
|
|
41
20
|
* `name` is the command without the slash and without a bot mention,
|
|
@@ -46,11 +25,10 @@ export function immediateKind(name, args = []) {
|
|
|
46
25
|
if (command === 'apprestart' || command === 'apprestartconfirm' || command === 'restartconfirm') {
|
|
47
26
|
return 'restart';
|
|
48
27
|
}
|
|
49
|
-
if (
|
|
50
|
-
if (command === 'plugins') {
|
|
28
|
+
if (QUEUED.has(command)) return '';
|
|
29
|
+
if (command === 'plugins' || command === 'plugin') {
|
|
51
30
|
const [action = ''] = args;
|
|
52
|
-
return PLUGIN_ACTIONS.has(String(action).toLowerCase()) ? '' :
|
|
31
|
+
return PLUGIN_ACTIONS.has(String(action).toLowerCase()) ? '' : command;
|
|
53
32
|
}
|
|
54
|
-
|
|
55
|
-
return '';
|
|
33
|
+
return command;
|
|
56
34
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-tg-bridge",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.7.1",
|
|
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",
|
|
@@ -66,6 +66,8 @@
|
|
|
66
66
|
"steer-queue.mjs",
|
|
67
67
|
"plugin/",
|
|
68
68
|
"profiles.mjs",
|
|
69
|
-
"cli-args.mjs"
|
|
69
|
+
"cli-args.mjs",
|
|
70
|
+
"thoughts.mjs",
|
|
71
|
+
"sync-runtime.mjs"
|
|
70
72
|
]
|
|
71
73
|
}
|
package/sync-runtime.mjs
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// Copy every runtime module from the repo into the live bridge directory,
|
|
2
|
+
// keeping a timestamped backup of what it replaces. Node, not PowerShell: the
|
|
3
|
+
// files are UTF-8 with Cyrillic, and Set-Content would mangle them.
|
|
4
|
+
import { copyFileSync, existsSync, mkdirSync, readdirSync } from 'node:fs';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
|
|
7
|
+
const repo = 'C:\\Users\\bistr\\Projects\\dsh-tg-bridge-oss';
|
|
8
|
+
const run = 'C:\\Users\\bistr\\.dsh\\tg-bridge';
|
|
9
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, '').slice(0, 15);
|
|
10
|
+
const files = readdirSync(repo).filter((f) => f.endsWith('.mjs'));
|
|
11
|
+
let copied = 0;
|
|
12
|
+
|
|
13
|
+
for (const file of files) {
|
|
14
|
+
const to = join(run, file);
|
|
15
|
+
if (existsSync(to)) copyFileSync(to, `${to}.bak-${stamp}`);
|
|
16
|
+
copyFileSync(join(repo, file), to);
|
|
17
|
+
copied += 1;
|
|
18
|
+
}
|
|
19
|
+
mkdirSync(run, { recursive: true });
|
|
20
|
+
console.log(`synced ${copied} modules from the repo to the runtime (backup stamp ${stamp})`);
|
package/thoughts.mjs
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// "What was the model thinking in the last turn?" — read straight from the
|
|
2
|
+
// session log instead of keeping a copy in memory.
|
|
3
|
+
//
|
|
4
|
+
// A session is `<sessions>/<cwd>/<id>/session.v4.jsonl.zstd`: one zstd frame per
|
|
5
|
+
// appended batch of records, and a `turn/start` record marks the beginning of a
|
|
6
|
+
// turn. Walking the file backwards from the newest frame is enough to reach the
|
|
7
|
+
// current turn, which keeps the command cheap on a 13 MB log with 16k frames.
|
|
8
|
+
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
|
9
|
+
import { join } from 'node:path';
|
|
10
|
+
import { zstdDecompressSync } from 'node:zlib';
|
|
11
|
+
|
|
12
|
+
const MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd]);
|
|
13
|
+
|
|
14
|
+
/** Every zstd frame start in `buf`, ascending. */
|
|
15
|
+
function frameStarts(buf) {
|
|
16
|
+
const starts = [];
|
|
17
|
+
let at = 0;
|
|
18
|
+
for (;;) {
|
|
19
|
+
const found = buf.indexOf(MAGIC, at);
|
|
20
|
+
if (found < 0) break;
|
|
21
|
+
starts.push(found);
|
|
22
|
+
at = found + MAGIC.length;
|
|
23
|
+
}
|
|
24
|
+
starts.push(buf.length);
|
|
25
|
+
return starts;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Path of a session file, or '' when the id is unknown. */
|
|
29
|
+
export function sessionFile(sessionsRoot, sessionId) {
|
|
30
|
+
if (!sessionId) return '';
|
|
31
|
+
let dirs = [];
|
|
32
|
+
try {
|
|
33
|
+
dirs = readdirSync(sessionsRoot, { withFileTypes: true }).filter((e) => e.isDirectory());
|
|
34
|
+
} catch {
|
|
35
|
+
return '';
|
|
36
|
+
}
|
|
37
|
+
for (const dir of dirs) {
|
|
38
|
+
const direct = join(sessionsRoot, dir.name, sessionId, 'session.v4.jsonl.zstd');
|
|
39
|
+
if (existsSync(direct)) return direct;
|
|
40
|
+
}
|
|
41
|
+
return '';
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Reasoning blocks of the last turn, oldest first. `maxChars` keeps the head of
|
|
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".
|
|
51
|
+
*/
|
|
52
|
+
export function lastTurnReasoning(file, { maxChars = 4000 } = {}) {
|
|
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 [];
|
|
61
|
+
let buf;
|
|
62
|
+
try {
|
|
63
|
+
buf = readFileSync(file);
|
|
64
|
+
} catch {
|
|
65
|
+
return [];
|
|
66
|
+
}
|
|
67
|
+
const starts = frameStarts(buf);
|
|
68
|
+
const lines = [];
|
|
69
|
+
let reachedTurnStart = false;
|
|
70
|
+
for (let i = starts.length - 2; i >= 0 && !reachedTurnStart; i--) {
|
|
71
|
+
let text = '';
|
|
72
|
+
try {
|
|
73
|
+
text = zstdDecompressSync(buf.subarray(starts[i], starts[i + 1])).toString('utf8');
|
|
74
|
+
} catch {
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
const parts = text.split('\n').filter(Boolean);
|
|
78
|
+
for (let j = parts.length - 1; j >= 0; j--) {
|
|
79
|
+
lines.push(parts[j]);
|
|
80
|
+
if (parts[j].includes('"type":"turn/start"')) {
|
|
81
|
+
reachedTurnStart = true;
|
|
82
|
+
break;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
lines.reverse();
|
|
87
|
+
const out = [];
|
|
88
|
+
for (const line of lines) {
|
|
89
|
+
let record;
|
|
90
|
+
try {
|
|
91
|
+
record = JSON.parse(line);
|
|
92
|
+
} catch {
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
if (record?.type !== 'assistant/message') continue;
|
|
96
|
+
for (const part of record.data?.message?.content ?? []) out.push(part);
|
|
97
|
+
}
|
|
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();
|
|
108
|
+
return text.length > maxChars ? `${text.slice(0, maxChars)}…` : text;
|
|
109
|
+
}
|
|
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
|
+
|
|
162
|
+
export { frameStarts };
|