dsh-tg-bridge 1.6.0 → 1.7.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/README.md +3 -0
- package/bot-menu.mjs +9 -0
- package/bridge.mjs +40 -1
- package/control.mjs +129 -3
- package/i18n.mjs +54 -3
- package/immediate.mjs +14 -36
- package/package.json +3 -2
- package/thoughts.mjs +93 -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
|
@@ -52,6 +52,9 @@ const COMMANDS = [
|
|
|
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. */
|
|
@@ -79,6 +82,9 @@ const COMMANDS_EN = [
|
|
|
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). */
|
|
@@ -106,6 +112,9 @@ const COMMANDS_ZH = [
|
|
|
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, sessionFile } from './thoughts.mjs';
|
|
14
15
|
|
|
15
16
|
const HOME = homedir();
|
|
16
17
|
const DSH_HOME = process.env.DSH_HOME || join(HOME, '.dsh');
|
|
@@ -416,6 +417,7 @@ export const CONTROL_COMMANDS = [
|
|
|
416
417
|
'status', 'models', 'model', 'profile', 'sessions', 'resume', 'plugins', 'plugin',
|
|
417
418
|
'skills', 'soul', 'restart', 'app', 'stop', 'new', 'seed', 'send', 'cd',
|
|
418
419
|
'prices', 'help', 'doctor', 'logs', 'lang', 'reasoning', 'goal', 'task',
|
|
420
|
+
'thoughts', 'version', 'update',
|
|
419
421
|
];
|
|
420
422
|
|
|
421
423
|
/**
|
|
@@ -1124,9 +1126,133 @@ export async function handleControl(ctx) {
|
|
|
1124
1126
|
return true;
|
|
1125
1127
|
}
|
|
1126
1128
|
|
|
1129
|
+
case '/thoughts': {
|
|
1130
|
+
// The reasoning of the last turn, pulled from the session log itself. It
|
|
1131
|
+
// is ephemeral: the reply lives a few minutes and then deletes itself, so
|
|
1132
|
+
// a long plan never turns into chat clutter.
|
|
1133
|
+
const sessionId = ctx.state.sessions?.[key];
|
|
1134
|
+
if (!sessionId) {
|
|
1135
|
+
say(t(lang, 'ctrl.thoughts.noSession'));
|
|
1136
|
+
return true;
|
|
1137
|
+
}
|
|
1138
|
+
const file = sessionFile(join(DSH_HOME, 'sessions'), sessionId);
|
|
1139
|
+
const text = file ? lastTurnReasoning(file, { maxChars: 4000 }) : '';
|
|
1140
|
+
if (!text) {
|
|
1141
|
+
say(t(lang, 'ctrl.thoughts.none'));
|
|
1142
|
+
return true;
|
|
1143
|
+
}
|
|
1144
|
+
say(t(lang, 'ctrl.thoughts.title', { chars: text.length }) + '\n\n' + text);
|
|
1145
|
+
return true;
|
|
1146
|
+
}
|
|
1147
|
+
|
|
1148
|
+
case '/version': {
|
|
1149
|
+
// Which bridge is running, which one npm has, and whether this install can
|
|
1150
|
+
// update itself. A report, so it answers even in the middle of a turn.
|
|
1151
|
+
const installed = bridgeVersion();
|
|
1152
|
+
const latest = npmLatest('dsh-tg-bridge');
|
|
1153
|
+
const where = process.env.DSH_BRIDGE_ROOT || join(DSH_HOME, 'tg-bridge');
|
|
1154
|
+
const lines = [t(lang, 'ctrl.version.title')];
|
|
1155
|
+
lines.push(t(lang, 'ctrl.version.installed', { v: installed || t(lang, 'ctrl.version.unknown') }));
|
|
1156
|
+
lines.push(t(lang, 'ctrl.version.latest', { v: latest || t(lang, 'ctrl.version.offline') }));
|
|
1157
|
+
if (installed && latest && installed !== latest) lines.push(t(lang, 'ctrl.version.update', { v: latest }));
|
|
1158
|
+
lines.push(t(lang, 'ctrl.version.root', { path: where }));
|
|
1159
|
+
lines.push(t(lang, 'ctrl.version.hint'));
|
|
1160
|
+
say(lines.join('\n'));
|
|
1161
|
+
return true;
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
case '/update': {
|
|
1165
|
+
// The person's own copy of the bridge, updated from npm. Nothing is
|
|
1166
|
+
// touched unless the release is newer, and the running process keeps its
|
|
1167
|
+
// old modules until the next `/restart confirm` — so a bad release never
|
|
1168
|
+
// takes the chat down by itself.
|
|
1169
|
+
if (String(arg).trim() === 'confirm') {
|
|
1170
|
+
const installed = bridgeVersion();
|
|
1171
|
+
const latest = npmLatest('dsh-tg-bridge');
|
|
1172
|
+
if (!latest) {
|
|
1173
|
+
say(t(lang, 'ctrl.update.offline'));
|
|
1174
|
+
return true;
|
|
1175
|
+
}
|
|
1176
|
+
if (installed && installed === latest) {
|
|
1177
|
+
say(t(lang, 'ctrl.update.current', { v: installed }));
|
|
1178
|
+
return true;
|
|
1179
|
+
}
|
|
1180
|
+
const root = process.env.DSH_BRIDGE_ROOT || join(DSH_HOME, 'tg-bridge');
|
|
1181
|
+
say(t(lang, 'ctrl.update.running', { v: latest }));
|
|
1182
|
+
// `npm install dsh-tg-bridge@x` inside the bridge's own directory would
|
|
1183
|
+
// drop a nested node_modules/dsh-tg-bridge and leave the running files
|
|
1184
|
+
// alone, so the release is fetched into a temp dir and its files are
|
|
1185
|
+
// copied over the top. Config, state and logs stay untouched.
|
|
1186
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
1187
|
+
const backup = join(root, `update-backup-${stamp}`);
|
|
1188
|
+
const work = join(tmpdir(), `dsh-tg-bridge-${stamp}`);
|
|
1189
|
+
const r = spawnSync(
|
|
1190
|
+
'npm',
|
|
1191
|
+
['install', '--no-save', '--no-audit', '--no-fund', '--prefix', work, `dsh-tg-bridge@${latest}`],
|
|
1192
|
+
{ encoding: 'utf8', shell: true, timeout: 240000, windowsHide: true },
|
|
1193
|
+
);
|
|
1194
|
+
const tail = `${r.stdout || ''}${r.stderr || ''}`.trim().split(/\r?\n/).slice(-6).join('\n');
|
|
1195
|
+
if (r.status !== 0) {
|
|
1196
|
+
say(t(lang, 'ctrl.update.failed', { code: r.status ?? '?' }) + (tail ? `\n\n${tail}` : ''));
|
|
1197
|
+
return true;
|
|
1198
|
+
}
|
|
1199
|
+
try {
|
|
1200
|
+
mkdirSync(backup, { recursive: true });
|
|
1201
|
+
for (const name of readdirSync(join(work, 'package'))) {
|
|
1202
|
+
const from = join(work, 'package', name);
|
|
1203
|
+
const to = join(root, name);
|
|
1204
|
+
if (existsSync(to)) copyFileSync(to, join(backup, name));
|
|
1205
|
+
copyFileSync(from, to);
|
|
1206
|
+
}
|
|
1207
|
+
} catch (error) {
|
|
1208
|
+
say(t(lang, 'ctrl.update.failed', { code: 'copy' }) + `\n\n${error.message}`);
|
|
1209
|
+
return true;
|
|
1210
|
+
} finally {
|
|
1211
|
+
try {
|
|
1212
|
+
rmSync(work, { recursive: true, force: true });
|
|
1213
|
+
} catch {}
|
|
1214
|
+
}
|
|
1215
|
+
say(t(lang, 'ctrl.update.done', { v: latest }));
|
|
1216
|
+
return true;
|
|
1217
|
+
}
|
|
1218
|
+
const installed = bridgeVersion();
|
|
1219
|
+
const latest = npmLatest('dsh-tg-bridge');
|
|
1220
|
+
if (!latest) {
|
|
1221
|
+
say(t(lang, 'ctrl.update.offline'));
|
|
1222
|
+
return true;
|
|
1223
|
+
}
|
|
1224
|
+
if (installed && installed === latest) {
|
|
1225
|
+
say(t(lang, 'ctrl.update.current', { v: installed }));
|
|
1226
|
+
return true;
|
|
1227
|
+
}
|
|
1228
|
+
say(t(lang, 'ctrl.update.available', { from: installed || '?', to: latest }));
|
|
1229
|
+
return true;
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1127
1232
|
default:
|
|
1128
1233
|
return false;
|
|
1129
1234
|
}
|
|
1130
1235
|
}
|
|
1131
1236
|
|
|
1132
|
-
|
|
1237
|
+
/** Version of the bridge this process runs, read from its own package.json. */
|
|
1238
|
+
function bridgeVersion() {
|
|
1239
|
+
const root = process.env.DSH_BRIDGE_ROOT || join(DSH_HOME, 'tg-bridge');
|
|
1240
|
+
try {
|
|
1241
|
+
return JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')).version || '';
|
|
1242
|
+
} catch {
|
|
1243
|
+
return '';
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
/** Latest published version of an npm package, or '' when npm is unreachable. */
|
|
1248
|
+
function npmLatest(name) {
|
|
1249
|
+
try {
|
|
1250
|
+
const r = spawnSync('npm', ['view', name, 'version'], { encoding: 'utf8', shell: true, timeout: 45000, windowsHide: true });
|
|
1251
|
+
const out = String(r.stdout || '').trim().split(/\s+/).pop() || '';
|
|
1252
|
+
return r.status === 0 && /^\d/.test(out) ? out : '';
|
|
1253
|
+
} catch {
|
|
1254
|
+
return '';
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
|
|
1258
|
+
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',
|
|
@@ -116,6 +116,20 @@ const DICT = {
|
|
|
116
116
|
'ctrl.soul.title': 'Persona ({path}):\n\n{text}',
|
|
117
117
|
'ctrl.soul.empty': 'Persona is empty. Set it: /soul <text>\nFile: {path}',
|
|
118
118
|
'ctrl.soul.saved': 'Persona updated in ~/.dsh/AGENTS.md. Applies to new sessions.',
|
|
119
|
+
'ctrl.version.title': 'Versions',
|
|
120
|
+
'ctrl.version.installed': 'Installed here: {v}',
|
|
121
|
+
'ctrl.version.latest': 'Latest on npm: {v}',
|
|
122
|
+
'ctrl.version.unknown': 'unknown',
|
|
123
|
+
'ctrl.version.offline': 'unreachable',
|
|
124
|
+
'ctrl.version.update': 'Update available: /update, then /update confirm',
|
|
125
|
+
'ctrl.version.root': 'Bridge directory: {path}',
|
|
126
|
+
'ctrl.version.hint': 'The new code loads after /restart confirm; the current chat keeps running until then.',
|
|
127
|
+
'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.',
|
|
128
|
+
'ctrl.update.current': 'Already on {v} — the latest published version.',
|
|
129
|
+
'ctrl.update.offline': 'npm is unreachable, so no version check is possible. Try again in a minute.',
|
|
130
|
+
'ctrl.update.running': 'Installing {v} into the bridge directory…',
|
|
131
|
+
'ctrl.update.done': 'Installed {v}. Load it: /restart confirm',
|
|
132
|
+
'ctrl.update.failed': 'The install failed (exit {code}). Nothing was changed; the bridge still runs the old code.',
|
|
119
133
|
'ctrl.app.usage': 'Usage: /app restart confirm — restart the DSH app.',
|
|
120
134
|
'ctrl.app.confirm': 'Restarting the app ends this chat. Repeat: /app restart confirm',
|
|
121
135
|
'ctrl.app.notRunning': 'DSH is not running — starting it.',
|
|
@@ -166,6 +180,9 @@ const DICT = {
|
|
|
166
180
|
'ctrl.logs.empty': 'The log is empty.',
|
|
167
181
|
'ctrl.logs.errors': 'Errors ({shown} of {total})',
|
|
168
182
|
'ctrl.logs.title': 'Log ({shown} of {total})',
|
|
183
|
+
'ctrl.thoughts.title': '🧠 Reasoning of the last turn ({chars} chars, kept for a few minutes):',
|
|
184
|
+
'ctrl.thoughts.none': 'The last turn stored no reasoning plan.',
|
|
185
|
+
'ctrl.thoughts.noSession': 'This topic has no session yet: send a task first.',
|
|
169
186
|
'goal.none': 'No goal in this topic. Set one: /goal <text>',
|
|
170
187
|
'goal.set': 'Goal: {text}',
|
|
171
188
|
'goal.default': 'Tasks',
|
|
@@ -254,7 +271,7 @@ const DICT = {
|
|
|
254
271
|
'status.failed': 'Ход не удался',
|
|
255
272
|
'status.queued': 'в очереди',
|
|
256
273
|
'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",
|
|
274
|
+
'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
275
|
'btn.stop': 'Стоп',
|
|
259
276
|
'btn.logs': 'Логи',
|
|
260
277
|
'btn.retry': 'Повторить',
|
|
@@ -351,6 +368,20 @@ const DICT = {
|
|
|
351
368
|
'ctrl.soul.title': 'Персона ({path}):\n\n{text}',
|
|
352
369
|
'ctrl.soul.empty': 'Персона пуста. Задать: /soul <text>\nФайл: {path}',
|
|
353
370
|
'ctrl.soul.saved': 'Персона обновлена в ~/.dsh/AGENTS.md. Применяется в новых сессиях.',
|
|
371
|
+
'ctrl.version.title': 'Версии',
|
|
372
|
+
'ctrl.version.installed': 'Установлено здесь: {v}',
|
|
373
|
+
'ctrl.version.latest': 'Последняя на npm: {v}',
|
|
374
|
+
'ctrl.version.unknown': 'неизвестно',
|
|
375
|
+
'ctrl.version.offline': 'недоступен',
|
|
376
|
+
'ctrl.version.update': 'Есть обновление: /update, затем /update confirm',
|
|
377
|
+
'ctrl.version.root': 'Каталог моста: {path}',
|
|
378
|
+
'ctrl.version.hint': 'Новый код включится после /restart confirm — до этого чат работает как есть.',
|
|
379
|
+
'ctrl.update.available': 'Работает {from}, на npm уже {to}.\nПоставить: /update confirm.\nДо /restart confirm всё работает на старом коде.',
|
|
380
|
+
'ctrl.update.current': 'Уже стоит {v} — это последняя опубликованная версия.',
|
|
381
|
+
'ctrl.update.offline': 'npm недоступен, проверить версию не могу. Попробуй через минуту.',
|
|
382
|
+
'ctrl.update.running': 'Ставлю {v} в каталог моста…',
|
|
383
|
+
'ctrl.update.done': 'Установлено {v}. Включить: /restart confirm',
|
|
384
|
+
'ctrl.update.failed': 'Установка не удалась (код {code}). Ничего не изменено, мост работает на старом коде.',
|
|
354
385
|
'ctrl.app.usage': 'Использование: /app restart confirm — перезапустить приложение DSH.',
|
|
355
386
|
'ctrl.app.confirm': 'Перезапуск приложения оборвёт этот чат. Повтори: /app restart confirm',
|
|
356
387
|
'ctrl.app.notRunning': 'DSH сейчас не запущен — поднимаю.',
|
|
@@ -401,6 +432,9 @@ const DICT = {
|
|
|
401
432
|
'ctrl.logs.empty': 'Лог пуст.',
|
|
402
433
|
'ctrl.logs.errors': 'Ошибки ({shown} из {total})',
|
|
403
434
|
'ctrl.logs.title': 'Лог ({shown} из {total})',
|
|
435
|
+
'ctrl.thoughts.title': '🧠 Рассуждения последнего хода ({chars} символов, повисят несколько минут):',
|
|
436
|
+
'ctrl.thoughts.none': 'В последнем ходе не сохранилось плана рассуждений.',
|
|
437
|
+
'ctrl.thoughts.noSession': 'В этой теме ещё нет сессии: сначала отправь задачу.',
|
|
404
438
|
'goal.none': 'В этой теме нет цели. Задать: /goal <текст>',
|
|
405
439
|
'goal.set': 'Цель: {text}',
|
|
406
440
|
'goal.default': 'Задачи',
|
|
@@ -489,7 +523,7 @@ const DICT = {
|
|
|
489
523
|
'status.failed': '运行失败',
|
|
490
524
|
'status.queued': '排队中',
|
|
491
525
|
'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",
|
|
526
|
+
'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
527
|
'btn.stop': '停止',
|
|
494
528
|
'btn.logs': '日志',
|
|
495
529
|
'btn.retry': '重试',
|
|
@@ -586,6 +620,20 @@ const DICT = {
|
|
|
586
620
|
'ctrl.soul.title': '人格({path}):\n\n{text}',
|
|
587
621
|
'ctrl.soul.empty': '人格为空。设置:/soul <文本>\n文件:{path}',
|
|
588
622
|
'ctrl.soul.saved': '人格已更新到 ~/.dsh/AGENTS.md。对新会话生效。',
|
|
623
|
+
'ctrl.version.title': '版本',
|
|
624
|
+
'ctrl.version.installed': '本地版本:{v}',
|
|
625
|
+
'ctrl.version.latest': 'npm 最新:{v}',
|
|
626
|
+
'ctrl.version.unknown': '未知',
|
|
627
|
+
'ctrl.version.offline': '不可达',
|
|
628
|
+
'ctrl.version.update': '有更新:/update,然后 /update confirm',
|
|
629
|
+
'ctrl.version.root': '桥接目录:{path}',
|
|
630
|
+
'ctrl.version.hint': '新代码在 /restart confirm 之后生效;在此之前聊天照常运行。',
|
|
631
|
+
'ctrl.update.available': '当前 {from},npm 上已是 {to}。\n安装:/update confirm。\n在 /restart confirm 之前一切仍用旧代码。',
|
|
632
|
+
'ctrl.update.current': '已经是 {v} —— 最新发布版本。',
|
|
633
|
+
'ctrl.update.offline': 'npm 不可达,无法检查版本。请稍后再试。',
|
|
634
|
+
'ctrl.update.running': '正在把 {v} 安装到桥接目录…',
|
|
635
|
+
'ctrl.update.done': '已安装 {v}。加载它:/restart confirm',
|
|
636
|
+
'ctrl.update.failed': '安装失败(退出码 {code})。没有做任何更改,桥接仍运行旧代码。',
|
|
589
637
|
'ctrl.app.usage': '用法:/app restart confirm —— 重启 DSH 应用。',
|
|
590
638
|
'ctrl.app.confirm': '重启应用会中断这个聊天。请重发:/app restart confirm',
|
|
591
639
|
'ctrl.app.notRunning': 'DSH 当前没有运行 —— 正在启动。',
|
|
@@ -636,6 +684,9 @@ const DICT = {
|
|
|
636
684
|
'ctrl.logs.empty': '日志为空。',
|
|
637
685
|
'ctrl.logs.errors': '错误({shown}/{total})',
|
|
638
686
|
'ctrl.logs.title': '日志({shown}/{total})',
|
|
687
|
+
'ctrl.thoughts.title': '🧠 上一轮的推理({chars} 字符,几分钟后消失):',
|
|
688
|
+
'ctrl.thoughts.none': '上一轮没有保存推理过程。',
|
|
689
|
+
'ctrl.thoughts.noSession': '本话题还没有会话:先发一个任务。',
|
|
639
690
|
'goal.none': '本话题还没有目标。设置:/goal <文本>',
|
|
640
691
|
'goal.set': '目标:{text}',
|
|
641
692
|
'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.0",
|
|
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,7 @@
|
|
|
66
66
|
"steer-queue.mjs",
|
|
67
67
|
"plugin/",
|
|
68
68
|
"profiles.mjs",
|
|
69
|
-
"cli-args.mjs"
|
|
69
|
+
"cli-args.mjs",
|
|
70
|
+
"thoughts.mjs"
|
|
70
71
|
]
|
|
71
72
|
}
|
package/thoughts.mjs
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
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
|
+
export function lastTurnReasoning(file, { maxChars = 4000 } = {}) {
|
|
49
|
+
if (!file || !existsSync(file)) return '';
|
|
50
|
+
let buf;
|
|
51
|
+
try {
|
|
52
|
+
buf = readFileSync(file);
|
|
53
|
+
} catch {
|
|
54
|
+
return '';
|
|
55
|
+
}
|
|
56
|
+
const starts = frameStarts(buf);
|
|
57
|
+
const lines = [];
|
|
58
|
+
let reachedTurnStart = false;
|
|
59
|
+
for (let i = starts.length - 2; i >= 0 && !reachedTurnStart; i--) {
|
|
60
|
+
let text = '';
|
|
61
|
+
try {
|
|
62
|
+
text = zstdDecompressSync(buf.subarray(starts[i], starts[i + 1])).toString('utf8');
|
|
63
|
+
} catch {
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
const parts = text.split('\n').filter(Boolean);
|
|
67
|
+
for (let j = parts.length - 1; j >= 0; j--) {
|
|
68
|
+
lines.push(parts[j]);
|
|
69
|
+
if (parts[j].includes('"type":"turn/start"')) {
|
|
70
|
+
reachedTurnStart = true;
|
|
71
|
+
break;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
lines.reverse();
|
|
76
|
+
const blocks = [];
|
|
77
|
+
for (const line of lines) {
|
|
78
|
+
let record;
|
|
79
|
+
try {
|
|
80
|
+
record = JSON.parse(line);
|
|
81
|
+
} catch {
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
if (record?.type !== 'assistant/message') continue;
|
|
85
|
+
for (const part of record.data?.message?.content ?? []) {
|
|
86
|
+
if (part?.type === 'reasoning' && part.text) blocks.push(part.text.trim());
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
const text = blocks.join('\n\n').trim();
|
|
90
|
+
return text.length > maxChars ? `${text.slice(0, maxChars)}…` : text;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export { frameStarts };
|