dsh-tg-bridge 1.22.0 → 1.24.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 CHANGED
@@ -112,7 +112,34 @@ Optional provider settings live in `config.json`:
112
112
  | `pricesUrl` | retired: `/prices` always reads OpenRouter's public list and labels the number as a reference for the model |
113
113
  | `vision.patch` | opt-in overlay profile for photo turns; default `""` — the turn's own model reads images |
114
114
  | `vision.enabled` | set `true` to run photo turns on `vision.patch` instead of the topic profile |
115
- | `fallbackModels` | free-model fallbacks; default `[]` |
115
+ | `fallbackModels` | ordered failover chain; default `[]` — see below |
116
+ | `maxParallel` | how many topics run at once, 1–8, default `3`; also `/jobs 5` in the chat |
117
+ | `replayWindowMs` | how old a journaled update may be and still be replayed after a restart; default `600000` (10 min) |
118
+
119
+ Each `fallbackModels` entry is one attempt, tried in order after the turn's own
120
+ model refuses:
121
+
122
+ ```json
123
+ {
124
+ "provider": "router-a",
125
+ "model": "some-model",
126
+ "patch": "~/.dsh/tg-bridge/model-a.yml",
127
+ "free": false
128
+ }
129
+ ```
130
+
131
+ `patch` is an overlay file with a single `agent-default-model` row
132
+ (`provider` + `model`); it is materialised once as its own profile, so the turn
133
+ keeps every other setting and only the model changes. `provider` is the id the
134
+ provider is written under in the profile — it decides whose key and host the
135
+ pre-flight probe asks, so the same model id on two routers stays two attempts.
136
+ `free` only adds `(free)` to the switch notice.
137
+
138
+ The chain may mix companies: a 503 from one provider says nothing about another,
139
+ so a busy channel skips its own models and the next company is still tried. Put
140
+ models from different companies next to each other — two arms of one router are
141
+ one outage, not two chances — and keep the `:free` models at the end, as the
142
+ last resort.
116
143
 
