dsh-tg-bridge 1.13.2 → 1.14.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/QUICKSTART.md CHANGED
@@ -83,7 +83,7 @@ Everything below is typed in the chat, not in a terminal.
83
83
  | See what it is doing | it posts a live progress message; `/thoughts` toggles the 💭 notes |
84
84
  | A plan you can tick off | `/goal <what done looks like>`, then `/task <step>`, then `/tasks` to tap items |
85
85
  | Stop a long answer | `/stop` |
86
- | Restart after an update | `/restart confirm` |
86
+ | Update the bridge | `/update` shows where you stand. By default it tells you once about a new release; `/update confirm` installs it and `/restart confirm` loads it. `/update off` stays on the version you have. |
87
87
  | Everything it can do | `/help` |
88
88
 
89
89
  `/lang` pins the reply language; without it the bridge answers in the language you
package/README.md CHANGED
@@ -185,18 +185,49 @@ Send the bot:
185
185
 
186
186
  ```
187
187
  Work: /cd · /new · /stop · /send · /seed
188
- Goals: /goal · /task
188
+ Goals: /goal · /task · /tasks
189
189
  Sessions: /status · /sessions · /resume
190
190
  Agents: /agents · /agents <id> · /agents set model|depth|filter
191
- Models: /model · /model <id> · /prices
191
+ Models: /model · /model <id> · /models · /prices
192
192
  Tuning: /effort · /permissions · /preset · /plan · /jobs · /remind
193
193
  Profiles: /profile · /profile <name> · /profile new <name> from <template>
194
- Extensions: /skills · /plugins · /soul
194
+ Sets: /agentset · /agentset use|off|new|copy|rm · /agentset model <v>
195
+ Extensions: /skills · /plugins · /plugin disable|enable <id> · /soul
196
+ Updates: /version · /update · /update confirm · /update on|off|check|auto · /subscribe on|off
195
197
  Diagnostics: /doctor · /logs [errors|N|text]
196
198
  Service: /app · /restart · /help
197
- Display: /lang · /reasoning on|off
199
+ Display: /lang · /reasoning on|off · /thoughts
198
200
  ```
199
201
 
202
+ Every command answers `/help` in the chat, in the language you write in. The
203
+ Telegram menu shows the same list, minus `/subscribe`: it is one line, and a
204
+ person who turns it off should not have to find it in a menu again.
205
+
206
+ ## Updates
207
+
208
+ The npm tag `latest` is a label, not an updater: installing a package pins the
209
+ version on disk, and nothing moves until something moves it. Three modes, one
210
+ per install (a global setting, since it is the install that updates, not a
211
+ topic):
212
+
213
+ | `/update …` | What happens |
214
+ |---|---|
215
+ | *(none)* | one line: what runs here, what is published, which mode is set |
216
+ | `check` (default) | one message per new release, at most once a day of checking |
217
+ | `auto` | the new release is fetched and installed by itself; `/restart confirm` loads it |
218
+ | `off` | no notices, no checks; `/version` still reports what is published |
219
+ | `confirm` | install now, keeping a copy of the old files in `update-backup-<date>` |
220
+
221
+ In every mode the running process keeps its modules until `/restart confirm`,
222
+ so a bad release never arrives in the middle of a chat. `/update off` pins the
223
+ install to the version it runs; `npx dsh-tg@latest setup` is how you follow
224
+ releases again.
225
+
226
+ Failure notices are not a thing here on purpose: the bridge cannot report a bug
227
+ to its own author, and a message about "something failed" that nobody can act on
228
+ is noise. What it does send is the release notice above, and only to the chat
229
+ that last ran a turn.
230
+
200
231
  ## How it works
201
232
 
