dsh-tg-bridge 1.12.1 → 1.13.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
@@ -19,6 +19,9 @@ blocks.
19
19
  the model's reasoning in a collapsed block you can tap open. A long turn adds a second
20
20
  collapsed block with every tool call, so the whole run stays in the chat as one message.
21
21
  - **No lost messages**: a journal with acknowledgement and replay.
22
+ - **Settings per topic**: `/agentset use reviewer` gives one topic its own model,
23
+ effort, permissions, agent preset and language while the others keep the profile;
24
+ `/agentset off` returns it. Four built-in sets ship read-only and can be copied.
22
25
  - **Fail-fast**: when the quota runs out it switches to a free model right away.
23
26
  - **`dsh-tg check`**: diagnostics in one command, no changes to the system.
24
27
  - **Languages**: menus and service messages in `en`, `ru`, `zh`; `/lang` switches the topic language, a new user gets theirs from the Telegram `language_code` (anything outside ru/zh → `en`).
package/agentsets.mjs ADDED
@@ -0,0 +1,239 @@
1
+ /**
2
+ * Agent sets: named bundles of per-topic agent settings that live next to
3
+ * state.json in their own file.
4
+ *
5
+ * Why not state.json: `saveState()` runs on every poll tick, so a preset blob
6
+ * would be re-serialised hundreds of times an hour, and a corrupt state.json
7
+ * already costs every topic its session — the two failure modes must not share
8
+ * a file. This store keeps its own revision counter and compare-and-swap so a
9
+ * write from a second process cannot silently drop a set saved 200 ms earlier.
10
+ *
11
+ * A set is a DELTA, never absolute: '' / [] / {} means "inherit from the
12
+ * profile". That is what lets two topics share one set object without one
13
+ * topic's later edit leaking into the other.
14
+ */
15
+ import { closeSync, existsSync, fsyncSync, openSync, readFileSync, renameSync, writeFileSync, writeSync } from 'node:fs';
16
+
17
+ export const ASETS_FILE = 'agentsets.json';
18
+ const ID = /^[a-z0-9][a-z0-9-]{0,23}$/;
19
+ const TRASH_TTL = 7 * 24 * 60 * 60 * 1000;
20
+ const TRASH_CAP = 20;
21
+
22
+ /** JSON of every set as it was loaded: what a rebase has to tell apart. */
23
+ function snapshot(sets) {
24
+ return JSON.parse(JSON.stringify(sets));
25
+ }
26
+
27
+ /** Fields a set may carry. Anything else is preserved but never read. */
28
+ export const FIELDS = ['model', 'provider', 'effort', 'permissions', 'dshPreset', 'lang', 'thinkBlock', 'base', 'notes'];
29
+ export const LIST_FIELDS = ['plugins', 'toolFilter', 'agents'];
30
+
31
+ export function emptySet(id, name = id) {
32
+ const now = new Date().toISOString();
33
+ return {
34
+ id,
35
+ name,
36
+ builtin: false,
37
+ schema: 1,
38
+ createdAt: now,
39
+ updatedAt: now,
40
+ base: '',
41
+ model: '',
42
+ provider: '',
43
+ effort: '',
44
+ permissions: '',
45
+ dshPreset: '',
46
+ plugins: { add: [], remove: [], disable: [], enable: [] },
47
+ toolFilter: { deny: [], allow: [] },
48
+ agents: {},
49
+ lang: '',
50
+ thinkBlock: '',
51
+ notes: '',
52
+ };
53
+ }
54
+
55
+ /** What every install gets for free. Read-only in Telegram: edit a copy. */
56
+ export function builtinSets() {
57
+ const make = (id, name, patch) => ({ ...emptySet(id, name), builtin: true, ...patch });
58
+ return {
59
+ normal: make('normal', 'Normal', {}),
60
+ careful: make('careful', 'Careful', { permissions: 'read-only', notes: 'Reads and plans, asks before writing.' }),
61
+ fast: make('fast', 'Fast', { effort: 'low', notes: 'Lowest declared effort: quick answers, less thinking.' }),
62
+ reviewer: make('reviewer', 'Reviewer', {
63
+ permissions: 'read-only',
64
+ effort: 'high',
65
+ notes: 'Reads the diff, reports findings, changes nothing.',
66
+ }),
67
+ };
68
+ }
69
+
70
+ export class AgentsetStore {
71
+ constructor(file) {
72
+ this.file = file;
73
+ this.data = null;
74
+ /** Every set as loaded, so a rebase can find this handle's own edits. */
75
+ this.before = {};
76
+ this.error = '';
77
+ }
78
+
79
+ /** Never throws: a broken file falls back to the builtins and reports why. */
80
+ load() {
81
+ const seed = { version: 1, rev: 0, updatedAt: new Date().toISOString(), sets: builtinSets(), trash: [] };
82
+ if (!existsSync(this.file)) {
83
+ this.data = seed;
84
+ this.before = snapshot(seed.sets);
85
+ this.error = '';
86
+ return this;
87
+ }
88
+ try {
89
+ const raw = JSON.parse(readFileSync(this.file, 'utf8').replace(/^\uFEFF/, ''));
90
+ if (!raw || typeof raw !== 'object' || typeof raw.sets !== 'object' || raw.sets === null) {
91
+ throw new Error('not an object with a sets map');
92
+ }
93
+ this.data = {
94
+ version: 1,
95
+ rev: Number(raw.rev) || 0,
96
+ updatedAt: raw.updatedAt || seed.updatedAt,
97
+ sets: { ...builtinSets(), ...raw.sets },
98
+ trash: Array.isArray(raw.trash) ? raw.trash : [],
99
+ };
100
+ this.before = snapshot(this.data.sets);
101
+ this.error = '';
102
+ } catch (error) {
103
+ this.data = seed;
104
+ this.before = snapshot(seed.sets);
105
+ this.error = `agentsets.json unreadable (${error.message}); builtins only`;
106
+ }
107
+ this.dropExpiredTrash();
108
+ return this;
109
+ }
110
+
111
+ get sets() {
112
+ if (!this.data) this.load();
113
+ return this.data.sets;
114
+ }
115
+
116
+ list() {
117
+ return Object.values(this.sets).sort((a, b) => Number(b.builtin) - Number(a.builtin) || a.id.localeCompare(b.id));
118
+ }
119
+
120
+ get(id) {
121
+ return this.sets[id] || null;
122
+ }
123
+
124
+ /** Create or replace one set. Returns { ok } or { ok:false, error }. */
125
+ put(set) {
126
+ if (!set || !ID.test(String(set.id || ''))) return { ok: false, error: 'bad-id' };
127
+ if (this.sets[set.id]?.builtin) return { ok: false, error: 'builtin-readonly' };
128
+ const now = new Date().toISOString();
129
+ const prev = this.sets[set.id];
130
+ this.sets[set.id] = {
131
+ ...emptySet(set.id, set.name || set.id),
132
+ ...prev,
133
+ ...set,
134
+ builtin: false,
135
+ createdAt: prev?.createdAt || now,
136
+ updatedAt: now,
137
+ };
138
+ return this.save();
139
+ }
140
+
141
+ /** Delete one set into the trash. Never touches state.json bindings. */
142
+ remove(id) {
143
+ const set = this.sets[id];
144
+ if (!set) return { ok: false, error: 'missing' };
145
+ if (set.builtin) return { ok: false, error: 'builtin-readonly' };
146
+ delete this.sets[id];
147
+ this.data.trash = [{ set, deletedAt: Date.now() }, ...this.data.trash].slice(0, TRASH_CAP);
148
+ return this.save();
149
+ }
150
+
151
+ /** Restore a deleted set. Returns the set or null. */
152
+ restore(id) {
153
+ const at = this.data.trash.findIndex((entry) => entry.set?.id === id);
154
+ if (at < 0) return null;
155
+ const [{ set }] = this.data.trash.splice(at, 1);
156
+ this.sets[id] = set;
157
+ return this.save().ok ? set : null;
158
+ }
159
+
160
+ trashList() {
161
+ if (!this.data) this.load();
162
+ this.dropExpiredTrash();
163
+ return this.data.trash.map((entry) => entry.set.id);
164
+ }
165
+
166
+ dropExpiredTrash() {
167
+ if (!this.data) return;
168
+ const cut = Date.now() - TRASH_TTL;
169
+ this.data.trash = this.data.trash.filter((entry) => Number(entry.deletedAt) > cut);
170
+ }
171
+
172
+ /**
173
+ * Compare-and-swap write: re-read the file's rev, refuse if somebody else
174
+ * bumped it since this handle loaded, and never reconstruct the object from
175
+ * known keys (a newer field must survive a downgrade).
176
+ */
177
+ save() {
178
+ const disk = this.diskRev();
179
+ if (disk === null) return { ok: false, error: 'unreadable', file: this.file };
180
+ if (disk !== this.data.rev) {
181
+ // One silent rebase instead of a failed write: re-read what the other
182
+ // writer saved, stamp this handle's edits on top of it, write once more.
183
+ const rev = this.data.rev;
184
+ const carried = Object.keys(this.data.sets)
185
+ .filter((id) => !this.before[id] || JSON.stringify(this.before[id]) !== JSON.stringify(this.data.sets[id]))
186
+ .map((id) => [id, this.data.sets[id]]);
187
+ this.load();
188
+ if (this.error || this.data.rev !== disk) return { ok: false, error: 'stale', diskRev: disk, rev };
189
+ // New, edited and deleted sets belong to this handle; everything else is
190
+ // whatever the other writer left on disk.
191
+ for (const [id, set] of carried) if (set) this.sets[id] = set;
192
+ }
193
+ this.data.rev += 1;
194
+ this.data.updatedAt = new Date().toISOString();
195
+ const text = JSON.stringify(this.data, null, 2);
196
+ const tmp = `${this.file}.tmp-${process.pid}`;
197
+ try {
198
+ const fd = openSync(tmp, 'w');
199
+ try {
200
+ writeSync(fd, text, 'utf8');
201
+ fsyncSync(fd);
202
+ } finally {
203
+ closeSync(fd);
204
+ }
205
+ renameSync(tmp, this.file);
206
+ } catch (error) {
207
+ // Fall back to a plain write: losing the atomic swap is better than
208
+ // losing the edit, and the file is small enough that a torn write needs
209
+ // a crash in the same millisecond.
210
+ try {
211
+ writeFileSync(this.file, text, 'utf8');
212
+ } catch (inner) {
213
+ return { ok: false, error: inner.message };
214
+ }
215
+ }
216
+ return { ok: true, rev: this.data.rev };
217
+ }
218
+
219
+ diskRev() {
220
+ try {
221
+ if (!existsSync(this.file)) return 0;
222
+ const raw = JSON.parse(readFileSync(this.file, 'utf8').replace(/^\uFEFF/, ''));
223
+ return Number(raw?.rev) || 0;
224
+ } catch {
225
+ return null;
226
+ }
227
+ }
228
+ }
229
+
230
+ /** `normal`, `My Set` → `my-set`; `''` when nothing usable is left. */
231
+ export function slugId(input) {
232
+ const slug = String(input || '')
233
+ .toLowerCase()
234
+ .replace(/[^a-z0-9]+/g, '-')
235
+ .replace(/^-+|-+$/g, '')
236
+ .slice(0, 24)
237
+ .replace(/-+$/, '');
238
+ return ID.test(slug) ? slug : '';
239
+ }
package/bot-menu.mjs CHANGED
@@ -53,6 +53,7 @@ const COMMANDS = [
53
53
  { command: 'reasoning', description: 'Заметки по ходу: /reasoning on|off' },
54
54
  { command: 'profile', description: 'Профиль темы: /profile <имя>, /profile new' },
55
55
  { command: 'agents', description: 'Агенты и субагенты: кто, на какой модели, кого запускали' },
56
+ { command: 'agentset', description: 'Набор настроек темы: модель, права, пресет одним переключателем' },
56
57
  { command: 'effort', description: 'Усилие рассуждения модели: /effort high' },
57
58
  { command: 'permissions', description: 'Права профиля: пресет песочницы и подтверждений' },
58
59
  { command: 'preset', description: 'Пресет агента (персона и инструменты): /preset <id>' },
@@ -90,6 +91,7 @@ const COMMANDS_EN = [
90
91
  { command: 'reasoning', description: 'Working notes: /reasoning on|off' },
91
92
  { command: 'profile', description: 'Topic profile: /profile <name>, /profile new' },
92
93
  { command: 'agents', description: 'Agents and subagents: who runs, on which model, who was spawned' },
94
+ { command: 'agentset', description: 'Named settings for this topic: model, permissions, preset in one switch' },
93
95
  { command: 'effort', description: 'Reasoning effort: /effort high' },
94
96
  { command: 'permissions', description: 'Profile permissions: sandbox and approval preset' },
95
97
  { command: 'preset', description: 'Agent preset (persona and tools): /preset <id>' },
@@ -127,6 +129,7 @@ const COMMANDS_ZH = [
127
129
  { command: 'reasoning', description: '工作记录:/reasoning on|off' },
128
130
  { command: 'profile', description: '话题配置档:/profile <名称>,/profile new' },
129
131
  { command: 'agents', description: '智能体与子智能体:谁在运行、用什么模型、启动过谁' },
132
+ { command: 'agentset', description: '本话题的命名设置:模型、权限、预设一键切换' },
130
133
  { command: 'effort', description: '推理力度:/effort high' },
131
134
  { command: 'permissions', description: '配置档权限:沙箱与确认预设' },
132
135
  { command: 'preset', description: '智能体预设(人格与工具):/preset <id>' },
package/bridge.mjs CHANGED
@@ -30,11 +30,14 @@ 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 { handleControl, CONTROL_COMMANDS, modelOf, reasoningOf } from './control.mjs';
33
+ import { handleControl, CONTROL_COMMANDS, modelOf, modelsOf, reasoningOf } from './control.mjs';
34
34
  import { drainGoalJobs, goalOf, renderPromptBlock } from './goals.mjs';
35
35
  import { renderPrices } from './prices.mjs';
36
36
  import { t, resolveLang } from './i18n.mjs';
37
37
  import { progressPanel, stepLine, addStep } from './panel.mjs';
38
+ import { AgentsetStore } from './agentsets.mjs';
39
+ import { profileValues, resolveSettings, settingsChip } from './settings.mjs';
40
+ import { parseAgentPresets, parsePermissionPresets, parseReasoningEfforts } from './agents.mjs';
38
41
 
39
42
  const HOME = homedir();
40
43
  const DSH_HOME = process.env.DSH_HOME || join(HOME, '.dsh');
@@ -161,6 +164,42 @@ function profileOf(key) {
161
164
  return (state.profiles && state.profiles[key]) || config.profile || 'headless';
162
165
  }
163
166
 
167
+ /**
168
+ * One line for the progress head saying which settings this topic overrides.
169
+ * Empty for every install that never binds a set: the panel stays as it was.
170
+ * An unreadable agentsets.json must not cost the turn its panel, so this never
171
+ * throws.
172
+ */
173
+ function settingsChipOf(key) {
174
+ try {
175
+ const id = state.agentsets?.[key];
176
+ if (!id) return '';
177
+ const set = new AgentsetStore(join(DIR, 'agentsets.json')).load().get(id);
178
+ if (!set) return '';
179
+ const profile = profileOf(key);
180
+ const patch = readFileSync(join(DSH_HOME, 'profiles', profile, 'cordis.patch.yml'), 'utf8');
181
+ const model = modelOf(profile);
182
+ const row = profileValues({
183
+ model,
184
+ permissions: parsePermissionPresets(patch)?.presets?.find((p) => p.sandbox)?.id || '',
185
+ preset: parseAgentPresets(patch)?.selected || '',
186
+ effort: '',
187
+ });
188
+ const resolved = resolveSettings({
189
+ set,
190
+ override: state.settings?.[key] || null,
191
+ profile: row,
192
+ models: modelsOf(profile),
193
+ efforts: parseReasoningEfforts(patch, set.model || row.model) || [],
194
+ permissions: parsePermissionPresets(patch)?.presets?.map((p) => p.id) || [],
195
+ presets: parseAgentPresets(patch)?.presets?.map((p) => p.id) || [],
196
+ });
197
+ return settingsChip(resolved, { name: set.name || set.id });
198
+ } catch {
199
+ return '';
200
+ }
201
+ }
202
+
164
203
  // The agent updates the topic goal list by dropping a job file (goal.mjs);
165
204
  // the bridge is the only writer of state.json, so there is no lock race.
166
205
  const GOAL_DIR = join(DIR, 'goal-jobs');
@@ -839,7 +878,7 @@ function killTurn(key) {
839
878
  * thinks for ten minutes still leaves one line in the chat — and the whole trail
840
879
  * one tap away.
841
880
  */
842
- async function startProgress(chatId, threadId, lang = 'ru', task = '') {
881
+ async function startProgress(chatId, threadId, lang = 'ru', task = '', chip = '') {
843
882
  const started = Date.now();
844
883
  const panelKey = sessionKey(chatId, threadId);
845
884
  const steps = [];
@@ -898,6 +937,7 @@ async function startProgress(chatId, threadId, lang = 'ru', task = '') {
898
937
  // the log itself is a file the command sends on demand.
899
938
  reasoning: state.thinkBlock?.[panelKey] === 'counter' ? 'counter' : 'block',
900
939
  task,
940
+ chip,
901
941
  cache,
902
942
  });
903
943
  };
@@ -1418,7 +1458,7 @@ ${t(lang, 'help.body')}`,
1418
1458
 
1419
1459
  // Live progress: one status message per turn, rewritten as the agent works.
1420
1460
  // Without it a long turn and a hung turn looked exactly alike in the chat.
1421
- const progress = await startProgress(chatId, threadId, lang, request);
1461
+ const progress = await startProgress(chatId, threadId, lang, request, settingsChipOf(key));
1422
1462
  // Turn telemetry for the log: what the agent did, how much it cost, on which
1423
1463
  // model. Without it /logs shows only "in" and "sent" — useless when asking
1424
1464
  // "why did this take 9 minutes".
@@ -1938,6 +1978,17 @@ async function handleCallback(query) {
1938
1978
  const answer = (text, show = false) =>
1939
1979
  tg('answerCallbackQuery', { callback_query_id: query.id, text, show_alert: show }).catch(() => {});
1940
1980
 
1981
+ // A button is a message without a sender the rest of the code can check, and
1982
+ // the chat itself may be a group. Anything that changes configuration must
1983
+ // come from an allowed user, exactly like the message path at the top of the
1984
+ // poll loop. The refusal is deliberately the same as "unknown button".
1985
+ const presser = query.from?.id;
1986
+ if (!config.allowedUserIds.includes(presser) && !config.allowedUserIds.includes(chatId)) {
1987
+ log(`ignored callback from ${presser} (chat ${chatId})`);
1988
+ await answer(t(lang, 'bridge.cb.unknown'));
1989
+ return;
1990
+ }
1991
+
1941
1992
  // Trim the buttons of the pressed message first: a button that already did
1942
1993
  // its job must not be pressable a second time.
1943
1994
  const clearKeyboard = () =>
package/control.mjs CHANGED
@@ -15,11 +15,13 @@ import { lastTurnReasoning, lastTurnReasoningSteps, lastTurnText, reasoningMarkd
15
15
  import { parseAgentPresets, parseModelSelection, parsePermissionPresets, parseReasoningEfforts, parseSubagentFleet, parseSubagentRows } from './agents.mjs';
16
16
  import { setRowConfig, unsetRowConfig } from './profile-edit.mjs';
17
17
  import { parseReminder, stampAt, upcoming } from './reminders.mjs';
18
+ import { AgentsetStore, emptySet, slugId } from './agentsets.mjs';
19
+ import { profileValues, resolveSettings } from './settings.mjs';
18
20
 
19
21
  const HOME = homedir();
20
22
  const DSH_HOME = process.env.DSH_HOME || join(HOME, '.dsh');
21
- const PROFILES = join(DSH_HOME, 'profiles');
22
- /** Where a reasoning log is written before it is sent as a document. */
23
+ const PROFILES = join(DSH_HOME, 'profiles');
24
+ /** Where a reasoning log is written before it is sent as a document. */
23
25
  const THOUGHT_DIR = join(DSH_HOME, 'tg-bridge', 'thoughts');
24
26
  const APP = join(process.env.LOCALAPPDATA || '', 'Programs', 'DeepSeek Harness');
25
27
  const EXE = join(APP, 'DeepSeek Harness.exe');
@@ -459,6 +461,75 @@ function setSoul(text) {
459
461
 
460
462
  const fmt = (rows) => rows.map((row) => ` ${row}`).join('\n');
461
463
 
464
+ /**
465
+ * Named bundles of per-topic agent settings. The file sits next to state.json
466
+ * and keeps its own revision counter, so a write from a second process cannot
467
+ * silently drop a set saved a moment earlier.
468
+ */
469
+ const AGENTSETS = join(process.env.DSH_TG_HOME || join(DSH_HOME, 'tg-bridge'), 'agentsets.json');
470
+ let agentsetStore = null;
471
+ function agentset() {
472
+ if (!agentsetStore) agentsetStore = new AgentsetStore(AGENTSETS).load();
473
+ return agentsetStore;
474
+ }
475
+
476
+ /** The set bound to this topic, or null. */
477
+ function agentsetOf(state, key) {
478
+ const id = state.agentsets?.[key];
479
+ return id ? agentset().get(id) : null;
480
+ }
481
+
482
+ /** What the topic's profile declares — the tier every set inherits from. */
483
+ function profileRowOf(profile) {
484
+ return profileValues({
485
+ model: modelOf(profile),
486
+ permissions: (parsePermissionPresets(read(patchPath(profile))) || {}).current || '',
487
+ preset: (parseAgentPresets(read(patchPath(profile))) || {}).selected || '',
488
+ effort: '',
489
+ lang: '',
490
+ });
491
+ }
492
+
493
+ /** Bind/unbind this topic. The set itself lives in agentsets.json. */
494
+ function bindAgentset(state, key, id) {
495
+ state.agentsets = state.agentsets || {};
496
+ if (id) state.agentsets[key] = id;
497
+ else delete state.agentsets[key];
498
+ }
499
+
500
+ /** One set rendered for a chat: what it owns, what it inherits. */
501
+ function agentsetCard(set, lang, profile, boundId) {
502
+ const row = profileRowOf(profile);
503
+ const resolved = resolveSettings({
504
+ set,
505
+ profile: row,
506
+ models: modelsOf(profile),
507
+ efforts: parseReasoningEfforts(read(patchPath(profile)), set.model || row.model) || [],
508
+ permissions: (parsePermissionPresets(read(patchPath(profile))) || {}).presets?.map((p) => p.id) || [],
509
+ presets: (parseAgentPresets(read(patchPath(profile))) || {}).presets?.map((p) => p.id) || [],
510
+ });
511
+ const pick = (field) => (set[field] ? set[field] : `— ${t(lang, 'ctrl.set.inherit')}`);
512
+ const lines = [
513
+ t(lang, `${boundId === set.id ? 'ctrl.set.titleBound' : 'ctrl.set.title'}`, { name: set.name || set.id }),
514
+ `${t(lang, 'ctrl.set.id')}: ${set.id}${set.builtin ? ` (${t(lang, 'ctrl.set.builtin')})` : ''}`,
515
+ `${t(lang, 'ctrl.set.field.model')}: ${pick('model')}`,
516
+ `${t(lang, 'ctrl.set.field.effort')}: ${pick('effort')}`,
517
+ `${t(lang, 'ctrl.set.field.permissions')}: ${pick('permissions')}`,
518
+ `${t(lang, 'ctrl.set.field.preset')}: ${pick('dshPreset')}`,
519
+ `${t(lang, 'ctrl.set.field.lang')}: ${pick('lang')}`,
520
+ ];
521
+ const warnings = [];
522
+ for (const field of ['model', 'effort', 'permissions', 'dshPreset']) {
523
+ if (String(resolved.sources[field] || '').endsWith('(invalid)')) {
524
+ warnings.push(t(lang, 'ctrl.set.dropped', { field }));
525
+ }
526
+ }
527
+ if (set.notes) lines.push('', set.notes);
528
+ if (warnings.length > 0) lines.push('', ...warnings);
529
+ lines.push('', t(lang, 'ctrl.set.hint'));
530
+ return lines.join('\n');
531
+ }
532
+
462
533
  /** Goal + task list as one message; empty list is shown, not hidden. */
463
534
  function goalView(goal, lang) {
464
535
  const { done, total } = progressOf(goal);
@@ -482,7 +553,7 @@ export const CONTROL_COMMANDS = [
482
553
  'jobs', 'remind', 'sessions', 'resume', 'plugins', 'plugin',
483
554
  'skills', 'soul', 'restart', 'app', 'stop', 'new', 'seed', 'send', 'cd',
484
555
  'prices', 'help', 'doctor', 'logs', 'lang', 'reasoning', 'goal', 'task',
485
- 'thoughts', 'version', 'update',
556
+ 'thoughts', 'version', 'update', 'agentset',
486
557
  ];
487
558
 
488
559
  /**
@@ -1684,98 +1755,98 @@ export async function handleControl(ctx) {
1684
1755
  return true;
1685
1756
  }
1686
1757
 
1687
- case '/thoughts': {
1688
- // The model's reasoning, read from the session log. Text by default (short,
1689
- // ephemeral, deletes itself); `file` and `all` write a Markdown log and send
1690
- // it as a document, because a five-hour turn is megabytes of text that no
1691
- // chat message can hold; `off` keeps the block out of the panel entirely.
1692
- const mode = String(arg || '').trim().toLowerCase();
1693
-
1694
- if (mode === 'off' || mode === 'on') {
1695
- state.thinkBlock = state.thinkBlock || {};
1696
- if (mode === 'off') state.thinkBlock[key] = 'counter';
1697
- else delete state.thinkBlock[key];
1698
- ctx.saveState?.();
1699
- say(t(lang, mode === 'off' ? 'ctrl.thoughts.off' : 'ctrl.thoughts.on'));
1700
- return true;
1701
- }
1702
-
1703
- const sessionId = ctx.state.sessions?.[key];
1704
- if (!sessionId) {
1705
- say(t(lang, 'ctrl.thoughts.noSession'));
1706
- return true;
1707
- }
1708
- const file = sessionFile(join(DSH_HOME, 'sessions'), sessionId);
1709
-
1710
- if (mode === 'file' || mode === 'all') {
1711
- const turns = mode === 'all'
1712
- ? sessionReasoningSteps(file).map((turn, index) => ({ title: t(lang, 'ctrl.thoughts.turn', { n: index + 1 }), steps: turn.steps }))
1713
- : [{ steps: lastTurnReasoningSteps(file) }];
1714
- const steps = turns.reduce((sum, turn) => sum + turn.steps.length, 0);
1715
- const chars = turns.reduce((sum, turn) => sum + turn.steps.reduce((n, step) => n + step.length, 0), 0);
1716
- if (!steps) {
1717
- say(t(lang, 'ctrl.thoughts.none'));
1718
- return true;
1719
- }
1720
- const now = new Date();
1721
- const pad = (n) => String(n).padStart(2, '0');
1722
- const date = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}`;
1723
- const stamp = date.replace(/[ :]/g, '-');
1724
- const path = join(THOUGHT_DIR, `reasoning-${stamp}-${mode}.md`);
1725
- try {
1726
- mkdirSync(THOUGHT_DIR, { recursive: true });
1727
- writeFileSync(path, reasoningMarkdown({
1728
- title: t(lang, mode === 'all' ? 'ctrl.thoughts.fileTitleAll' : 'ctrl.thoughts.fileTitleLast'),
1729
- meta: [date, t(lang, 'ctrl.thoughts.fileMeta', { steps, chars, turns: turns.length })],
1730
- stepTitle: t(lang, 'ctrl.thoughts.step'),
1731
- turns,
1732
- }), 'utf8');
1733
- // A log is a keepsake, not an archive: a week is plenty and the dir
1734
- // does not grow without bound.
1735
- for (const name of readdirSync(THOUGHT_DIR)) {
1736
- if (!name.startsWith('reasoning-')) continue;
1737
- const old = join(THOUGHT_DIR, name);
1738
- try {
1739
- if (Date.now() - statSync(old).mtimeMs > 7 * 86400000) rmSync(old, { force: true });
1740
- } catch {}
1741
- }
1742
- if (ctx.sendFile) {
1743
- await ctx.sendFile(path, t(lang, 'ctrl.thoughts.fileCaption', { chars, steps }));
1744
- return true;
1745
- }
1746
- // No file transport in this context (tests): the log still leaves as text.
1747
- say(`${t(lang, 'ctrl.thoughts.fileCaption', { chars, steps })}\n\n${readFileSync(path, 'utf8').slice(0, 3200)}`);
1748
- return true;
1749
- } catch (error) {
1750
- say(t(lang, 'ctrl.thoughts.fileError', { error: String(error.message).slice(0, 120) }));
1751
- return true;
1752
- }
1753
- }
1754
-
1755
- const text = file ? lastTurnReasoning(file, { maxChars: 20000 }) : '';
1756
- if (!text) {
1757
- // Not every turn plans: a one-word answer has no reasoning part at all.
1758
- // Saying "here is what the last turn answered" beats a dead end that
1759
- // looks like a broken command.
1760
- const answered = file ? lastTurnText(file, { maxChars: 1200 }) : '';
1761
- say(answered
1762
- ? `${t(lang, 'ctrl.thoughts.none')}\n\n${t(lang, 'ctrl.thoughts.lastAnswer')}\n\n${answered}\n\n${t(lang, 'ctrl.thoughts.hint')}`
1763
- : `${t(lang, 'ctrl.thoughts.none')}\n\n${t(lang, 'ctrl.thoughts.hint')}`);
1764
- return true;
1765
- }
1766
- // A message caps at 4096 characters; a long plan goes out in parts instead
1767
- // of being cut at the first one with a "…" that hides the rest.
1768
- const title = t(lang, 'ctrl.thoughts.title', { chars: text.length });
1769
- const parts = [];
1770
- for (let at = 0; at < text.length; at += 3600) parts.push(text.slice(at, at + 3600));
1771
- parts.forEach((part, index) => {
1772
- const last = index === parts.length - 1;
1773
- const head = parts.length > 1 ? `${title} (${index + 1}/${parts.length})` : title;
1774
- say(`${head}\n\n${part}${last ? `\n\n${t(lang, 'ctrl.thoughts.hint')}` : ''}`);
1775
- });
1776
- return true;
1777
- }
1778
-
1758
+ case '/thoughts': {
1759
+ // The model's reasoning, read from the session log. Text by default (short,
1760
+ // ephemeral, deletes itself); `file` and `all` write a Markdown log and send
1761
+ // it as a document, because a five-hour turn is megabytes of text that no
1762
+ // chat message can hold; `off` keeps the block out of the panel entirely.
1763
+ const mode = String(arg || '').trim().toLowerCase();
1764
+
1765
+ if (mode === 'off' || mode === 'on') {
1766
+ state.thinkBlock = state.thinkBlock || {};
1767
+ if (mode === 'off') state.thinkBlock[key] = 'counter';
1768
+ else delete state.thinkBlock[key];
1769
+ ctx.saveState?.();
1770
+ say(t(lang, mode === 'off' ? 'ctrl.thoughts.off' : 'ctrl.thoughts.on'));
1771
+ return true;
1772
+ }
1773
+
1774
+ const sessionId = ctx.state.sessions?.[key];
1775
+ if (!sessionId) {
1776
+ say(t(lang, 'ctrl.thoughts.noSession'));
1777
+ return true;
1778
+ }
1779
+ const file = sessionFile(join(DSH_HOME, 'sessions'), sessionId);
1780
+
1781
+ if (mode === 'file' || mode === 'all') {
1782
+ const turns = mode === 'all'
1783
+ ? sessionReasoningSteps(file).map((turn, index) => ({ title: t(lang, 'ctrl.thoughts.turn', { n: index + 1 }), steps: turn.steps }))
1784
+ : [{ steps: lastTurnReasoningSteps(file) }];
1785
+ const steps = turns.reduce((sum, turn) => sum + turn.steps.length, 0);
1786
+ const chars = turns.reduce((sum, turn) => sum + turn.steps.reduce((n, step) => n + step.length, 0), 0);
1787
+ if (!steps) {
1788
+ say(t(lang, 'ctrl.thoughts.none'));
1789
+ return true;
1790
+ }
1791
+ const now = new Date();
1792
+ const pad = (n) => String(n).padStart(2, '0');
1793
+ const date = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}`;
1794
+ const stamp = date.replace(/[ :]/g, '-');
1795
+ const path = join(THOUGHT_DIR, `reasoning-${stamp}-${mode}.md`);
1796
+ try {
1797
+ mkdirSync(THOUGHT_DIR, { recursive: true });
1798
+ writeFileSync(path, reasoningMarkdown({
1799
+ title: t(lang, mode === 'all' ? 'ctrl.thoughts.fileTitleAll' : 'ctrl.thoughts.fileTitleLast'),
1800
+ meta: [date, t(lang, 'ctrl.thoughts.fileMeta', { steps, chars, turns: turns.length })],
1801
+ stepTitle: t(lang, 'ctrl.thoughts.step'),
1802
+ turns,
1803
+ }), 'utf8');
1804
+ // A log is a keepsake, not an archive: a week is plenty and the dir
1805
+ // does not grow without bound.
1806
+ for (const name of readdirSync(THOUGHT_DIR)) {
1807
+ if (!name.startsWith('reasoning-')) continue;
1808
+ const old = join(THOUGHT_DIR, name);
1809
+ try {
1810
+ if (Date.now() - statSync(old).mtimeMs > 7 * 86400000) rmSync(old, { force: true });
1811
+ } catch {}
1812
+ }
1813
+ if (ctx.sendFile) {
1814
+ await ctx.sendFile(path, t(lang, 'ctrl.thoughts.fileCaption', { chars, steps }));
1815
+ return true;
1816
+ }
1817
+ // No file transport in this context (tests): the log still leaves as text.
1818
+ say(`${t(lang, 'ctrl.thoughts.fileCaption', { chars, steps })}\n\n${readFileSync(path, 'utf8').slice(0, 3200)}`);
1819
+ return true;
1820
+ } catch (error) {
1821
+ say(t(lang, 'ctrl.thoughts.fileError', { error: String(error.message).slice(0, 120) }));
1822
+ return true;
1823
+ }
1824
+ }
1825
+
1826
+ const text = file ? lastTurnReasoning(file, { maxChars: 20000 }) : '';
1827
+ if (!text) {
1828
+ // Not every turn plans: a one-word answer has no reasoning part at all.
1829
+ // Saying "here is what the last turn answered" beats a dead end that
1830
+ // looks like a broken command.
1831
+ const answered = file ? lastTurnText(file, { maxChars: 1200 }) : '';
1832
+ say(answered
1833
+ ? `${t(lang, 'ctrl.thoughts.none')}\n\n${t(lang, 'ctrl.thoughts.lastAnswer')}\n\n${answered}\n\n${t(lang, 'ctrl.thoughts.hint')}`
1834
+ : `${t(lang, 'ctrl.thoughts.none')}\n\n${t(lang, 'ctrl.thoughts.hint')}`);
1835
+ return true;
1836
+ }
1837
+ // A message caps at 4096 characters; a long plan goes out in parts instead
1838
+ // of being cut at the first one with a "…" that hides the rest.
1839
+ const title = t(lang, 'ctrl.thoughts.title', { chars: text.length });
1840
+ const parts = [];
1841
+ for (let at = 0; at < text.length; at += 3600) parts.push(text.slice(at, at + 3600));
1842
+ parts.forEach((part, index) => {
1843
+ const last = index === parts.length - 1;
1844
+ const head = parts.length > 1 ? `${title} (${index + 1}/${parts.length})` : title;
1845
+ say(`${head}\n\n${part}${last ? `\n\n${t(lang, 'ctrl.thoughts.hint')}` : ''}`);
1846
+ });
1847
+ return true;
1848
+ }
1849
+
1779
1850
  case '/version': {
1780
1851
  // Which bridge is running, which one npm has, and whether this install can
1781
1852
  // update itself. A report, so it answers even in the middle of a turn.
@@ -1869,6 +1940,166 @@ export async function handleControl(ctx) {
1869
1940
  return true;
1870
1941
  }
1871
1942
 
1943
+ case '/agentset': {
1944
+ const store = agentset();
1945
+ if (store.error) say(t(lang, 'ctrl.set.storeBroken', { error: store.error }));
1946
+ const bound = state.agentsets?.[key] || '';
1947
+ const ids = () => store.list().map((set) => set.id).join(', ');
1948
+ const parts = String(arg || '').trim().split(/\s+/).filter(Boolean);
1949
+ const verb = (parts[0] || '').toLowerCase();
1950
+ const rest = parts.slice(1);
1951
+ const text = (value) => rest.join(' ').trim();
1952
+
1953
+ /** Shared failure lanes: every write reports the same three ways. */
1954
+ const commit = (id, result) => {
1955
+ if (result.ok) return true;
1956
+ if (result.error === 'stale') say(t(lang, 'ctrl.set.stale'));
1957
+ else if (result.error === 'unreadable') say(t(lang, 'ctrl.set.unreadable', { error: result.file || AGENTSETS }));
1958
+ else if (result.error === 'builtin-readonly') say(t(lang, 'ctrl.set.builtinReadonly', { id }));
1959
+ else if (result.error === 'bad-id') say(t(lang, 'ctrl.set.badId'));
1960
+ else if (result.error === 'missing') say(t(lang, 'ctrl.set.unknown', { id, list: ids() }));
1961
+ else say(t(lang, 'ctrl.set.failed', { error: result.error || '?' }));
1962
+ return false;
1963
+ };
1964
+
1965
+ if (!verb) {
1966
+ const sets = store.list();
1967
+ const lines = [
1968
+ t(lang, 'ctrl.set.list', { n: sets.length }),
1969
+ ...sets.map((set) => {
1970
+ const mark = set.id === bound ? '•' : ' ';
1971
+ const note = set.builtin ? t(lang, 'ctrl.set.builtin') : set.notes || t(lang, 'ctrl.set.custom');
1972
+ return `${mark} ${set.id} — ${set.name || set.id} (${note})`;
1973
+ }),
1974
+ '',
1975
+ bound ? t(lang, 'ctrl.set.boundNow', { name: store.get(bound)?.name || bound }) : t(lang, 'ctrl.set.noneBound', { profile: activeProfile }),
1976
+ t(lang, 'ctrl.set.usage'),
1977
+ t(lang, 'ctrl.set.hint'),
1978
+ ];
1979
+ say(lines.join('\n'));
1980
+ return true;
1981
+ }
1982
+
1983
+ if (verb === 'show') {
1984
+ const set = store.get(rest[0] || bound);
1985
+ if (!set) {
1986
+ say(t(lang, 'ctrl.set.unknown', { id: rest[0] || '', list: ids() }));
1987
+ return true;
1988
+ }
1989
+ say(agentsetCard(set, lang, activeProfile, bound));
1990
+ return true;
1991
+ }
1992
+
1993
+ if (verb === 'use') {
1994
+ const id = rest[0] || '';
1995
+ const set = store.get(id);
1996
+ if (!set) {
1997
+ say(t(lang, 'ctrl.set.unknown', { id, list: ids() }));
1998
+ return true;
1999
+ }
2000
+ if (bound === id) {
2001
+ say(t(lang, 'ctrl.set.same'));
2002
+ return true;
2003
+ }
2004
+ // Binding a builtin is fine: nobody writes to it, it is only a
2005
+ // starting point that the profile tier still overrides per field.
2006
+ bindAgentset(state, key, id);
2007
+ // A set that carries language or the thinking block changes this topic's
2008
+ // own preferences too; those live in state, not in the profile.
2009
+ if (set.lang) state.lang = { ...(state.lang || {}), [key]: set.lang };
2010
+ if (set.thinkBlock) state.thinkBlock = { ...(state.thinkBlock || {}), [key]: set.thinkBlock };
2011
+ ctx.saveState();
2012
+ say(t(lang, 'ctrl.set.bound', { name: set.name || set.id }));
2013
+ return true;
2014
+ }
2015
+
2016
+ if (verb === 'off') {
2017
+ if (!bound) {
2018
+ say(t(lang, 'ctrl.set.same'));
2019
+ return true;
2020
+ }
2021
+ bindAgentset(state, key, '');
2022
+ ctx.saveState();
2023
+ say(t(lang, 'ctrl.set.unbound', { profile: activeProfile }));
2024
+ return true;
2025
+ }
2026
+
2027
+ if (verb === 'new' || verb === 'copy') {
2028
+ // `/agentset new <name> [from <id>]`, and the shorthand
2029
+ // `/agentset copy <name> <id>`.
2030
+ const fromWord = rest.indexOf('from', 1);
2031
+ const bare = fromWord > 0 ? rest.slice(0, fromWord).join(' ') : rest[0] || '';
2032
+ const sourceId = fromWord > 0 ? rest[fromWord + 1] || '' : rest[1] || '';
2033
+ const source = sourceId ? store.get(sourceId) : null;
2034
+ if (sourceId && !source) {
2035
+ say(t(lang, 'ctrl.set.unknown', { id: sourceId, list: ids() }));
2036
+ return true;
2037
+ }
2038
+ const id = slugId(bare || sourceId);
2039
+ if (!id) {
2040
+ say(t(lang, 'ctrl.set.badId'));
2041
+ return true;
2042
+ }
2043
+ if (store.get(id)) {
2044
+ say(t(lang, 'ctrl.set.exists', { id }));
2045
+ return true;
2046
+ }
2047
+ const next = source ? { ...source, id, name: bare || id, builtin: false, createdAt: undefined } : emptySet(id, bare || id);
2048
+ if (commit(id, store.put(next))) say(t(lang, 'ctrl.set.created', { id }));
2049
+ return true;
2050
+ }
2051
+
2052
+ if (verb === 'rm') {
2053
+ const id = rest[0] || '';
2054
+ const set = store.get(id);
2055
+ if (!set) {
2056
+ say(t(lang, 'ctrl.set.unknown', { id, list: ids() }));
2057
+ return true;
2058
+ }
2059
+ const users = Object.entries(state.agentsets || {}).filter(([, ref]) => ref === id).map(([ref]) => ref);
2060
+ if (users.length > 0) {
2061
+ say(t(lang, 'ctrl.set.inUse', { id, keys: users.join(', ') }));
2062
+ return true;
2063
+ }
2064
+ if (commit(id, store.remove(id))) say(t(lang, 'ctrl.set.removed', { id }));
2065
+ return true;
2066
+ }
2067
+
2068
+ if (verb === 'reload') {
2069
+ agentsetStore = new AgentsetStore(AGENTSETS).load();
2070
+ say(agentset().error ? t(lang, 'ctrl.set.storeBroken', { error: agentset().error }) : t(lang, 'ctrl.set.reloaded', { n: agentset().list().length }));
2071
+ return true;
2072
+ }
2073
+
2074
+ // Anything else is a field edit on a set: `/agentset model glm-5.3 [id]`,
2075
+ // `/agentset model inherit`. The DSH profile keeps its own /agents set …
2076
+ // verbs; this one only ever writes the topic's set.
2077
+ const field = verb;
2078
+ const known = new Set(['model', 'effort', 'permissions', 'preset', 'lang', 'notes']);
2079
+ if (!known.has(field)) {
2080
+ say(t(lang, 'ctrl.set.badField', { field, list: [...known].join(', ') }));
2081
+ return true;
2082
+ }
2083
+ // The last word names the set only when it is one; otherwise the whole
2084
+ // tail is the value ("/agentset model glm 5.3" would be a model id).
2085
+ const maybe = store.get(rest[rest.length - 1]);
2086
+ const target = maybe || (bound ? store.get(bound) : null);
2087
+ const set = target || store.get(rest[0]);
2088
+ if (!set) {
2089
+ say(t(lang, 'ctrl.set.unknown', { id: rest[rest.length - 1] || '', list: ids() }));
2090
+ return true;
2091
+ }
2092
+ const valueWords = maybe ? rest.slice(0, -1) : rest;
2093
+ const value = valueWords.join(' ').trim();
2094
+ const cleared = !value || value === 'inherit' || value === '-';
2095
+ const storeField = field === 'preset' ? 'dshPreset' : field;
2096
+ const next = { ...set, [storeField]: cleared ? '' : value };
2097
+ if (commit(set.id, store.put(next))) {
2098
+ say(cleared ? t(lang, 'ctrl.set.fieldCleared', { field }) : t(lang, 'ctrl.set.fieldSet', { field, value, name: set.name || set.id }));
2099
+ }
2100
+ return true;
2101
+ }
2102
+
1872
2103
  default:
1873
2104
  return false;
1874
2105
  }
package/i18n.mjs CHANGED
@@ -20,7 +20,7 @@ const DICT = {
20
20
  'status.failed': 'Turn failed',
21
21
  'status.queued': 'queued',
22
22
  'status.stop': 'Stop',
23
- 'help.body': "Write the task as plain text. Each forum topic is its own session:\n\nWork: /cd \u003cproject\u003e · /new · /stop · /send \u003cfile\u003e · /seed \u003ctext\u003e\nGoals: /goal · /task\nSessions: /status · /sessions [n] · /resume \u003cid\u003e\nAgents: /agents · /agents set model|depth|filter … @tool\nModels: /model · /model \u003cid\u003e · /prices · /thoughts\nTuning: /effort · /permissions · /preset · /plan · /jobs · /remind\nExtensions: /skills · /plugins · /plugin add|remove · /soul\nVersions: /version · /update · /update confirm\nOther: /lang · /reasoning · /doctor · /logs [errors|N] · /app · /restart · /help",
23
+ 'help.body': "Write the task as plain text. Each forum topic is its own session:\n\nWork: /cd \u003cproject\u003e · /new · /stop · /send \u003cfile\u003e · /seed \u003ctext\u003e\nGoals: /goal · /task\nSessions: /status · /sessions [n] · /resume \u003cid\u003e\nAgents: /agents · /agents set model|depth|filter … @tool\nModels: /model · /model \u003cid\u003e · /prices · /thoughts\nTuning: /effort · /permissions · /preset · /agentset [use|show|off|new] · /plan · /jobs · /remind\nExtensions: /skills · /plugins · /plugin add|remove · /soul\nVersions: /version · /update · /update confirm\nOther: /lang · /reasoning · /doctor · /logs [errors|N] · /app · /restart · /help",
24
24
  'btn.stop': 'Stop',
25
25
  'btn.logs': 'Logs',
26
26
  'btn.retry': 'Retry',
@@ -32,7 +32,7 @@ const DICT = {
32
32
  'msg.transcribing': '🎤 Transcribing…',
33
33
  'status.steps': 'steps',
34
34
  'status.thinking': 'waiting for the model',
35
- 'status.thinkTitle': 'Reasoning',
35
+ 'status.thinkTitle': 'Reasoning',
36
36
  'status.stepsTitle': 'Steps',
37
37
  'status.thinkCut': 'earlier reasoning hidden',
38
38
  'err.timeout': 'no activity for {min} min — turn interrupted',
@@ -232,16 +232,16 @@ const DICT = {
232
232
  'ctrl.thoughts.title': '🧠 Reasoning of the last turn ({chars} chars, kept for a few minutes):',
233
233
  'ctrl.thoughts.none': 'The last turn stored no reasoning plan.',
234
234
  'ctrl.thoughts.lastAnswer': 'What the last turn answered:',
235
- 'ctrl.thoughts.noSession': 'This topic has no session yet: send a task first.',
236
- 'ctrl.thoughts.hint': 'Whole log as a file: /thoughts file · whole session: /thoughts all · hide the block: /thoughts off',
237
- 'ctrl.thoughts.fileCaption': '🧠 Reasoning log · {chars} chars · {steps} steps',
238
- 'ctrl.thoughts.off': 'The reasoning block is off in this chat. /thoughts file still sends the whole log as a file.',
239
- 'ctrl.thoughts.on': 'The reasoning block is back in the turn panel.',
240
- 'ctrl.thoughts.fileError': 'Could not build the log file: {error}',
241
- 'ctrl.thoughts.fileTitleLast': 'Reasoning of the last turn',
242
- 'ctrl.thoughts.fileTitleAll': 'Reasoning of the whole session',
243
- 'ctrl.thoughts.fileMeta': '{steps} steps · {chars} chars · {turns} turns',
244
- 'ctrl.thoughts.step': 'Step',
235
+ 'ctrl.thoughts.noSession': 'This topic has no session yet: send a task first.',
236
+ 'ctrl.thoughts.hint': 'Whole log as a file: /thoughts file · whole session: /thoughts all · hide the block: /thoughts off',
237
+ 'ctrl.thoughts.fileCaption': '🧠 Reasoning log · {chars} chars · {steps} steps',
238
+ 'ctrl.thoughts.off': 'The reasoning block is off in this chat. /thoughts file still sends the whole log as a file.',
239
+ 'ctrl.thoughts.on': 'The reasoning block is back in the turn panel.',
240
+ 'ctrl.thoughts.fileError': 'Could not build the log file: {error}',
241
+ 'ctrl.thoughts.fileTitleLast': 'Reasoning of the last turn',
242
+ 'ctrl.thoughts.fileTitleAll': 'Reasoning of the whole session',
243
+ 'ctrl.thoughts.fileMeta': '{steps} steps · {chars} chars · {turns} turns',
244
+ 'ctrl.thoughts.step': 'Step',
245
245
  'ctrl.thoughts.turn': 'Turn {n}',
246
246
  'goal.none': 'No goal in this topic. Set one: /goal <text>',
247
247
  'goal.set': 'Goal: {text}',
@@ -387,6 +387,41 @@ const DICT = {
387
387
  'ctrl.remind.inHour': 'in {n} h',
388
388
  'ctrl.remind.inDay': 'in {n} d',
389
389
  'ctrl.remind.due': '⏰ {text}',
390
+ 'ctrl.set.title': '🧰 Set: {name}',
391
+ 'ctrl.set.titleBound': '🧰 Set: {name} — bound to this topic',
392
+ 'ctrl.set.id': 'Id',
393
+ 'ctrl.set.field.model': 'Model',
394
+ 'ctrl.set.field.effort': 'Effort',
395
+ 'ctrl.set.field.permissions': 'Permissions',
396
+ 'ctrl.set.field.preset': 'Agent preset',
397
+ 'ctrl.set.field.lang': 'Language',
398
+ 'ctrl.set.inherit': 'from the profile',
399
+ 'ctrl.set.list': 'Sets: {n}',
400
+ 'ctrl.set.custom': 'custom',
401
+ 'ctrl.set.builtin': 'built-in',
402
+ 'ctrl.set.boundNow': 'This topic uses {name}.',
403
+ 'ctrl.set.noneBound': 'No set bound: this topic follows profile {profile}.',
404
+ 'ctrl.set.usage': 'Bind: /agentset use <id> · card: /agentset show [id] · detach: /agentset off · new: /agentset new <name> [from <id>]',
405
+ 'ctrl.set.hint': 'A set is a delta over the profile: an empty field inherits it. Edit one field with /agentset model|effort|permissions|preset|lang <value> [id], or "inherit" to clear.',
406
+ 'ctrl.set.bound': '✅ This topic now uses {name}. Applies from the next turn.',
407
+ 'ctrl.set.unbound': '✅ Back to profile {profile}.',
408
+ 'ctrl.set.same': 'Already in that state.',
409
+ 'ctrl.set.unknown': 'No set "{id}". Available: {list}',
410
+ 'ctrl.set.exists': 'A set "{id}" already exists.',
411
+ 'ctrl.set.badId': 'Name it with lowercase letters, digits and dashes, up to 24 characters.',
412
+ 'ctrl.set.created': '✅ Set {id} created. Fill it: /agentset model <value> {id}',
413
+ 'ctrl.set.removed': '🗑 Set {id} removed (kept in the trash for 7 days).',
414
+ 'ctrl.set.inUse': 'Set {id} is bound to: {keys}. Detach it there first.',
415
+ 'ctrl.set.builtinReadonly': '{id} is built-in and read-only. Copy it: /agentset copy <new-name> {id}',
416
+ 'ctrl.set.badField': 'No field "{field}". Editable: {list}',
417
+ 'ctrl.set.fieldSet': '✅ {field} → {value} in {name}.',
418
+ 'ctrl.set.fieldCleared': '✅ {field} inherits the profile again.',
419
+ 'ctrl.set.stale': 'Somebody changed the sets meanwhile — repeat the command.',
420
+ 'ctrl.set.unreadable': 'agentsets.json cannot be rewritten ({error}) — fix or move it first.',
421
+ 'ctrl.set.failed': 'Could not save the set ({error}).',
422
+ 'ctrl.set.storeBroken': '⚠️ {error}',
423
+ 'ctrl.set.reloaded': 'Reloaded: {n} sets.',
424
+ 'ctrl.set.dropped': 'Not applied: {field} — the profile does not declare it.',
390
425
  },
391
426
  ru: {
392
427
  'status.working': 'Работаю',
@@ -395,7 +430,7 @@ const DICT = {
395
430
  'status.failed': 'Ход не удался',
396
431
  'status.queued': 'в очереди',
397
432
  'status.stop': 'Стоп',
398
- 'help.body': "Задачу можно писать обычным текстом. Каждая ветка форума — отдельная сессия:\n\nРабота: /cd \u003cпроект\u003e · /new · /stop · /send \u003cфайл\u003e · /seed \u003cтекст\u003e\nЦели: /goal · /task\nСессии: /status · /sessions [n] · /resume \u003cid\u003e\nАгенты: /agents · /agents set model|depth|filter … @tool\nМодели: /model · /model \u003cid\u003e · /prices · /thoughts\nНастройка: /effort · /permissions · /preset · /plan · /jobs · /remind\nРасширения: /skills · /plugins · /plugin add|remove · /soul\nВерсии: /version · /update · /update confirm\nПрочее: /lang · /reasoning · /doctor · /logs [errors|N] · /app · /restart · /help",
433
+ 'help.body': "Задачу можно писать обычным текстом. Каждая ветка форума — отдельная сессия:\n\nРабота: /cd \u003cпроект\u003e · /new · /stop · /send \u003cфайл\u003e · /seed \u003cтекст\u003e\nЦели: /goal · /task\nСессии: /status · /sessions [n] · /resume \u003cid\u003e\nАгенты: /agents · /agents set model|depth|filter … @tool\nМодели: /model · /model \u003cid\u003e · /prices · /thoughts\nНастройка: /effort · /permissions · /preset · /agentset [use|show|off|new] · /plan · /jobs · /remind\nРасширения: /skills · /plugins · /plugin add|remove · /soul\nВерсии: /version · /update · /update confirm\nПрочее: /lang · /reasoning · /doctor · /logs [errors|N] · /app · /restart · /help",
399
434
  'btn.stop': 'Стоп',
400
435
  'btn.logs': 'Логи',
401
436
  'btn.retry': 'Повторить',
@@ -407,7 +442,7 @@ const DICT = {
407
442
  'msg.transcribing': '🎤 Расшифровываю…',
408
443
  'status.steps': 'шагов',
409
444
  'status.thinking': 'жду модель',
410
- 'status.thinkTitle': 'Размышления',
445
+ 'status.thinkTitle': 'Размышления',
411
446
  'status.stepsTitle': 'Шаги',
412
447
  'status.thinkCut': 'начало скрыто',
413
448
  'err.timeout': 'нет активности {min} мин — ход прерван',
@@ -607,16 +642,16 @@ const DICT = {
607
642
  'ctrl.thoughts.title': '🧠 Рассуждения последнего хода ({chars} символов, повисят несколько минут):',
608
643
  'ctrl.thoughts.none': 'В последнем ходе не сохранилось плана рассуждений.',
609
644
  'ctrl.thoughts.lastAnswer': 'Последний ход ответил так:',
610
- 'ctrl.thoughts.noSession': 'В этой теме ещё нет сессии: сначала отправь задачу.',
611
- 'ctrl.thoughts.hint': 'Весь лог файлом: /thoughts file · вся сессия: /thoughts all · убрать блок: /thoughts off',
612
- 'ctrl.thoughts.fileCaption': '🧠 Лог рассуждений · {chars} символов · шагов {steps}',
613
- 'ctrl.thoughts.off': 'Блок рассуждений в этом чате выключен. Полный лог по-прежнему отдаёт /thoughts file.',
614
- 'ctrl.thoughts.on': 'Блок рассуждений снова в панели хода.',
615
- 'ctrl.thoughts.fileError': 'Не смог собрать файл лога: {error}',
616
- 'ctrl.thoughts.fileTitleLast': 'Размышления последнего хода',
617
- 'ctrl.thoughts.fileTitleAll': 'Размышления всей сессии',
618
- 'ctrl.thoughts.fileMeta': 'шагов {steps} · {chars} символов · ходов {turns}',
619
- 'ctrl.thoughts.step': 'Шаг',
645
+ 'ctrl.thoughts.noSession': 'В этой теме ещё нет сессии: сначала отправь задачу.',
646
+ 'ctrl.thoughts.hint': 'Весь лог файлом: /thoughts file · вся сессия: /thoughts all · убрать блок: /thoughts off',
647
+ 'ctrl.thoughts.fileCaption': '🧠 Лог рассуждений · {chars} символов · шагов {steps}',
648
+ 'ctrl.thoughts.off': 'Блок рассуждений в этом чате выключен. Полный лог по-прежнему отдаёт /thoughts file.',
649
+ 'ctrl.thoughts.on': 'Блок рассуждений снова в панели хода.',
650
+ 'ctrl.thoughts.fileError': 'Не смог собрать файл лога: {error}',
651
+ 'ctrl.thoughts.fileTitleLast': 'Размышления последнего хода',
652
+ 'ctrl.thoughts.fileTitleAll': 'Размышления всей сессии',
653
+ 'ctrl.thoughts.fileMeta': 'шагов {steps} · {chars} символов · ходов {turns}',
654
+ 'ctrl.thoughts.step': 'Шаг',
620
655
  'ctrl.thoughts.turn': 'Ход {n}',
621
656
  'goal.none': 'В этой теме нет цели. Задать: /goal <текст>',
622
657
  'goal.set': 'Цель: {text}',
@@ -762,6 +797,41 @@ const DICT = {
762
797
  'ctrl.remind.inHour': 'через {n} ч',
763
798
  'ctrl.remind.inDay': 'через {n} д',
764
799
  'ctrl.remind.due': '⏰ {text}',
800
+ 'ctrl.set.title': '🧰 Набор: {name}',
801
+ 'ctrl.set.titleBound': '🧰 Набор: {name} — привязан к этой теме',
802
+ 'ctrl.set.id': 'Идентификатор',
803
+ 'ctrl.set.field.model': 'Модель',
804
+ 'ctrl.set.field.effort': 'Усилие',
805
+ 'ctrl.set.field.permissions': 'Права',
806
+ 'ctrl.set.field.preset': 'Пресет агента',
807
+ 'ctrl.set.field.lang': 'Язык',
808
+ 'ctrl.set.inherit': 'из профиля',
809
+ 'ctrl.set.list': 'Наборов: {n}',
810
+ 'ctrl.set.custom': 'свой',
811
+ 'ctrl.set.builtin': 'встроенный',
812
+ 'ctrl.set.boundNow': 'Тема работает на «{name}».',
813
+ 'ctrl.set.noneBound': 'Набор не привязан: тема идёт по профилю {profile}.',
814
+ 'ctrl.set.usage': 'Привязать: /agentset use <id> · карточка: /agentset show [id] · отвязать: /agentset off · создать: /agentset new <имя> [из <id>]',
815
+ 'ctrl.set.hint': 'Набор — дельта к профилю: пустое поле наследуется. Одно поле: /agentset model|effort|permissions|preset|lang <значение> [id], «inherit» очищает.',
816
+ 'ctrl.set.bound': '✅ Тема перешла на «{name}». Действует со следующего хода.',
817
+ 'ctrl.set.unbound': '✅ Снова профиль {profile}.',
818
+ 'ctrl.set.same': 'Уже так.',
819
+ 'ctrl.set.unknown': 'Набора «{id}» нет. Есть: {list}',
820
+ 'ctrl.set.exists': 'Набор «{id}» уже существует.',
821
+ 'ctrl.set.badId': 'Имя — строчные латинские буквы, цифры и дефис, до 24 символов.',
822
+ 'ctrl.set.created': '✅ Набор {id} создан. Заполнить: /agentset model <значение> {id}',
823
+ 'ctrl.set.removed': '🗑 Набор {id} удалён (лежит в корзине 7 дней).',
824
+ 'ctrl.set.inUse': 'Набор {id} привязан к темам: {keys}. Сначала отвяжи.',
825
+ 'ctrl.set.builtinReadonly': '«{id}» встроенный и только для чтения. Скопируй: /agentset copy <новое-имя> {id}',
826
+ 'ctrl.set.badField': 'Поля «{field}» нет. Можно: {list}',
827
+ 'ctrl.set.fieldSet': '✅ {field} → {value} в наборе {name}.',
828
+ 'ctrl.set.fieldCleared': '✅ {field} снова берётся из профиля.',
829
+ 'ctrl.set.stale': 'Наборы успели измениться — повтори команду.',
830
+ 'ctrl.set.unreadable': 'agentsets.json не перезаписать ({error}) — сначала почини или убери файл.',
831
+ 'ctrl.set.failed': 'Не удалось сохранить набор ({error}).',
832
+ 'ctrl.set.storeBroken': '⚠️ {error}',
833
+ 'ctrl.set.reloaded': 'Перечитано: наборов {n}.',
834
+ 'ctrl.set.dropped': 'Не применено: {field} — профиль этого не объявляет.',
765
835
  },
766
836
  zh: {
767
837
  'status.working': '处理中',
@@ -770,7 +840,7 @@ const DICT = {
770
840
  'status.failed': '运行失败',
771
841
  'status.queued': '排队中',
772
842
  'status.stop': '停止',
773
- 'help.body': "任务直接以文本发送。每个论坛话题是一个独立会话:\n\n工作: /cd \u003c项目\u003e · /new · /stop · /send \u003c文件\u003e · /seed \u003c文本\u003e\n目标: /goal · /task\n会话: /status · /sessions [n] · /resume \u003cid\u003e\n智能体: /agents · /agents set model|depth|filter … @tool\n模型: /model · /model \u003cid\u003e · /prices · /thoughts\n调优: /effort · /permissions · /preset · /plan · /jobs · /remind\n扩展: /skills · /plugins · /plugin add|remove · /soul\n版本: /version · /update · /update confirm\n其他: /lang · /reasoning · /doctor · /logs [errors|N] · /app · /restart · /help",
843
+ 'help.body': "任务直接以文本发送。每个论坛话题是一个独立会话:\n\n工作: /cd \u003c项目\u003e · /new · /stop · /send \u003c文件\u003e · /seed \u003c文本\u003e\n目标: /goal · /task\n会话: /status · /sessions [n] · /resume \u003cid\u003e\n智能体: /agents · /agents set model|depth|filter … @tool\n模型: /model · /model \u003cid\u003e · /prices · /thoughts\n调优: /effort · /permissions · /preset · /agentset [use|show|off|new] · /plan · /jobs · /remind\n扩展: /skills · /plugins · /plugin add|remove · /soul\n版本: /version · /update · /update confirm\n其他: /lang · /reasoning · /doctor · /logs [errors|N] · /app · /restart · /help",
774
844
  'btn.stop': '停止',
775
845
  'btn.logs': '日志',
776
846
  'btn.retry': '重试',
@@ -782,7 +852,7 @@ const DICT = {
782
852
  'msg.transcribing': '🎤 正在转写…',
783
853
  'status.steps': '步',
784
854
  'status.thinking': '等待模型',
785
- 'status.thinkTitle': '推理',
855
+ 'status.thinkTitle': '推理',
786
856
  'status.stepsTitle': '步骤',
787
857
  'status.thinkCut': '前文已省略',
788
858
  'err.timeout': '{min} 分钟无活动 — 已中断',
@@ -982,16 +1052,16 @@ const DICT = {
982
1052
  'ctrl.thoughts.title': '🧠 上一轮的推理({chars} 字符,几分钟后消失):',
983
1053
  'ctrl.thoughts.none': '上一轮没有保存推理过程。',
984
1054
  'ctrl.thoughts.lastAnswer': '上一轮的回答:',
985
- 'ctrl.thoughts.noSession': '本话题还没有会话:先发一个任务。',
986
- 'ctrl.thoughts.hint': '完整日志文件:/thoughts file · 整个会话:/thoughts all · 隐藏区块:/thoughts off',
987
- 'ctrl.thoughts.fileCaption': '🧠 推理日志 · {chars} 字符 · {steps} 步',
988
- 'ctrl.thoughts.off': '本聊天的推理区块已关闭。完整日志仍可用 /thoughts file 获取。',
989
- 'ctrl.thoughts.on': '推理区块已回到进度面板。',
990
- 'ctrl.thoughts.fileError': '无法生成日志文件:{error}',
991
- 'ctrl.thoughts.fileTitleLast': '上一轮的推理',
992
- 'ctrl.thoughts.fileTitleAll': '整个会话的推理',
993
- 'ctrl.thoughts.fileMeta': '{steps} 步 · {chars} 字符 · {turns} 轮',
994
- 'ctrl.thoughts.step': '步骤',
1055
+ 'ctrl.thoughts.noSession': '本话题还没有会话:先发一个任务。',
1056
+ 'ctrl.thoughts.hint': '完整日志文件:/thoughts file · 整个会话:/thoughts all · 隐藏区块:/thoughts off',
1057
+ 'ctrl.thoughts.fileCaption': '🧠 推理日志 · {chars} 字符 · {steps} 步',
1058
+ 'ctrl.thoughts.off': '本聊天的推理区块已关闭。完整日志仍可用 /thoughts file 获取。',
1059
+ 'ctrl.thoughts.on': '推理区块已回到进度面板。',
1060
+ 'ctrl.thoughts.fileError': '无法生成日志文件:{error}',
1061
+ 'ctrl.thoughts.fileTitleLast': '上一轮的推理',
1062
+ 'ctrl.thoughts.fileTitleAll': '整个会话的推理',
1063
+ 'ctrl.thoughts.fileMeta': '{steps} 步 · {chars} 字符 · {turns} 轮',
1064
+ 'ctrl.thoughts.step': '步骤',
995
1065
  'ctrl.thoughts.turn': '第 {n} 轮',
996
1066
  'goal.none': '本话题还没有目标。设置:/goal <文本>',
997
1067
  'goal.set': '目标:{text}',
@@ -1137,6 +1207,41 @@ const DICT = {
1137
1207
  'ctrl.remind.inHour': '{n} 小时后',
1138
1208
  'ctrl.remind.inDay': '{n} 天后',
1139
1209
  'ctrl.remind.due': '⏰ {text}',
1210
+ 'ctrl.set.title': '🧰 方案:{name}',
1211
+ 'ctrl.set.titleBound': '🧰 方案:{name} — 已绑定本话题',
1212
+ 'ctrl.set.id': '标识',
1213
+ 'ctrl.set.field.model': '模型',
1214
+ 'ctrl.set.field.effort': '思考力度',
1215
+ 'ctrl.set.field.permissions': '权限',
1216
+ 'ctrl.set.field.preset': '智能体预设',
1217
+ 'ctrl.set.field.lang': '语言',
1218
+ 'ctrl.set.inherit': '沿用配置档',
1219
+ 'ctrl.set.list': '方案数:{n}',
1220
+ 'ctrl.set.custom': '自定义',
1221
+ 'ctrl.set.builtin': '内置',
1222
+ 'ctrl.set.boundNow': '本话题使用「{name}」。',
1223
+ 'ctrl.set.noneBound': '未绑定方案:本话题按配置档 {profile} 运行。',
1224
+ 'ctrl.set.usage': '绑定:/agentset use <id> · 卡片:/agentset show [id] · 取消:/agentset off · 新建:/agentset new <名称> [from <id>]',
1225
+ 'ctrl.set.hint': '方案是对配置档的增量:留空的字段沿用配置档。改单项:/agentset model|effort|permissions|preset|lang <值> [id],inherit 表示清除。',
1226
+ 'ctrl.set.bound': '✅ 本话题已改用「{name}」,下一轮生效。',
1227
+ 'ctrl.set.unbound': '✅ 已恢复配置档 {profile}。',
1228
+ 'ctrl.set.same': '已经是这样。',
1229
+ 'ctrl.set.unknown': '没有方案「{id}」。可用:{list}',
1230
+ 'ctrl.set.exists': '方案「{id}」已存在。',
1231
+ 'ctrl.set.badId': '名称用小写字母、数字和连字符,最多 24 个字符。',
1232
+ 'ctrl.set.created': '✅ 已创建方案 {id}。填写:/agentset model <值> {id}',
1233
+ 'ctrl.set.removed': '🗑 已删除方案 {id}(在回收站保留 7 天)。',
1234
+ 'ctrl.set.inUse': '方案 {id} 已绑定到:{keys}。请先解绑。',
1235
+ 'ctrl.set.builtinReadonly': '「{id}」是内置的,只读。可复制:/agentset copy <新名称> {id}',
1236
+ 'ctrl.set.badField': '没有字段「{field}」。可改:{list}',
1237
+ 'ctrl.set.fieldSet': '✅ 方案 {name} 的 {field} → {value}。',
1238
+ 'ctrl.set.fieldCleared': '✅ {field} 改回沿用配置档。',
1239
+ 'ctrl.set.stale': '方案已被改动——请重试命令。',
1240
+ 'ctrl.set.unreadable': 'agentsets.json 无法重写({error})——请先修复或移走该文件。',
1241
+ 'ctrl.set.failed': '保存方案失败({error})。',
1242
+ 'ctrl.set.storeBroken': '⚠️ {error}',
1243
+ 'ctrl.set.reloaded': '已重新读取:方案 {n} 个。',
1244
+ 'ctrl.set.dropped': '未应用:{field}——配置档没有声明。',
1140
1245
  },
1141
1246
  };
1142
1247
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-tg-bridge",
3
- "version": "1.12.1",
3
+ "version": "1.13.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",
@@ -45,6 +45,8 @@
45
45
  "cordis.patch.yml",
46
46
  "control.mjs",
47
47
  "agents.mjs",
48
+ "agentsets.mjs",
49
+ "settings.mjs",
48
50
  "panel.mjs",
49
51
  "profile-edit.mjs",
50
52
  "reminders.mjs",
package/panel.mjs CHANGED
@@ -94,13 +94,17 @@ export function progressPanel({
94
94
  // thing sent after a message arrives, so this is what makes that first
95
95
  // message say "принял: …" instead of a generic spinner.
96
96
  task = '',
97
+ // Which settings this topic actually overrides, e.g. "Reviewer · glm-5.3/high".
98
+ // It rides in the head, so the panel budget above counts it automatically.
99
+ chip = '',
97
100
  } = {}) {
98
101
  const snippet = String(task).replace(/\s+/g, ' ').trim().slice(0, 48);
102
+ const mark = String(chip).trim() ? ` · ${String(chip).trim()}` : '';
99
103
  const head = final
100
- ? `✅ ${t(lang, 'status.done')} · ${seconds} ${secondsUnit(lang)}`
104
+ ? `✅ ${t(lang, 'status.done')} · ${seconds} ${secondsUnit(lang)}${mark}`
101
105
  : snippet
102
- ? `⏳ ${t(lang, 'status.accepted')}: «${snippet}${String(task).trim().length > 48 ? '…' : ''}» · ${seconds} ${secondsUnit(lang)}`
103
- : `⏳ ${t(lang, 'status.working')}… ${seconds} ${secondsUnit(lang)}`;
106
+ ? `⏳ ${t(lang, 'status.accepted')}: «${snippet}${String(task).trim().length > 48 ? '…' : ''}» · ${seconds} ${secondsUnit(lang)}${mark}`
107
+ : `⏳ ${t(lang, 'status.working')}… ${seconds} ${secondsUnit(lang)}${mark}`;
104
108
  const mind = thoughts.map((line) => `💭 ${line}`);
105
109
  const base = [head, ...mind, cache].filter(Boolean).join('\n').length;
106
110
 
package/settings.mjs ADDED
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Resolution of the settings that decide what a turn runs.
3
+ *
4
+ * Four tiers, narrowest first:
5
+ *
6
+ * per-topic override (state.settings[key]) > agentset field > profile row
7
+ * > install default (the profile `headless` itself points at)
8
+ *
9
+ * The result is a flat, plain object plus a `sources` map that says where each
10
+ * value came from — the card and `/status` must be able to show "the set is
11
+ * broken" and "the set was ignored" as different things.
12
+ *
13
+ * Pure by design: no file access, no state writes. The caller reads the profile
14
+ * row values once and passes them in, so the same function serves the command
15
+ * replies and the turn spawn.
16
+ */
17
+ import { FIELDS } from './agentsets.mjs';
18
+
19
+ /** Parsed profile-row values, as the caller read them from the patch. */
20
+ export function profileValues({ model = {}, permissions = '', preset = '', effort = '', lang = '' } = {}) {
21
+ return {
22
+ model: model.model && model.model !== '?' ? model.model : '',
23
+ provider: model.provider && model.provider !== '?' ? model.provider : '',
24
+ permissions: permissions || '',
25
+ dshPreset: preset || '',
26
+ effort: effort || '',
27
+ lang: lang || '',
28
+ };
29
+ }
30
+
31
+ /**
32
+ * @param {object} input
33
+ * @param {object} input.set the agentset bound to the topic, or null
34
+ * @param {object} input.override `state.settings[key]` for this topic, or null
35
+ * @param {object} input.profile `profileValues(...)` of the topic's profile
36
+ * @param {string[]} input.models declared model ids of the topic's profile
37
+ * @param {string[]} input.efforts declared effort ids for the winning model
38
+ * @param {string[]} input.permissions declared permission preset ids
39
+ * @param {string[]} input.presets declared dsh agent preset ids
40
+ */
41
+ export function resolveSettings({
42
+ set = null,
43
+ override = null,
44
+ profile = profileValues(),
45
+ models = [],
46
+ efforts = [],
47
+ permissions = [],
48
+ presets = [],
49
+ } = {}) {
50
+ const src = {};
51
+ const from = (field, ...values) => {
52
+ for (const [tier, value] of [
53
+ ['topic', override?.[field]],
54
+ ['set', set?.[field]],
55
+ ['profile', profile[field]],
56
+ ]) {
57
+ if (typeof value === 'string' && value.trim() !== '') {
58
+ src[field] = tier;
59
+ return value.trim();
60
+ }
61
+ }
62
+ src[field] = 'default';
63
+ return '';
64
+ };
65
+
66
+ const model = from('model');
67
+ const provider = from('provider');
68
+ const effort = from('effort');
69
+
70
+ // A model the profile never declared would only fail on the next turn, so it
71
+ // is dropped here — and the source says so, which is how the card explains
72
+ // itself instead of silently running something else.
73
+ const modelDropped = Boolean(model) && models.length > 0 && !models.includes(model);
74
+ const checkedModel = { value: modelDropped ? profile.model : model };
75
+ if (modelDropped) {
76
+ src.model = `${src.model} (invalid)`;
77
+ src.provider = `${src.provider} (follows model)`;
78
+ }
79
+ // A profile with no declared efforts answers with an empty list, and then the
80
+ // value is trusted: refusing it would drop a legitimate id the list cannot see.
81
+ const effortList = efforts;
82
+ const effortDropped = Boolean(effort) && effortList.length > 0 && !effortList.includes(effort);
83
+ const checkedEffort = { value: effortDropped ? (profile.effort || '') : effort };
84
+ if (effortDropped) src.effort = `${src.effort} (invalid)`;
85
+ const permissionsDropped = Boolean(permissions.length) && !permissions.includes(from('permissions'));
86
+ const checkedPermissions = { value: permissionsDropped ? profile.permissions : from('permissions') };
87
+ if (permissionsDropped) src.permissions = `${src.permissions} (invalid)`;
88
+ const presetDropped = Boolean(presets.length) && !presets.includes(from('dshPreset'));
89
+ const checkedPreset = { value: presetDropped ? profile.dshPreset : from('dshPreset'), ok: !presetDropped };
90
+ if (!checkedPreset.ok) src.dshPreset = `${src.dshPreset} (invalid)`;
91
+
92
+ const plugins = {
93
+ add: [...(set?.plugins?.add || [])],
94
+ remove: [...(set?.plugins?.remove || [])],
95
+ disable: [...(set?.plugins?.disable || [])],
96
+ enable: [...(set?.plugins?.enable || [])],
97
+ };
98
+ const toolFilter = {
99
+ deny: [...(set?.toolFilter?.deny || [])],
100
+ allow: [...(set?.toolFilter?.allow || [])],
101
+ };
102
+ const agents = { ...(set?.agents || {}) };
103
+
104
+ const out = {
105
+ model: checkedModel.value,
106
+ provider: checkedModel.ok ? provider : profile.provider,
107
+ effort: checkedEffort.value,
108
+ permissions: checkedPermissions.value,
109
+ dshPreset: checkedPreset.value,
110
+ lang: from('lang'),
111
+ thinkBlock: set?.thinkBlock || '',
112
+ plugins,
113
+ toolFilter,
114
+ agents,
115
+ base: set?.base || '',
116
+ sources: src,
117
+ };
118
+ out.touchesProfile = touchesProfile(out);
119
+ return out;
120
+ }
121
+
122
+ /**
123
+ * Would this resolution have to become a profile of its own? Only values that
124
+ * came from the topic or the set count: a value inherited from the profile is
125
+ * already true of the profile and needs no overlay.
126
+ */
127
+ export function touchesProfile(resolved) {
128
+ const own = (field) => resolved.sources?.[field] === 'topic' || resolved.sources?.[field] === 'set';
129
+ return Boolean(
130
+ own('model')
131
+ || own('effort')
132
+ || own('permissions')
133
+ || own('dshPreset')
134
+ || Object.keys(resolved.agents || {}).length
135
+ || resolved.toolFilter?.deny?.length
136
+ || resolved.toolFilter?.allow?.length,
137
+ );
138
+ }
139
+
140
+ /**
141
+ * One line for the progress panel: only the fields that actually differ from
142
+ * the bare profile. Empty string means "render nothing", so an install that
143
+ * never uses sets sees a byte-identical panel.
144
+ */
145
+ export function settingsChip(resolved, { name = '' } = {}) {
146
+ if (!resolved || !resolved.touchesProfile) return '';
147
+ const own = (field) => resolved.sources?.[field] === 'topic' || resolved.sources?.[field] === 'set';
148
+ const parts = [];
149
+ if (name) parts.push(name);
150
+ const route = own('model') || own('effort')
151
+ ? `${resolved.model}${resolved.effort ? `/${resolved.effort}` : ''}`
152
+ : '';
153
+ if (route) parts.push(route);
154
+ if (own('permissions') && resolved.permissions) parts.push(resolved.permissions);
155
+ return parts.join(' · ');
156
+ }
157
+
158
+ /** The field list a hand-written `/agentset edit` may touch. */
159
+ export const EDITABLE = FIELDS;