dsh-tg-bridge 1.17.0 → 1.19.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
@@ -82,7 +82,7 @@ Everything below is typed in the chat, not in a terminal.
82
82
  | Cheaper or stronger model | `/model` then pick, or `/model <id>` |
83
83
  | More freedom for commands | `/permissions` |
84
84
  | See what it is doing | it posts a live progress message; `/thoughts` toggles the 💭 notes |
85
- | A plan you can tick off | `/goal <what done looks like>`, then `/task <step>`, then `/tasks` to tap items |
85
+ | A plan you can tick off | `/goal <what done looks like>`, then `/task <step>`, then bare `/task` to tap items |
86
86
  | Stop a long answer | `/stop` |
87
87
  | Tell me about new versions, or stop | /update on / /update off — neither one installs anything |
88
88
  | Install an update, then load it | /update confirm, then /restart confirm |
package/README.md CHANGED
@@ -22,9 +22,9 @@ a bot that answers, one step at a time.
22
22
  the model's reasoning in a collapsed block you can tap open. A long turn adds a second
23
23
  collapsed block with every tool call, so the whole run stays in the chat as one message.
24
24
  - **No lost messages**: a journal with acknowledgement and replay.
25
- - **Settings per topic**: `/agentset use reviewer` gives one topic its own model,
25
+ - **Settings per topic**: `/crew use reviewer` gives one topic its own model,
26
26
  effort, permissions, agent preset and language while the others keep the profile;
27
- `/agentset off` returns it. Four built-in sets ship read-only and can be copied.
27
+ `/crew off` returns it. Four built-in sets ship read-only and can be copied.
28
28
  - **Fail-fast**: when the quota runs out it switches to a free model right away.
29
29
  - **`dsh-tg check`**: diagnostics in one command, no changes to the system.
30
30
  - **Languages**: menus and service messages in `en`, `ru`, `zh`; `/lang` pins the topic language, and without it a new topic takes the language of the message itself (Cyrillic → `ru`, Han characters → `zh`), then the Telegram `language_code`, then `en`.
@@ -165,6 +165,7 @@ Error replies end with a code, which tells you what to fix:
165
165
  | `SANDBOX_DENY` | DSH denied access to a file or directory: check the project path and permissions |
166
166
  | `UNKNOWN_MODEL` | the model from the config is unavailable: `/model` lists the working ones |
167
167
  | `EMPTY_RESPONSE` | the model returned nothing: retry or switch model (`/model`) |
168
+ | `TURN_TIME_CAP` | the turn hit its own time ceiling: the work is saved, press Continue |
168
169
  | `TURN_FAILED` | cause not recognized: `/doctor` and `/logs errors` |
169
170
 
170
171
  ## Checks
@@ -185,14 +186,14 @@ Send the bot:
185
186
 
