dsh-tg-bridge 1.17.0 → 1.18.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/bridge.mjs +56 -6
- package/menu-card.mjs +12 -0
- package/model-probe.mjs +126 -0
- package/package.json +2 -1
package/bridge.mjs
CHANGED
|
@@ -30,6 +30,7 @@ import { createAlbumBuffer } from './albums.mjs';
|
|
|
30
30
|
import { turnArgs } from './cli-args.mjs';
|
|
31
31
|
import { chunk, markdownParts, toPlainText, toTelegramHtml } from './format.mjs';
|
|
32
32
|
import { ensureProfile } from './profiles.mjs';
|
|
33
|
+
import { firstLiveModel, describeVerdicts, probeHint, probeModel } from './model-probe.mjs';
|
|
33
34
|
import { handleControl, CONTROL_COMMANDS, modelOf, modelsOf, reasoningOf } from './control.mjs';
|
|
34
35
|
import { bridgeVersion, installRelease, npmLatestAsync } from './control.mjs';
|
|
35
36
|
import { dueForCheck, updateState } from './update-policy.mjs';
|
|
@@ -47,7 +48,7 @@ import { commandFor, renderSettingsCard, settingsCurrent } from './settings-card
|
|
|
47
48
|
import { answerRewindPress, cutSession, isRewindPress } from './rewind-buttons.mjs';
|
|
48
49
|
import { applyRewind, newestBackup, restoreBackup } from './rewind.mjs';
|
|
49
50
|
import { sessionFile } from './thoughts.mjs';
|
|
50
|
-
import { MENU_PREFIX, commandForName, isMenuPress, renderPanel } from './menu-card.mjs';
|
|
51
|
+
import { MENU_PREFIX, commandForName, isMenuPress, renderPanel, runsUnasked } from './menu-card.mjs';
|
|
51
52
|
|
|
52
53
|
const HOME = homedir();
|
|
53
54
|
const DSH_HOME = process.env.DSH_HOME || join(HOME, '.dsh');
|
|
@@ -1756,10 +1757,24 @@ ${t(lang, 'help.body')}`,
|
|
|
1756
1757
|
// chain as well, otherwise the bridge sits on AUTH 403 and gives up.
|
|
1757
1758
|
const FALLBACK_TRIGGERS = /RATE_LIMIT|503|all providers|нет активности|EMPTY_RESPONSE|TIMEOUT|overloaded|AUTH|403|insufficient_user_quota|quota|UNKNOWN_MODEL|MISSING_CREDENTIAL/i;
|
|
1758
1759
|
const QUOTA_LIKE = /insufficient_user_quota|AUTH\b|\b403\b|\b401\b|quota|balance|баланс|payment|billing/i;
|
|
1760
|
+
// "get_channel_failed / all providers are busy" is the provider's own channel
|
|
1761
|
+
// pool, not the model: when it is down, it is down for every model in the
|
|
1762
|
+
// chain. One probe then answers in seconds what four full turns spent 741
|
|
1763
|
+
// seconds discovering.
|
|
1764
|
+
const CHANNEL_DOWN = /get_channel_failed|all providers|no providers|503/i;
|
|
1759
1765
|
const tried = [];
|
|
1760
1766
|
for (const entry of chain) {
|
|
1761
1767
|
if (!result.error || !FALLBACK_TRIGGERS.test(result.error)) break;
|
|
1762
1768
|
if (!entry.patch || !existsSync(entry.patch)) continue;
|
|
1769
|
+
// The provider's channel pool is down: every model in the chain will answer
|
|
1770
|
+
// the same 503. Ask once, quickly, and say so instead of burning a turn per
|
|
1771
|
+
// model. A probe that DOES answer proves the pool is back — then the chain
|
|
1772
|
+
// goes on, and the fallback at hand is tried as usual.
|
|
1773
|
+
if (tried.length >= 1 && CHANNEL_DOWN.test(result.error)) {
|
|
1774
|
+
const verdict = await probeModel(config.primaryModel || 'deepseek-v4.1-flash-1017');
|
|
1775
|
+
log(`channel down after ${tried.length} model(s): probe says ${verdict.kind}; not trying ${entry.model}`);
|
|
1776
|
+
if (!verdict.ok) break;
|
|
1777
|
+
}
|
|
1763
1778
|
const quotaLike = QUOTA_LIKE.test(result.error);
|
|
1764
1779
|
// Quota failures never deserve a retry of the same model: the balance is
|
|
1765
1780
|
// gone, so waiting is pure loss. Anything else gets one retry at most.
|
|
@@ -1785,13 +1800,41 @@ ${t(lang, 'help.body')}`,
|
|
|
1785
1800
|
});
|
|
1786
1801
|
if (!result.error) break;
|
|
1787
1802
|
}
|
|
1788
|
-
// Every model refused
|
|
1789
|
-
|
|
1790
|
-
|
|
1803
|
+
// Every model refused. Before saying "all models are unavailable", ask each
|
|
1804
|
+
// channel directly with a 1-token request: a 503 storm usually clears within
|
|
1805
|
+
// seconds, and the verdict tells the person whether the balance is gone or the
|
|
1806
|
+
// provider is merely busy — the old message always claimed quota.
|
|
1807
|
+
let probeKind = '';
|
|
1808
|
+
if (result.error && FALLBACK_TRIGGERS.test(result.error)) {
|
|
1809
|
+
const models = [config.primaryModel || 'deepseek-v4.1-flash-1017', ...chain.map((entry) => entry.model)];
|
|
1810
|
+
const { live, verdicts } = await firstLiveModel(models);
|
|
1811
|
+
if (live) {
|
|
1812
|
+
log(`probe: ${live.model} answers after ${verdicts.length} check(s), retrying the turn there`);
|
|
1813
|
+
const entry = chain.find((item) => item.model === live.model);
|
|
1814
|
+
result = await runTurnLive(text, sessionAtStart, key, {
|
|
1815
|
+
onEvent,
|
|
1816
|
+
onAbort: () => killTurn(key),
|
|
1817
|
+
onHeartbeat: () => progress.heartbeat(),
|
|
1818
|
+
profile: entry ? ensureProfile(entry.patch) : turnProfile,
|
|
1819
|
+
cwd,
|
|
1820
|
+
lang,
|
|
1821
|
+
});
|
|
1822
|
+
} else {
|
|
1823
|
+
// Nothing answers: the verdict is the only useful part of the failure.
|
|
1824
|
+
probeKind = describeVerdicts(verdicts);
|
|
1825
|
+
log(`probe: no channel answers (${verdicts.map((v) => `${v.model}:${v.kind}`).join(', ')})`);
|
|
1826
|
+
}
|
|
1827
|
+
}
|
|
1828
|
+
// Every model refused — or the provider's own channel pool was down and the
|
|
1829
|
+
// chain stopped early, which is the same answer to the person: one message
|
|
1830
|
+
// naming the causes, not a cascade of errors.
|
|
1831
|
+
if (result.error && tried.length > 0 && (probeKind || tried.length >= (Array.isArray(config.fallbackModels) ? config.fallbackModels.length : 0))) {
|
|
1832
|
+
log(`all fallbacks exhausted for ${where}: ${tried.length} probe=${probeKind || 'n/a'}`);
|
|
1833
|
+
const verdictLine = probeKind ? `\n${probeHint(probeKind, lang)}` : '';
|
|
1791
1834
|
result = {
|
|
1792
1835
|
sessionId: result.sessionId,
|
|
1793
1836
|
text: '',
|
|
1794
|
-
error: t(lang, 'bridge.fallback.allDown', { list: tried.map((line) => `• ${line}`).join('\n') }),
|
|
1837
|
+
error: t(lang, 'bridge.fallback.allDown', { list: tried.map((line) => `• ${line}`).join('\n') }) + verdictLine,
|
|
1795
1838
|
};
|
|
1796
1839
|
}
|
|
1797
1840
|
// A session opened in the desktop UI holds its write handle, so the CLI
|
|
@@ -1844,6 +1887,9 @@ ${t(lang, 'help.body')}`,
|
|
|
1844
1887
|
await send(chatId, result.text || t(lang, 'bridge.progress.emptyReply'), threadId);
|
|
1845
1888
|
}
|
|
1846
1889
|
|
|
1890
|
+
// `probeHint` lives in model-probe.mjs: this file used it at the call site and
|
|
1891
|
+
// defined it below, and the hint never reached the person.
|
|
1892
|
+
|
|
1847
1893
|
/**
|
|
1848
1894
|
* Turn a raw CLI/provider error into `CODE` plus one actionable line.
|
|
1849
1895
|
*
|
|
@@ -2323,7 +2369,11 @@ async function handleCallback(query) {
|
|
|
2323
2369
|
}
|
|
2324
2370
|
}
|
|
2325
2371
|
await clearKeyboard();
|
|
2326
|
-
|
|
2372
|
+
// `/new` and `/stop` change something when typed alone, and a stray tap on
|
|
2373
|
+
// them is a command nobody asked for — so they open their explanation.
|
|
2374
|
+
const typed = runsUnasked(name) && CONTROL_COMMANDS.includes(name)
|
|
2375
|
+
? commandForName(name, { t: (k, v) => t(lang, k, v) })
|
|
2376
|
+
: `/help ${name}`;
|
|
2327
2377
|
await answer(typed || t(lang, 'bridge.cb.unknown'));
|
|
2328
2378
|
if (!typed) return;
|
|
2329
2379
|
log(`menu press /${name} for ${key}`);
|
package/menu-card.mjs
CHANGED
|
@@ -69,4 +69,16 @@ export function commandForName(name, { t }) {
|
|
|
69
69
|
const bare = ['cd', 'resume', 'seed', 'send', 'effort', 'logs', 'rewind'];
|
|
70
70
|
if (bare.includes(name)) return `/help ${name}`;
|
|
71
71
|
return `/${name}`;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Whether `/menu` done alone would change something. Almost every command only
|
|
76
|
+
* reports what is already true; `new` and `stop` do not, and a stray tap on them
|
|
77
|
+
* would be a command nobody asked for. Those open their explanation instead.
|
|
78
|
+
*/
|
|
79
|
+
const CHANGES_ALONE = ['new', 'stop'];
|
|
80
|
+
|
|
81
|
+
/** Whether a press labelled `name`, tapped on its own, is safe to run. */
|
|
82
|
+
export function runsUnasked(name) {
|
|
83
|
+
return !CHANGES_ALONE.includes(name);
|
|
72
84
|
}
|
package/model-probe.mjs
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// Live model probe.
|
|
2
|
+
//
|
|
3
|
+
// A turn that ends with "all models are unavailable" is useless on its own: the
|
|
4
|
+
// person cannot tell an exhausted balance from a provider that is merely busy,
|
|
5
|
+
// and the bridge used to burn 12 minutes before saying it. One tiny request per
|
|
6
|
+
// channel answers that question in seconds, and a channel that answers can be
|
|
7
|
+
// used for one more attempt instead of giving up.
|
|
8
|
+
import { readFileSync } from 'node:fs';
|
|
9
|
+
import { homedir } from 'node:os';
|
|
10
|
+
import { join } from 'node:path';
|
|
11
|
+
|
|
12
|
+
const DSH_HOME = process.env.DSH_HOME || join(homedir(), '.dsh');
|
|
13
|
+
const CRED = join(DSH_HOME, '.credentials.yaml');
|
|
14
|
+
const BASE = process.env.UNOROUTER_BASE_URL || 'https://api.unorouter.com/v1';
|
|
15
|
+
|
|
16
|
+
function secret(name) {
|
|
17
|
+
const fromEnv = (process.env[name] || '').trim();
|
|
18
|
+
if (fromEnv) return fromEnv;
|
|
19
|
+
try {
|
|
20
|
+
const yaml = readFileSync(CRED, 'utf8');
|
|
21
|
+
const m = yaml.match(new RegExp(`^\\s*${name}:\\s*["']?([^"'\\s]+)`, 'm'));
|
|
22
|
+
return m ? m[1] : '';
|
|
23
|
+
} catch {
|
|
24
|
+
return '';
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Classify a provider answer into something the chat can act on. */
|
|
29
|
+
function classify(status, body) {
|
|
30
|
+
const text = String(body || '');
|
|
31
|
+
if (status === 200) return 'ok';
|
|
32
|
+
if (/insufficient_user_quota|balance|billing|payment/i.test(text)) return 'balance';
|
|
33
|
+
if (/get_channel_failed|all providers|rate limit|busy/i.test(text)) return 'busy';
|
|
34
|
+
if (status === 401 || status === 403) return 'auth';
|
|
35
|
+
if (status === 404) return 'missing';
|
|
36
|
+
return 'other';
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* One 1-token completion. `ok` means the channel really answers for this
|
|
41
|
+
* account right now — not just that the name exists.
|
|
42
|
+
*/
|
|
43
|
+
async function probeModel(model, { timeoutMs = 15000 } = {}) {
|
|
44
|
+
const key = secret('UNOROUTER_API_KEY');
|
|
45
|
+
if (!key) return { model, ok: false, kind: 'auth', detail: 'UNOROUTER_API_KEY is missing' };
|
|
46
|
+
const controller = new AbortController();
|
|
47
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
48
|
+
try {
|
|
49
|
+
const response = await fetch(`${BASE}/chat/completions`, {
|
|
50
|
+
method: 'POST',
|
|
51
|
+
headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' },
|
|
52
|
+
body: JSON.stringify({ model, messages: [{ role: 'user', content: 'ping' }], max_tokens: 1, stream: false }),
|
|
53
|
+
signal: controller.signal,
|
|
54
|
+
});
|
|
55
|
+
const body = await response.text();
|
|
56
|
+
const kind = classify(response.status, body);
|
|
57
|
+
return {
|
|
58
|
+
model,
|
|
59
|
+
ok: kind === 'ok',
|
|
60
|
+
kind,
|
|
61
|
+
status: response.status,
|
|
62
|
+
detail: kind === 'ok' ? '' : body.slice(0, 200),
|
|
63
|
+
};
|
|
64
|
+
} catch (error) {
|
|
65
|
+
return { model, ok: false, kind: 'network', detail: String(error?.message ?? error) };
|
|
66
|
+
} finally {
|
|
67
|
+
clearTimeout(timer);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** First channel that answers, or null. Probes run in order, so the cheapest wins. */
|
|
72
|
+
async function firstLiveModel(models) {
|
|
73
|
+
const seen = new Set();
|
|
74
|
+
const verdicts = [];
|
|
75
|
+
for (const model of models) {
|
|
76
|
+
if (!model || seen.has(model)) continue;
|
|
77
|
+
seen.add(model);
|
|
78
|
+
const verdict = await probeModel(model);
|
|
79
|
+
verdicts.push(verdict);
|
|
80
|
+
if (verdict.ok) return { live: verdict, verdicts };
|
|
81
|
+
}
|
|
82
|
+
return { live: null, verdicts };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Short human line for the failure message: what is actually wrong. */
|
|
86
|
+
function describeVerdicts(verdicts) {
|
|
87
|
+
const kinds = new Set(verdicts.map((v) => v.kind));
|
|
88
|
+
if (kinds.has('balance')) return 'balance';
|
|
89
|
+
if (kinds.has('busy')) return 'busy';
|
|
90
|
+
if (kinds.has('auth')) return 'auth';
|
|
91
|
+
if (kinds.has('network')) return 'network';
|
|
92
|
+
return 'unknown';
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* What to tell the person once the probe has a verdict. The old version glued
|
|
97
|
+
* the verdict onto a raw provider string, and the message opened with the tail
|
|
98
|
+
* of an English error ("...balance" + "in"). The verdict is the message.
|
|
99
|
+
*/
|
|
100
|
+
function probeHint(kind, lang = 'ru') {
|
|
101
|
+
const text = {
|
|
102
|
+
balance: {
|
|
103
|
+
ru: 'Баланс провайдера пуст: проба вернула 403 «недостаточно средств». Пополни счёт или переключись на free-модель через /model.',
|
|
104
|
+
en: 'The provider balance is empty: the probe got a 403 "insufficient funds". Top up, or switch to a free model with /model.',
|
|
105
|
+
zh: '提供商余额为空:探测返回 403「余额不足」。请充值,或用 /model 切换到免费模型。',
|
|
106
|
+
},
|
|
107
|
+
busy: {
|
|
108
|
+
ru: 'Провайдер перегружен: все каналы отдают 503. Это не баланс — повтори через пару минут.',
|
|
109
|
+
en: 'The provider is overloaded: every channel answers 503. Not a balance problem — try again in a few minutes.',
|
|
110
|
+
zh: '提供商过载:所有通道都返回 503。不是余额问题——过几分钟再试。',
|
|
111
|
+
},
|
|
112
|
+
auth: {
|
|
113
|
+
ru: 'Ключ не принят: провайдер вернул 401/403. Проверь ~/.dsh/.credentials.yaml.',
|
|
114
|
+
en: 'The key was rejected: the provider answered 401/403. Check ~/.dsh/.credentials.yaml.',
|
|
115
|
+
zh: '密钥未被接受:提供商返回 401/403。请检查 ~/.dsh/.credentials.yaml。',
|
|
116
|
+
},
|
|
117
|
+
network: {
|
|
118
|
+
ru: 'Сеть не отвечает: проба не достучалась до провайдера. Проверь VPN и IPv4.',
|
|
119
|
+
en: 'The network does not answer: the probe could not reach the provider. Check VPN and IPv4.',
|
|
120
|
+
zh: '网络无响应:探测无法连接提供商。请检查 VPN 和 IPv4。',
|
|
121
|
+
},
|
|
122
|
+
};
|
|
123
|
+
return text[kind]?.[lang] ?? text[kind]?.ru ?? '';
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export { probeModel, firstLiveModel, describeVerdicts, probeHint };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-tg-bridge",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.18.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",
|
|
@@ -78,6 +78,7 @@
|
|
|
78
78
|
"steer-queue.mjs",
|
|
79
79
|
"plugin/",
|
|
80
80
|
"profiles.mjs",
|
|
81
|
+
"model-probe.mjs",
|
|
81
82
|
"aset-profile.mjs",
|
|
82
83
|
"aset-schema.mjs",
|
|
83
84
|
"aset-job.mjs",
|