117
144
  Get your id from [@userinfobot](https://t.me/userinfobot), the token from
118
145
  [@BotFather](https://t.me/BotFather).
package/bridge.mjs CHANGED
@@ -32,7 +32,7 @@ import { turnArgs } from './cli-args.mjs';
32
32
  import { chunk, markdownParts, toPlainText, toTelegramHtml } from './format.mjs';
33
33
  import { mediaPrompt, readVoiceIntoText } from './media.mjs';
34
34
  import { busyNotices, clearBusyNotice, steerAvailable, steerMediaMessage, steerRunningTurn } from './steer.mjs';
35
- import { MAX_PARALLEL, approvals, bufferAlbum, enqueue, lastPrompt, queues, rewindUsed, setMessageHandler } from './queue.mjs';
35
+ import { MAX_PARALLEL, approvals, bufferAlbum, enqueue, lastPrompt, queues, redeliver, rewindUsed, setMessageHandler } from './queue.mjs';
36
36
  import { applyAsetJob, settingsChipOf, turnProfileOf } from './profile-view.mjs';
37
37
  import { handleMessage } from './handle-message.mjs';
38
38
  import { boundSetOf, handleCallback, handleCardPress, renderTaskCard, taskRows } from './callbacks.mjs';
@@ -204,7 +204,23 @@ async function main() {
204
204
  Promise.resolve()
205
205
  .then(() => handleMessage(msg))
206
206
  .then(() => ack(update.update_id))
207
- .catch((error) => log(`command ${immediate} failed: ${error.message}`));
207
+ // A command that threw is answered by the log, not by a replay. Leaving
208
+ // it pending meant every restart ran it again: `/update` installed the
209
+ // release, died on an undefined name, was never acked, and the journal
210
+ // replayed it four times — the chat got "already on 1.22.0" three times
211
+ // for one typed command.
212
+ .catch(async (error) => {
213
+ log(`command ${immediate} failed: ${error.message}`);
214
+ // The person typed a command and got nothing back: silence reads as
215
+ // "still working". One line, then the update is done with.
216
+ const lang = resolveLang(state, queueKey, msg, config);
217
+ await send(
218
+ msg.chat.id,
219
+ t(lang, 'msg.commandFailed', { cmd: immediate, err: String(error.message).slice(0, 200) }),
220
+ thread,
221
+ ).catch(() => {});
222
+ ack(update.update_id);
223
+ });
208
224
  return;
209
225
  }
210
226
  // Telegram splits an album into one update per file, all sharing a
@@ -229,7 +245,7 @@ async function main() {
229
245
  if (activeTurns.has(queueKey) && sessionId) {
230
246
  if (steerText && !steerMedia) {
231
247
  try {
232
- const job = steerRunningTurn(msg, steerText, sessionId, thread, deliverTurn);
248
+ const job = steerRunningTurn(msg, steerText, sessionId, thread, redeliver);
233
249
  log(`steer handled outside the queue: ${job.id}`);
234
250
  ack(update.update_id);
235
251
  } catch (error) {
@@ -243,7 +259,7 @@ async function main() {
243
259
  // the voicemail in a directory nobody reads again.
244
260
  ack(update.update_id);
245
261
  const lang = resolveLang(state, queueKey, msg, config);
246
- void steerMediaMessage(msg, sessionId, queueKey, thread, lang, deliverTurn).catch((error) => {
262
+ void steerMediaMessage(msg, sessionId, queueKey, thread, lang, redeliver).catch((error) => {
247
263
  // The attachment could not be prepared (download, transcription). It
248
264
  // still deserves an answer, so let the normal path take it: it retries
249
265
  // the same work and reports the failure itself.
@@ -263,8 +279,11 @@ async function main() {
263
279
  ack(update.update_id);
264
280
  if (replay) log(`replayed update ${update.update_id} after restart`);
265
281
  } catch (error) {
266
- // Keep the pending file: the next start retries it once.
267
- log(`turn error for update ${update.update_id}: ${error.message}`);
282
+ // One retry, then the answer is owed by nobody: a turn that throws the
283
+ // same way on every start would otherwise be replayed on every restart
284
+ // until the TTL, filling the chat with identical failures.
285
+ log(`turn error for update ${update.update_id}: ${error.message}${replay ? ' (already a retry, dropping)' : ''}`);
286
+ if (replay) ack(update.update_id);
268
287
  }
269
288
  },
270
289
  // Only plain text prompts can queue behind a turn; commands are
@@ -308,10 +327,27 @@ async function main() {
308
327
  // leave the update pending forever, so the bridge replayed it, died, and was
309
328
  // restarted by the supervisor — every ninety seconds, with a stack trace and
310
329
  // nothing else. Drop the entry after reporting it.
330
+ //
331
+ // And a replay is only for what was genuinely mid-flight. After a bad release
332
+ // left nineteen updates unacked, the next start would have re-run a whole
333
+ // evening of turns the owner had already been answered for — the same money
334
+ // twice, in messages he had read. Age is the only signal the journal carries
335
+ // that separates "we died under this" from "this was answered or abandoned
336
+ // long ago", so anything older than the window is dropped and said out loud.
337
+ const replayWindowMs = Number(config.replayWindowMs) > 0
338
+ ? Number(config.replayWindowMs)
339
+ : 10 * 60 * 1000;
311
340
  const owed = pendingUpdates();
312
- if (owed.length > 0) {
313
- log(`replaying ${owed.length} pending update(s) from the journal`);
314
- for (const { update } of owed) {
341
+ const now = Date.now();
342
+ const fresh = owed.filter(({ at }) => !at || now - at <= replayWindowMs);
343
+ const stale = owed.filter(({ at }) => at && now - at > replayWindowMs);
344
+ if (stale.length > 0) {
345
+ log(`dropping ${stale.length} pending update(s) older than ${Math.round(replayWindowMs / 60000)} min: ${stale.map(({ id }) => id).join(', ')}`);
346
+ for (const { id } of stale) ack(id);
347
+ }
348
+ if (fresh.length > 0) {
349
+ log(`replaying ${fresh.length} pending update(s) from the journal`);
350
+ for (const { update } of fresh) {
315
351
  try {
316
352
  accept(update, true);
317
353
  } catch (error) {
package/callbacks.mjs CHANGED
@@ -9,13 +9,13 @@ import { resolveLang, t } from './i18n.mjs';
9
9
  import { sessionKey } from './keys.mjs';
10
10
  import { commandForName, isMenuPress, menuTarget, renderPanel, runsUnasked } from './menu-card.mjs';
11
11
  import { DIR, DSH_HOME, LOG } from './paths.mjs';
12
- import { MAX_PARALLEL, approvals, enqueue, lastPrompt, rewindUsed } from './queue.mjs';
12
+ import { approvals, enqueue, lastPrompt, maxParallel, rewindUsed } from './queue.mjs';
13
13
  import { answerRewindPress, cutSession, isRewindPress } from './rewind-buttons.mjs';
14
14
  import { applyRewind, newestBackup, restoreBackup } from './rewind.mjs';
15
15
  import { runCommandFromButton } from './run-command.mjs';
16
16
  import { commandFor, renderSettingsCard, settingsCurrent } from './settings-card.mjs';
17
17
  import { config, done, log, saveState, state } from './state.mjs';
18
- import { send, sendFile, tg } from './telegram.mjs';
18
+ import { inlineKeyboard, send, sendFile, tg } from './telegram.mjs';
19
19
  import { sessionFile } from './thoughts.mjs';
20
20
  import { activeTurns, killTurn, profileOf } from './turn.mjs';
21
21
  import { readFileSync } from 'node:fs';
@@ -142,6 +142,16 @@ export async function handleCallback(query) {
142
142
  return;
143
143
  }
144
144
 
145
+ // A parallel-slot button from the /jobs card. It runs the command the card
146
+ // advertises, so validation and storage live in one place and a tap cannot
147
+ // write a value `/jobs <n>` would refuse. The command redraws the card, so the
148
+ // answer to the press is the new state, not a second message about it.
149
+ if (data.startsWith('jb:')) {
150
+ await clearKeyboard();
151
+ await runCommandFromButton(`/jobs ${data.slice(3)}`, { chatId, threadId, key });
152
+ return;
153
+ }
154
+
145
155
  if (isMenuPress(data)) {
146
156
  // The panel is a set of cards: the hub, then one page per section. Moving
147
157
  // between them edits this message, so browsing costs no new messages. A
@@ -154,7 +164,7 @@ export async function handleCallback(query) {
154
164
  chat_id: chatId,
155
165
  message_id: messageId,
156
166
  text: card.text,
157
- reply_markup: { inline_keyboard: card.keyboard },
167
+ reply_markup: { inline_keyboard: inlineKeyboard(card.keyboard) },
158
168
  ...(threadId > 0 ? { message_thread_id: threadId } : {}),
159
169
  }).catch(() => {});
160
170
  await answer(t(lang, 'bridge.cb.done'));
@@ -262,7 +272,7 @@ export async function handleCallback(query) {
262
272
  chat_id: chatId,
263
273
  message_id: messageId,
264
274
  text,
265
- reply_markup: { inline_keyboard: taskRows(goal) },
275
+ reply_markup: { inline_keyboard: inlineKeyboard(taskRows(goal)) },
266
276
  }).catch(() => {});
267
277
  await answer(t(lang, goal.tasks[n - 1]?.done ? 'bridge.cb.taskDone' : 'bridge.cb.taskUndone'));
268
278
  log(`task ${n} toggled for ${key}`);
@@ -315,7 +325,7 @@ export async function handleCardPress(query, ctx) {
315
325
  chat_id: chatId,
316
326
  message_id: messageId,
317
327
  text: card.text,
318
- reply_markup: { inline_keyboard: card.keyboard },
328
+ reply_markup: { inline_keyboard: inlineKeyboard(card.keyboard) },
319
329
  ...(threadId > 0 ? { message_thread_id: threadId } : {}),
320
330
  }).catch((error) => log(`settings card redraw failed: ${error.message}`));
321
331
  await tg('answerCallbackQuery', { callback_query_id: query.id }).catch(() => {});
@@ -348,7 +358,7 @@ export async function handleCardPress(query, ctx) {
348
358
  replies.push(String(text ?? ''));
349
359
  return Promise.resolve(0);
350
360
  },
351
- jobs: () => ({ active: [], queued: 0, max: MAX_PARALLEL }),
361
+ jobs: () => ({ active: [], queued: 0, max: maxParallel() }),
352
362
  api: tg,
353
363
  sendFile: () => Promise.resolve(0),
354
364
  profile: profileOf(key),
@@ -8,6 +8,7 @@
8
8
  "turnTimeoutMs": 0,
9
9
  "busyNoticeMs": 45000,
10
10
  "maxParallel": 3,
11
+ "replayWindowMs": 600000,
11
12
  "approvalTimeoutMs": 600000,
12
13
  "generalLobby": true,
13
14
  "topicLog": true,
@@ -1,15 +1,16 @@
1
- // Agent sets: a named bundle of subagents a topic can be bound to, with the card and the keyboard that edit it.
2
- //
3
- // Split out of `control.mjs` by the 500-line plan: the command handlers that
4
- // follow call these, and none of them needs the dispatcher to do it.
5
- import { join } from 'node:path';
6
- import { t } from '../i18n.mjs';
7
- import { parseAgentPresets, parsePermissionPresets, parseReasoningEfforts } from '../agents.mjs';
8
- import { AgentsetStore } from '../agentsets.mjs';
9
- import { profileValues, resolveSettings } from '../settings.mjs';
10
- import { DSH_HOME } from '../paths.mjs';
11
-
12
- import { read, patchPath, modelsOf, modelOf } from './models.mjs';
1
+ // Agent sets: a named bundle of subagents a topic can be bound to, with the card and the keyboard that edit it.
2
+ //
3
+ // Split out of `control.mjs` by the 500-line plan: the command handlers that
4
+ // follow call these, and none of them needs the dispatcher to do it.
5
+ import { join } from 'node:path';
6
+ import { t } from '../i18n.mjs';
7
+ import { parseAgentPresets, parsePermissionPresets, parseReasoningEfforts } from '../agents.mjs';
8
+ import { AgentsetStore } from '../agentsets.mjs';
9
+ import { profileValues, resolveSettings } from '../settings.mjs';
10
+ import { DSH_HOME } from '../paths.mjs';
11
+ import { cardKeyboard } from '../aset-schema.mjs';
12
+
13
+ import { read, patchPath, modelsOf, modelOf } from './models.mjs';
13
14
  export const fmt = (rows) => rows.map((row) => ` ${row}`).join('\n');
14
15
 
15
16
  /**
@@ -63,7 +63,7 @@ function versionCard(lang) {
63
63
  }
64
64
 
65
65
  export async function handleBridgeCommands(ctx) {
66
- const { command, arg, send, reply, log, profile, state, key, config, lang: rawLang } = ctx;
66
+ const { command, arg, send, reply, log, profile, state, key, config, lang: rawLang, saveState } = ctx;
67
67
  // The topic's language, then the config default, then English. Never Russian:
68
68
  // a group that has no opinion still must not guess a language.
69
69
  const lang = normalizeLang(rawLang) || normalizeLang(config?.lang) || 'en';
@@ -34,7 +34,7 @@ import { taskKeyboard, goalView, taskView, reasoningOf, filterLogLines } from '.
34
34
  import { updatePolicy, bridgeRoot, copyRelease, installRelease, bridgeVersion, newestModuleMtime, npmLatest, npmLatestAsync } from './release.mjs';
35
35
 
36
36
  export async function handlePluginCommands(ctx) {
37
- const { command, arg, send, reply, log, profile, state, key, config, lang: rawLang } = ctx;
37
+ const { command, arg, send, reply, log, profile, state, key, config, lang: rawLang, saveState } = ctx;
38
38
  // The topic's language, then the config default, then English. Never Russian:
39
39
  // a group that has no opinion still must not guess a language.
40
40
  const lang = normalizeLang(rawLang) || normalizeLang(config?.lang) || 'en';
@@ -32,6 +32,7 @@ import { agentsOf, fleetOf, patchRows, skillsOf, AGENTS, PERSONA_HEADING, soulOf
32
32
  import { fmt, AGENTSETS, agentset, agentsetOf, profileRowOf, bindAgentset, agentsetCard, agentsetKeyboard } from './agentsets.mjs';
33
33
  import { taskKeyboard, goalView, taskView, reasoningOf, filterLogLines } from './tasks.mjs';
34
34
  import { updatePolicy, bridgeRoot, copyRelease, installRelease, bridgeVersion, newestModuleMtime, npmLatest, npmLatestAsync } from './release.mjs';
35
+ import { CAP_CHOICES, CAP_MAX, CAP_MIN, setParallel } from '../jobs-cap.mjs';
35
36
 
36
37
  export async function handleTaskCommands(ctx) {
37
38
  const { command, arg, send, reply, log, profile, state, key, config, lang: rawLang } = ctx;
@@ -155,8 +156,27 @@ export async function handleTaskCommands(ctx) {
155
156
  // What survives — and what a person waiting on a reply actually needs —
156
157
  // is the bridge's queue: which topics are running now, for how long, and
157
158
  // how many waits behind them.
159
+ //
160
+ // The card also owns the ceiling. It was a config-file key nobody could
161
+ // reach from the chat, and a wrong value showed up as "your message is
162
+ // waiting for a free slot" with no way to widen it. `/jobs 5` sets it, and
163
+ // so does a button — both through `setParallel`, so they cannot disagree,
164
+ // and the card is redrawn either way, so the answer is the new state.
165
+ const asked = String(arg || '').trim();
166
+ let set = null;
167
+ if (asked) {
168
+ set = setParallel(asked, { config, saveConfig: ctx.saveConfig, log });
169
+ if (!set.ok) {
170
+ say(t(lang, 'ctrl.jobs.capRange', { min: CAP_MIN, max: CAP_MAX }));
171
+ return true;
172
+ }
173
+ }
158
174
  const snapshot = ctx.jobs ? ctx.jobs() : { active: [], queued: 0, max: 0 };
159
- const lines = [t(lang, 'ctrl.jobs.title')];
175
+ const lines = [];
176
+ // One message: what changed, then the state it changed to. Two messages
177
+ // for one tap is noise in a chat that is already long.
178
+ if (set) lines.push(t(lang, set.saved ? 'ctrl.jobs.capSet' : 'ctrl.jobs.capUnsaved', { n: set.n }), '');
179
+ lines.push(t(lang, 'ctrl.jobs.title'));
160
180
  if (snapshot.active.length === 0) {
161
181
  lines.push(t(lang, 'ctrl.jobs.idle'));
162
182
  } else {
@@ -168,7 +188,15 @@ export async function handleTaskCommands(ctx) {
168
188
  }
169
189
  lines.push(t(lang, 'ctrl.jobs.queued', { n: snapshot.queued, max: snapshot.max }));
170
190
  lines.push(t(lang, 'ctrl.jobs.hint'));
171
- say(lines.join('\n'));
191
+ const cap = Number(snapshot.max) || 0;
192
+ lines.push(t(lang, 'ctrl.jobs.cap', { n: cap }));
193
+ // The numbers a person actually picks from. `jb:` is answered in
194
+ // callbacks.mjs by running `/jobs <n>`, the same command this argument runs.
195
+ const rows = [CAP_CHOICES.map((n) => ({
196
+ text: n === cap ? `• ${n}` : String(n),
197
+ data: `jb:${n}`,
198
+ }))];
199
+ say(lines.join('\n'), { keyboard: rows });
172
200
  return true;
173
201
  }
174
202
  case '/remind': {
package/fallback.mjs ADDED
@@ -0,0 +1,141 @@
1
+ // The model chain: what the bridge does when the first route refuses.
2
+ //
3
+ // Extracted from `handle-message.mjs`, which sits at the 500-line ceiling, and
4
+ // because a chain that mixes companies is a decision of its own: which model,
5
+ // on whose route, and when to stop asking.
6
+ //
7
+ // One behaviour changed while moving it. A provider whose channel pool is down
8
+ // (`get_channel_failed`, "all providers are busy") used to end the whole chain
9
+ // after a single probe, because every model sat on one router and the probe
10
+ // answered for all of them. With models from different companies that break is
11
+ // wrong: a 503 from one route says nothing about another company's, so each
12
+ // entry is probed on its own provider and a dead pool skips only its models.
13
+ import { existsSync } from 'node:fs';
14
+ import { t } from './i18n.mjs';
15
+ import { describeVerdicts, firstLiveModel, probeHint, probeModel } from './model-probe.mjs';
16
+ import { ensureProfile } from './profiles.mjs';
17
+ import { config, log } from './state.mjs';
18
+ import { killTurn, runTurnLive } from './turn.mjs';
19
+
20
+ /** Errors that mean "this route cannot answer now", not "the task is wrong". */
21
+ export const FALLBACK_TRIGGERS = /RATE_LIMIT|503|get_channel_failed|all providers|нет активности|EMPTY_RESPONSE|TIMEOUT|overloaded|AUTH|403|insufficient_user_quota|quota|UNKNOWN_MODEL|MISSING_CREDENTIAL/i;
22
+ /** A dead balance is not a busy provider: it must reach the free tail as well. */
23
+ export const QUOTA_LIKE = /insufficient_user_quota|AUTH\b|\b403\b|\b401\b|quota|balance|баланс|payment|billing/i;
24
+ /** The provider's own channel pool, not the model: it is down for every model. */
25
+ export const CHANNEL_DOWN = /get_channel_failed|all providers|no providers|503/i;
26
+
27
+ /** `provider/model` — the way the chat names a route. */
28
+ export function labelOf(entry = {}) {
29
+ const model = String(entry.model || '');
30
+ return entry.provider ? `${entry.provider}/${model}` : model;
31
+ }
32
+
33
+ /**
34
+ * Whether the chain's failure deserves one message that names the causes.
35
+ *
36
+ * Three ways to get here: every entry was tried, a probe found nothing alive, or
37
+ * entries were skipped because their own route was dead. A short chain with no
38
+ * verdict is the one case that must stay quiet — it is not proof of anything.
39
+ */
40
+ export function exhausted({ tried = [], chainLength = 0, probeKind = '' } = {}) {
41
+ if (tried.length === 0) return false;
42
+ return Boolean(probeKind) || tried.length >= chainLength;
43
+ }
44
+
45
+ /**
46
+ * Walk the chain after a failed turn and return the turn's final result.
47
+ *
48
+ * @param {object} ctx
49
+ * @param {object} ctx.result the failed turn: `{error}` decides whether to go on
50
+ * @param {Array} ctx.chain `config.fallbackModels`: `{model, provider?, patch, free?}`
51
+ * @param {object} ctx.primary `{provider, model}` this topic actually runs on
52
+ * @param {string} ctx.turnProfile the profile the first attempt used
53
+ * @param {string} ctx.topicProfile the topic's own profile, used if a patch is unusable
54
+ * @returns {Promise<object>} the same shape `runTurnLive` returns
55
+ */
56
+ export async function runFallbackChain({
57
+ result, chain = [], primary = {}, text, sessionAtStart, key = '', where = '', chatId, threadId,
58
+ lang = 'ru', cwd = '', turnProfile = '', topicProfile = '', telemetry = {}, onEvent = null,
59
+ thoughtEnv = {}, send,
60
+ }) {
61
+ const run = (profile) => runTurnLive(text, sessionAtStart, key, {
62
+ onEvent,
63
+ onAbort: () => killTurn(key),
64
+ env: thoughtEnv,
65
+ // Same overlay problem as the vision turn: the host CLI has no --patch. A
66
+ // patch file that is missing or unreadable must not turn into an empty
67
+ // `--profile` argument, so the topic's own profile is the fallback.
68
+ profile: profile || topicProfile || config.profile,
69
+ cwd,
70
+ lang,
71
+ });
72
+ const tried = [];
73
+
74
+ for (const entry of chain) {
75
+ if (!result.error || !FALLBACK_TRIGGERS.test(result.error)) break;
76
+ if (!entry.patch || !existsSync(entry.patch)) continue;
77
+ // A dead channel pool skips only the models behind it: another company's
78
+ // route is a separate question, and the old probe asked the first provider
79
+ // about all of them. A balance error is not probed — it already names the
80
+ // model that refused, and a probe would spend a request to learn that.
81
+ if (CHANNEL_DOWN.test(result.error)) {
82
+ const verdict = await probeModel(entry.model, { provider: entry.provider });
83
+ if (!verdict.ok) {
84
+ log(`channel down for ${labelOf(entry)}: probe says ${verdict.kind}; skipping it`);
85
+ tried.push(`${labelOf(entry)}: ${verdict.kind}`);
86
+ continue;
87
+ }
88
+ log(`channel down, but ${labelOf(entry)} answers the probe; trying it`);
89
+ }
90
+ // Quota failures never deserve a retry of the same model: the balance is
91
+ // gone, so waiting is pure loss. Anything else is transient.
92
+ const quotaLike = QUOTA_LIKE.test(result.error);
93
+ const reason = quotaLike ? t(lang, 'bridge.fallback.quota') : t(lang, 'bridge.fallback.noAnswer');
94
+ tried.push(`${labelOf(entry)}: ${String(result.error).slice(0, 120)}`);
95
+ log(`fallback to ${labelOf(entry)} for ${where} reason=${quotaLike ? 'quota' : 'transient'} after: ${String(result.error).slice(0, 120)}`);
96
+ telemetry.model = labelOf(entry);
97
+ // The person sees every switch, not only the final give-up: a chain of five
98
+ // companies that silently ends on the fifth reads like a hang.
99
+ await send(chatId, t(lang, 'bridge.fallback.switched', {
100
+ reason,
101
+ model: labelOf(entry),
102
+ free: entry.free ? ' (free)' : '',
103
+ }), threadId);
104
+ result = await run(ensureProfile(entry.patch));
105
+ if (!result.error) break;
106
+ }
107
+
108
+ // Every model refused. Before saying "all models are unavailable", ask each
109
+ // route directly with a 1-token request: a 503 storm usually clears within
110
+ // seconds, and the verdict tells the person whether a balance is gone or a
111
+ // provider is merely busy.
112
+ let probeKind = '';
113
+ if (result.error && FALLBACK_TRIGGERS.test(result.error)) {
114
+ const models = [
115
+ { model: primary.model, provider: primary.provider || '' },
116
+ ...chain.map((entry) => ({ model: entry.model, provider: entry.provider || '' })),
117
+ ].filter((item) => item.model && item.model !== '?');
118
+ const { live, verdicts } = await firstLiveModel(models);
119
+ if (live) {
120
+ log(`probe: ${labelOf(live)} answers after ${verdicts.length} check(s), retrying the turn there`);
121
+ const entry = chain.find((item) => item.model === live.model
122
+ && (!live.provider || item.provider === live.provider));
123
+ result = await run(entry ? ensureProfile(entry.patch) : turnProfile);
124
+ } else {
125
+ // Nothing answers: the verdict is the only useful part of the failure.
126
+ probeKind = describeVerdicts(verdicts);
127
+ log(`probe: no channel answers (${verdicts.map((v) => `${labelOf(v)}:${v.kind}`).join(', ')})`);
128
+ }
129
+ }
130
+ // One message naming the causes, not a cascade of errors.
131
+ if (result.error && exhausted({ tried, chainLength: chain.length, probeKind })) {
132
+ log(`all fallbacks exhausted for ${where}: ${tried.length} probe=${probeKind || 'n/a'}`);
133
+ const verdictLine = probeKind ? `\n${probeHint(probeKind, lang)}` : '';
134
+ result = {
135
+ sessionId: result.sessionId,
136
+ text: '',
137
+ error: t(lang, 'bridge.fallback.allDown', { list: tried.map((line) => `• ${line}`).join('\n') }) + verdictLine,
138
+ };
139
+ }
140
+ return result;
141
+ }
@@ -8,25 +8,23 @@
8
8
  import { GENERAL_SAFE, commandOf } from './commands.mjs';
9
9
  import { CONTROL_COMMANDS, handleControl, modelOf, reasoningOf } from './control.mjs';
10
10
  import { explainFailure } from './failures.mjs';
11
+ import { runFallbackChain } from './fallback.mjs';
11
12
  import { goalOf, renderPromptBlock } from './goals.mjs';
12
13
  import { resolveLang, t } from './i18n.mjs';
13
14
  import { sessionKey, threadOf } from './keys.mjs';
14
15
  import { mediaPrompt } from './media.mjs';
15
16
  import { keyboardCommand } from './menu-card.mjs';
16
- import { describeVerdicts, firstLiveModel, probeHint, probeModel } from './model-probe.mjs';
17
17
  import { looksLikeReasoning, stepLine } from './panel.mjs';
18
18
  import { DIR, GOAL_CMD, THOUGHT_DIR } from './paths.mjs';
19
19
  import { renderPrices } from './prices.mjs';
20
20
  import { settingsChipOf, turnProfileOf } from './profile-view.mjs';
21
- import { ensureProfile } from './profiles.mjs';
22
21
  import { startProgress } from './progress.mjs';
23
- import { MAX_PARALLEL, lastPrompt, queues } from './queue.mjs';
22
+ import { lastPrompt, maxParallel, queues } from './queue.mjs';
24
23
  import { token } from './secrets.mjs';
25
- import { config, done, log, saveState, state } from './state.mjs';
24
+ import { config, done, log, saveConfig, saveState, state } from './state.mjs';
26
25
  import { send, sendEphemeral, sendFile, sendWithMarkup, tg } from './telegram.mjs';
27
26
  import { ensureTopicSeed, logTopicToGeneral, newestBoundTopic, startTopicFromMessage, topicName, topicSeeded, topicSeededRecently, touchTopic } from './topics.mjs';
28
27
  import { activeTurns, killTurn, liveSessions, profileOf, runTurnLive, turnStartedAt, typingLoop } from './turn.mjs';
29
- import { existsSync } from 'node:fs';
30
28
  import { join } from 'node:path';
31
29
 
32
30
  export async function handleMessage(msg, album = null) {
@@ -226,15 +224,15 @@ ${t(lang, 'help.body')}`,
226
224
  config,
227
225
  activeTurns,
228
226
  saveState,
227
+ saveConfig,
229
228
  log,
230
229
  send,
231
- // What `/jobs` shows: the turns that hold a slot right now and how many
232
- // wait behind them. `queues` counts a topic that is running too, so the
233
- // waiters are the keys without an active turn.
230
+ // What `/jobs` shows: the turns holding a slot, and the keys without an
231
+ // active turn waiting behind them.
234
232
  jobs: () => ({
235
233
  active: [...activeTurns.keys()].map((topic) => ({ key: topic, startedAt: turnStartedAt.get(topic) || 0 })),
236
234
  queued: [...queues.keys()].filter((topic) => !activeTurns.has(topic)).length,
237
- max: MAX_PARALLEL,
235
+ max: maxParallel(),
238
236
  }),
239
237
  api: tg,
240
238
  sendFile: (p, caption = '') => sendFile(chatId, threadId, p, caption),
@@ -355,91 +353,29 @@ ${t(lang, 'help.body')}`,
355
353
  // route ("all providers are busy", 503, or a turn that emits nothing at all)
356
354
  // used to end as silence. Retry the SAME prompt on the next model in the
357
355
  // chain before giving up — the person cares about an answer, not the vendor.
358
- const chain = Array.isArray(config.fallbackModels) ? config.fallbackModels : [];
359
- // A dead paid balance is not a "busy provider": it must trigger the free
360
- // chain as well, otherwise the bridge sits on AUTH 403 and gives up.
361
- const FALLBACK_TRIGGERS = /RATE_LIMIT|503|all providers|нет активности|EMPTY_RESPONSE|TIMEOUT|overloaded|AUTH|403|insufficient_user_quota|quota|UNKNOWN_MODEL|MISSING_CREDENTIAL/i;
362
- const QUOTA_LIKE = /insufficient_user_quota|AUTH\b|\b403\b|\b401\b|quota|balance|баланс|payment|billing/i;
363
- // "get_channel_failed / all providers are busy" is the provider's own channel
364
- // pool, not the model: when it is down, it is down for every model in the
365
- // chain. One probe then answers in seconds what four full turns spent 741
366
- // seconds discovering.
367
- const CHANNEL_DOWN = /get_channel_failed|all providers|no providers|503/i;
368
- const tried = [];
369
- for (const entry of chain) {
370
- if (!result.error || !FALLBACK_TRIGGERS.test(result.error)) break;
371
- if (!entry.patch || !existsSync(entry.patch)) continue;
372
- // The provider's channel pool is down: every model in the chain will answer
373
- // the same 503. Ask once, quickly, and say so instead of burning a turn per
374
- // model. A probe that DOES answer proves the pool is back — then the chain
375
- // goes on, and the fallback at hand is tried as usual.
376
- if (tried.length >= 1 && CHANNEL_DOWN.test(result.error)) {
377
- const verdict = await probeModel(config.primaryModel || 'deepseek-v4.1-flash-1017');
378
- log(`channel down after ${tried.length} model(s): probe says ${verdict.kind}; not trying ${entry.model}`);
379
- if (!verdict.ok) break;
380
- }
381
- const quotaLike = QUOTA_LIKE.test(result.error);
382
- // Quota failures never deserve a retry of the same model: the balance is
383
- // gone, so waiting is pure loss. Anything else gets one retry at most.
384
- const reason = quotaLike ? t(lang, 'bridge.fallback.quota') : t(lang, 'bridge.fallback.noAnswer');
385
- tried.push(`${entry.model}: ${String(result.error).slice(0, 120)}`);
386
- log(`fallback to ${entry.model} for ${where} reason=${quotaLike ? 'quota' : 'transient'} after: ${String(result.error).slice(0, 120)}`);
387
- telemetry.model = entry.model;
388
- await send(chatId, t(lang, 'bridge.fallback.switched', {
389
- reason,
390
- model: entry.model,
391
- free: entry.free ? ' (free)' : '',
392
- }), threadId);
393
- result = await runTurnLive(text, sessionAtStart, key, {
394
- onEvent,
395
- onAbort: () => killTurn(key),
396
- onHeartbeat: () => progress.heartbeat(), env: thoughtEnv,
397
- // Same overlay problem as the vision turn: the host CLI has no --patch.
398
- // A patch file that is missing or unreadable must not turn into an empty
399
- // --profile argument, so the topic's own profile is the fallback.
400
- profile: ensureProfile(entry.patch) || profileOf(key) || config.profile,
401
- cwd,
402
- lang,
403
- });
404
- if (!result.error) break;
405
- }
406
- // Every model refused. Before saying "all models are unavailable", ask each
407
- // channel directly with a 1-token request: a 503 storm usually clears within
408
- // seconds, and the verdict tells the person whether the balance is gone or the
409
- // provider is merely busy — the old message always claimed quota.
410
- let probeKind = '';
411
- if (result.error && FALLBACK_TRIGGERS.test(result.error)) {
412
- const models = [config.primaryModel || 'deepseek-v4.1-flash-1017', ...chain.map((entry) => entry.model)];
413
- const { live, verdicts } = await firstLiveModel(models);
414
- if (live) {
415
- log(`probe: ${live.model} answers after ${verdicts.length} check(s), retrying the turn there`);
416
- const entry = chain.find((item) => item.model === live.model);
417
- result = await runTurnLive(text, sessionAtStart, key, {
418
- onEvent,
419
- onAbort: () => killTurn(key),
420
- onHeartbeat: () => progress.heartbeat(),
421
- profile: entry ? ensureProfile(entry.patch) : turnProfile,
422
- cwd,
423
- lang,
424
- });
425
- } else {
426
- // Nothing answers: the verdict is the only useful part of the failure.
427
- probeKind = describeVerdicts(verdicts);
428
- log(`probe: no channel answers (${verdicts.map((v) => `${v.model}:${v.kind}`).join(', ')})`);
429
- }
430
- }
431
- // Every model refused — or the provider's own channel pool was down and the
432
- // chain stopped early, which is the same answer to the person: one message
433
- // naming the causes, not a cascade of errors.
434
- if (result.error && tried.length > 0 && (probeKind || tried.length >= (Array.isArray(config.fallbackModels) ? config.fallbackModels.length : 0))) {
435
- log(`all fallbacks exhausted for ${where}: ${tried.length} probe=${probeKind || 'n/a'}`);
436
- const verdictLine = probeKind ? `\n${probeHint(probeKind, lang)}` : '';
437
- result = {
438
- sessionId: result.sessionId,
439
- text: '',
440
- error: t(lang, 'bridge.fallback.allDown', { list: tried.map((line) => `• ${line}`).join('\n') }) + verdictLine,
441
- };
442
- }
356
+ // The walk lives in `fallback.mjs`: a chain that mixes companies needs a probe
357
+ // per provider, and this file is at its size ceiling.
358
+ result = await runFallbackChain({
359
+ result,
360
+ chain: Array.isArray(config.fallbackModels) ? config.fallbackModels : [],
361
+ // The route this topic actually runs on, so a final verdict names the right
362
+ // host instead of a hardcoded one.
363
+ primary: modelOf(turnProfile || profileOf(key) || config.profile),
364
+ text,
365
+ sessionAtStart,
366
+ key,
367
+ where,
368
+ chatId,
369
+ threadId,
370
+ lang,
371
+ cwd,
372
+ turnProfile,
373
+ topicProfile: profileOf(key),
374
+ telemetry,
375
+ onEvent,
376
+ thoughtEnv,
377
+ send,
378
+ });
443
379
  // A session opened in the desktop UI holds its write handle, so the CLI
444
380
  // refuses to adopt it. Retry once, then continue in a fresh session instead
445
381
  // of failing the user's message.
package/i18n/en/core.mjs CHANGED
@@ -14,7 +14,7 @@ export default {
14
14
  'settings.state.on': 'on',
15
15
  'settings.state.off': 'off',
16
16
  'settings.state.auto': 'auto',
17
- '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 · /tasks [\u003ctext\u003e|done N] · /tasks (tap to tick)\nSessions: /status · /sessions [\u003cid\u003e] · /rewind [n|undo|fork [n]|branches] · /new · /profile \u003cname\u003e\nAgents: /agents · /agents set model|depth|filter … @tool\nModels: /model · /model \u003cid\u003e · /prices · /thoughts\nTuning: /effort · /permissions · /preset · /crew [use|show|off|new] · /plan · /jobs · /remind\nExtensions: /skills · /plugins [add|remove] · /soul\nVersions: /update [confirm|on|off|auto] · /subscribe on|off\nOther: /settings · /lang · /reasoning · /doctor · /logs [errors|N] · /app · /restart · /help\nPanels: /menu — the same commands as buttons, page by page. /menu on puts four keys under the message field.",
17
+ '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 · /tasks [\u003ctext\u003e|done N] · /tasks (tap to tick)\nSessions: /status · /sessions [\u003cid\u003e] · /rewind [n|undo|fork [n]|branches] · /new · /profile \u003cname\u003e\nAgents: /agents · /agents set model|depth|filter … @tool\nModels: /model · /model \u003cid\u003e · /prices · /thoughts\nTuning: /effort · /permissions · /preset · /crew [use|show|off|new] · /plan · /jobs [n] · /remind\nExtensions: /skills · /plugins [add|remove] · /soul\nVersions: /update [confirm|on|off|auto] · /subscribe on|off\nOther: /settings · /lang · /reasoning · /doctor · /logs [errors|N] · /app · /restart · /help\nPanels: /menu — the same commands as buttons, page by page. /menu on puts four keys under the message field.",
18
18
  'settings.reply.title': 'What the bot says',
19
19
  'settings.agent.title': 'Who answers, and how hard it works',
20
20
  'settings.updates.title': 'New releases (this install, not this topic)',
@@ -93,6 +93,7 @@ export default {
93
93
  'cmd.restart.started': 'Restarting the bridge…',
94
94
  'msg.generalGuard': "This is the General topic, where topics are started. {cmd} changes “{topic}”, so open that topic and send it there. Reading works here: /status, /sessions, /stop.",
95
95
  'msg.unknownCommand': 'Unknown command: {cmd}. Open /help — it lists everything this bot can do.',
96
+ 'msg.commandFailed': '⚠️ /{cmd} failed: {err}\nNothing was half-done on purpose — check /logs before running it again.',
96
97
  'msg.langSet': 'Language set to English.',
97
98
  'msg.reasoningOn': 'Working notes on: 💭 lines will appear in the progress message.\nOff: /reasoning off',
98
99
  'msg.reasoningOff': 'Working notes off. The progress message keeps the step list only.\nOn: /reasoning on',
package/i18n/en/ctrl.mjs CHANGED
@@ -390,6 +390,10 @@ export default {
390
390
  'ctrl.jobs.thisTopic': 'this topic',
391
391
  'ctrl.jobs.queued': 'Waiting behind: {n} (up to {max} turns run at once)',
392
392
  'ctrl.jobs.hint': 'A turn is one DSH process: its own background jobs die with it. /stop ends this topic\'s turn.',
393
+ 'ctrl.jobs.cap': 'Parallel turns at once: {n}. Tap a number below, or send /jobs 5.',
394
+ 'ctrl.jobs.capSet': 'Parallel turns at once: {n}. Saved to config.json — it applies to the next turn that starts, no restart needed.',
395
+ 'ctrl.jobs.capUnsaved': 'Parallel turns at once: {n} for this process only — config.json could not be written, so a restart goes back to the old value. Check /logs.',
396
+ 'ctrl.jobs.capRange': 'A number from 1 to 8. Each parallel turn is a full DSH process, so more than 8 on one machine makes every turn slower, not faster.',
393
397
  'ctrl.remind.title': '⏰ Reminders',
394
398
  'ctrl.remind.empty': 'Nothing scheduled.',
395
399
  'ctrl.remind.line': '{n}. {when} ({left}) — {text}',
package/i18n/ru/core.mjs CHANGED
@@ -14,7 +14,7 @@ export default {
14
14
  'settings.state.on': 'вкл',
15
15
  'settings.state.off': 'выкл',
16
16
  'settings.state.auto': 'авто',
17
- 'help.body': "Задачу можно писать обычным текстом. Каждая ветка форума — отдельная сессия:\n\nРабота: /cd \u003cпроект\u003e · /new · /stop · /send \u003cфайл\u003e · /seed \u003cтекст\u003e\nЦели: /goal · /tasks [\u003ctext\u003e|done N] · /tasks (нажать, чтобы отметить)\nСессии: /status · /sessions [\u003cid\u003e] · /rewind [n|undo|fork [n]|branches] · /new · /profile \u003cимя\u003e\nАгенты: /agents · /agents set model|depth|filter … @tool\nМодели: /model · /model \u003cid\u003e · /prices · /thoughts\nНастройка: /effort · /permissions · /preset · /crew [use|show|off|new] · /plan · /jobs · /remind\nРасширения: /skills · /plugins [add|remove] · /soul\nВерсии: /update [confirm|on|off|auto] · /subscribe on|off\nПрочее: /settings · /lang · /reasoning · /doctor · /logs [errors|N] · /app · /restart · /help\nПанели: /menu — те же команды кнопками, по страницам. /menu on добавляет четыре клавиши под полем ввода.",
17
+ 'help.body': "Задачу можно писать обычным текстом. Каждая ветка форума — отдельная сессия:\n\nРабота: /cd \u003cпроект\u003e · /new · /stop · /send \u003cфайл\u003e · /seed \u003cтекст\u003e\nЦели: /goal · /tasks [\u003ctext\u003e|done N] · /tasks (нажать, чтобы отметить)\nСессии: /status · /sessions [\u003cid\u003e] · /rewind [n|undo|fork [n]|branches] · /new · /profile \u003cимя\u003e\nАгенты: /agents · /agents set model|depth|filter … @tool\nМодели: /model · /model \u003cid\u003e · /prices · /thoughts\nНастройка: /effort · /permissions · /preset · /crew [use|show|off|new] · /plan · /jobs [n] · /remind\nРасширения: /skills · /plugins [add|remove] · /soul\nВерсии: /update [confirm|on|off|auto] · /subscribe on|off\nПрочее: /settings · /lang · /reasoning · /doctor · /logs [errors|N] · /app · /restart · /help\nПанели: /menu — те же команды кнопками, по страницам. /menu on добавляет четыре клавиши под полем ввода.",
18
18
  'settings.reply.title': 'Что бот говорит',
19
19
  'settings.agent.title': 'Кто отвечает и как старается',
20
20
  'settings.updates.title': 'Новые версии (эта установка, не тема)',
@@ -93,6 +93,7 @@ export default {
93
93
  'cmd.restart.started': 'Перезапускаю мост…',
94
94
  'msg.generalGuard': "Это общая тема «Все» — здесь темы начинаются. {cmd} меняет «{topic}», поэтому откройте ту тему и отправьте команду там. Читать можно и здесь: /status, /sessions, /stop.",
95
95
  'msg.unknownCommand': 'Неизвестная команда: {cmd}. Открой /help — там всё, что умеет бот.',
96
+ 'msg.commandFailed': '⚠️ /{cmd} не сработала: {err}\nНичего не сделано наполовину намеренно — посмотри /logs, прежде чем повторять.',
96
97
  'msg.langSet': 'Язык переключён на русский.',
97
98
  'msg.reasoningOn': 'Заметки по ходу включены: 💭 будут появляться в сообщении прогресса.\nВыключить: /reasoning off',
98
99
  'msg.reasoningOff': 'Заметки по ходу выключены. В прогрессе остаётся только список шагов.\nВключить: /reasoning on',
package/i18n/ru/ctrl.mjs CHANGED
@@ -390,6 +390,10 @@ export default {
390
390
  'ctrl.jobs.thisTopic': 'эта тема',
391
391
  'ctrl.jobs.queued': 'Ждут позади: {n} (одновременно идёт до {max} ходов)',
392
392
  'ctrl.jobs.hint': 'Ход — это один процесс DSH: его фоновые задачи умирают вместе с ним. /stop завершает ход этой темы.',
393
+ 'ctrl.jobs.cap': 'Одновременных ходов: {n}. Нажми число ниже или отправь /jobs 5.',
394
+ 'ctrl.jobs.capSet': 'Одновременных ходов: {n}. Записано в config.json — применится к следующему начатому ходу, перезапуск не нужен.',
395
+ 'ctrl.jobs.capUnsaved': 'Одновременных ходов: {n} только для этого процесса — config.json не записался, после перезапуска вернётся старое значение. Посмотри /logs.',
396
+ 'ctrl.jobs.capRange': 'Число от 1 до 8. Каждый параллельный ход — отдельный процесс DSH, поэтому больше 8 на одной машине замедляет все ходы, а не ускоряет.',
393
397
  'ctrl.remind.title': '⏰ Напоминания',
394
398
  'ctrl.remind.empty': 'Ничего не запланировано.',
395
399
  'ctrl.remind.line': '{n}. {when} ({left}) — {text}',
package/i18n/zh/core.mjs CHANGED
@@ -14,7 +14,7 @@ export default {
14
14
  'settings.state.on': '开',
15
15
  'settings.state.off': '关',
16
16
  'settings.state.auto': '自动',
17
- 'help.body': "任务直接以文本发送。每个论坛话题是一个独立会话:\n\n工作: /cd \u003c项目\u003e · /new · /stop · /send \u003c文件\u003e · /seed \u003c文本\u003e\n目标: /goal · /tasks [\u003ctext\u003e|done N] · /tasks(点击勾选)\n会话: /status · /sessions [\u003cid\u003e] · /rewind [n|undo|fork [n]|branches] · /new · /profile \u003c名称\u003e\n智能体: /agents · /agents set model|depth|filter … @tool\n模型: /model · /model \u003cid\u003e · /prices · /thoughts\n调优: /effort · /permissions · /preset · /crew [use|show|off|new] · /plan · /jobs · /remind\n扩展: /skills · /plugins [add|remove] · /soul\n版本: /update [confirm|on|off|auto] · /subscribe on|off\n其他: /settings · /lang · /reasoning · /doctor · /logs [errors|N] · /app · /restart · /help\n面板: /menu — 同样的命令做成按钮,分页浏览。/menu on 在输入框下方加四个键。",
17
+ 'help.body': "任务直接以文本发送。每个论坛话题是一个独立会话:\n\n工作: /cd \u003c项目\u003e · /new · /stop · /send \u003c文件\u003e · /seed \u003c文本\u003e\n目标: /goal · /tasks [\u003ctext\u003e|done N] · /tasks(点击勾选)\n会话: /status · /sessions [\u003cid\u003e] · /rewind [n|undo|fork [n]|branches] · /new · /profile \u003c名称\u003e\n智能体: /agents · /agents set model|depth|filter … @tool\n模型: /model · /model \u003cid\u003e · /prices · /thoughts\n调优: /effort · /permissions · /preset · /crew [use|show|off|new] · /plan · /jobs [n] · /remind\n扩展: /skills · /plugins [add|remove] · /soul\n版本: /update [confirm|on|off|auto] · /subscribe on|off\n其他: /settings · /lang · /reasoning · /doctor · /logs [errors|N] · /app · /restart · /help\n面板: /menu — 同样的命令做成按钮,分页浏览。/menu on 在输入框下方加四个键。",
18
18
  'settings.reply.title': '机器人怎么说',
19
19
  'settings.agent.title': '谁来回答、投入多少',
20
20
  'settings.updates.title': '新版本(针对本次安装,而非话题)',
@@ -93,6 +93,7 @@ export default {
93
93
  'cmd.restart.started': '正在重启桥…',
94
94
  'msg.generalGuard': "这里是「全部」主题,用来开新话题。{cmd} 会改动「{topic}」,请打开那个话题再发送。这里可以直接读:/status、/sessions、/stop。",
95
95
  'msg.unknownCommand': '未知命令:{cmd}。打开 /help 查看机器人支持的全部命令。',
96
+ 'msg.commandFailed': '⚠️ /{cmd} 执行失败:{err}\n不会故意留下做了一半的状态——重试前先看 /logs。',
96
97
  'msg.langSet': '界面语言已切换为中文。',
97
98
  'msg.reasoningOn': '工作记录已开启:💭 会显示在进度消息里。\n关闭:/reasoning off',
98
99
  'msg.reasoningOff': '工作记录已关闭,进度消息只保留步骤列表。\n开启:/reasoning on',
package/i18n/zh/ctrl.mjs CHANGED
@@ -390,6 +390,10 @@ export default {
390
390
  'ctrl.jobs.thisTopic': '本话题',
391
391
  'ctrl.jobs.queued': '后面等待:{n}(同时最多 {max} 轮)',
392
392
  'ctrl.jobs.hint': '一轮就是一个 DSH 进程:它的后台任务随进程结束。 /stop 结束本话题的轮次。',
393
+ 'ctrl.jobs.cap': '同时运行的轮次:{n}。点下面的数字,或发送 /jobs 5。',
394
+ 'ctrl.jobs.capSet': '同时运行的轮次:{n}。已写入 config.json——下一轮开始时生效,无需重启。',
395
+ 'ctrl.jobs.capUnsaved': '同时运行的轮次:{n},仅本进程有效——config.json 未能写入,重启后会回到旧值。请看 /logs。',
396
+ 'ctrl.jobs.capRange': '数字范围 1 到 8。每个并行轮次都是一个完整的 DSH 进程,所以同一台机器上超过 8 会让所有轮次变慢,而不是变快。',
393
397
  'ctrl.remind.title': '⏰ 提醒',
394
398
  'ctrl.remind.empty': '没有安排。',
395
399
  'ctrl.remind.line': '{n}. {when}({left})— {text}',
package/jobs-cap.mjs ADDED
@@ -0,0 +1,29 @@
1
+ // The parallel-turn ceiling: one rule, two ways in.
2
+ //
3
+ // `/jobs 5` and the buttons under the `/jobs` card write the same number, and a
4
+ // tap must not be able to store a value the command would refuse. The ceiling is
5
+ // a real machine limit — every parallel turn is a whole DSH process — so the
6
+ // range is closed at eight and the refusal says why instead of clamping.
7
+ //
8
+ // The live config changes first and is persisted second: a failed write costs
9
+ // the setting after a restart, not the setting now, and the caller reports which
10
+ // of the two happened rather than claiming a save it did not make.
11
+ export const CAP_MIN = 1;
12
+ export const CAP_MAX = 8;
13
+
14
+ /** The values the card offers. Five rows of buttons is already a lot of thumb. */
15
+ export const CAP_CHOICES = [1, 2, 3, 4, 5, 8];
16
+
17
+ /**
18
+ * Apply a ceiling. Returns `{ ok:false }` for anything outside the range, and
19
+ * `{ ok:true, n, saved }` otherwise, with `saved` false when config.json could
20
+ * not be written.
21
+ */
22
+ export function setParallel(value, { config, saveConfig, log }) {
23
+ const n = Number(String(value).trim());
24
+ if (!Number.isInteger(n) || n < CAP_MIN || n > CAP_MAX) return { ok: false };
25
+ config.maxParallel = n;
26
+ const saved = Boolean(saveConfig && saveConfig());
27
+ if (log) log(`maxParallel set to ${n}${saved ? '' : ' (config.json write failed)'}`);
28
+ return { ok: true, n, saved };
29
+ }
package/model-probe.mjs CHANGED
@@ -26,38 +26,83 @@ function secret(name) {
26
26
  }
27
27
 
28
28
  /**
29
- * The provider this install answers through first: its base URL and the name of
30
- * the env var holding its key, read from the profile the bridge runs with.
29
+ * Split the `providers:` block of a profile patch into rows: `{id, lines}`.
30
+ *
31
+ * The file is hand-written YAML with a fixed shape — `providers:` at two spaces,
32
+ * a provider id at six, its fields deeper — and a full YAML parser would be a
33
+ * dependency for four fields. The row indent is read from the first child line
34
+ * rather than assumed, so a reformatted profile still parses.
35
+ */
36
+ export function providerRows(patch) {
37
+ const lines = String(patch || '').split('\n');
38
+ const at = lines.findIndex((line) => /^\s*providers:\s*$/.test(line));
39
+ if (at < 0) return [];
40
+ const firstChild = lines.slice(at + 1).find((line) => line.trim() && !/^\s*#/.test(line));
41
+ const rowIndent = (/^(\s*)/.exec(firstChild || '')?.[1] || '').length;
42
+ const rows = [];
43
+ let current = null;
44
+ for (let i = at + 1; i < lines.length; i += 1) {
45
+ const line = lines[i];
46
+ if (!line.trim()) continue;
47
+ if (/^\s*#/.test(line)) {
48
+ if (current) current.lines.push(line);
49
+ continue;
50
+ }
51
+ const depth = (/^(\s*)/.exec(line)[1] || '').length;
52
+ // The block ends at the first line shallower than a provider row.
53
+ if (depth < rowIndent) break;
54
+ const row = depth === rowIndent ? /^\s*([\w.-]+):\s*$/.exec(line) : null;
55
+ if (row) {
56
+ current = { id: row[1], lines: [] };
57
+ rows.push(current);
58
+ continue;
59
+ }
60
+ if (current) current.lines.push(line);
61
+ }
62
+ return rows;
63
+ }
64
+
65
+ /**
66
+ * One provider row from the profile the bridge runs with: base URL, the env var
67
+ * holding its key, and the API shape it speaks.
31
68
  *
32
69
  * Nothing is hardcoded here on purpose. A probe against a host the bot does not
33
70
  * use reports the wrong fault — "your key is rejected" when the key was never
34
71
  * meant for that host — and a wrong answer is worse than no answer.
72
+ *
73
+ * With one router in the chain a single row described every attempt. A chain
74
+ * that mixes companies has a row per company, and asking provider A about
75
+ * provider B's model is the same wrong answer as asking a host the bot never
76
+ * uses, so the caller names the provider and gets that row.
77
+ *
78
+ * @param {string} [wanted] provider id as the profile writes it; empty = first
35
79
  */
36
- let cachedProvider;
37
- export function firstProvider() {
38
- if (cachedProvider !== undefined) return cachedProvider;
80
+ const providerCache = new Map();
81
+ export function providerFor(wanted = '') {
82
+ const id = String(wanted || '').trim();
83
+ if (providerCache.has(id)) return providerCache.get(id);
39
84
  const profile = process.env.DSH_PROFILE || 'headless';
40
85
  let patch = '';
41
86
  try {
42
87
  patch = readFileSync(join(DSH_HOME, 'profiles', profile, 'cordis.patch.yml'), 'utf8');
43
88
  } catch {
44
- cachedProvider = null;
45
- return cachedProvider;
89
+ providerCache.set(id, null);
90
+ return null;
46
91
  }
47
- const lines = patch.split('\n');
48
- const at = lines.findIndex((line) => /^\s*providers:\s*$/.test(line));
49
- const found = { baseUrl: '', keyEnv: '' };
50
- if (at >= 0) {
51
- // The first provider block: both fields belong to the row the bot tries
52
- // first, which is the one a verdict is about.
53
- for (let i = at + 1; i < lines.length; i += 1) {
54
- if (/^\S/.test(lines[i])) break;
55
- const base = lines[i].match(/^\s+baseURL:\s*["']?([^"'\s]+)/);
92
+ const found = { id: '', baseUrl: '', keyEnv: '', api: '' };
93
+ // Every provider row in the block: its id, its indent, and the lines under it.
94
+ for (const row of providerRows(patch)) {
95
+ if (id && row.id !== id) continue;
96
+ found.id = row.id;
97
+ for (const line of row.lines) {
98
+ const base = line.match(/^\s+baseURL:\s*["']?([^"'\s]+)/);
56
99
  if (base && !found.baseUrl) found.baseUrl = base[1].replace(/\/+$/, '');
57
- const key = lines[i].match(/^\s+apiKeyEnv:\s*["']?([^"'\s]+)/);
100
+ const key = line.match(/^\s+apiKeyEnv:\s*["']?([^"'\s]+)/);
58
101
  if (key && !found.keyEnv) found.keyEnv = key[1];
59
- if (found.baseUrl && found.keyEnv) break;
102
+ const api = line.match(/^\s+api:\s*["']?([^"'\s]+)/);
103
+ if (api && !found.api) found.api = api[1];
60
104
  }
105
+ break;
61
106
  }
62
107
  // The profile row is the source of truth. These two overrides exist for the
63
108
  // one case the file cannot describe — pointing the probe at a different host
@@ -65,8 +110,14 @@ export function firstProvider() {
65
110
  // public and a name here would ship someone's vendor with it.
66
111
  const baseUrl = (process.env.DSH_PROBE_BASE_URL || found.baseUrl || '').trim().replace(/\/+$/, '');
67
112
  const keyEnv = (process.env.DSH_PROBE_KEY_ENV || '').trim() || found.keyEnv;
68
- cachedProvider = baseUrl ? { baseUrl, keyEnv } : null;
69
- return cachedProvider;
113
+ const provider = baseUrl ? { id: found.id, baseUrl, keyEnv, api: found.api } : null;
114
+ providerCache.set(id, provider);
115
+ return provider;
116
+ }
117
+
118
+ /** The provider the install answers through first: the profile's first row. */
119
+ export function firstProvider() {
120
+ return providerFor('');
70
121
  }
71
122
 
72
123
  /** Classify a provider answer into something the chat can act on. */
@@ -83,10 +134,17 @@ function classify(status, body) {
83
134
  /**
84
135
  * One 1-token completion. `ok` means the channel really answers for this
85
136
  * account right now — not just that the name exists.
137
+ *
138
+ * `provider` names whose route to ask: with a single router the profile's first
139
+ * row answered for every model, but a chain that mixes companies must ask the
140
+ * company that owns the model — otherwise the verdict describes a host that was
141
+ * never tried, and a working route gets skipped for someone else's 503.
86
142
  */
87
- async function probeModel(model, { timeoutMs = 15000 } = {}) {
88
- const provider = firstProvider();
89
- if (!provider) return { model, ok: false, kind: 'unknown', detail: 'no provider base url in this profile' };
143
+ async function probeModel(model, { timeoutMs = 15000, provider: wanted = '' } = {}) {
144
+ const provider = providerFor(wanted);
145
+ if (!provider) {
146
+ return { model, ok: false, kind: 'unknown', detail: wanted ? `no provider ${wanted} in this profile` : 'no provider base url in this profile' };
147
+ }
90
148
  const key = secret(provider.keyEnv);
91
149
  if (!key) return { model, ok: false, kind: 'auth', detail: `${provider.keyEnv || 'the key'} is missing` };
92
150
  const controller = new AbortController();
@@ -114,16 +172,25 @@ async function probeModel(model, { timeoutMs = 15000 } = {}) {
114
172
  }
115
173
  }
116
174
 
117
- /** First channel that answers, or null. Probes run in order, so the cheapest wins. */
175
+ /**
176
+ * First channel that answers, or null. Probes run in order, so the cheapest wins.
177
+ *
178
+ * Entries are `{model, provider}`: the same model name can exist on two routers,
179
+ * and probing one of them twice would burn a request to learn nothing.
180
+ */
118
181
  async function firstLiveModel(models) {
119
182
  const seen = new Set();
120
183
  const verdicts = [];
121
- for (const model of models) {
122
- if (!model || seen.has(model)) continue;
123
- seen.add(model);
124
- const verdict = await probeModel(model);
125
- verdicts.push(verdict);
126
- if (verdict.ok) return { live: verdict, verdicts };
184
+ for (const item of models) {
185
+ const model = typeof item === 'string' ? item : item?.model;
186
+ const provider = typeof item === 'string' ? '' : item?.provider || '';
187
+ if (!model) continue;
188
+ const id = `${provider}/${model}`;
189
+ if (seen.has(id)) continue;
190
+ seen.add(id);
191
+ const verdict = await probeModel(model, { provider });
192
+ verdicts.push({ ...verdict, provider });
193
+ if (verdict.ok) return { live: { ...verdict, provider }, verdicts };
127
194
  }
128
195
  return { live: null, verdicts };
129
196
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-tg-bridge",
3
- "version": "1.22.0",
3
+ "version": "1.24.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",
@@ -101,6 +101,7 @@
101
101
  "plugin/",
102
102
  "profiles.mjs",
103
103
  "model-probe.mjs",
104
+ "fallback.mjs",
104
105
  "aset-profile.mjs",
105
106
  "aset-schema.mjs",
106
107
  "aset-job.mjs",
@@ -142,6 +143,7 @@
142
143
  "handle-message.mjs",
143
144
  "callbacks.mjs",
144
145
  "run-command.mjs",
146
+ "jobs-cap.mjs",
145
147
  "job-loops.mjs"
146
148
  ],
147
149
  "homepage": "https://github.com/aleksvega/dsh-tg-bridge#readme",
package/queue.mjs CHANGED
@@ -11,7 +11,7 @@ import { langFor } from './commands.mjs';
11
11
  import { resolveLang, t } from './i18n.mjs';
12
12
  import { sessionKey, threadOf } from './keys.mjs';
13
13
  import { RESTART_MARKER } from './paths.mjs';
14
- import { config, log, state } from './state.mjs';
14
+ import { config, log, saveConfig, state } from './state.mjs';
15
15
  import { busyNotices, clearBusyNotice, steerAvailable, steerMediaMessage } from './steer.mjs';
16
16
  import { send, tg } from './telegram.mjs';
17
17
  import { liveSessions, profileOf, turnStartedAt } from './turn.mjs';
@@ -21,7 +21,7 @@ let handle = () => { throw new Error('queue: message handler is not wired'); };
21
21
  export function setMessageHandler(fn) { handle = fn; }
22
22
 
23
23
  /** A steer that outlived its turn becomes a turn of its own. */
24
- const redeliver = (key, message) => enqueue(key, () => handle(message));
24
+ export const redeliver = (key, message) => enqueue(key, () => handle(message));
25
25
  // Per-topic turn queues: one turn at a time inside a topic, different topics run
26
26
  // in parallel. Bounded, because every turn is a full Electron process.
27
27
  export const queues = new Map();
package/run-command.mjs CHANGED
@@ -3,8 +3,8 @@
3
3
  import { langFor } from './commands.mjs';
4
4
  import { handleControl } from './control.mjs';
5
5
  import { t } from './i18n.mjs';
6
- import { MAX_PARALLEL } from './queue.mjs';
7
- import { config, log, saveState, state } from './state.mjs';
6
+ import { maxParallel, queues } from './queue.mjs';
7
+ import { config, log, saveConfig, saveState, state } from './state.mjs';
8
8
  import { send, sendEphemeral, sendFile, sendWithMarkup, tg } from './telegram.mjs';
9
9
  import { ensureTopicSeed } from './topics.mjs';
10
10
  import { activeTurns, profileOf, turnStartedAt } from './turn.mjs';
@@ -25,12 +25,13 @@ export async function runCommandFromButton(typed, { chatId, threadId, key }) {
25
25
  config,
26
26
  activeTurns,
27
27
  saveState,
28
+ saveConfig,
28
29
  log,
29
30
  send,
30
31
  jobs: () => ({
31
32
  active: [...activeTurns.keys()].map((topic) => ({ key: topic, startedAt: turnStartedAt.get(topic) || 0 })),
32
33
  queued: [...queues.keys()].filter((topic) => !activeTurns.has(topic)).length,
33
- max: MAX_PARALLEL,
34
+ max: maxParallel(),
34
35
  }),
35
36
  api: tg,
36
37
  sendFile: (p, caption = '') => sendFile(chatId, threadId, p, caption),
package/state.mjs CHANGED
@@ -76,6 +76,28 @@ export function saveDone() {
76
76
  }
77
77
  }
78
78
 
79
+ /**
80
+ * Write config.json back.
81
+ *
82
+ * Only for a setting the owner changed from the chat: `config` is the live
83
+ * object every module reads, so mutating it first and persisting second means a
84
+ * failed write costs the restart, not the current setting. Re-reads the file so
85
+ * keys written by hand (tokens, profiles) are not dropped by a stale copy.
86
+ */
87
+ export function saveConfig() {
88
+ try {
89
+ let onDisk = {};
90
+ try {
91
+ onDisk = JSON.parse(readFileSync(join(DIR, 'config.json'), 'utf8').replace(/^\uFEFF/, ''));
92
+ } catch {}
93
+ writeAtomic(join(DIR, 'config.json'), `${JSON.stringify({ ...onDisk, ...config }, null, 2)}\n`);
94
+ return true;
95
+ } catch (error) {
96
+ log(`config.json write failed: ${error.message}`);
97
+ return false;
98
+ }
99
+ }
100
+
79
101
  export function pendingPath(updateId) {
80
102
  return join(PENDING_DIR, `${updateId}.json`);
81
103
  }
@@ -127,7 +149,10 @@ export function pendingUpdates() {
127
149
  continue;
128
150
  }
129
151
  try {
130
- out.push({ update: JSON.parse(readFileSync(full, 'utf8')), id });
152
+ // `at` is the moment the update arrived, which is what the replay loop
153
+ // needs to tell "this was mid-flight when we died" from "this has been
154
+ // sitting here for hours and the person has long since moved on".
155
+ out.push({ update: JSON.parse(readFileSync(full, 'utf8')), id, at: stat.mtimeMs });
131
156
  } catch {
132
157
  try { unlinkSync(full); } catch {}
133
158
  }
package/steer.mjs CHANGED
@@ -13,7 +13,7 @@ import { config, log, state } from './state.mjs';
13
13
  import { resolveLang, t } from './i18n.mjs';
14
14
  import { sessionKey } from './keys.mjs';
15
15
  import { activeTurns } from './turn.mjs';
16
- import { send } from './telegram.mjs';
16
+ import { send, tg } from './telegram.mjs';
17
17
  import { mediaPrompt } from './media.mjs';
18
18
  /**
19
19
  * Queue notices, one per topic. A notice exists only while the person is
package/telegram.mjs CHANGED
@@ -84,6 +84,40 @@ export async function downloadFile(fileId, fileName) {
84
84
  * shapes a person can end up with, so every call site hands its intent here
85
85
  * instead of building `reply_markup` itself.
86
86
  */
87
+ /**
88
+ * Rows of buttons, in the one shape Telegram accepts.
89
+ *
90
+ * The cards build buttons as `{ text, data }` — a payload, not a Telegram field,
91
+ * because the card does not know or care where it will be drawn. Telegram wants
92
+ * `callback_data` and rejects the *whole message* with "Text buttons are not
93
+ * allowed in the inline keyboard" when it sees `data` instead. That rejection was
94
+ * swallowed by the `.catch(() => {})` on every send, so `/menu`, `/settings` and
95
+ * the task card drew nothing at all and said nothing about it.
96
+ *
97
+ * One conversion here, at the edge, so a card can keep its own vocabulary.
98
+ */
99
+ export function inlineKeyboard(rows) {
100
+ if (!Array.isArray(rows)) return rows;
101
+ const out = [];
102
+ for (const row of rows) {
103
+ if (!Array.isArray(row)) { out.push(row); continue; }
104
+ const buttons = [];
105
+ for (const button of row) {
106
+ if (!button || typeof button !== 'object') { buttons.push(button); continue; }
107
+ const { data, ...rest } = button;
108
+ const payload = rest.callback_data ?? rest.url ?? rest.web_app ?? data;
109
+ // A button with neither a payload nor a link is a label Telegram refuses —
110
+ // and it refuses the whole message, not the button.
111
+ if (payload === undefined) continue;
112
+ buttons.push(rest.callback_data !== undefined || rest.url !== undefined || rest.web_app !== undefined
113
+ ? rest
114
+ : { ...rest, callback_data: String(payload) });
115
+ }
116
+ if (buttons.length > 0) out.push(buttons);
117
+ }
118
+ return out;
119
+ }
120
+
87
121
  export async function sendWithMarkup(chatId, threadId, text, extra = {}) {
88
122
  const thread = threadId > 0 ? { message_thread_id: threadId } : {};
89
123
  if (extra.removeKeyboard) {
@@ -107,9 +141,15 @@ export async function sendWithMarkup(chatId, threadId, text, extra = {}) {
107
141
  chat_id: chatId,
108
142
  text,
109
143
  disable_web_page_preview: true,
110
- reply_markup: { inline_keyboard: extra.keyboard },
144
+ reply_markup: { inline_keyboard: inlineKeyboard(extra.keyboard) },
111
145
  ...thread,
112
- }).catch(() => {});
146
+ }).catch((error) => {
147
+ // Silence here cost a release: the card never appeared and the log said
148
+ // nothing. A keyboard Telegram refuses is a bug in this repo, so say which
149
+ // button it was and still deliver the text without buttons.
150
+ log(`inline keyboard rejected (${String(error.message).slice(0, 160)}); sending without buttons`);
151
+ return tg('sendMessage', { chat_id: chatId, text, disable_web_page_preview: true, ...thread }).catch(() => {});
152
+ });
113
153
  }
114
154
  return send(chatId, text, threadId);
115
155
  }