186
187
  ```
187
188
  Work: /cd · /new · /stop · /send · /seed
188
- Goals: /goal · /task · /tasks
189
+ Goals: /goal · /task · /task done|rm <n>
189
190
  Sessions: /status · /sessions · /resume
190
191
  Agents: /agents · /agents <id> · /agents set model|depth|filter
191
- Models: /model · /model <id> · /models · /prices
192
+ Models: /model · /model <id> · /prices
192
193
  Tuning: /effort · /permissions · /preset · /plan · /jobs · /remind
193
194
  Profiles: /profile · /profile <name> · /profile new <name> from <template>
194
- Sets: /agentset · /agentset use|off|new|copy|rm · /agentset model <v>
195
- Extensions: /skills · /plugins · /plugin disable|enable <id> · /soul
195
+ Sets: /crew · /crew use|off|new|copy|rm · /crew model <v>
196
+ Extensions: /skills · /plugins · /plugins disable|enable <id> · /soul
196
197
  Updates: /version · /update · /update confirm · /update on|off|check|auto · /subscribe on|off
197
198
  Diagnostics: /doctor · /logs [errors|N|text]
198
199
  Service: /app · /restart · /help
@@ -212,7 +213,7 @@ delete it and the chat is back to what it was.
212
213
 
213
214
  Nothing on the card is only available on the card. `/settings` is for people who
214
215
  would rather press a labelled button than remember which of `/effort`,
215
- `/preset` and `/agentset` changes what.
216
+ `/preset` and `/crew` changes what.
216
217
 
217
218
  Every command answers `/help` in the chat, in the language you write in: a
218
219
  message written in Cyrillic or Han characters switches the topic to Russian or
package/bridge.mjs CHANGED
@@ -30,6 +30,8 @@ import { createAlbumBuffer } from './albums.mjs';
30
30
  import { turnArgs } from './cli-args.mjs';
31
31
  import { chunk, markdownParts, toPlainText, toTelegramHtml } from './format.mjs';
32
32
  import { ensureProfile } from './profiles.mjs';
33
+ import { firstLiveModel, describeVerdicts, probeHint, probeModel } from './model-probe.mjs';
34
+ import { explainFailure } from './failures.mjs';
33
35
  import { handleControl, CONTROL_COMMANDS, modelOf, modelsOf, reasoningOf } from './control.mjs';
34
36
  import { bridgeVersion, installRelease, npmLatestAsync } from './control.mjs';
35
37
  import { dueForCheck, updateState } from './update-policy.mjs';
@@ -47,7 +49,7 @@ import { commandFor, renderSettingsCard, settingsCurrent } from './settings-card
47
49
  import { answerRewindPress, cutSession, isRewindPress } from './rewind-buttons.mjs';
48
50
  import { applyRewind, newestBackup, restoreBackup } from './rewind.mjs';
49
51
  import { sessionFile } from './thoughts.mjs';
50
- import { MENU_PREFIX, commandForName, isMenuPress, renderPanel } from './menu-card.mjs';
52
+ import { MENU_PREFIX, commandForName, isMenuPress, keyboardCommand, menuTarget, renderPanel, runsUnasked } from './menu-card.mjs';
51
53
 
52
54
  const HOME = homedir();
53
55
  const DSH_HOME = process.env.DSH_HOME || join(HOME, '.dsh');
@@ -802,6 +804,42 @@ function topicName(chatId, threadId) {
802
804
  * a button cannot do is money or state the person did not mean — so a press
803
805
  * never falls through to an AI turn.
804
806
  */
807
+ /**
808
+ * A message that carries buttons. Inline rows are the usual case; a persistent
809
+ * reply keyboard (`/menu on`) and taking it away again are the two other markup
810
+ * shapes a person can end up with, so every call site hands its intent here
811
+ * instead of building `reply_markup` itself.
812
+ */
813
+ async function sendWithMarkup(chatId, threadId, text, extra = {}) {
814
+ const thread = threadId > 0 ? { message_thread_id: threadId } : {};
815
+ if (extra.removeKeyboard) {
816
+ return tg('sendMessage', {
817
+ chat_id: chatId,
818
+ text,
819
+ reply_markup: { remove_keyboard: true },
820
+ ...thread,
821
+ }).catch(() => {});
822
+ }
823
+ if (extra.persistent) {
824
+ return tg('sendMessage', {
825
+ chat_id: chatId,
826
+ text,
827
+ reply_markup: { keyboard: extra.persistent, resize_keyboard: true, is_persistent: true },
828
+ ...thread,
829
+ }).catch(() => {});
830
+ }
831
+ if (extra.keyboard) {
832
+ return tg('sendMessage', {
833
+ chat_id: chatId,
834
+ text,
835
+ disable_web_page_preview: true,
836
+ reply_markup: { inline_keyboard: extra.keyboard },
837
+ ...thread,
838
+ }).catch(() => {});
839
+ }
840
+ return send(chatId, text, threadId);
841
+ }
842
+
805
843
  async function runCommandFromButton(typed, { chatId, threadId, key }) {
806
844
  const lang = langFor(chatId, threadId);
807
845
  const [head, ...rest] = typed.trim().split(/\s+/);
@@ -829,15 +867,7 @@ async function runCommandFromButton(typed, { chatId, threadId, key }) {
829
867
  sendFile: (p, caption = '') => sendFile(chatId, threadId, p, caption),
830
868
  seedTopic: ensureTopicSeed,
831
869
  profile: profileOf(key),
832
- reply: (out, extra = {}) => (extra.keyboard
833
- ? tg('sendMessage', {
834
- chat_id: chatId,
835
- text: out,
836
- disable_web_page_preview: true,
837
- reply_markup: { inline_keyboard: extra.keyboard },
838
- ...(threadId > 0 ? { message_thread_id: threadId } : {}),
839
- }).catch(() => {})
840
- : send(chatId, out, threadId)),
870
+ reply: (out, extra = {}) => sendWithMarkup(chatId, threadId, out, extra),
841
871
  stopTurn: (k) => {
842
872
  const child = activeTurns.get(k);
843
873
  if (!child) return false;
@@ -1555,6 +1585,20 @@ async function handleMessage(msg, album = null) {
1555
1585
  }
1556
1586
  }
1557
1587
 
1588
+ // A tap on the persistent keyboard (`/menu on`) arrives as its own label,
1589
+ // with no slash: "Меню", "Статус", "Стоп", "Новый". Only while the keyboard is
1590
+ // on — the same word typed by hand is a prompt, not a command. The label is
1591
+ // matched in every language, because the keyboard outlives a /lang switch.
1592
+ if (state.menu?.[key]) {
1593
+ const mapped = ['ru', 'en', 'zh']
1594
+ .map((code) => keyboardCommand(text, { t: (k, v) => t(code, k, v) }))
1595
+ .find(Boolean);
1596
+ if (mapped) {
1597
+ log(`menu key "${text}" -> ${mapped} for ${key}`);
1598
+ text = mapped;
1599
+ }
1600
+ }
1601
+
1558
1602
  const space = text.indexOf(' ');
1559
1603
  const head = space === -1 ? text : text.slice(0, space);
1560
1604
  const command = commandOf(head);
@@ -1639,15 +1683,7 @@ ${t(lang, 'help.body')}`,
1639
1683
  lang,
1640
1684
  });
1641
1685
  },
