dsh-tg-bridge 1.25.0 → 1.25.1
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 +38 -2
- package/callbacks.mjs +26 -1
- package/commands-registry.mjs +1 -1
- package/config.example.json +1 -0
- package/control/cmd-bridge.mjs +5 -1
- package/control/cmd-fallback.mjs +239 -0
- package/control.mjs +2 -1
- package/failures.mjs +8 -0
- package/fallback-card.mjs +181 -0
- package/fallback.mjs +179 -22
- package/help-explain.mjs +1 -1
- package/i18n/en/core.mjs +9 -1
- package/i18n/en/fallback.mjs +51 -0
- package/i18n/en.mjs +5 -4
- package/i18n/ru/core.mjs +9 -1
- package/i18n/ru/fallback.mjs +51 -0
- package/i18n/ru.mjs +5 -4
- package/i18n/zh/core.mjs +9 -1
- package/i18n/zh/fallback.mjs +51 -0
- package/i18n/zh.mjs +9 -8
- package/menu-card.mjs +2 -1
- package/package.json +3 -1
- package/report.mjs +1 -1
package/README.md
CHANGED
|
@@ -118,6 +118,7 @@ Optional provider settings live in `config.json`:
|
|
|
118
118
|
| `vision.patch` | opt-in overlay profile for photo turns; default `""` — the turn's own model reads images |
|
|
119
119
|
| `vision.enabled` | set `true` to run photo turns on `vision.patch` instead of the topic profile |
|
|
120
120
|
| `fallbackModels` | ordered failover chain; default `[]` — see below |
|
|
121
|
+
| `fallbackEnabled` | `false` switches the whole chain off without editing the list; `/fallback off` sets it |
|
|
121
122
|
| `maxParallel` | how many topics run at once, 1–8, default `3`; also `/jobs 5` in the chat |
|
|
122
123
|
| `replayWindowMs` | how old a journaled update may be and still be replayed after a restart; default `600000` (10 min) |
|
|
123
124
|
|
|
@@ -129,7 +130,8 @@ model refuses:
|
|
|
129
130
|
"provider": "router-a",
|
|
130
131
|
"model": "some-model",
|
|
131
132
|
"patch": "~/.dsh/tg-bridge/model-a.yml",
|
|
132
|
-
"free": false
|
|
133
|
+
"free": false,
|
|
134
|
+
"off": false
|
|
133
135
|
}
|
|
134
136
|
```
|
|
135
137
|
|
|
@@ -138,7 +140,9 @@ model refuses:
|
|
|
138
140
|
keeps every other setting and only the model changes. `provider` is the id the
|
|
139
141
|
provider is written under in the profile — it decides whose key and host the
|
|
140
142
|
pre-flight probe asks, so the same model id on two routers stays two attempts.
|
|
141
|
-
`free` only adds `(free)` to the switch notice.
|
|
143
|
+
`free` only adds `(free)` to the switch notice. `off` keeps an entry in the list
|
|
144
|
+
but out of the walk; an entry whose `patch` file is missing is skipped the same
|
|
145
|
+
way, and the chat says so instead of counting it.
|
|
142
146
|
|
|
143
147
|
The chain may mix companies: a 503 from one provider says nothing about another,
|
|
144
148
|
so a busy channel skips its own models and the next company is still tried. Put
|
|
@@ -146,6 +150,38 @@ models from different companies next to each other — two arms of one router ar
|
|
|
146
150
|
one outage, not two chances — and keep the `:free` models at the end, as the
|
|
147
151
|
last resort.
|
|
148
152
|
|
|
153
|
+
**What starts a switch.** Anything the provider itself says no to: a 400/413/422
|
|
154
|
+
refusal (its own validator rejecting the request), 401/403 (key refused), 402 or
|
|
155
|
+
a quota/balance message (empty account), 404 (that model id is not carried),
|
|
156
|
+
429 (rate limit), 5xx and `get_channel_failed` / "all providers busy" (the pool
|
|
157
|
+
is down), a dropped connection or DNS/TLS failure, and an empty answer. A refusal
|
|
158
|
+
gets one other route, not the whole chain: it is replayed in full, and if the
|
|
159
|
+
second vendor refuses identically the request — not the route — is what is wrong,
|
|
160
|
+
so the reply says to start a fresh session with `/new`.
|
|
161
|
+
|
|
162
|
+
**What does not start a switch.** The turn time cap, `/stop`, a session or
|
|
163
|
+
directory error, a missing `dsh` binary: no other vendor changes those, and a
|
|
164
|
+
replay would cost a full turn to learn the same thing. They are listed in the
|
|
165
|
+
card so the distinction is visible instead of guessed.
|
|
166
|
+
|
|
167
|
+
### `/fallback` — the chain from the chat
|
|
168
|
+
|
|
169
|
+
```
|
|
170
|
+
/fallback the card: chain state, numbered routes, what starts a switch
|
|
171
|
+
/fallback on | off the whole chain (per route: /fallback off 3)
|
|
172
|
+
/fallback use 3 | skip 3 one route back in or out
|
|
173
|
+
/fallback up 3 | down 3 move a route in the order
|
|
174
|
+
/fallback test [3] ask each route (or one) with a 1-token request
|
|
175
|
+
/fallback add <provider>/<model> write an overlay and append the route
|
|
176
|
+
/fallback remove 3 drop a route from the list (its overlay file stays)
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
Every line has a button on the card: `● n` switches a route, `↑ n` / `↓ n` move
|
|
180
|
+
it, and the card redraws in place after each press. `test` proves the key and the
|
|
181
|
+
channel are alive — not that the provider accepts this conversation, so a route
|
|
182
|
+
can answer `ping` and still refuse a long prompt with a 400. The card says that
|
|
183
|
+
in as many words.
|
|
184
|
+
|
|
149
185
|
Get your id from [@userinfobot](https://t.me/userinfobot), the token from
|
|
150
186
|
[@BotFather](https://t.me/BotFather).
|
|
151
187
|
|
package/callbacks.mjs
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
// update or an approval, and only one handler may claim it.
|
|
4
4
|
import { AgentsetStore } from './agentsets.mjs';
|
|
5
5
|
import { CONTROL_COMMANDS, handleControl, reasoningOf } from './control.mjs';
|
|
6
|
+
import { isFallbackPress, pressTarget } from './fallback-card.mjs';
|
|
6
7
|
import { progressOf, toggleTask } from './goals.mjs';
|
|
7
8
|
import { handleMessage } from './handle-message.mjs';
|
|
8
9
|
import { resolveLang, t } from './i18n.mjs';
|
|
@@ -14,7 +15,7 @@ import { answerRewindPress, cutSession, isRewindPress } from './rewind-buttons.m
|
|
|
14
15
|
import { applyRewind, newestBackup, restoreBackup } from './rewind.mjs';
|
|
15
16
|
import { runCommandFromButton } from './run-command.mjs';
|
|
16
17
|
import { commandFor, renderSettingsCard, settingsCurrent } from './settings-card.mjs';
|
|
17
|
-
import { config, done, log, saveState, state } from './state.mjs';
|
|
18
|
+
import { config, done, log, saveConfig, saveState, state } from './state.mjs';
|
|
18
19
|
import { inlineKeyboard, send, sendFile, tg } from './telegram.mjs';
|
|
19
20
|
import { sessionFile } from './thoughts.mjs';
|
|
20
21
|
import { activeTurns, killTurn, profileOf } from './turn.mjs';
|
|
@@ -152,6 +153,27 @@ export async function handleCallback(query) {
|
|
|
152
153
|
return;
|
|
153
154
|
}
|
|
154
155
|
|
|
156
|
+
// A button on the failover card. Every press becomes the verb of `/fallback`,
|
|
157
|
+
// so a tap and a typed line land in the same code — and the command redraws the
|
|
158
|
+
// card, which is why the old keyboard is trimmed only when the press leaves it.
|
|
159
|
+
if (isFallbackPress(data)) {
|
|
160
|
+
const target = pressTarget(data);
|
|
161
|
+
const words = { t: 'toggle', u: 'up', d: 'down', x: 'test', e: 'chain', s: 'show' };
|
|
162
|
+
// `r` is two verbs on one letter: with a number it removes that route, alone
|
|
163
|
+
// it opens the remove list. Anything else is a stale card and does nothing.
|
|
164
|
+
const verb = target && (target.verb === 'r' ? (target.n ? 'remove' : 'menu') : words[target.verb]);
|
|
165
|
+
if (!verb) {
|
|
166
|
+
await answer(t(lang, 'bridge.cb.unknown'));
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
const typed = target.n && verb !== 'menu' ? `/fallback ${verb} ${target.n}` : `/fallback ${verb}`;
|
|
170
|
+
await clearKeyboard();
|
|
171
|
+
await answer(typed);
|
|
172
|
+
log(`fallback press ${typed} for ${key}`);
|
|
173
|
+
await runCommandFromButton(typed, { chatId, threadId, key, lang });
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
|
|
155
177
|
if (isMenuPress(data)) {
|
|
156
178
|
// The panel is a set of cards: the hub, then one page per section. Moving
|
|
157
179
|
// between them edits this message, so browsing costs no new messages. A
|
|
@@ -349,6 +371,9 @@ export async function handleCardPress(query, ctx) {
|
|
|
349
371
|
config,
|
|
350
372
|
activeTurns,
|
|
351
373
|
saveState,
|
|
374
|
+
// `/fallback` writes config.json; without this the press would look applied
|
|
375
|
+
// and vanish on restart, which is the worst of both answers.
|
|
376
|
+
saveConfig,
|
|
352
377
|
log,
|
|
353
378
|
send: (text) => {
|
|
354
379
|
replies.push(String(text ?? ''));
|
package/commands-registry.mjs
CHANGED
|
@@ -12,7 +12,7 @@ export const CONTROL_COMMANDS = [
|
|
|
12
12
|
'skills', 'soul', 'restart', 'app', 'stop', 'new', 'seed', 'send', 'cd',
|
|
13
13
|
'prices', 'help', 'doctor', 'logs', 'report', 'lang', 'reasoning', 'goal', 'task', 'tasks',
|
|
14
14
|
'thoughts', 'version', 'update', 'crew', 'agentset', 'subscribe', 'settings',
|
|
15
|
-
'rewind', 'fork', 'branches', 'menu',
|
|
15
|
+
'rewind', 'fork', 'branches', 'menu', 'fallback',
|
|
16
16
|
];
|
|
17
17
|
|
|
18
18
|
/**
|
package/config.example.json
CHANGED
package/control/cmd-bridge.mjs
CHANGED
|
@@ -19,6 +19,7 @@ import { applyFork, planFork, planRewind } from '../rewind.mjs';
|
|
|
19
19
|
import { cutSession, isRewindPress } from '../rewind-buttons.mjs';
|
|
20
20
|
import { renderRewindCard, renderRewindUsage } from '../rewind-card.mjs';
|
|
21
21
|
import { MENU_GROUPS, commandForName, renderPanel, replyKeyboard } from '../menu-card.mjs';
|
|
22
|
+
import { chainSummary } from '../fallback-card.mjs';
|
|
22
23
|
import { explainCommand } from '../help-explain.mjs';
|
|
23
24
|
import { profileValues, resolveSettings } from '../settings.mjs';
|
|
24
25
|
import { UPDATE_DEFAULTS, describeUpdate, modeChange, updateState } from '../update-policy.mjs';
|
|
@@ -341,7 +342,10 @@ export async function handleBridgeCommands(ctx) {
|
|
|
341
342
|
const toOwner = Boolean(owner) && Number(chatId) === owner && !Number(threadId);
|
|
342
343
|
const patchText = read(patchPath(activeProfile));
|
|
343
344
|
const preset = effectivePreset(patchText)?.id || '';
|
|
344
|
-
|
|
345
|
+
// The same renderer the card uses: a report that counted routes a turn
|
|
346
|
+
// would skip is the report that hides the bug it was opened for.
|
|
347
|
+
const entries = Array.isArray(config.fallbackModels) ? config.fallbackModels : [];
|
|
348
|
+
const chain = chainSummary(entries, { t: (k, v) => t(lang, k, v) });
|
|
345
349
|
const failure = state.lastFailure?.[key]?.error || '';
|
|
346
350
|
const text = buildReport({
|
|
347
351
|
version: bridgeVersion(),
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
// `/fallback`: the failover chain, as a card a person can change from the chat.
|
|
2
|
+
//
|
|
3
|
+
// The chain used to be a `config.json` key with no reader: a turn that failed on
|
|
4
|
+
// one vendor either switched to something nobody chose or, more often, did not
|
|
5
|
+
// switch at all, and the chat could not say why. The card answers "what is behind
|
|
6
|
+
// this route", and every button runs a verb of this command, so a tap and a typed
|
|
7
|
+
// line can never disagree.
|
|
8
|
+
//
|
|
9
|
+
// One group of the `/` surface. `control.mjs` owns the dispatch and this file owns
|
|
10
|
+
// the command.
|
|
11
|
+
import { writeFileSync } from 'node:fs';
|
|
12
|
+
import { join } from 'node:path';
|
|
13
|
+
import { normalizeLang, t } from '../i18n.mjs';
|
|
14
|
+
import { DIR } from '../paths.mjs';
|
|
15
|
+
import { removeKeyboard, renderFallbackCard, renderProbe } from '../fallback-card.mjs';
|
|
16
|
+
import { labelOf } from '../fallback.mjs';
|
|
17
|
+
import { probeModel, providerRows } from '../model-probe.mjs';
|
|
18
|
+
import { modelOf, patchPath, read } from './models.mjs';
|
|
19
|
+
|
|
20
|
+
/** Provider ids as the profile spells them: a route on an unknown one cannot boot. */
|
|
21
|
+
function providerIds(profile) {
|
|
22
|
+
return providerRows(read(patchPath(profile))).map((row) => row.id).filter(Boolean);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** `unorouter/kimi-k3:free` → `{provider, model}`; a bare id keeps the given provider. */
|
|
26
|
+
export function splitRoute(wanted, fallbackProvider = '') {
|
|
27
|
+
const text = String(wanted || '').trim();
|
|
28
|
+
const at = text.indexOf('/');
|
|
29
|
+
if (at > 0) return { provider: text.slice(0, at), model: text.slice(at + 1) };
|
|
30
|
+
return { provider: fallbackProvider, model: text };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* The overlay file one route needs, in the shape the shipped ones have.
|
|
35
|
+
*
|
|
36
|
+
* The host CLI has no `--patch`, so a route is a profile materialised from this
|
|
37
|
+
* file by `ensureProfile()`; a chain entry without a readable overlay is a route
|
|
38
|
+
* the turn silently skips, which is the failure this command exists to end.
|
|
39
|
+
*/
|
|
40
|
+
export function overlayText({ provider, model }) {
|
|
41
|
+
return `- id: agent-default-model\n config:\n provider: ${provider}\n model: ${model}\n`;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Stable file name for a route: `model-<provider>-<model>.yml`.
|
|
46
|
+
*
|
|
47
|
+
* The shape the shipped overlays already have (`model-glm-5_3.yml`): dots and
|
|
48
|
+
* dashes stay, because they are part of the model id, and a colon — the `:free`
|
|
49
|
+
* suffix — becomes an underscore, because a colon is not a filename character on
|
|
50
|
+
* Windows. The same route therefore gets the same file on every platform.
|
|
51
|
+
*/
|
|
52
|
+
export function overlayName({ provider, model }) {
|
|
53
|
+
const slug = `${provider}-${model}`.replace(/[^a-z0-9.-]+/gi, '_').replace(/^_+|_+$/g, '');
|
|
54
|
+
return `model-${slug}.yml`;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** What the chat calls a probe result. */
|
|
58
|
+
const VERDICT = {
|
|
59
|
+
ok: 'ok',
|
|
60
|
+
balance: 'balance',
|
|
61
|
+
auth: 'auth',
|
|
62
|
+
busy: 'busy',
|
|
63
|
+
network: 'network',
|
|
64
|
+
missing: 'missing',
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
export async function handleFallbackCommands(ctx) {
|
|
68
|
+
const { command, arg, reply, log, profile, config, lang: rawLang } = ctx;
|
|
69
|
+
const lang = normalizeLang(rawLang) || normalizeLang(config?.lang) || 'en';
|
|
70
|
+
const say = (text, extra) => (extra ? reply(text, extra) : reply(text));
|
|
71
|
+
const activeProfile = profile || config.profile || 'headless';
|
|
72
|
+
if ((ctx.effective || command) !== '/fallback') return false;
|
|
73
|
+
|
|
74
|
+
// Read fresh on every press: a button may arrive after another one already
|
|
75
|
+
// reordered the chain, and acting on the card's copy would move the wrong route.
|
|
76
|
+
const chain = Array.isArray(config.fallbackModels) ? config.fallbackModels : [];
|
|
77
|
+
const enabled = config.fallbackEnabled !== false;
|
|
78
|
+
const tr = (key, vars) => t(lang, key, vars);
|
|
79
|
+
const save = () => {
|
|
80
|
+
const ok = typeof ctx.saveConfig === 'function' ? ctx.saveConfig() : false;
|
|
81
|
+
if (!ok) log('fallback: config.json was not written; the change lives until restart');
|
|
82
|
+
return ok;
|
|
83
|
+
};
|
|
84
|
+
const card = (extra = '') => {
|
|
85
|
+
const body = renderFallbackCard({ t: tr, chain, primary: modelOf(activeProfile), enabled });
|
|
86
|
+
say(extra ? `${extra}\n\n${body.text}` : body.text, { keyboard: body.keyboard });
|
|
87
|
+
};
|
|
88
|
+
const done = (key, vars) => card(t(lang, save() ? key : 'ctrl.fallback.unsaved', vars));
|
|
89
|
+
|
|
90
|
+
const [word = '', ...rest] = String(arg || '').trim().split(/\s+/).filter(Boolean);
|
|
91
|
+
const verb = word.toLowerCase();
|
|
92
|
+
const n = Number(rest[0] || word);
|
|
93
|
+
const at = Number.isInteger(n) && n > 0 ? n - 1 : -1;
|
|
94
|
+
const entry = at >= 0 ? chain[at] : null;
|
|
95
|
+
// Answers and returns true in one step: a handler that says something and
|
|
96
|
+
// returns falsy makes the button router claim the press was unknown.
|
|
97
|
+
const missing = () => {
|
|
98
|
+
say(t(lang, 'ctrl.fallback.noSuch', { n: rest[0] || word }));
|
|
99
|
+
return true;
|
|
100
|
+
};
|
|
101
|
+
const setOff = (value) => {
|
|
102
|
+
if (value) entry.off = true;
|
|
103
|
+
else delete entry.off;
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
switch (verb) {
|
|
107
|
+
case '':
|
|
108
|
+
case 'show':
|
|
109
|
+
case 's':
|
|
110
|
+
card();
|
|
111
|
+
return true;
|
|
112
|
+
|
|
113
|
+
// The whole chain, on or off. Off is a promise: `runFallbackChain` reads the
|
|
114
|
+
// key before it sends anything, so no turn can switch behind the switch.
|
|
115
|
+
// With a number the same two words act on one route, because `off 3` is what
|
|
116
|
+
// a person types after reading the list.
|
|
117
|
+
case 'on':
|
|
118
|
+
case 'off': {
|
|
119
|
+
if (rest.length > 0) {
|
|
120
|
+
if (!entry) return missing();
|
|
121
|
+
setOff(verb === 'off');
|
|
122
|
+
done('ctrl.fallback.toggled', { route: labelOf(entry), state: tr(entry.off ? 'ctrl.fallback.routeOff' : 'ctrl.fallback.routeOn') });
|
|
123
|
+
return true;
|
|
124
|
+
}
|
|
125
|
+
config.fallbackEnabled = verb === 'on';
|
|
126
|
+
done(verb === 'on' ? 'ctrl.fallback.chainOn' : 'ctrl.fallback.chainOff');
|
|
127
|
+
return true;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// One route. The card's ● button sends `toggle`, and the two explicit words
|
|
131
|
+
// exist for a typed line: a toggle cannot express "on", and a press that
|
|
132
|
+
// arrives twice must land in the same state, not flip back.
|
|
133
|
+
case 'use':
|
|
134
|
+
case 'skip':
|
|
135
|
+
case 'toggle': {
|
|
136
|
+
if (!entry) return missing();
|
|
137
|
+
if (verb === 'use') setOff(false);
|
|
138
|
+
else if (verb === 'skip') setOff(true);
|
|
139
|
+
else setOff(!entry.off);
|
|
140
|
+
done('ctrl.fallback.toggled', { route: labelOf(entry), state: tr(entry.off ? 'ctrl.fallback.routeOff' : 'ctrl.fallback.routeOn') });
|
|
141
|
+
return true;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
case 'up':
|
|
145
|
+
case 'down': {
|
|
146
|
+
if (!entry) return missing();
|
|
147
|
+
const to = verb === 'up' ? at - 1 : at + 1;
|
|
148
|
+
if (to < 0 || to >= chain.length) {
|
|
149
|
+
say(t(lang, 'ctrl.fallback.edge', { route: labelOf(entry) }));
|
|
150
|
+
return true;
|
|
151
|
+
}
|
|
152
|
+
[chain[at], chain[to]] = [chain[to], chain[at]];
|
|
153
|
+
done('ctrl.fallback.moved', { route: labelOf(entry), n: to + 1 });
|
|
154
|
+
return true;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
case 'remove': {
|
|
158
|
+
if (!entry) return missing();
|
|
159
|
+
// Only the chain entry goes: the overlay file may also be a vision patch,
|
|
160
|
+
// and a file left behind costs a few bytes while a deleted one costs a turn.
|
|
161
|
+
const [gone] = chain.splice(at, 1);
|
|
162
|
+
done('ctrl.fallback.removed', { route: labelOf(gone) });
|
|
163
|
+
return true;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
case 'add': {
|
|
167
|
+
const route = splitRoute(rest.join(' '));
|
|
168
|
+
if (!route.model) {
|
|
169
|
+
say(t(lang, 'ctrl.fallback.addUsage'));
|
|
170
|
+
return true;
|
|
171
|
+
}
|
|
172
|
+
const known = providerIds(activeProfile);
|
|
173
|
+
const provider = route.provider || known[0] || '';
|
|
174
|
+
if (!known.includes(provider)) {
|
|
175
|
+
say(t(lang, 'ctrl.fallback.unknownProvider', { name: provider || '?', list: known.join(', ') }));
|
|
176
|
+
return true;
|
|
177
|
+
}
|
|
178
|
+
const full = `${provider}/${route.model}`;
|
|
179
|
+
if (chain.some((item) => item.provider === provider && item.model === route.model)) {
|
|
180
|
+
say(t(lang, 'ctrl.fallback.dupe', { route: full }));
|
|
181
|
+
return true;
|
|
182
|
+
}
|
|
183
|
+
const patch = join(DIR, overlayName({ provider, model: route.model }));
|
|
184
|
+
writeFileSync(patch, overlayText({ provider, model: route.model }), 'utf8');
|
|
185
|
+
const fresh = { provider, model: route.model, patch };
|
|
186
|
+
if (/:free$/i.test(route.model)) fresh.free = true;
|
|
187
|
+
chain.push(fresh);
|
|
188
|
+
log(`fallback: added ${full} at ${patch}`);
|
|
189
|
+
done('ctrl.fallback.added', { route: full });
|
|
190
|
+
return true;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// A probe proves the key works, not that this conversation is acceptable: the
|
|
194
|
+
// hint says so, because "route is fine" beside a 400 would be a lie.
|
|
195
|
+
case 'test':
|
|
196
|
+
case 'x': {
|
|
197
|
+
const targets = entry ? [entry] : chain;
|
|
198
|
+
if (targets.length === 0) {
|
|
199
|
+
say(t(lang, 'ctrl.fallback.empty'));
|
|
200
|
+
return true;
|
|
201
|
+
}
|
|
202
|
+
const rows = [];
|
|
203
|
+
for (const item of targets) {
|
|
204
|
+
const verdict = await probeModel(item.model, { provider: item.provider });
|
|
205
|
+
rows.push({ n: chain.indexOf(item) + 1, route: labelOf(item), kind: VERDICT[verdict.kind] || 'other' });
|
|
206
|
+
log(`fallback probe ${labelOf(item)}: ${verdict.kind}${verdict.detail ? ` (${String(verdict.detail).slice(0, 80)})` : ''}`);
|
|
207
|
+
}
|
|
208
|
+
// One way back to the card: the probe answer is long, and the person who
|
|
209
|
+
// just learned route 4 is dead wants the list, not a typed command.
|
|
210
|
+
say(renderProbe({ t: tr, rows }), { keyboard: [[{ text: t(lang, 'ctrl.fallback.back'), data: 'fb:s' }]] });
|
|
211
|
+
return true;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// Removing asks for a second, named press: a number is only trustworthy while
|
|
215
|
+
// the card that printed it is still the card on screen.
|
|
216
|
+
case 'menu':
|
|
217
|
+
case 'r': {
|
|
218
|
+
if (chain.length === 0) {
|
|
219
|
+
say(t(lang, 'ctrl.fallback.empty'));
|
|
220
|
+
return true;
|
|
221
|
+
}
|
|
222
|
+
say(t(lang, 'ctrl.fallback.removeTitle'), { keyboard: removeKeyboard({ t: tr, chain }) });
|
|
223
|
+
return true;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
case 'e':
|
|
227
|
+
case 'chain': {
|
|
228
|
+
config.fallbackEnabled = !enabled;
|
|
229
|
+
done(config.fallbackEnabled ? 'ctrl.fallback.chainOn' : 'ctrl.fallback.chainOff');
|
|
230
|
+
return true;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
default:
|
|
234
|
+
// A word this command does not know is a usage line, not a prompt: the
|
|
235
|
+
// handler claims every `/fallback …`, so a typo never reaches the model.
|
|
236
|
+
say(t(lang, 'ctrl.fallback.usage'));
|
|
237
|
+
return true;
|
|
238
|
+
}
|
|
239
|
+
}
|
package/control.mjs
CHANGED
|
@@ -29,6 +29,7 @@ import { COMMAND_ALIASES, CONTROL_COMMANDS, DOCUMENTED_COMMANDS } from './comman
|
|
|
29
29
|
|
|
30
30
|
import { handleAgentCommands } from './control/cmd-agents.mjs';
|
|
31
31
|
import { handleBridgeCommands } from './control/cmd-bridge.mjs';
|
|
32
|
+
import { handleFallbackCommands } from './control/cmd-fallback.mjs';
|
|
32
33
|
import { handlePluginCommands } from './control/cmd-plugin.mjs';
|
|
33
34
|
import { handleSessionCommands } from './control/cmd-session.mjs';
|
|
34
35
|
import { handleSkillCommands } from './control/cmd-skills.mjs';
|
|
@@ -105,7 +106,7 @@ export async function handleControl(ctx) {
|
|
|
105
106
|
// that is not its job. The order is alphabetical, not meaningful: no two
|
|
106
107
|
// groups claim the same command, so a miss falls through to `default` below.
|
|
107
108
|
const child = { ...ctx, effective, command, arg: effectiveArgText, send, reply, log, profile, state, key, config, lang };
|
|
108
|
-
for (const handler of [handleAgentCommands, handleBridgeCommands, handlePluginCommands, handleSessionCommands, handleSkillCommands, handleTaskCommands, handleViewCommands]) {
|
|
109
|
+
for (const handler of [handleAgentCommands, handleBridgeCommands, handleFallbackCommands, handlePluginCommands, handleSessionCommands, handleSkillCommands, handleTaskCommands, handleViewCommands]) {
|
|
109
110
|
if (await handler(child)) return true;
|
|
110
111
|
}
|
|
111
112
|
// Nothing claimed it: the bridge answers an unknown `/` command itself, with
|
package/failures.mjs
CHANGED
|
@@ -28,6 +28,14 @@ export function explainFailure(text, lang = 'ru') {
|
|
|
28
28
|
'SANDBOX_DENY', 'bridge.fail.sandbox'],
|
|
29
29
|
[/UNKNOWN_MODEL|model not found|no such model/i,
|
|
30
30
|
'UNKNOWN_MODEL', 'bridge.fail.unknownModel'],
|
|
31
|
+
// A provider refusing the request shape is not the same as a dead balance:
|
|
32
|
+
// the fallback chain already tried the other companies, so the honest advice
|
|
33
|
+
// is "this request, not this route". Only the 400 class is a verdict on the
|
|
34
|
+
// request; a 429 or a 5xx is load, and each has its own sentence below.
|
|
35
|
+
[/INVALID_REQUEST|invalid_request_error|API error \((?:400|413|422)\)|HTTP (?:400|413|422)|Bad Request/i,
|
|
36
|
+
'PROVIDER_REJECT', 'bridge.fail.reject'],
|
|
37
|
+
[/RATE_LIMIT|\b429\b|rate.?limit|too many requests/i,
|
|
38
|
+
'RATE_LIMITED', 'bridge.fail.rate'],
|
|
31
39
|
[/empty response|EMPTY_RESPONSE|no output|пустой ответ/i,
|
|
32
40
|
'EMPTY_RESPONSE', 'bridge.fail.empty'],
|
|
33
41
|
];
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
// The failover card: the chain as a person can see it and change it.
|
|
2
|
+
//
|
|
3
|
+
// Why a card and not a config key: `fallbackModels` was invisible from the chat,
|
|
4
|
+
// so the only way to learn whether a failover would ever happen was to open
|
|
5
|
+
// config.json on the machine — and the honest answer to "why did it not switch"
|
|
6
|
+
// was often "nothing was configured to switch to". A numbered list with a button
|
|
7
|
+
// per route answers both questions, and the numbering is 1-based because it is
|
|
8
|
+
// what the person types next.
|
|
9
|
+
//
|
|
10
|
+
// This module renders; `control/cmd-fallback.mjs` changes. Keeping the two apart
|
|
11
|
+
// is what lets `/report` show the same lines without a second formatter.
|
|
12
|
+
import { existsSync } from 'node:fs';
|
|
13
|
+
import { labelOf } from './fallback.mjs';
|
|
14
|
+
|
|
15
|
+
/** Telegram's ceiling on callback payloads. */
|
|
16
|
+
const MAX_PAYLOAD = 64;
|
|
17
|
+
|
|
18
|
+
export const FALLBACK_PREFIX = 'fb:';
|
|
19
|
+
|
|
20
|
+
export function isFallbackPress(value) {
|
|
21
|
+
return String(value || '').startsWith(FALLBACK_PREFIX);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** A payload the router accepts: `fb:<verb>` or `fb:<verb>:<n>`. */
|
|
25
|
+
function press(verb, n = 0) {
|
|
26
|
+
const data = n ? `${FALLBACK_PREFIX}${verb}:${n}` : `${FALLBACK_PREFIX}${verb}`;
|
|
27
|
+
if (data.length > MAX_PAYLOAD) throw new Error(`payload too long: ${data}`);
|
|
28
|
+
return data;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** `fb:u:3` → `{ verb: 'u', n: 3 }`; anything else is null, never a throw. */
|
|
32
|
+
export function pressTarget(data) {
|
|
33
|
+
const text = String(data || '');
|
|
34
|
+
if (!text.startsWith(FALLBACK_PREFIX)) return null;
|
|
35
|
+
const [verb = '', raw = ''] = text.slice(FALLBACK_PREFIX.length).split(':');
|
|
36
|
+
if (!verb) return null;
|
|
37
|
+
const n = Number(raw);
|
|
38
|
+
return { verb, n: Number.isInteger(n) && n > 0 ? n : 0 };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Whether a route can actually be started.
|
|
43
|
+
*
|
|
44
|
+
* A missing overlay is the failure this guards: the entry sits in the chain, so
|
|
45
|
+
* the card counted it as a route while the turn skipped it without a word. A
|
|
46
|
+
* route that cannot boot is not a route, and the card says so instead of
|
|
47
|
+
* counting it.
|
|
48
|
+
*/
|
|
49
|
+
export function isUsable(entry) {
|
|
50
|
+
return Boolean(entry && entry.patch && existsSync(entry.patch));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The marks that change what a route is worth: free, switched off, unstartable. */
|
|
54
|
+
function marksOf(entry, { t }) {
|
|
55
|
+
const marks = [];
|
|
56
|
+
if (entry.free) marks.push(t('ctrl.fallback.free'));
|
|
57
|
+
if (entry.off) marks.push(t('ctrl.fallback.off'));
|
|
58
|
+
if (!isUsable(entry)) marks.push(t('ctrl.fallback.broken'));
|
|
59
|
+
return marks;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** `1. provider/model` plus the marks that change the answer: free, off, broken. */
|
|
63
|
+
export function chainLine(entry, index, { t }) {
|
|
64
|
+
const marks = marksOf(entry, { t });
|
|
65
|
+
const tail = marks.length ? ` · ${marks.join(' · ')}` : '';
|
|
66
|
+
return `${index + 1}. ${labelOf(entry) || t('ctrl.fallback.unnamed')}${tail}`;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* The chain in one line, for `/report`: the count, then the routes in order.
|
|
71
|
+
*
|
|
72
|
+
* The report is read by a maintainer who cannot see the card, and a bare list of
|
|
73
|
+
* names would hide the routes the turn skips — the very reason a report is opened.
|
|
74
|
+
*/
|
|
75
|
+
export function chainSummary(chain = [], { t }) {
|
|
76
|
+
if (chain.length === 0) return t('ctrl.fallback.empty');
|
|
77
|
+
const routes = chain.map((entry, index) => {
|
|
78
|
+
const marks = marksOf(entry, { t });
|
|
79
|
+
const tail = marks.length ? ` (${marks.join(' · ')})` : '';
|
|
80
|
+
return `${index + 1}. ${labelOf(entry) || t('ctrl.fallback.unnamed')}${tail}`;
|
|
81
|
+
});
|
|
82
|
+
return `${describeChain(chain, { t })} — ${routes.join(' → ')}`;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* What the chain is worth in one line: how many routes a turn would really try.
|
|
87
|
+
*
|
|
88
|
+
* "7 routes" while three overlays are missing and two are switched off is the
|
|
89
|
+
* kind of number that makes a person stop trusting the card, so the count is the
|
|
90
|
+
* usable one and the rest is spelled out beside it.
|
|
91
|
+
*/
|
|
92
|
+
export function describeChain(chain = [], { t }) {
|
|
93
|
+
if (chain.length === 0) return t('ctrl.fallback.empty');
|
|
94
|
+
const live = chain.filter((entry) => isUsable(entry) && !entry.off).length;
|
|
95
|
+
const off = chain.filter((entry) => entry.off).length;
|
|
96
|
+
const broken = chain.filter((entry) => !isUsable(entry)).length;
|
|
97
|
+
const extra = [
|
|
98
|
+
off ? t('ctrl.fallback.countOff', { n: off }) : '',
|
|
99
|
+
broken ? t('ctrl.fallback.countBroken', { n: broken }) : '',
|
|
100
|
+
].filter(Boolean).join(', ');
|
|
101
|
+
return t('ctrl.fallback.count', { n: live, total: chain.length, extra: extra ? ` (${extra})` : '' });
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* One row per route: the switch, then the two arrows.
|
|
106
|
+
*
|
|
107
|
+
* Three buttons is what fits a phone without a second card, and each carries the
|
|
108
|
+
* number it acts on, so a card left on screen while the chain changed cannot move
|
|
109
|
+
* a route nobody chose.
|
|
110
|
+
*/
|
|
111
|
+
export function fallbackKeyboard({ t, chain = [], enabled = true }) {
|
|
112
|
+
const rows = chain.map((entry, index) => {
|
|
113
|
+
const n = index + 1;
|
|
114
|
+
return [
|
|
115
|
+
{ text: `${entry.off ? '○' : '●'} ${n}`, data: press('t', n) },
|
|
116
|
+
{ text: `↑ ${n}`, data: press('u', n) },
|
|
117
|
+
{ text: `↓ ${n}`, data: press('d', n) },
|
|
118
|
+
];
|
|
119
|
+
});
|
|
120
|
+
rows.push([
|
|
121
|
+
{ text: t('ctrl.fallback.test'), data: press('x') },
|
|
122
|
+
{ text: enabled ? t('ctrl.fallback.disable') : t('ctrl.fallback.enable'), data: press('e') },
|
|
123
|
+
]);
|
|
124
|
+
if (chain.length > 0) rows.push([{ text: t('ctrl.fallback.remove'), data: press('r') }]);
|
|
125
|
+
return rows;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* The whole card: the route this topic answers on, the numbered chain, what
|
|
130
|
+
* starts a failover, and the buttons that change it.
|
|
131
|
+
*
|
|
132
|
+
* `primary` is not part of the chain, and printing it above the list is what
|
|
133
|
+
* stops "why is the first model not the one I asked for".
|
|
134
|
+
*/
|
|
135
|
+
export function renderFallbackCard({ t, chain = [], primary = {}, enabled = true }) {
|
|
136
|
+
const lines = [
|
|
137
|
+
t('ctrl.fallback.title'),
|
|
138
|
+
t('ctrl.fallback.mode', { state: enabled ? t('ctrl.fallback.on') : t('ctrl.fallback.offState') }),
|
|
139
|
+
];
|
|
140
|
+
const here = labelOf(primary);
|
|
141
|
+
if (here) lines.push(t('ctrl.fallback.primary', { route: here }));
|
|
142
|
+
lines.push('', describeChain(chain, { t }));
|
|
143
|
+
for (const [index, entry] of chain.entries()) lines.push(chainLine(entry, index, { t }));
|
|
144
|
+
lines.push('', t('ctrl.fallback.triggers'), t('ctrl.fallback.notTriggers'));
|
|
145
|
+
if (chain.length === 0) lines.push('', t('ctrl.fallback.addUsage'));
|
|
146
|
+
lines.push('', t('ctrl.fallback.foot'));
|
|
147
|
+
return { text: lines.join('\n'), keyboard: fallbackKeyboard({ t, chain, enabled }) };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* The remove menu: one button per route, because removing by number is a guess
|
|
152
|
+
* about which number is which, and a wrong guess costs a route.
|
|
153
|
+
*/
|
|
154
|
+
export function removeKeyboard({ t, chain = [] }) {
|
|
155
|
+
const rows = chain.map((entry, index) => [{
|
|
156
|
+
text: `${index + 1}. ${labelOf(entry)}`,
|
|
157
|
+
data: press('r', index + 1),
|
|
158
|
+
}]);
|
|
159
|
+
rows.push([{ text: t('ctrl.fallback.back'), data: press('s') }]);
|
|
160
|
+
return rows;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* The answer to `/fallback test`: one line per route and the honest footnote.
|
|
165
|
+
*
|
|
166
|
+
* A probe proves the key works, not that the provider accepts this conversation;
|
|
167
|
+
* a card that said "all routes are fine" beside a 400 would send the person to
|
|
168
|
+
* the wrong fix.
|
|
169
|
+
*/
|
|
170
|
+
export function renderProbe({ t, rows = [] }) {
|
|
171
|
+
const lines = [t('ctrl.fallback.testTitle')];
|
|
172
|
+
for (const row of rows) {
|
|
173
|
+
lines.push(t('ctrl.fallback.testLine', {
|
|
174
|
+
n: row.n,
|
|
175
|
+
route: row.route,
|
|
176
|
+
verdict: t(`ctrl.fallback.verdict.${row.kind}`),
|
|
177
|
+
}));
|
|
178
|
+
}
|
|
179
|
+
lines.push('', t('ctrl.fallback.testHint'));
|
|
180
|
+
return lines.join('\n');
|
|
181
|
+
}
|