202
233
  ```
package/bot-menu.mjs CHANGED
@@ -42,9 +42,11 @@ const COMMANDS = [
42
42
  { command: 'sessions', description: 'Сессии темы — обычный текст продолжает последнюю' },
43
43
  { command: 'resume', description: 'Продолжить сессию: /resume <id>' },
44
44
  { command: 'model', description: 'Показать или сменить: /model, /model <id>' },
45
+ { command: 'models', description: 'Все модели профиля и цены' },
45
46
  { command: 'skills', description: 'Скиллы: список или текст одного' },
46
47
  { command: 'soul', description: 'Персона: показать или задать' },
47
48
  { command: 'plugins', description: 'Список и управление: add/remove/disable/enable' },
49
+ { command: 'plugin', description: 'Один плагин: /plugin disable <id>' },
48
50
  { command: 'app', description: 'Приложение DSH, не мост: /app restart confirm' },
49
51
  { command: 'restart', description: 'Перезапуск моста: /restart confirm' },
50
52
  { command: 'doctor', description: 'Диагностика: мост, сеть, диск, плагины, сессия' },
@@ -81,9 +83,11 @@ const COMMANDS_EN = [
81
83
  { command: 'sessions', description: 'Sessions of this topic — plain text continues the last one' },
82
84
  { command: 'resume', description: 'Continue a session: /resume <id>' },
83
85
  { command: 'model', description: 'Show or switch: /model, /model <id>' },
86
+ { command: 'models', description: 'All models of this profile with prices' },
84
87
  { command: 'skills', description: 'Installed skills' },
85
88
  { command: 'soul', description: 'Agent persona' },
86
89
  { command: 'plugins', description: 'List and manage: add/remove/disable/enable' },
90
+ { command: 'plugin', description: 'One plugin: /plugin disable <id>' },
87
91
  { command: 'app', description: 'DSH desktop app (not the bridge)' },
88
92
  { command: 'restart', description: 'Restart the bridge: /restart confirm' },
89
93
  { command: 'doctor', description: 'Diagnostics: bridge, network, disk, plugins, session' },
@@ -101,8 +105,8 @@ const COMMANDS_EN = [
101
105
  { command: 'jobs', description: 'What the bridge runs now: turns and queue' },
102
106
  { command: 'remind', description: 'Reminder: /remind +15m text or 09:30 text' },
103
107
  { command: 'thoughts', description: 'Reasoning of the last turn (text, file or off)' },
104
- { command: 'version', description: 'Bridge version and the latest on npm' },
105
- { command: 'update', description: 'Update the bridge from npm: /update confirm' },
108
+ { command: 'version', description: 'Bridge version and how updates are handled' },
109
+ { command: 'update', description: 'Update and its mode: /update, /update on|off|confirm' },
106
110
  ];
107
111
 
108
112
  /** Chinese menu (language_code: zh-hans). */
@@ -120,9 +124,11 @@ const COMMANDS_ZH = [
120
124
  { command: 'sessions', description: '本主题的会话 —— 直接发文字会延续最近一个' },
121
125
  { command: 'resume', description: '继续会话:/resume <id>' },
122
126
  { command: 'model', description: '查看或切换:/model, /model <id>' },
127
+ { command: 'models', description: '本配置档的全部模型与价格' },
123
128
  { command: 'skills', description: '已安装的技能' },
124
129
  { command: 'soul', description: '代理人格设定' },
125
130
  { command: 'plugins', description: '列表与管理:add/remove/disable/enable' },
131
+ { command: 'plugin', description: '单个插件:/plugin disable <id>' },
126
132
  { command: 'app', description: 'DSH 桌面应用(不是桥接)' },
127
133
  { command: 'restart', description: '重启桥接:/restart confirm' },
128
134
  { command: 'doctor', description: '诊断:桥接、网络、磁盘、插件、会话' },
package/bridge.mjs CHANGED
@@ -31,6 +31,8 @@ import { turnArgs } from './cli-args.mjs';
31
31
  import { chunk, markdownParts, toPlainText, toTelegramHtml } from './format.mjs';
32
32
  import { ensureProfile } from './profiles.mjs';
33
33
  import { handleControl, CONTROL_COMMANDS, modelOf, modelsOf, reasoningOf } from './control.mjs';
34
+ import { bridgeVersion, installRelease, npmLatestAsync } from './control.mjs';
35
+ import { dueForCheck, updateState } from './update-policy.mjs';
34
36
  import { drainGoalJobs, goalOf, progressOf, renderPromptBlock, toggleTask } from './goals.mjs';
35
37
  import { renderPrices } from './prices.mjs';
36
38
  import { t, resolveLang } from './i18n.mjs';
@@ -749,6 +751,22 @@ function langFor(chatId, threadId = 0) {
749
751
  return resolveLang(state, sessionKey(chatId, threadId), null, config);
750
752
  }
751
753
 
754
+ /**
755
+ * Where a release notice goes: the last chat a turn ran in.
756
+ *
757
+ * `state.sessions[key]` is a session id, not a record, so the order is by last
758
+ * use — the bridge records it in `state.lastKey` whenever it starts a turn. With
759
+ * no session at all (a fresh install that never talked) a notice is pointless,
760
+ * and nothing is sent.
761
+ */
762
+ function lastTurnTarget() {
763
+ const key = typeof state.lastKey === 'string' ? state.lastKey : '';
764
+ const [chat, thread] = key.split(':');
765
+ const chatId = Number(chat);
766
+ if (!Number.isInteger(chatId) || chatId <= 0) return null;
767
+ return { chatId, threadId: Number(thread) || 0 };
768
+ }
769
+
752
770
  async function send(chatId, text, threadId = 0, replyTo = 0) {
753
771
  // Who is reading: the topic's language decides even the fallback line, so an
754
772
  // English or Chinese topic never sees a Russian placeholder.
@@ -1566,6 +1584,12 @@ ${t(lang, 'help.body')}`,
1566
1584
  // (two messages a few seconds apart, or a copy-paste), and the late writer
1567
1585
  // then attached a fresh session id to a conversation that already had one.
1568
1586
  const sessionAtStart = state.sessions[key];
1587
+ // Remember the topic a turn is running in: it is where a release notice goes,
1588
+ // since a notice is about the install and the install serves every topic.
1589
+ if (state.lastKey !== key) {
1590
+ state.lastKey = key;
1591
+ saveState();
1592
+ }
1569
1593
  // Project directory bound to this topic (set with /cd); config.cwd otherwise.
1570
1594
  const cwd = (state.cwd && state.cwd[key]) || config.cwd;
1571
1595
  // What the person actually wrote, before any injected block: the progress
@@ -2509,7 +2533,53 @@ async function main() {
2509
2533
  }
2510
2534
 
2511
2535
  let pollFailures = 0;
