dsh-tg-bridge 1.26.1 → 1.28.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
@@ -24,6 +24,10 @@ a bot that answers, one step at a time.
24
24
  the model's reasoning in a collapsed block you can tap open. A long turn adds a second
25
25
  collapsed block with every tool call, so the whole run stays in the chat as one message.
26
26
  - **No lost messages**: a journal with acknowledgement and replay.
27
+ - **Knows how busy the computer is**: `/load` shows free space on the topic's disk,
28
+ free RAM and average CPU, plus how many turns are running and waiting. `/load on`
29
+ makes a prompt wait instead of starting while the machine is over a limit you set
30
+ — kept, never refused, and one press sends it anyway.
27
31
  - **Settings per topic**: `/crew use reviewer` gives one topic its own model,
28
32
  effort, permissions, agent preset and language while the others keep the profile;
29
33
  `/crew off` returns it. Four built-in sets ship read-only and can be copied.
@@ -87,6 +91,27 @@ npx dsh-tg-bridge@latest setup
87
91
  `init` writes the token, your id and the working directory; `setup` registers
88
92
  autostart and starts the bridge.
89
93
 
94
+ ### What it needs from DSH
95
+
96
+ The bridge is a client of the DSH CLI, and the surface it uses is small enough to
97
+ write down: `--profile`, `--json`, `--session-id`, `--expose-internals <cli.js>`
98
+ when the app binary runs the CLI, and the `{"type": ...}` JSON events on stdout.
99
+ Profiles are read as files (`cordis.patch.yml`, `package.json`) under
100
+ `~/.dsh/profiles`. `package.json` spells the supported range out in
101
+ `engines.dsh`, and it is capped below `0.3.0` on purpose: a minor bump may rename
102
+ an event, and a bridge that guesses is a bridge that answers with silence.
103
+
104
+ Two escape hatches, for a moved app or a DSH that ships differently:
105
+
106
+ ```bash
107
+ DSH_BIN=/usr/local/bin/dsh # the CLI itself, no entrypoint argument
108
+ DSH_CLI_JS=/opt/dsh/lib/cli.js # just the CLI entrypoint, run by DSH_BIN
109
+ DSH_APP_DIR=/opt/DeepSeek-Harness # where the desktop app is installed
110
+ ```
111
+
112
+ `/doctor` prints the command a turn would actually run, so a machine where these
113
+ matter says so instead of failing with an empty answer.
114
+
90
115
  **As a DSH plugin** (the package carries a `dsh.bundle`; the catalog entry is
91
116
  pending review):
92
117
 
@@ -172,7 +197,8 @@ card so the distinction is visible instead of guessed.
172
197
  /fallback use 3 | skip 3 one route back in or out
173
198
  /fallback up 3 | down 3 move a route in the order
174
199
  /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
200
+ /fallback add <provider>/<model> write an overlay and append the route
201
+ /fallback first <provider>/<model> put it at the head: tried before every other route
176
202
  /fallback remove 3 drop a route from the list (its overlay file stays)
177
203
  ```
178
204
 
@@ -182,6 +208,18 @@ channel are alive — not that the provider accepts this conversation, so a rout
182
208
  can answer `ping` and still refuse a long prompt with a 400. The card says that
183
209
  in as many words.
184
210
 
211
+ `test` also times each route: how long it takes to produce the first token, and
212
+ which live route is fastest right now. Two routes that both answer are not
213
+ equally good — 400 ms and 9 s feel like different products — and the head of the
214
+ chain is the one a person picks on that number. A route that did not answer
215
+ prints no time, so `no balance · 120 ms` can never read as "works, just slow".
216
+
217
+ `first` exists because `add` appends: when the route you want should answer
218
+ *before* the primary, appending it means moving it up eight times and guessing
219
+ where the head is. `/fallback first router-a/deepseek-v4.1-flash` writes the
220
+ same overlay and puts it at position 1 — or moves it there if it is already in
221
+ the chain.
222
+
185
223
  Get your id from [@userinfobot](https://t.me/userinfobot), the token from
186
224
  [@BotFather](https://t.me/BotFather).
187
225
 
@@ -270,6 +308,7 @@ Extensions: /skills · /plugins · /plugins search <word> · /plugins disable|
270
308
  Updates: /update · /update confirm · /update on|off|check|auto · /subscribe on|off
271
309
  Diagnostics: /doctor · /logs [errors|N|text] · /report
272
310
  Service: /app · /restart · /help
311
+ Machine: /load · /load on|off · /load limit cpu|ram|disk <n>
273
312
  Settings: /settings — the same switches as buttons, grouped in four tabs
274
313
  Display: /lang · /reasoning off|card|chat · /pin on|off · /thoughts
275
314
  ```
