dsh-tg-bridge 1.23.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,10 +112,35 @@ 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
116
  | `maxParallel` | how many topics run at once, 1–8, default `3`; also `/jobs 5` in the chat |
117
117
  | `replayWindowMs` | how old a journaled update may be and still be replayed after a restart; default `600000` (10 min) |
118
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.
143
+
119
144
  Get your id from [@userinfobot](https://t.me/userinfobot), the token from
120
145
  [@BotFather](https://t.me/BotFather).
121
146
 
@@ -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
  /**
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,17 +8,16 @@
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
22
  import { lastPrompt, maxParallel, queues } from './queue.mjs';
24
23
  import { token } from './secrets.mjs';
@@ -26,7 +25,6 @@ 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) {
@@ -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/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.23.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",