2536
+ // Release and failure notices ride the poll loop's own idle: they are one
2537
+ // message every few hours at most, and a timer would keep the process awake
2538
+ // for nothing. The first check runs a few minutes after a start, so a
2539
+ // restarting machine does not hit the registry on every boot.
2540
+ const notice = { mode: '', startAt: Date.now() + 3 * 60 * 1000 };
2541
+ const noticeMode = () => (state.update && typeof state.update.mode === 'string' ? state.update.mode : 'check');
2542
+ /** Where a notice goes: the chat that last ran a turn. */
2543
+ const noticeTarget = () => lastTurnTarget();
2544
+ const maybeNotice = async () => {
2545
+ try {
2546
+ const target = noticeTarget();
2547
+ if (!target) return;
2548
+ const mode = noticeMode();
2549
+ const checkedAt = Number(state.update?.checkedAt) || 0;
2550
+ if (mode === 'off' || !dueForCheck({ mode, checkedAt, now: Date.now() })) return;
2551
+ // One attempt per interval, even if it fails: an offline laptop must not
2552
+ // retry the registry on every poll.
2553
+ state.update = { ...(state.update || {}), checkedAt: Date.now() };
2554
+ saveState();
2555
+ const latest = await npmLatestAsync();
2556
+ if (!latest) return;
2557
+ const lang = langFor(target.chatId, target.threadId);
2558
+ const result = updateState({ installed: bridgeVersion(), latest, mode, notified: state.update?.notified || '' });
2559
+ if (result.auto) {
2560
+ // The files change, the running process does not: the person still says
2561
+ // when the new code loads, so a bad release never arrives mid-chat.
2562
+ const backup = installRelease(latest);
2563
+ state.update = { ...(state.update || {}), notified: latest };
2564
+ saveState();
2565
+ await send(target.chatId, t(lang, 'ctrl.update.done', { v: latest }) + '\n' + t(lang, 'ctrl.update.backup', { path: join(DIR, backup) }), target.threadId);
2566
+ return;
2567
+ }
2568
+ if (!result.notify) return;
2569
+ state.update = { ...(state.update || {}), notified: latest };
2570
+ saveState();
2571
+ await send(target.chatId, t(lang, 'ctrl.subscribe.notice', { v: latest }), target.threadId);
2572
+ } catch (error) {
2573
+ log(`update notice skipped: ${error.message}`);
2574
+ }
2575
+ };
2512
2576
  for (;;) {
2577
+ if (Date.now() >= notice.startAt) {
2578
+ notice.startAt = Date.now() + 15 * 60 * 1000;
2579
+ if (notice.mode !== noticeMode()) notice.startAt = Date.now() + 3 * 60 * 1000;
2580
+ notice.mode = noticeMode();
2581
+ void maybeNotice();
2582
+ }
2513
2583
  try {
2514
2584
  // `callback_query` is required for inline buttons: without it Telegram
2515
2585
  // never delivers button presses, so «Стоп» would draw but do nothing.
package/control.mjs CHANGED
@@ -17,6 +17,7 @@ import { setRowConfig, unsetRowConfig } from './profile-edit.mjs';
17
17
  import { parseReminder, stampAt, upcoming } from './reminders.mjs';
18
18
  import { AgentsetStore, emptySet, slugId } from './agentsets.mjs';
19
19
  import { profileValues, resolveSettings } from './settings.mjs';
20
+ import { UPDATE_DEFAULTS, describeUpdate, modeChange, updateState } from './update-policy.mjs';
20
21
 
21
22
  const HOME = homedir();
22
23
  const DSH_HOME = process.env.DSH_HOME || join(HOME, '.dsh');
@@ -602,7 +603,7 @@ export const CONTROL_COMMANDS = [
602
603
  'jobs', 'remind', 'sessions', 'resume', 'plugins', 'plugin',
603
604
  'skills', 'soul', 'restart', 'app', 'stop', 'new', 'seed', 'send', 'cd',
604
605
  'prices', 'help', 'doctor', 'logs', 'lang', 'reasoning', 'goal', 'task', 'tasks',
605
- 'thoughts', 'version', 'update', 'agentset',
606
+ 'thoughts', 'version', 'update', 'agentset', 'subscribe',
606
607
  ];
607
608
 
608
609
  /**
@@ -1940,9 +1941,20 @@ export async function handleControl(ctx) {
1940
1941
  // touched unless the release is newer, and the running process keeps its
1941
1942
  // old modules until the next `/restart confirm` — so a bad release never
1942
1943
  // takes the chat down by itself.
1943
- if (String(arg).trim() === 'confirm') {
1944
- const installed = bridgeVersion();
1945
- const latest = npmLatest('dsh-tg-bridge');
1944
+ const policy = updatePolicy(state);
1945
+ const installed = bridgeVersion();
1946
+ const latest = npmLatest('dsh-tg-bridge');
1947
+ const sub = String(arg).trim().toLowerCase();
1948
+ if (['off', 'check', 'auto'].includes(sub)) {
1949
+ const change = modeChange({ installed, latest, command: sub });
1950
+ if (change.store) {
1951
+ Object.assign(policy, change.store);
1952
+ saveState();
1953
+ }
1954
+ say(change.text);
1955
+ return true;
1956
+ }
1957
+ if (sub === 'confirm') {
1946
1958
  if (!latest) {
1947
1959
  say(t(lang, 'ctrl.update.offline'));
1948
1960
  return true;
@@ -1951,55 +1963,44 @@ export async function handleControl(ctx) {
1951
1963
  say(t(lang, 'ctrl.update.current', { v: installed }));
1952
1964
  return true;
1953
1965
  }
1954
- const root = process.env.DSH_BRIDGE_ROOT || join(DSH_HOME, 'tg-bridge');
1955
1966
  say(t(lang, 'ctrl.update.running', { v: latest }));
1956
- // `npm install dsh-tg-bridge@x` inside the bridge's own directory would
1957
- // drop a nested node_modules/dsh-tg-bridge and leave the running files
1958
- // alone, so the release is fetched into a temp dir and its files are
1959
- // copied over the top. Config, state and logs stay untouched.
1960
- const stamp = new Date().toISOString().replace(/[:.]/g, '-');
1961
- const backup = join(root, `update-backup-${stamp}`);
1962
- const work = join(tmpdir(), `dsh-tg-bridge-${stamp}`);
1963
- const r = spawnSync(
1964
- 'npm',
1965
- ['install', '--no-save', '--no-audit', '--no-fund', '--prefix', work, `dsh-tg-bridge@${latest}`],
1966
- { encoding: 'utf8', shell: true, timeout: 240000, windowsHide: true },
1967
- );
1968
- const tail = `${r.stdout || ''}${r.stderr || ''}`.trim().split(/\r?\n/).slice(-6).join('\n');
1969
- if (r.status !== 0) {
1970
- say(t(lang, 'ctrl.update.failed', { code: r.status ?? '?' }) + (tail ? `\n\n${tail}` : ''));
1971
- return true;
1972
- }
1967
+ let backup = '';
1973
1968
  try {
1974
- mkdirSync(backup, { recursive: true });
1975
- for (const name of readdirSync(join(work, 'package'))) {
1976
- const from = join(work, 'package', name);
1977
- const to = join(root, name);
1978
- if (existsSync(to)) copyFileSync(to, join(backup, name));
1979
- copyFileSync(from, to);
1980
- }
1969
+ backup = installRelease(latest);
1981
1970
  } catch (error) {
1982
- say(t(lang, 'ctrl.update.failed', { code: 'copy' }) + `\n\n${error.message}`);
1971
+ say(t(lang, 'ctrl.update.failed', { code: 'npm' }) + `\n\n${String(error.message).slice(-700)}`);
1983
1972
  return true;
1984
- } finally {
1985
- try {
1986
- rmSync(work, { recursive: true, force: true });
1987
- } catch {}
1988
1973
  }
1989
- say(t(lang, 'ctrl.update.done', { v: latest }));
1974
+ // The files on disk are the new ones now; this process still runs the
1975
+ // old code, so the way back is one folder name.
1976
+ policy.notified = latest;
1977
+ saveState();
1978
+ say(t(lang, 'ctrl.update.done', { v: latest }) + `\n${t(lang, 'ctrl.update.backup', { path: join(bridgeRoot(), backup) })}`);
1990
1979
  return true;
1991
1980
  }
1981
+ // No argument: where this install stands, in one sentence.
1982
+ say(describeUpdate(updateState({ installed, latest, mode: policy.mode, notified: policy.notified })));
1983
+ return true;
1984
+ }
1985
+
1986
+ case '/subscribe': {
1987
+ // A notice per new release, at most once per release, and nothing when the
1988
+ // registry does not answer. Not a command menu entry: it is one line, and
1989
+ // a person who turns it off should not have to find it again in /help.
1990
+ const policy = updatePolicy(state);
1992
1991
  const installed = bridgeVersion();
1993
1992
  const latest = npmLatest('dsh-tg-bridge');
1994
- if (!latest) {
1995
- say(t(lang, 'ctrl.update.offline'));
1993
+ const [on] = String(arg).trim().split(/\s+/);
1994
+ if (on === 'on' || on === 'off') {
1995
+ policy.mode = on === 'on' ? 'check' : 'off';
1996
+ policy.pinned = on === 'off' ? installed : '';
1997
+ policy.notified = latest;
1998
+ saveState();
1999
+ say(t(lang, on === 'on' ? 'ctrl.subscribe.on' : 'ctrl.subscribe.off', { v: installed || '?' }));
1996
2000
  return true;
1997
2001
  }
1998
- if (installed && installed === latest) {
1999
- say(t(lang, 'ctrl.update.current', { v: installed }));
2000
- return true;
2001
- }
2002
- say(t(lang, 'ctrl.update.available', { from: installed || '?', to: latest }));
2002
+ const where = policy.mode === 'off' ? t(lang, 'ctrl.subscribe.stateOff') : t(lang, 'ctrl.subscribe.stateOn');
2003
+ say(`${t(lang, 'ctrl.subscribe.title')}\n${where}\n${describeUpdate(updateState({ installed, latest, mode: policy.mode, notified: policy.notified }))}`);
2003
2004
  return true;
2004
2005
  }
2005
2006
 
@@ -2168,6 +2169,59 @@ export async function handleControl(ctx) {
2168
2169
  }
2169
2170
  }
2170
2171
 
2172
+ /**
2173
+ * The install-wide update settings: a mode, which release was already announced,
2174
+ * when npm was last asked and the version a person chose to stay on. They live
2175
+ * in state.json, not in a topic, because it is the install that updates.
2176
+ */
2177
+ function updatePolicy(state) {
2178
+ if (!state.update || typeof state.update !== 'object') state.update = { ...UPDATE_DEFAULTS };
2179
+ return state.update;
2180
+ }
2181
+
2182
+ /** Where this install's files live. */
2183
+ function bridgeRoot() {
2184
+ return process.env.DSH_BRIDGE_ROOT || join(DSH_HOME, 'tg-bridge');
2185
+ }
2186
+
2187
+ /**
2188
+ * Replace this install's files with the given release, fetched from npm into a
2189
+ * temp dir and copied over the top: `npm install` inside the bridge's own
2190
+ * directory would drop a nested node_modules and leave the running files alone.
2191
+ * Everything else in the directory (config, state, logs, backups) is left where
2192
+ * it is. Returns the directory name the old files were saved under.
2193
+ */
2194
+ function installRelease(version) {
2195
+ const root = bridgeRoot();
2196
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
2197
+ const backup = `update-backup-${stamp}`;
2198
+ const work = join(tmpdir(), `dsh-tg-bridge-${stamp}`);
2199
+ try {
2200
+ const r = spawnSync('npm', ['install', '--no-save', '--no-audit', '--no-fund', '--prefix', work, `dsh-tg-bridge@${version}`], {
2201
+ encoding: 'utf8',
2202
+ shell: true,
2203
+ timeout: 240000,
2204
+ windowsHide: true,
2205
+ });
2206
+ if (r.status !== 0) {
2207
+ const tail = `${r.stdout || ''}${r.stderr || ''}`.trim().split(/\r?\n/).slice(-6).join('\n');
2208
+ throw new Error(`npm exited ${r.status ?? '?'}${tail ? `\n${tail}` : ''}`);
2209
+ }
2210
+ mkdirSync(join(root, backup), { recursive: true });
2211
+ for (const name of readdirSync(join(work, 'package'))) {
2212
+ const from = join(work, 'package', name);
2213
+ const to = join(root, name);
2214
+ if (existsSync(to)) copyFileSync(to, join(backup, name));
2215
+ copyFileSync(from, to);
2216
+ }
2217
+ return backup;
2218
+ } finally {
2219
+ try {
2220
+ rmSync(work, { recursive: true, force: true });
2221
+ } catch {}
2222
+ }
2223
+ }
2224
+
2171
2225
  /** Version of the bridge this process runs, read from its own package.json. */
2172
2226
  function bridgeVersion() {
2173
2227
  const root = process.env.DSH_BRIDGE_ROOT || join(DSH_HOME, 'tg-bridge');
@@ -2202,4 +2256,42 @@ function npmLatest(name) {
2202
2256
  }
2203
2257
  }
2204
2258
 
2205
- export { DSH_HOME, modelOf, modelsOf, pluginsOf, recentSessions, skillsOf, soulOf, bridgeVersion, npmLatest };
2259
+ /**
2260
+ * The same question, asked without blocking the event loop.
2261
+ *
2262
+ * The command surface may block for a second (`spawnSync` is simpler and the
2263
+ * person is waiting anyway); the poll loop may not, because a stalled `npm view`
2264
+ * there would also stop `getUpdates`.
2265
+ */
2266
+ function npmLatestAsync(name = 'dsh-tg-bridge') {
2267
+ return new Promise((resolve) => {
2268
+ let out = '';
2269
+ let child;
2270
+ try {
2271
+ child = spawn('npm', ['view', name, 'version'], { shell: true, windowsHide: true });
2272
+ } catch {
2273
+ resolve('');
2274
+ return;
2275
+ }
2276
+ const timer = setTimeout(() => {
2277
+ try {
2278
+ child.kill();
2279
+ } catch {}
2280
+ resolve('');
2281
+ }, 45000);
2282
+ child.stdout.on('data', (d) => {
2283
+ out += d;
2284
+ });
2285
+ child.on('error', () => {
2286
+ clearTimeout(timer);
2287
+ resolve('');
2288
+ });
2289
+ child.on('close', (code) => {
2290
+ clearTimeout(timer);
2291
+ const version = out.trim().split(/\s+/).pop() || '';
2292
+ resolve(code === 0 && /^\d/.test(version) ? version : '');
2293
+ });
2294
+ });
2295
+ }
2296
+
2297
+ export { DSH_HOME, modelOf, modelsOf, pluginsOf, recentSessions, skillsOf, soulOf, bridgeVersion, npmLatest, npmLatestAsync, installRelease };
package/i18n.mjs CHANGED
@@ -20,7 +20,7 @@ const DICT = {
20
20
  'status.failed': 'Turn failed',
21
21
  'status.queued': 'queued',
22
22
  'status.stop': 'Stop',
23
- '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 · /tasks\nSessions: /status · /sessions [n] · /resume \u003cid\u003e\nAgents: /agents · /agents set model|depth|filter … @tool\nModels: /model · /model \u003cid\u003e · /prices · /thoughts\nTuning: /effort · /permissions · /preset · /agentset [use|show|off|new] · /plan · /jobs · /remind\nExtensions: /skills · /plugins · /plugin add|remove · /soul\nVersions: /version · /update · /update confirm\nOther: /lang · /reasoning · /doctor · /logs [errors|N] · /app · /restart · /help",
23
+ '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 · /tasks\nSessions: /status · /sessions [n] · /resume \u003cid\u003e\nAgents: /agents · /agents set model|depth|filter … @tool\nModels: /model · /model \u003cid\u003e · /models · /prices · /thoughts\nTuning: /effort · /permissions · /preset · /agentset [use|show|off|new] · /plan · /jobs · /remind\nExtensions: /skills · /plugins · /plugin add|remove · /soul\nVersions: /version · /update [confirm|on|off|auto] · /subscribe on|off\nOther: /lang · /reasoning · /doctor · /logs [errors|N] · /app · /restart · /help",
24
24
  'btn.stop': 'Stop',
25
25
  'btn.logs': 'Logs',
26
26
  'btn.retry': 'Retry',
@@ -164,6 +164,13 @@ const DICT = {
164
164
  'ctrl.version.unknown': 'unknown',
165
165
  'ctrl.version.offline': 'unreachable',
166
166
  'ctrl.version.update': 'Update available: /update, then /update confirm',
167
+ 'ctrl.version.backup': 'Old files kept in {path}',
168
+ 'ctrl.subscribe.title': 'New releases and failures',
169
+ 'ctrl.subscribe.stateOn': 'Notices are on: one message per new version, checked at most once a day.',
170
+ 'ctrl.subscribe.stateOff': 'Notices are off. /version still shows what is published.',
171
+ 'ctrl.subscribe.on': 'Will tell you once about each new release. Nothing installs by itself.',
172
+ 'ctrl.subscribe.notice': 'Version {v} is out. /update confirm installs it; the new code loads on /restart confirm.',
173
+ 'ctrl.subscribe.off': 'No more notices. This install stays on {v}.',
167
174
  'ctrl.version.root': 'Bridge directory: {path}',
168
175
  'ctrl.version.stale': 'Files are newer than this process ({when}) — /restart confirm loads them.',
169
176
  'ctrl.version.hint': 'The new code loads after /restart confirm; the current chat keeps running until then.',
@@ -172,6 +179,7 @@ const DICT = {
172
179
  'ctrl.update.offline': 'npm is unreachable, so no version check is possible. Try again in a minute.',
173
180
  'ctrl.update.running': 'Installing {v} into the bridge directory…',
174
181
  'ctrl.update.done': 'Installed {v}. Load it: /restart confirm',
182
+ 'ctrl.update.backup': 'The way back: copy that folder over this one, or run /update confirm after a fix.',
175
183
  'ctrl.update.failed': 'The install failed (exit {code}). Nothing was changed; the bridge still runs the old code.',
176
184
  'ctrl.app.usage': 'Usage: /app restart confirm — restart the DSH app.',
177
185
  'ctrl.app.confirm': 'Restarting the app ends this chat. Repeat: /app restart confirm',
@@ -435,7 +443,7 @@ const DICT = {
435
443
  'status.failed': 'Ход не удался',
436
444
  'status.queued': 'в очереди',
437
445
  'status.stop': 'Стоп',
438
- 'help.body': "Задачу можно писать обычным текстом. Каждая ветка форума — отдельная сессия:\n\nРабота: /cd \u003cпроект\u003e · /new · /stop · /send \u003cфайл\u003e · /seed \u003cтекст\u003e\nЦели: /goal · /task · /tasks\nСессии: /status · /sessions [n] · /resume \u003cid\u003e\nАгенты: /agents · /agents set model|depth|filter … @tool\nМодели: /model · /model \u003cid\u003e · /prices · /thoughts\nНастройка: /effort · /permissions · /preset · /agentset [use|show|off|new] · /plan · /jobs · /remind\nРасширения: /skills · /plugins · /plugin add|remove · /soul\nВерсии: /version · /update · /update confirm\nПрочее: /lang · /reasoning · /doctor · /logs [errors|N] · /app · /restart · /help",
446
+ 'help.body': "Задачу можно писать обычным текстом. Каждая ветка форума — отдельная сессия:\n\nРабота: /cd \u003cпроект\u003e · /new · /stop · /send \u003cфайл\u003e · /seed \u003cтекст\u003e\nЦели: /goal · /task · /tasks\nСессии: /status · /sessions [n] · /resume \u003cid\u003e\nАгенты: /agents · /agents set model|depth|filter … @tool\nМодели: /model · /model \u003cid\u003e · /models · /prices · /thoughts\nНастройка: /effort · /permissions · /preset · /agentset [use|show|off|new] · /plan · /jobs · /remind\nРасширения: /skills · /plugins · /plugin add|remove · /soul\nВерсии: /version · /update [confirm|on|off|auto] · /subscribe on|off\nПрочее: /lang · /reasoning · /doctor · /logs [errors|N] · /app · /restart · /help",
439
447
  'btn.stop': 'Стоп',
440
448
  'btn.logs': 'Логи',
441
449
  'btn.retry': 'Повторить',
@@ -579,6 +587,13 @@ const DICT = {
579
587
  'ctrl.version.unknown': 'неизвестно',
580
588
  'ctrl.version.offline': 'недоступен',
581
589
  'ctrl.version.update': 'Есть обновление: /update, затем /update confirm',
590
+ 'ctrl.version.backup': 'Старые файлы сохранены в {path}',
591
+ 'ctrl.subscribe.title': 'Новые версии и сбои',
592
+ 'ctrl.subscribe.stateOn': 'Уведомления включены: одно сообщение на новую версию, проверка не чаще раза в сутки.',
593
+ 'ctrl.subscribe.stateOff': 'Уведомления выключены. /version по-прежнему показывает, что опубликовано.',
594
+ 'ctrl.subscribe.on': 'Сообщу один раз о каждой новой версии. Сама ничего не ставится.',
595
+ 'ctrl.subscribe.notice': 'Вышла версия {v}. /update confirm её поставит, новый код включится после /restart confirm.',
596
+ 'ctrl.subscribe.off': 'Больше не уведомляю. Установка останется на {v}.',
582
597
  'ctrl.version.root': 'Каталог моста: {path}',
583
598
  'ctrl.version.stale': 'Файлы новее запуска ({when}) — /restart confirm загрузит их.',
584
599
  'ctrl.version.hint': 'Новый код включится после /restart confirm — до этого чат работает как есть.',
@@ -587,6 +602,7 @@ const DICT = {
587
602
  'ctrl.update.offline': 'npm недоступен, проверить версию не могу. Попробуй через минуту.',
588
603
  'ctrl.update.running': 'Ставлю {v} в каталог моста…',
589
604
  'ctrl.update.done': 'Установлено {v}. Включить: /restart confirm',
605
+ 'ctrl.update.backup': 'Путь назад: скопировать этот каталог поверх текущих файлов или снова /update confirm после исправления.',
590
606
  'ctrl.update.failed': 'Установка не удалась (код {code}). Ничего не изменено, мост работает на старом коде.',
591
607
  'ctrl.app.usage': 'Использование: /app restart confirm — перезапустить приложение DSH.',
592
608
  'ctrl.app.confirm': 'Перезапуск приложения оборвёт этот чат. Повтори: /app restart confirm',
@@ -850,7 +866,7 @@ const DICT = {
850
866
  'status.failed': '运行失败',
851
867
  'status.queued': '排队中',
852
868
  'status.stop': '停止',
853
- 'help.body': "任务直接以文本发送。每个论坛话题是一个独立会话:\n\n工作: /cd \u003c项目\u003e · /new · /stop · /send \u003c文件\u003e · /seed \u003c文本\u003e\n目标: /goal · /task · /tasks\n会话: /status · /sessions [n] · /resume \u003cid\u003e\n智能体: /agents · /agents set model|depth|filter … @tool\n模型: /model · /model \u003cid\u003e · /prices · /thoughts\n调优: /effort · /permissions · /preset · /agentset [use|show|off|new] · /plan · /jobs · /remind\n扩展: /skills · /plugins · /plugin add|remove · /soul\n版本: /version · /update · /update confirm\n其他: /lang · /reasoning · /doctor · /logs [errors|N] · /app · /restart · /help",
869
+ 'help.body': "任务直接以文本发送。每个论坛话题是一个独立会话:\n\n工作: /cd \u003c项目\u003e · /new · /stop · /send \u003c文件\u003e · /seed \u003c文本\u003e\n目标: /goal · /task · /tasks\n会话: /status · /sessions [n] · /resume \u003cid\u003e\n智能体: /agents · /agents set model|depth|filter … @tool\n模型: /model · /model \u003cid\u003e · /models · /prices · /thoughts\n调优: /effort · /permissions · /preset · /agentset [use|show|off|new] · /plan · /jobs · /remind\n扩展: /skills · /plugins · /plugin add|remove · /soul\n版本: /version · /update [confirm|on|off|auto] · /subscribe on|off\n其他: /lang · /reasoning · /doctor · /logs [errors|N] · /app · /restart · /help",
854
870
  'btn.stop': '停止',
855
871
  'btn.logs': '日志',
856
872
  'btn.retry': '重试',
@@ -994,6 +1010,13 @@ const DICT = {
994
1010
  'ctrl.version.unknown': '未知',
995
1011
  'ctrl.version.offline': '不可达',
996
1012
  'ctrl.version.update': '有更新:/update,然后 /update confirm',
1013
+ 'ctrl.version.backup': '旧文件保存在 {path}',
1014
+ 'ctrl.subscribe.title': '新版本与故障',
1015
+ 'ctrl.subscribe.stateOn': '通知开启:每个新版本只发一条,每天最多检查一次。',
1016
+ 'ctrl.subscribe.stateOff': '通知已关闭。/version 仍会显示已发布的内容。',
1017
+ 'ctrl.subscribe.on': '每个新版本会通知一次,不会自行安装。',
1018
+ 'ctrl.subscribe.notice': '新版本 {v} 已发布。/update confirm 安装,/restart confirm 后生效。',
1019
+ 'ctrl.subscribe.off': '不再通知。此安装保持在 {v}。',
997
1020
  'ctrl.version.root': '桥接目录:{path}',
998
1021
  'ctrl.version.stale': '文件比本进程更新({when})—— /restart confirm 后生效。',
999
1022
  'ctrl.version.hint': '新代码在 /restart confirm 之后生效;在此之前聊天照常运行。',
@@ -1002,6 +1025,7 @@ const DICT = {
1002
1025
  'ctrl.update.offline': 'npm 不可达,无法检查版本。请稍后再试。',
1003
1026
  'ctrl.update.running': '正在把 {v} 安装到桥接目录…',
1004
1027
  'ctrl.update.done': '已安装 {v}。加载它:/restart confirm',
1028
+ 'ctrl.update.backup': '回退方法:把该目录覆盖回来,或在修复后再执行 /update confirm。',
1005
1029
  'ctrl.update.failed': '安装失败(退出码 {code})。没有做任何更改,桥接仍运行旧代码。',
1006
1030
  'ctrl.app.usage': '用法:/app restart confirm —— 重启 DSH 应用。',
1007
1031
  'ctrl.app.confirm': '重启应用会中断这个聊天。请重发:/app restart confirm',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-tg-bridge",
3
- "version": "1.13.2",
3
+ "version": "1.14.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",
@@ -56,6 +56,7 @@
56
56
  "goal.mjs",
57
57
  "format.mjs",
58
58
  "i18n.mjs",
59
+ "update-policy.mjs",
59
60
  "media-text.mjs",
60
61
  "albums.mjs",
61
62
  "prices.mjs",
@@ -0,0 +1,130 @@
1
+ // Version policy: the npm tag `latest` is a label, not an updater. Nothing on a
2
+ // machine moves to a new release unless something moves it — `npx` on a fresh
3
+ // run, `npm i -g`, or a scheduled job. This module is the decision half of that
4
+ // (what to do about a release), kept apart from the bridge so it can be tested
5
+ // without a bot, a network or a profile.
6
+ //
7
+ // Modes, one per install (a global setting, because it is the install that
8
+ // updates, not a topic):
9
+ //
10
+ // off never touch the files; `/version` still reports whether a release exists
11
+ // check notice once per new version, never update on its own (the default)
12
+ // auto fetch and install a new release on its own; the person restarts
13
+ //
14
+ // In every mode the running process keeps its modules until `/restart confirm`:
15
+ // an update that replaced files under a live turn would be the one change nobody
16
+ // can debug. So "auto" means "the files are already new when you say restart".
17
+
18
+ /** Modes a person can pick, in the order `/update` lists them. */
19
+ export const UPDATE_MODES = ['off', 'check', 'auto'];
20
+
21
+ /**
22
+ * The version the bridge should run: the newest published one that is not newer
23
+ * than the line this install was made for.
24
+ *
25
+ * Version 1 of this policy is just "the published latest". The shape is here
26
+ * because the alternative — always taking `latest` — is what hands a person a
27
+ * 0.3.0 prerelease the day it appears, and the pin has to live in the stored
28
+ * version string (this bridge's own version), not in a second field nobody
29
+ * remembers to bump.
30
+ */
31
+ export function targetVersion(latest) {
32
+ return latest || '';
33
+ }
34
+
35
+ /** Compare two dotted versions; 1 when a > b, -1 when a < b, 0 when equal. */
36
+ export function compareVersions(a = '', b = '') {
37
+ const parse = (v) => String(v).split('-')[0].split('.').map((n) => Number.parseInt(n, 10) || 0);
38
+ const [x, y] = [parse(a), parse(b)];
39
+ for (let i = 0; i < Math.max(x.length, y.length); i += 1) {
40
+ const d = (x[i] || 0) - (y[i] || 0);
41
+ if (d !== 0) return d > 0 ? 1 : -1;
42
+ }
43
+ return 0;
44
+ }
45
+
46
+ /**
47
+ * What `/version` (or a notice) should say about where this install stands.
48
+ *
49
+ * Inputs are the stored settings and the numbers we could get; the answer never
50
+ * promises a network call succeeded when it did not, because "you are up to
51
+ * date" printed offline is worse than "could not check".
52
+ */
53
+ export function updateState({ installed = '', latest = '', mode = 'check', notified = '', checkedAt = 0, now = Date.now() }) {
54
+ const result = { mode: UPDATE_MODES.includes(mode) ? mode : 'check', installed, latest, behind: false, notify: false, auto: false };
55
+ if (!latest) return result; // npm unreachable: nothing is known, nothing changes
56
+ const target = targetVersion(latest);
57
+ result.target = target;
58
+ const cmp = installed ? compareVersions(target, installed) : 1;
59
+ result.behind = cmp > 0;
60
+ // One notice per version, and never the version already running.
61
+ result.notify = result.behind && notified !== target && result.mode !== 'off';
62
+ result.auto = result.behind && result.mode === 'auto';
63
+ result.checkedAt = checkedAt || now;
64
+ return result;
65
+ }
66
+
67
+ /**
68
+ * How often to ask npm, per mode. A release is not a second-to-second event and
69
+ * `npm view` is a network round trip from a machine that may be on a slow link,
70
+ * so hourly for auto is often enough; the ordinary install is asked once a day.
71
+ */
72
+ export function checkIntervalMs(mode = 'check') {
73
+ if (mode === 'off') return 0;
74
+ if (mode === 'auto') return 60 * 60 * 1000;
75
+ return 24 * 60 * 60 * 1000;
76
+ }
77
+
78
+ /** Should a check run now? */
79
+ export function dueForCheck({ mode = 'check', checkedAt = 0, now = Date.now() }) {
80
+ const interval = checkIntervalMs(mode);
81
+ return interval > 0 && now - checkedAt >= interval;
82
+ }
83
+
84
+ /** One line for `/version`, no markdown (the bridge sends plain text). */
85
+ export function describeUpdate(state) {
86
+ const { installed, target, mode, latest } = state;
87
+ const have = installed ? `installed ${installed}` : 'installed version unknown';
88
+ if (!latest) return `${have}; the registry did not answer, so a newer release is unknown.`;
89
+ if (!state.behind) return `${have}; ${target} is the newest published one.`;
90
+ const how =
91
+ mode === 'auto'
92
+ ? `auto-update is on: ${latest} will be installed, then /restart confirm loads it`
93
+ : mode === 'off'
94
+ ? 'auto-update is off: /update confirm installs it'
95
+ : `notified once: /update on turns the notice off, /update confirm installs it`;
96
+ return `${have}, ${latest} is out. ${how}.`;
97
+ }
98
+
99
+ /**
100
+ * What `/update on|off|check` has to do to leave the install where the person
101
+ * asked it to be.
102
+ *
103
+ * One rule, said plainly: `off` and `on` mean "stay on the version I have now",
104
+ * because only an install that is already up to date would otherwise read the
105
+ * switch as "stop telling me, and also never update". Going back to following
106
+ * releases is `npm i -g dsh-tg-bridge@latest` or `npx dsh-tg@latest setup` — the
107
+ * command that also proves the new version starts.
108
+ */
109
+ export function modeChange({ installed = '', latest = '', command = '' } = {}) {
110
+ if (command === 'off') {
111
+ return {
112
+ store: { mode: 'off', pinned: installed, notified: latest },
113
+ text: `update checks are off; this install stays on ${installed || 'its current version'}${latest && latest !== installed ? `, and ${latest} is waiting for /update confirm` : ''}`,
114
+ };
115
+ }
116
+ if (command === 'check') return { store: { mode: 'check', pinned: '', notified: '' }, text: 'a notice appears once per new version; nothing installs by itself' };
117
+ if (command === 'auto') {
118
+ // Only an install already on the newest release can follow releases again:
119
+ // switching the policy on top of an old version would mean two updates at
120
+ // once, one of them unattended.
121
+ if (latest && installed && compareVersions(installed, latest) < 0) {
122
+ return { store: null, text: `this install is still on ${installed}; run /update confirm first, then /update auto` };
123
+ }
124
+ return { store: { mode: 'auto', pinned: '', notified: '' }, text: 'new releases install by themselves; /restart confirm loads them' };
125
+ }
126
+ return { store: null, text: 'use: /update (status) · off · check · auto · confirm', invalid: true };
127
+ }
128
+
129
+ /** Storage shape for the settings file, so callers agree on one place. */
130
+ export const UPDATE_DEFAULTS = { mode: 'check', notified: '', checkedAt: 0, pinned: '' };