1642
- reply: (out, extra = {}) => (extra.keyboard
1643
- ? tg('sendMessage', {
1644
- chat_id: chatId,
1645
- text: out,
1646
- disable_web_page_preview: true,
1647
- reply_markup: { inline_keyboard: extra.keyboard },
1648
- ...(threadId > 0 ? { message_thread_id: threadId } : {}),
1649
- }).catch(() => {})
1650
- : send(chatId, out, threadId)),
1686
+ reply: (out, extra = {}) => sendWithMarkup(chatId, threadId, out, extra),
1651
1687
  stopTurn: (k) => {
1652
1688
  const child = activeTurns.get(k);
1653
1689
  if (!child) return false;
@@ -1756,10 +1792,24 @@ ${t(lang, 'help.body')}`,
1756
1792
  // chain as well, otherwise the bridge sits on AUTH 403 and gives up.
1757
1793
  const FALLBACK_TRIGGERS = /RATE_LIMIT|503|all providers|нет активности|EMPTY_RESPONSE|TIMEOUT|overloaded|AUTH|403|insufficient_user_quota|quota|UNKNOWN_MODEL|MISSING_CREDENTIAL/i;
1758
1794
  const QUOTA_LIKE = /insufficient_user_quota|AUTH\b|\b403\b|\b401\b|quota|balance|баланс|payment|billing/i;
1795
+ // "get_channel_failed / all providers are busy" is the provider's own channel
1796
+ // pool, not the model: when it is down, it is down for every model in the
1797
+ // chain. One probe then answers in seconds what four full turns spent 741
1798
+ // seconds discovering.
1799
+ const CHANNEL_DOWN = /get_channel_failed|all providers|no providers|503/i;
1759
1800
  const tried = [];
1760
1801
  for (const entry of chain) {
1761
1802
  if (!result.error || !FALLBACK_TRIGGERS.test(result.error)) break;
1762
1803
  if (!entry.patch || !existsSync(entry.patch)) continue;
1804
+ // The provider's channel pool is down: every model in the chain will answer
1805
+ // the same 503. Ask once, quickly, and say so instead of burning a turn per
1806
+ // model. A probe that DOES answer proves the pool is back — then the chain
1807
+ // goes on, and the fallback at hand is tried as usual.
1808
+ if (tried.length >= 1 && CHANNEL_DOWN.test(result.error)) {
1809
+ const verdict = await probeModel(config.primaryModel || 'deepseek-v4.1-flash-1017');
1810
+ log(`channel down after ${tried.length} model(s): probe says ${verdict.kind}; not trying ${entry.model}`);
1811
+ if (!verdict.ok) break;
1812
+ }
1763
1813
  const quotaLike = QUOTA_LIKE.test(result.error);
1764
1814
  // Quota failures never deserve a retry of the same model: the balance is
1765
1815
  // gone, so waiting is pure loss. Anything else gets one retry at most.
@@ -1785,13 +1835,41 @@ ${t(lang, 'help.body')}`,
1785
1835
  });
1786
1836
  if (!result.error) break;
1787
1837
  }