package/bridge.mjs CHANGED
@@ -166,6 +166,20 @@ async function main() {
166
166
  `✅ ${t(lang, 'msg.restarted', { pid: process.pid })}`,
167
167
  notice.threadId || 0,
168
168
  );
169
+ // A turn is a child process, so the restart killed it. The topic it was
170
+ // working in is left with a card stuck on ⏳ and no reason for it: the
171
+ // person there typed a message, walked away, and comes back to a card
172
+ // that stopped moving. Say so where the work was, not only where the
173
+ // restart was ordered.
174
+ for (const place of Array.isArray(notice.interrupted) ? notice.interrupted : []) {
175
+ if (place.chatId === notice.chatId && (place.threadId || 0) === (notice.threadId || 0)) continue;
176
+ try {
177
+ const there = resolveLang(state, sessionKey(place.chatId, place.threadId || 0), null, config);
178
+ await send(place.chatId, `⚠️ ${t(there, 'msg.turnInterrupted')}`, place.threadId || 0);
179
+ } catch (error) {
180
+ log(`interrupted notice failed for ${place.chatId}:${place.threadId}: ${error.message}`);
181
+ }
182
+ }
169
183
  }
170
184
  }
171
185
  } catch (error) {
package/callbacks.mjs CHANGED
@@ -7,10 +7,11 @@ import { isFallbackPress, pressTarget } from './fallback-card.mjs';
7
7
  import { progressOf, toggleTask } from './goals.mjs';
8
8
  import { handleMessage } from './handle-message.mjs';
9
9
  import { resolveLang, t } from './i18n.mjs';
10
+ import { handleLoadPress } from './load-guard.mjs';
10
11
  import { sessionKey } from './keys.mjs';
11
12
  import { commandForName, isMenuPress, menuTarget, renderPanel, runsUnasked } from './menu-card.mjs';
12
13
  import { DIR, DSH_HOME, LOG } from './paths.mjs';
13
- import { approvals, enqueue, lastPrompt, maxParallel, rewindUsed } from './queue.mjs';
14
+ import { approvals, enqueue, lastPrompt, maxParallel, redeliver, rewindUsed } from './queue.mjs';
14
15
  import { answerRewindPress, cutSession, isRewindPress } from './rewind-buttons.mjs';
15
16
  import { applyRewind, newestBackup, restoreBackup } from './rewind.mjs';
16
17
  import { runCommandFromButton } from './run-command.mjs';
@@ -153,6 +154,13 @@ export async function handleCallback(query) {
153
154
  return;
154
155
  }
155
156
 
157
+ // A button on the load card, or on the notice that held a prompt back. Both
158
+ // are `/load` verbs, so the tap and the typed command run the same code.
159
+ if (data.startsWith('ld:')) {
160
+ await handleLoadPress({ data, key, t, lang, answer, clearKeyboard, redeliver, runCommandFromButton, chatId, threadId, log });
161
+ return;
162
+ }
163
+
156
164
  // A button on the failover card. Every press becomes the verb of `/fallback`,
157
165
  // so a tap and a typed line land in the same code — and the command redraws the
158
166
  // card, which is why the old keyboard is trimmed only when the press leaves it.
package/cli-args.mjs CHANGED
@@ -6,11 +6,16 @@
6
6
  // `--json ... --patch x.yml` the app received `--patch`, answered
7
7
  // `{"type":"error","message":"unknown option '--patch'"}` and exited 1 — every
8
8
  // photo turn and every fallback-model attempt died in about five seconds.
9
- export function turnArgs({ cli, profile, extraArgs = [], sessionId = '', task }) {
10
- if (!cli) throw new Error('turnArgs: cli path is required');
9
+ // `lead` is what goes before `--profile`, and it is not always
10
+ // `--expose-internals <cli.js>`: the Electron app needs that, a plain `dsh` on
11
+ // PATH needs nothing (see `dsh-launch.mjs`). Keeping `cli` as a fallback means
12
+ // the old call still reads the way it did.
13
+ export function turnArgs({ lead = null, cli, profile, extraArgs = [], sessionId = '', task }) {
14
+ const prefix = lead || (cli ? ['--expose-internals', cli] : null);
15
+ if (!prefix) throw new Error('turnArgs: lead or cli is required');
11
16
  if (!profile) throw new Error('turnArgs: profile is required');
12
17
  if (typeof task !== 'string' || !task) throw new Error('turnArgs: task is required');
13
- const args = ['--expose-internals', cli, '--profile', profile, ...extraArgs, '--json'];
18
+ const args = [...prefix, '--profile', profile, ...extraArgs, '--json'];
14
19
  if (sessionId) args.push('--session-id', sessionId);
15
20
  args.push(task);
16
21
  return args;
@@ -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', 'pin', 'goal', 'task', 'tasks',
14
14
  'thoughts', 'version', 'update', 'crew', 'agentset', 'subscribe', 'settings',
15
- 'rewind', 'fork', 'branches', 'menu', 'fallback',
15
+ 'rewind', 'fork', 'branches', 'menu', 'fallback', 'load',
16
16
  ];
17
17
 
18
18
  /**
@@ -20,12 +20,14 @@ 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
22
  import { chainSummary } from '../fallback-card.mjs';
23
+ import { driveOf, sampleDisk } from '../machine.mjs';
24
+ import { describeLaunch, dshLaunch } from '../dsh-launch.mjs';
23
25
  import { explainCommand } from '../help-explain.mjs';
24
26
  import { profileValues, resolveSettings } from '../settings.mjs';
25
27
  import { UPDATE_DEFAULTS, describeUpdate, modeChange, updateState } from '../update-policy.mjs';
26
28
  import { isNewer, pluginInfo, rowLine, searchPlugins } from '../plugin-search.mjs';
27
29
  import { COMMAND_ALIASES, CONTROL_COMMANDS, DOCUMENTED_COMMANDS } from '../commands-registry.mjs';
28
- import { APP, CLI_JS, DSH_CMD, DSH_HOME, DIR, EXE, HOME, LOG, PROFILES, THOUGHT_DIR } from '../paths.mjs';
30
+ import { APP, CLI_JS, DSH_CMD, DSH_HOME, DIR, EXE, HOME, LOG, PROFILES, RESTART_NOTICE, THOUGHT_DIR } from '../paths.mjs';
29
31
  import { read, readJson, patchPath, pkgPath, OVERLAY_MARK, modelsOf, modelOf, windowOf, modelIndent, depthOf, modelsReport, setModel, disabledIds, setDisabled, writePatch } from './models.mjs';
30
32
  import { listPids, waitForExit, waitForStart, pluginsOf, bundleRowIds, addBundle, removeBundle, createProfile, dshPlugin } from './plugins.mjs';
31
33
  import { cwdSlug, bareId, stamp, recentSessions, sessionTitle } from './sessions.mjs';
@@ -83,12 +85,29 @@ export async function handleBridgeCommands(ctx) {
83
85
  const bridge = fileURLToPath(new URL('./bridge.mjs', import.meta.url));
84
86
  // Tell the replacement process where to confirm, so the chat does not go
85
87
  // silent after "Перезапускаю мост…" (it did, twice on 2026-10-24).
88
+ //
89
+ // It also carries the topics whose turn this restart is about to kill. A
90
+ // turn is a child process: `process.exit` takes it down with the bridge, and
91
+ // the topic it was working in keeps a card that says ⏳ forever, with nothing
92
+ // to explain it. The person in that topic finds out by scrolling to a card
93
+ // that stopped moving — so the new process names each one.
94
+ const interrupted = [...(ctx.activeTurns?.keys?.() || [])]
95
+ .map((k) => String(k).split(':'))
96
+ .map(([chat, thread]) => ({ chatId: Number(chat), threadId: Number(thread) || 0 }))
97
+ .filter((t2) => Number.isFinite(t2.chatId) && t2.chatId > 0);
86
98
  try {
87
- writeFileSync(
88
- fileURLToPath(new URL('./restart-notice.json', import.meta.url)),
89
- JSON.stringify({ chatId: ctx.chatId, threadId: ctx.threadId || 0, at: Date.now() }),
90
- 'utf8',
91
- );
99
+ // The path the reader uses, not a path relative to this file: this case
100
+ // lives in `control/`, and the old `new URL('./restart-notice.json', …)`
101
+ // wrote the note one directory below where `bridge.mjs` looked for it.
102
+ // Every restart confirmation since then was silently lost — the person
103
+ // saw "Перезапускаю мост…" and then nothing, which is exactly the doubt
104
+ // the note exists to remove.
105
+ writeFileSync(RESTART_NOTICE, JSON.stringify({
106
+ chatId: ctx.chatId,
107
+ threadId: ctx.threadId || 0,
108
+ at: Date.now(),
109
+ interrupted,
110
+ }), 'utf8');
92
111
  } catch (error) {
93
112
  log(`restart notice not written: ${error.message}`);
94
113
  }
@@ -209,16 +228,23 @@ export async function handleBridgeCommands(ctx) {
209
228
  add(t(lang, 'ctrl.doctor.logLines'), String(lines.length - start));
210
229
  } catch {}
211
230
 
212
- // Disk space: the silent killer of model downloads and OCR.
213
- try {
214
- const drives = execFileSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', '(Get-PSDrive C).Free'], {
215
- encoding: 'utf8',
216
- windowsHide: true,
217
- timeout: 15000,
218
- });
219
- const free = Number(drives) || 0;
220
- add(t(lang, 'ctrl.doctor.disk'), t(lang, 'ctrl.doctor.diskFree', { gb: (free / 1024 ** 3).toFixed(1) }));
221
- } catch {}
231
+ // Disk space: the silent killer of model downloads and OCR. This used to
232
+ // shell out to `powershell (Get-PSDrive C)`, so on macOS and Linux the row
233
+ // simply vanished — a diagnostic that is silent on the platform you are
234
+ // debugging is worse than none.
235
+ const disk = sampleDisk(driveOf(config.cwd || ''));
236
+ if (disk.freeGb !== null) {
237
+ // `C:\` is a path; the row wants the name of a disk, so the separator
238
+ // and its colon both go: "Disk C", "Disk /".
239
+ const label = disk.drive.replace(/[\\/:]+$/, '') || disk.drive;
240
+ add(t(lang, 'ctrl.doctor.disk', { drive: label }), t(lang, 'ctrl.doctor.diskFree', { gb: disk.freeGb.toFixed(1) }));
241
+ }
242
+
243
+ // Which binary a turn would actually start. On a machine where the app is
244
+ // missing but `dsh` is on PATH (or the other way round) this is the row
245
+ // that explains why every turn fails, so it is worth one line always.
246
+ const launch = dshLaunch({ exists: existsSync });
247
+ add(t(lang, 'ctrl.doctor.turnCmd'), `${describeLaunch(launch)}${launch.kind === 'cli' ? t(lang, 'ctrl.doctor.turnCmdPath') : ''}`);
222
248
 
223
249
  // Project directory bound to this topic and whether it exists. The bridge
224
250
  // default is a fact, not an accident: say when it is being used.
@@ -62,6 +62,9 @@ const VERDICT = {
62
62
  busy: 'busy',
63
63
  network: 'network',
64
64
  missing: 'missing',
65
+ // A 200 with no body: the route took the request and said nothing. Saying "ok"
66
+ // there is how a dead channel looks healthy on the card.
67
+ empty: 'empty',
65
68
  };
66
69
 
67
70
  export async function handleFallbackCommands(ctx) {
@@ -190,6 +193,49 @@ export async function handleFallbackCommands(ctx) {
190
193
  return true;
191
194
  }
192
195
 
196
+ // A route the person wants tried FIRST, not appended.
197
+ //
198
+ // `add` puts a route at the tail, which is right for a spare and wrong for
199
+ // the one that should answer when the primary is busy: moving it up eight
200
+ // times is eight presses, and the last one is always a guess about where the
201
+ // head is. This is `add` plus "put it in front", in one word.
202
+ case 'first':
203
+ case 'head': {
204
+ const route = splitRoute(rest.join(' '));
205
+ if (!route.model) {
206
+ say(t(lang, 'ctrl.fallback.addUsage'));
207
+ return true;
208
+ }
209
+ const known = providerIds(activeProfile);
210
+ const provider = route.provider || known[0] || '';
211
+ if (!known.includes(provider)) {
212
+ say(t(lang, 'ctrl.fallback.unknownProvider', { name: provider || '?', list: known.join(', ') }));
213
+ return true;
214
+ }
215
+ const full = `${provider}/${route.model}`;
216
+ // Already in the chain: move it instead of adding a twin. Two entries of
217
+ // one route would be tried twice for the same failure.
218
+ const existing = chain.findIndex((item) => item.provider === provider && item.model === route.model);
219
+ if (existing === 0) {
220
+ say(t(lang, 'ctrl.fallback.alreadyFirst', { route: full }));
221
+ return true;
222
+ }
223
+ if (existing > 0) {
224
+ const [moved] = chain.splice(existing, 1);
225
+ chain.unshift(moved);
226
+ done('ctrl.fallback.moved', { route: labelOf(moved), n: 1 });
227
+ return true;
228
+ }
229
+ const patch = join(DIR, overlayName({ provider, model: route.model }));
230
+ writeFileSync(patch, overlayText({ provider, model: route.model }), 'utf8');
231
+ const fresh = { provider, model: route.model, patch };
232
+ if (/:free$/i.test(route.model)) fresh.free = true;
233
+ chain.unshift(fresh);
234
+ log(`fallback: added ${full} at the head (${patch})`);
235
+ done('ctrl.fallback.addedFirst', { route: full });
236
+ return true;
237
+ }
238
+
193
239
  // A probe proves the key works, not that this conversation is acceptable: the
194
240
  // hint says so, because "route is fine" beside a 400 would be a lie.
195
241
  //
@@ -217,8 +263,8 @@ export async function handleFallbackCommands(ctx) {
217
263
  }));
218
264
  const rows = targets.map((item) => {
219
265
  const verdict = verdicts.get(item) || { kind: 'other' };
220
- log(`fallback probe ${labelOf(item)}: ${verdict.kind}${verdict.detail ? ` (${String(verdict.detail).slice(0, 80)})` : ''}`);
221
- return { n: chain.indexOf(item) + 1, route: labelOf(item), kind: VERDICT[verdict.kind] || 'other' };
266
+ log(`fallback probe ${labelOf(item)}: ${verdict.kind} ${verdict.ms || 0}ms${verdict.detail ? ` (${String(verdict.detail).slice(0, 80)})` : ''}`);
267
+ return { n: chain.indexOf(item) + 1, route: labelOf(item), kind: VERDICT[verdict.kind] || 'other', ms: verdict.ms };
222
268
  });
223
269
  // One way back to the card: the probe answer is long, and the person who
224
270
  // just learned route 4 is dead wants the list, not a typed command.
@@ -0,0 +1,66 @@
1
+ // `/load`: what this computer is doing, and the guard that keeps it usable.
2
+ //
3
+ // One group of the `/` surface. `control.mjs` owns the dispatch and this file
4
+ // owns the command.
5
+ import { normalizeLang, t } from '../i18n.mjs';
6
+ import { guardOf, sampleMachine } from '../machine.mjs';
7
+ import { loadPress, renderLoadCard } from '../load-card.mjs';
8
+ import { saveConfig } from '../state.mjs';
9
+
10
+ /** The card, drawn once and reused by every verb that ends in "show me". */
11
+ async function drawLoad({ ctx, lang, guard }) {
12
+ const jobs = ctx.jobs ? ctx.jobs() : { active: [], queued: 0, max: 0 };
13
+ const sample = await sampleMachine({ drive: undefined });
14
+ const card = renderLoadCard({
15
+ t: (key, vars) => t(lang, key, vars),
16
+ sample,
17
+ guard,
18
+ turns: jobs.active.length,
19
+ queued: jobs.queued,
20
+ max: jobs.max,
21
+ });
22
+ await ctx.reply(card.text, { reply_markup: { inline_keyboard: card.keyboard } });
23
+ }
24
+
25
+ export async function handleLoadCommands(ctx) {
26
+ const { command, arg, reply, log, config, lang: rawLang } = ctx;
27
+ const lang = normalizeLang(rawLang) || normalizeLang(config?.lang) || 'en';
28
+ const effective = ctx.effective || command;
29
+ if (effective !== '/load') return false;
30
+
31
+ const guard = guardOf(config.loadGuard);
32
+ const verb = String(arg || '').trim().toLowerCase();
33
+ if (!verb) {
34
+ await drawLoad({ ctx, lang, guard });
35
+ return true;
36
+ }
37
+ if (verb === 'on' || verb === 'off' || verb === 'guard') {
38
+ const want = verb === 'guard' ? !guard.enabled : verb === 'on';
39
+ config.loadGuard = { ...guard, enabled: want };
40
+ saveConfig();
41
+ log(`load guard ${want ? 'on' : 'off'}: cpu>${guard.cpuPct}%, ram<${guard.ramFreePct}%, disk<${guard.diskFreeGb}GB`);
42
+ await drawLoad({ ctx, lang, guard: { ...guard, enabled: want } });
43
+ return true;
44
+ }
45
+ // `/load limit cpu 80` — one number at a time, because a person changing the
46
+ // limit is looking at the reading that annoyed them.
47
+ const [, what, raw] = /^(?:limit|l)\s+(cpu|ram|disk)\s+(\d+(?:[.,]\d+)?)$/.exec(verb) || [];
48
+ if (what) {
49
+ const value = Number(String(raw).replace(',', '.'));
50
+ const field = what === 'cpu' ? 'cpuPct' : what === 'ram' ? 'ramFreePct' : 'diskFreeGb';
51
+ const next = { ...guard, [field]: value };
52
+ config.loadGuard = next;
53
+ saveConfig();
54
+ log(`load limit ${field}=${value}`);
55
+ await drawLoad({ ctx, lang, guard: next });
56
+ return true;
57
+ }
58
+ if (verb === 'limit' || verb === 'limits') {
59
+ await reply(t(lang, 'ctrl.load.limitsNow', { cpu: guard.cpuPct, ram: guard.ramFreePct, disk: guard.diskFreeGb }));
60
+ return true;
61
+ }
62
+ await reply(t(lang, 'ctrl.load.usage'));
63
+ return true;
64
+ }
65
+
66
+ export { loadPress };
@@ -123,9 +123,14 @@ export async function handleViewCommands(ctx) {
123
123
  return true;
124
124
  }
125
125
  const desktop = scope === 'both' ? setModel('desktop', wanted) : false;
126
+ // Report the route the patch now carries, not the string that was typed:
127
+ // `/model deepseek-v4.1-flash` leaves the provider as it was, and the answer
128
+ // is the only place that says so. "Model → deepseek" while the turn still
129
+ // runs on the slow host is the confusion this line exists to remove.
130
+ const route = modelOf(activeProfile);
126
131
  say(t(lang, 'ctrl.model.switched', {
127
132
  name: activeProfile,
128
- model: wanted,
133
+ model: `${route.provider}/${route.model}`,
129
134
  desktop: desktop ? t(lang, 'ctrl.model.withDesktop', { model: wanted }) : '',
130
135
  }));
131
136
  return true;
@@ -1,12 +1,13 @@
1
- // Reading and changing a profile's model: the patch row, the overlay, the window.
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 { copyFileSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
6
- import { join } from 'node:path';
7
- import { t } from '../i18n.mjs';
8
- import { PROFILES } from '../paths.mjs';
9
-
1
+ // Reading and changing a profile's model: the patch row, the overlay, the window.
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 { copyFileSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
6
+ import { join } from 'node:path';
7
+ import { t } from '../i18n.mjs';
8
+ import { providerRows } from '../model-probe.mjs';
9
+ import { PROFILES } from '../paths.mjs';
10
+
10
11
  export const read = (path) => {
11
12
  try {
12
13
  return readFileSync(path, 'utf8');
@@ -134,15 +135,40 @@ export function modelsReport(lang, profile) {
134
135
  ].join('\n');
135
136
  }
136
137
 
137
- /** Rewrite the default model of a profile; returns false for an unknown id. */
138
+ /**
139
+ * Rewrite the default model of a profile; returns false for an unknown id.
140
+ *
141
+ * `provider/model` moves the route as well as the model. Without that a person
142
+ * who wants the SAME model on a different router has no way to say so: `/model
143
+ * deepseek-v4.1-flash` keeps whatever provider the patch already had, so the
144
+ * switch silently keeps the slow host — the one case where "I changed the model"
145
+ * and "the answers come from somewhere else now" are different claims.
146
+ */
138
147
  export function setModel(profile, wanted) {
148
+ const text0 = String(wanted || '').trim();
149
+ const slash = text0.indexOf('/');
150
+ const provider = slash > 0 ? text0.slice(0, slash) : '';
151
+ const model = slash > 0 ? text0.slice(slash + 1) : text0;
152
+ if (!model) return false;
139
153
  const ids = modelsOf(profile);
140
- if (ids.length > 0 && !ids.includes(wanted)) return false;
154
+ if (ids.length > 0 && !ids.includes(model)) return false;
141
155
  const path = patchPath(profile);
142
156
  const text = read(path);
143
- const re = /(- id: agent-default-model[\s\S]*?^\s+model:\s*)(\S+)/m;
144
- if (!re.test(text)) return false;
145
- writeFileSync(path, text.replace(re, `$1${wanted}`), 'utf8');
157
+ // A provider the profile does not declare cannot boot the turn: writing it
158
+ // anyway would leave a patch that looks edited and a bot that cannot answer,
159
+ // so the row is checked before the file is touched.
160
+ if (provider && !providerRows(text).some((row) => row.id === provider)) return false;
161
+ const block = /- id: agent-default-model[\s\S]*?(?=\n- id:|\n- insert:|$)/.exec(text);
162
+ if (!block) return false;
163
+ // Provider first, then model: both live in the same block, and replacing the
164
+ // block wholesale would drop `reasoningEffort` and anything else a person set.
165
+ let next = block[0].replace(/^(\s+model:\s*)\S+/m, `$1${model}`);
166
+ if (provider) {
167
+ if (/^\s+provider:\s*\S+/m.test(next)) next = next.replace(/^(\s+provider:\s*)\S+/m, `$1${provider}`);
168
+ else next = next.replace(/^(\s+model:\s*\S+)/m, `$1\n provider: ${provider}`);
169
+ }
170
+ if (next === block[0]) return false;
171
+ writeFileSync(path, text.replace(block[0], next), 'utf8');
146
172
  return true;
147
173
  }
148
174