1788
- // Every model refused: one message naming the causes, not a cascade of errors.
1789
- if (result.error && tried.length > 0 && tried.length >= (Array.isArray(config.fallbackModels) ? config.fallbackModels.length : 0)) {
1790
- log(`all fallbacks exhausted for ${where}: ${tried.length}`);
1838
+ // Every model refused. Before saying "all models are unavailable", ask each
1839
+ // channel directly with a 1-token request: a 503 storm usually clears within
1840
+ // seconds, and the verdict tells the person whether the balance is gone or the
1841
+ // provider is merely busy — the old message always claimed quota.
1842
+ let probeKind = '';
1843
+ if (result.error && FALLBACK_TRIGGERS.test(result.error)) {
1844
+ const models = [config.primaryModel || 'deepseek-v4.1-flash-1017', ...chain.map((entry) => entry.model)];
1845
+ const { live, verdicts } = await firstLiveModel(models);
1846
+ if (live) {
1847
+ log(`probe: ${live.model} answers after ${verdicts.length} check(s), retrying the turn there`);
1848
+ const entry = chain.find((item) => item.model === live.model);
1849
+ result = await runTurnLive(text, sessionAtStart, key, {
1850
+ onEvent,
1851
+ onAbort: () => killTurn(key),
1852
+ onHeartbeat: () => progress.heartbeat(),
1853
+ profile: entry ? ensureProfile(entry.patch) : turnProfile,
1854
+ cwd,
1855
+ lang,
1856
+ });
1857
+ } else {
1858
+ // Nothing answers: the verdict is the only useful part of the failure.
1859
+ probeKind = describeVerdicts(verdicts);
1860
+ log(`probe: no channel answers (${verdicts.map((v) => `${v.model}:${v.kind}`).join(', ')})`);
1861
+ }
1862
+ }
1863
+ // Every model refused — or the provider's own channel pool was down and the
1864
+ // chain stopped early, which is the same answer to the person: one message
1865
+ // naming the causes, not a cascade of errors.
1866
+ if (result.error && tried.length > 0 && (probeKind || tried.length >= (Array.isArray(config.fallbackModels) ? config.fallbackModels.length : 0))) {
1867
+ log(`all fallbacks exhausted for ${where}: ${tried.length} probe=${probeKind || 'n/a'}`);
1868
+ const verdictLine = probeKind ? `\n${probeHint(probeKind, lang)}` : '';
1791
1869
  result = {
1792
1870
  sessionId: result.sessionId,
1793
1871
  text: '',
1794
- error: t(lang, 'bridge.fallback.allDown', { list: tried.map((line) => `• ${line}`).join('\n') }),
1872
+ error: t(lang, 'bridge.fallback.allDown', { list: tried.map((line) => `• ${line}`).join('\n') }) + verdictLine,
1795
1873
  };
1796
1874
  }
1797
1875
  // A session opened in the desktop UI holds its write handle, so the CLI
@@ -1844,39 +1922,9 @@ ${t(lang, 'help.body')}`,
1844
1922
  await send(chatId, result.text || t(lang, 'bridge.progress.emptyReply'), threadId);
1845
1923
  }
1846
1924
 
1847
- /**
1848
- * Turn a raw CLI/provider error into `CODE` plus one actionable line.
1849
- *
1850
- * Raw text like `AUTH 403 insufficient_user_quota` means nothing to a person on
1851
- * a phone; the code makes the failure greppable and the hint says what to do.
1852
- */
1853
- function explainFailure(text, lang = 'ru') {
1854
- const raw = String(text);
1855
- // The regular expressions match the CLI's and the provider's own words, so
1856
- // they stay as they are; only the hint on the right follows the topic language.
1857
- const cases = [
1858
- [/insufficient_user_quota|insufficient quota|AUTH\b|\b402\b|\bbalance\b|баланс|billing/i,
1859
- 'INSUFFICIENT_QUOTA', 'bridge.fail.quota'],
1860
- [/Conflict: terminated by other getUpdates|\b409\b/i,
1861
- 'TG_CONFLICT', 'bridge.fail.conflict'],
1862
- [/MISSING_CREDENTIAL|no credentials|not authenticated/i,
1863
- 'MISSING_CREDENTIAL', 'bridge.fail.noCredential'],
1864
- [/ENOENT|not recognized|не найден.*dsh|dsh\.cmd/i,
1865
- 'NO_DSH_CLI', 'bridge.fail.noCli'],
1866
- [/fetch failed|ETIMEDOUT|ECONNREFUSED|ENOTFOUND|socket hang up|network/i,
1867
- 'NETWORK', 'bridge.fail.network'],
1868
- [/EACCES|EPERM|access is denied|отказано в доступе|sandbox|permission denied/i,
1869
- 'SANDBOX_DENY', 'bridge.fail.sandbox'],
1870
- [/UNKNOWN_MODEL|model not found|no such model/i,
1871
- 'UNKNOWN_MODEL', 'bridge.fail.unknownModel'],
1872
- [/empty response|EMPTY_RESPONSE|no output|пустой ответ/i,
1873
- 'EMPTY_RESPONSE', 'bridge.fail.empty'],
1874
- ];
1875
- for (const [re, code, hint] of cases) {
1876
- if (re.test(raw)) return `${raw}\n\n${code}: ${t(lang, hint)}`;
1877
- }
1878
- return `${raw}\n\nTURN_FAILED: ${t(lang, 'bridge.fail.generic')}`;
1879
- }
1925
+ // `probeHint` lives in model-probe.mjs: this file used it at the call site and
1926
+ // defined it below, and the hint never reached the person.
1927
+
1880
1928
 
1881
1929
  // Per-topic turn queues: one turn at a time inside a topic, different topics run
1882
1930
  // in parallel. Bounded, because every turn is a full Electron process.
@@ -2301,29 +2349,60 @@ async function handleCallback(query) {
2301
2349
  return;
2302
2350
  }
2303
2351
 
2352
+ if (data.startsWith('fk:')) {
2353
+ // A branch button from /branches. It does what `/resume <id>` does, so the
2354
+ // topic moves onto that branch and the answer comes from the command
2355
+ // itself — one implementation, one sentence.
2356
+ const wanted = data.slice(3);
2357
+ if (!/^session-[0-9a-f-]{36}$/.test(wanted)) {
2358
+ await answer(t(lang, 'bridge.cb.unknown'));
2359
+ return;
2360
+ }
2361
+ await clearKeyboard();
2362
+ await runCommandFromButton(`/resume ${wanted.slice(8)}`, { chatId, threadId, key, lang });
2363
+ return;
2364
+ }
2365
+
2304
2366
  if (isMenuPress(data)) {
2305
- // The panel. A press is exactly a typed command, so it goes through the same
2306
- // `handleControl`; the card is replaced by whatever that command answers, and
2307
- // if it draws a card of its own (settings, rewind) this one is simply gone.
2308
- // `mn:g:<group>` switches tabs in place — that is the only press that does
2309
- // not run a command.
2310
- const [verb, name] = data.slice(MENU_PREFIX.length).split(':');
2311
- if (verb === 'g') {
2312
- const card = renderPanel({ t: (k, v) => t(lang, k, v), page: name });
2313
- if (card) {
2314
- await tg('editMessageText', {
2315
- chat_id: chatId,
2316
- message_id: messageId,
2317
- text: card.text,
2318
- reply_markup: { inline_keyboard: card.keyboard },
2319
- ...(threadId > 0 ? { message_thread_id: threadId } : {}),
2320
- }).catch(() => {});
2321
- await answer(t(lang, 'bridge.cb.done'));
2322
- return;
2323
- }
2367
+ // The panel is a set of cards: the hub, then one page per section. Moving
2368
+ // between them edits this message, so browsing costs no new messages. A
2369
+ // command press is exactly a typed command, so it goes through the same
2370
+ // `handleControl`; the card is replaced by whatever that command answers.
2371
+ const target = menuTarget(data);
2372
+ if (target.kind === 'hub' || target.kind === 'section') {
2373
+ const card = renderPanel({ t: (k, v) => t(lang, k, v), page: target.page || '' });
2374
+ await tg('editMessageText', {
2375
+ chat_id: chatId,
2376
+ message_id: messageId,
2377
+ text: card.text,
2378
+ reply_markup: { inline_keyboard: card.keyboard },
2379
+ ...(threadId > 0 ? { message_thread_id: threadId } : {}),
2380
+ }).catch(() => {});
2381
+ await answer(t(lang, 'bridge.cb.done'));
2382
+ return;
2383
+ }
2384
+ if (target.kind === 'close') {
2385
+ // The card collapses into one line that can be deleted by hand, and the
2386
+ // buttons go with it: a panel that stays open is a panel that lies about
2387
+ // being closed.
2388
+ await tg('editMessageText', {
2389
+ chat_id: chatId,
2390
+ message_id: messageId,
2391
+ text: t(lang, 'ctrl.menu.closed'),
2392
+ reply_markup: { inline_keyboard: [] },
2393
+ ...(threadId > 0 ? { thread_id: threadId, message_thread_id: threadId } : {}),
2394
+ }).catch(() => {});
2395
+ await answer(t(lang, 'ctrl.menu.closedToast'));
2396
+ log(`menu closed for ${key}`);
2397
+ return;
2324
2398
  }
2399
+ const name = target.kind === 'command' ? target.name : '';
2325
2400
  await clearKeyboard();
2326
- const typed = commandForName(name, { t: (k, v) => t(lang, k, v) });
2401
+ // `/new` and `/stop` change something when typed alone, and a stray tap on
2402
+ // them is a command nobody asked for — so they open their explanation.
2403
+ const typed = runsUnasked(name) && CONTROL_COMMANDS.includes(name)
2404
+ ? commandForName(name, { t: (k, v) => t(lang, k, v) })
2405
+ : `/help ${name}`;
2327
2406
  await answer(typed || t(lang, 'bridge.cb.unknown'));
2328
2407
  if (!typed) return;
2329
2408
  log(`menu press /${name} for ${key}`);
@@ -2908,4 +2987,4 @@ async function main() {
2908
2987
  }
2909
2988
  }
2910
2989
 
2911
- main();
2990
+ main();
package/control.mjs CHANGED
@@ -17,10 +17,10 @@ import { setRowConfig, unsetRowConfig } from './profile-edit.mjs';
17
17
  import { parseReminder, stampAt, upcoming } from './reminders.mjs';
18
18
  import { AgentsetStore, emptySet, slugId } from './agentsets.mjs';
19
19
  import { SETTINGS_PAGES, renderSettingsCard, settingsCurrent } from './settings-card.mjs';
20
- import { planRewind } from './rewind.mjs';
20
+ import { applyFork, planFork, planRewind } from './rewind.mjs';
21
21
  import { cutSession, isRewindPress } from './rewind-buttons.mjs';
22
22
  import { renderRewindCard, renderRewindUsage } from './rewind-card.mjs';
23
- import { MENU_GROUPS, commandForName, renderPanel } from './menu-card.mjs';
23
+ import { MENU_GROUPS, commandForName, renderPanel, replyKeyboard } from './menu-card.mjs';
24
24
  import { explainCommand } from './help-explain.mjs';
25
25
  import { profileValues, resolveSettings } from './settings.mjs';
26
26
  import { UPDATE_DEFAULTS, describeUpdate, modeChange, updateState } from './update-policy.mjs';
@@ -673,10 +673,30 @@ export const CONTROL_COMMANDS = [
673
673
  'jobs', 'remind', 'sessions', 'resume', 'plugins', 'plugin',
674
674
  'skills', 'soul', 'restart', 'app', 'stop', 'new', 'seed', 'send', 'cd',
675
675
  'prices', 'help', 'doctor', 'logs', 'lang', 'reasoning', 'goal', 'task', 'tasks',
676
- 'thoughts', 'version', 'update', 'agentset', 'subscribe', 'settings',
677
- 'rewind', 'menu',
676
+ 'thoughts', 'version', 'update', 'crew', 'agentset', 'subscribe', 'settings',
677
+ 'rewind', 'fork', 'branches', 'menu',
678
678
  ];
679
679
 
680
+ /**
681
+ * Old spellings that no longer have a job of their own. A phone keyboard turns
682
+ * `task` into `tasks` and `model` into `models` without the person noticing, so
683
+ * each pair is ONE command: one name in `/help` and the panel, and the other
684
+ * spelling quietly routed to it. A name that is documented is a name a person
685
+ * can mistype; a name that is not documented is a name nobody has to remember.
686
+ */
687
+ export const COMMAND_ALIASES = {
688
+ tasks: 'task',
689
+ models: 'model',
690
+ plugin: 'plugins',
691
+ agentset: 'crew',
692
+ };
693
+
694
+ /**
695
+ * What `/help`, the panel and the Telegram menu are allowed to say. Aliases are
696
+ * deliberately absent: they work, and they are never advertised.
697
+ */
698
+ export const DOCUMENTED_COMMANDS = CONTROL_COMMANDS.filter((name) => !COMMAND_ALIASES[name]);
699
+
680
700
  /**
681
701
  * Working notes ("💭" lines in the progress message) are on unless the topic or
682
702
  * the config says otherwise. Per-topic wins over the install default, so one
@@ -723,11 +743,16 @@ export async function handleControl(ctx) {
723
743
  // without one it follows the install default.
724
744
  const activeProfile = profile || config.profile || 'headless';
725
745
 
746
+ // Old spellings of a command route to the one name that owns the job, before
747
+ // anything else looks at the argument.
748
+ const bare = command.startsWith('/') ? command.slice(1) : command;
749
+ const canonical = COMMAND_ALIASES[bare];
750
+ let effective = canonical ? `/${canonical}` : command;
751
+
726
752
  // One command for one job: `/plugins` is both the list and the way to change
727
753
  // things. Two near-identical names (`/plugin` / `/plugins`) invited the exact
728
754
  // mistake of typing the plural with an action. The singular form stays as an
729
755
  // alias so old instructions and muscle memory keep working.
730
- let effective = command;
731
756
  if (effective === '/plugins') {
732
757
  const [maybeAction] = String(arg || '').trim().split(/\s+/);
733
758
  // `/plugins add|remove|disable|enable …` is the same work as `/plugin …`;
@@ -1721,11 +1746,28 @@ export async function handleControl(ctx) {
1721
1746
  }
1722
1747
 
1723
1748
  case '/menu': {
1724
- // The panel: a few buttons, one per job, and each of them runs the command
1725
- // a person would otherwise have to spell. It replaces itself on a press,
1726
- // which is why nothing here tries to stay in the chat.
1749
+ // Two ways in. `/menu` is the hub card: six sections, each one a page of
1750
+ // commands that replace the card in place, so nobody has to spell a
1751
+ // command and the chat keeps one message instead of a wall of them.
1752
+ // `/menu on|off` is the other way: a Telegram reply keyboard under the
1753
+ // message field, which is what a person who does not read commands at all
1754
+ // needs — and it can be taken away again.
1727
1755
  const page = String(arg || '').trim().toLowerCase();
1728
- const card = renderPanel({ t: (k, vars) => t(lang, k, vars), page: MENU_GROUPS.includes(page) ? page : MENU_GROUPS[0] });
1756
+ if (page === 'on' || page === 'off') {
1757
+ state.menu = state.menu || {};
1758
+ state.menu[key] = page === 'on';
1759
+ ctx.saveState();
1760
+ log(`menu keyboard ${page} for ${key}`);
1761
+ await reply(
1762
+ t(lang, page === 'on' ? 'ctrl.menu.keyOn' : 'ctrl.menu.keyOff'),
1763
+ page === 'on' ? { persistent: replyKeyboard({ t: (k, vars) => t(lang, k, vars) }) } : { removeKeyboard: true },
1764
+ );
1765
+ return true;
1766
+ }
1767
+ const card = renderPanel({
1768
+ t: (k, vars) => t(lang, k, vars),
1769
+ page: MENU_GROUPS.includes(page) ? page : '',
1770
+ });
1729
1771
  await reply(card.text, { keyboard: card.keyboard });
1730
1772
  return true;
1731
1773
  }
@@ -1769,6 +1811,57 @@ export async function handleControl(ctx) {
1769
1811
  return true;
1770
1812
  }
1771
1813
 
1814
+ case '/fork': {
1815
+ // The desktop app's "branch from here", without losing the road you were
1816
+ // on: the session is not cut, a copy of it up to the branch point becomes
1817
+ // a session of its own, and this topic moves onto the copy. `/fork` alone
1818
+ // branches from the end; `/fork 2` branches from two turns back.
1819
+ const sessionId = state.sessions[key] || '';
1820
+ if (!sessionId) { say(t(lang, 'ctrl.fork.noSession')); return true; }
1821
+ if (ctx.activeTurns && ctx.activeTurns.has(key)) { say(t(lang, 'ctrl.fork.busy')); return true; }
1822
+ const wanted = String(arg || '').trim().toLowerCase();
1823
+ const steps = wanted ? Number.parseInt(wanted, 10) : 0;
1824
+ if (wanted && (!Number.isInteger(steps) || steps < 0)) { say(t(lang, 'ctrl.fork.usage')); return true; }
1825
+ const file = sessionFile(join(DSH_HOME, 'sessions'), sessionId);
1826
+ const plan = planFork(file, steps);
1827
+ if (plan.reason) {
1828
+ // The same refusals as a cut: a session being written is the one file
1829
+ // this must never copy, and the reason is the same sentence.
1830
+ say(t(lang, `ctrl.rewind.refused.${plan.reason}`, { total: plan.total, dropped: steps }));
1831
+ return true;
1832
+ }
1833
+ let made;
1834
+ try {
1835
+ made = applyFork(file, plan.offset, plan.size);
1836
+ } catch (error) {
1837
+ say(t(lang, 'ctrl.fork.failed', { error: error.message }));
1838
+ return true;
1839
+ }
1840
+ state.sessions[key] = made.id;
1841
+ state.forks = state.forks || {};
1842
+ const list = state.forks[key] || [];
1843
+ list.push({ id: made.id, from: sessionId, at: Date.now(), kept: plan.kept });
1844
+ // The last dozen is enough to pick from, and state.json stays small.
1845
+ state.forks[key] = list.slice(-12);
1846
+ ctx.saveState();
1847
+ log(`fork ${sessionId} -> ${made.id} at turn ${plan.kept} for ${key}`);
1848
+ say(t(lang, 'ctrl.fork.done', { id: made.id, kept: plan.kept }));
1849
+ return true;
1850
+ }
1851
+
1852
+ case '/branches': {
1853
+ const list = state.forks?.[key] || [];
1854
+ const current = state.sessions[key] || '';
1855
+ if (!list.length) { say(t(lang, 'ctrl.fork.none')); return true; }
1856
+ const rows = list.map((entry) => [{
1857
+ text: `${entry.id === current ? '• ' : ''}${entry.id.slice(8, 16)} · ${t(lang, 'ctrl.fork.turns', { n: entry.kept })}`,
1858
+ data: `fk:${entry.id}`,
1859
+ }]);
1860
+ const head = [t(lang, 'ctrl.fork.list', { n: list.length }), t(lang, 'ctrl.fork.current', { id: current || '—' })];
1861
+ await reply(head.join('\n'), { keyboard: rows });
1862
+ return true;
1863
+ }
1864
+
1772
1865
  case '/new': {
1773
1866
  delete state.sessions[key];
1774
1867
  ctx.saveState();
@@ -2182,7 +2275,7 @@ export async function handleControl(ctx) {
2182
2275
  return true;
2183
2276
  }
2184
2277
 
2185
- case '/agentset': {
2278
+ case '/crew': {
2186
2279
  const store = agentset();
2187
2280
  if (store.error) say(t(lang, 'ctrl.set.storeBroken', { error: store.error }));
2188
2281
  const bound = state.agentsets?.[key] || '';
package/failures.mjs ADDED
@@ -0,0 +1,44 @@
1
+ // What a failed turn says, and why. Kept apart from the bridge so the rules can
2
+ // be tested without starting a bot: every cause has one sentence, in the
3
+ // reader's language, and the sentence names the next action.
4
+ import { t } from './i18n.mjs';
5
+
6
+ /**
7
+ * Turn a raw CLI/provider error into `CODE` plus one actionable line.
8
+ *
9
+ * Raw text like `AUTH 403 insufficient_user_quota` means nothing to a person on
10
+ * a phone; the code makes the failure greppable and the hint says what to do.
11
+ */
12
+ export function explainFailure(text, lang = 'ru') {
13
+ const raw = String(text);
14
+ // The regular expressions match the CLI's and the provider's own words, so
15
+ // they stay as they are; only the hint on the right follows the topic language.
16
+ const cases = [
17
+ [/insufficient_user_quota|insufficient quota|AUTH\b|\b402\b|\bbalance\b|баланс|billing/i,
18
+ 'INSUFFICIENT_QUOTA', 'bridge.fail.quota'],
19
+ [/Conflict: terminated by other getUpdates|\b409\b/i,
20
+ 'TG_CONFLICT', 'bridge.fail.conflict'],
21
+ [/MISSING_CREDENTIAL|no credentials|not authenticated/i,
22
+ 'MISSING_CREDENTIAL', 'bridge.fail.noCredential'],
23
+ [/ENOENT|not recognized|не найден.*dsh|dsh\.cmd/i,
24
+ 'NO_DSH_CLI', 'bridge.fail.noCli'],
25
+ [/fetch failed|ETIMEDOUT|ECONNREFUSED|ENOTFOUND|socket hang up|network/i,
26
+ 'NETWORK', 'bridge.fail.network'],
27
+ [/EACCES|EPERM|access is denied|отказано в доступе|sandbox|permission denied/i,
28
+ 'SANDBOX_DENY', 'bridge.fail.sandbox'],
29
+ [/UNKNOWN_MODEL|model not found|no such model/i,
30
+ 'UNKNOWN_MODEL', 'bridge.fail.unknownModel'],
31
+ [/empty response|EMPTY_RESPONSE|no output|пустой ответ/i,
32
+ 'EMPTY_RESPONSE', 'bridge.fail.empty'],
33
+ ];
34
+ // The clock, not the provider. The turn stopped itself with the session on
35
+ // disk, so "repeat the request" would throw away everything it produced.
36
+ const minutes = raw.match(/turn exceeded\s+(\d+)\s*min/i) || raw.match(/hard cap\s+(\d+)\s*min/i);
37
+ if (/turn exceeded\s+\d+\s*min/i.test(raw) || /turn hard cap/i.test(raw)) {
38
+ return `${raw}\n\nTURN_TIME_CAP: ${t(lang, 'bridge.fail.timeCap', { minutes: minutes ? minutes[1] : '?' })}`;
39
+ }
40
+ for (const [re, code, hint] of cases) {
41
+ if (re.test(raw)) return `${raw}\n\n${code}: ${t(lang, hint)}`;
42
+ }
43
+ return `${raw}\n\nTURN_FAILED: ${t(lang, 'bridge.fail.generic')}`;
44
+ }
package/help-explain.mjs CHANGED
@@ -1,18 +1,21 @@
1
- // Which commands need a sentence each, and which only need their line from
2
- // /help. The pairs are the whole reason this exists: /task and /tasks, /model
3
- // and /models, /plugin and /plugins are one letter apart and do different jobs,
4
- // so a lookup must say which is which before it says anything else.
5
- import { CONTROL_COMMANDS } from './control.mjs';
1
+ // Which command sits in which /help group, and what to say when somebody asks
2
+ // about one. Every command has exactly one name now: the lookalike pairs
3
+ // (/task|/tasks, /model|/models, /plugin|/plugins, /agents|/agentset) were one
4
+ // letter apart and did different jobs, which is a mistake a phone keyboard makes
5
+ // for the person. The old spellings still work, and asking about one answers with
6
+ // the command that owns the job — nothing here ever advertises an alias.
7
+ import { COMMAND_ALIASES, CONTROL_COMMANDS } from './control.mjs';
6
8
  import { t } from './i18n.mjs';
7
9
 
8
10
  /** The /help group each command is listed under. */
9
11
  const SECTION = {
10
12
  cd: 'Work', new: 'Work', stop: 'Work', send: 'Work', seed: 'Work',
11
- goal: 'Goals', task: 'Goals', tasks: 'Goals',
12
- status: 'Sessions', sessions: 'Sessions', resume: 'Sessions', rewind: 'Sessions', profile: 'Sessions',
13
- agents: 'Agents', model: 'Models', models: 'Models', prices: 'Models', thoughts: 'Models',
14
- effort: 'Tuning', permissions: 'Tuning', preset: 'Tuning', agentset: 'Tuning', plan: 'Tuning', jobs: 'Tuning', remind: 'Tuning',
15
- skills: 'Extensions', plugins: 'Extensions', plugin: 'Extensions', soul: 'Extensions',
13
+ goal: 'Goals', task: 'Goals',
14
+ status: 'Sessions', sessions: 'Sessions', resume: 'Sessions', rewind: 'Sessions', fork: 'Sessions',
15
+ branches: 'Sessions', profile: 'Sessions',
16
+ agents: 'Agents', model: 'Models', prices: 'Models', thoughts: 'Models',
17
+ effort: 'Tuning', permissions: 'Tuning', preset: 'Tuning', crew: 'Tuning', plan: 'Tuning', jobs: 'Tuning', remind: 'Tuning',
18
+ skills: 'Extensions', plugins: 'Extensions', soul: 'Extensions',
16
19
  version: 'Versions', update: 'Versions', subscribe: 'Versions',
17
20
  settings: 'Other', lang: 'Other', reasoning: 'Other', doctor: 'Other', logs: 'Other',
18
21
  app: 'Other', restart: 'Other', help: 'Other', menu: 'Panels',
@@ -24,8 +27,12 @@ const SECTION = {
24
27
  * /help that lists them, so a reader still sees the command in context.
25
28
  */
26
29
  export function explainCommand(name, lang, t) {
27
- const clean = String(name || '').trim().toLowerCase().replace(/^\//, '');
28
- if (!CONTROL_COMMANDS.includes(clean)) return '';
30
+ const typed = String(name || '').trim().toLowerCase().replace(/^\//, '');
31
+ if (!CONTROL_COMMANDS.includes(typed)) return '';
32
+ // An old spelling answers as the command that owns the job. Saying "that one
33
+ // is the same as /task" would teach the alias back, which is the confusion
34
+ // this file exists to end.
35
+ const clean = COMMAND_ALIASES[typed] || typed;
29
36
  const about = t(lang, `ctrl.help.about.${clean}`);
30
37
  if (about && !about.startsWith('ctrl.help.about.')) return about;
31
38
  const body = String(t(lang, 'help.body'));
@@ -33,4 +40,4 @@ export function explainCommand(name, lang, t) {
33
40
  const line = want ? (body.split('\n').find((row) => row.startsWith(`${want}:`)) || '') : '';
34
41
  const head = t(lang, 'ctrl.help.versus', { name: clean });
35
42
  return line ? `${head}\n\n${line}` : head;
36
- }
43
+ }