dsh-tg-bridge 1.12.0 → 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');
@@ -329,7 +368,15 @@ function providerKeys(cfg) {
329
368
  function findToken() {
330
369
  const env = (process.env.DSH_TELEGRAM_BOT_TOKEN || '').trim();
331
370
  if (env) return env;
332
- for (const name of ['DSH_TELEGRAM_BOT_TOKEN', 'DSH_TELEGRAM_BOT_TOKEN_3278A97027814C501779F5E2']) {
371
+ // The suffixed name carries a random id of the machine that created the
372
+ // secret (DSH_TELEGRAM_BOT_TOKEN_<hex>), so it must not be spelled out here:
373
+ // any install is free to carry its own suffix. Try the plain name first, then
374
+ // whatever suffixed variants the credentials file actually holds.
375
+ const suffixes = [];
376
+ try {
377
+ for (const m of readFileSync(CRED, 'utf8').matchAll(/^\s*(DSH_TELEGRAM_BOT_TOKEN_[A-Z0-9_]+):/gm)) suffixes.push(m[1]);
378
+ } catch {}
379
+ for (const name of ['DSH_TELEGRAM_BOT_TOKEN', ...suffixes]) {
333
380
  try {
334
381
  const value = readSecret(name);
335
382
  if (value) return value;
@@ -831,7 +878,7 @@ function killTurn(key) {
831
878
  * thinks for ten minutes still leaves one line in the chat — and the whole trail
832
879
  * one tap away.
833
880
  */
834
- async function startProgress(chatId, threadId, lang = 'ru', task = '') {
881
+ async function startProgress(chatId, threadId, lang = 'ru', task = '', chip = '') {
835
882
  const started = Date.now();
836
883
  const panelKey = sessionKey(chatId, threadId);
837
884
  const steps = [];
@@ -890,6 +937,7 @@ async function startProgress(chatId, threadId, lang = 'ru', task = '') {
890
937
  // the log itself is a file the command sends on demand.
891
938
  reasoning: state.thinkBlock?.[panelKey] === 'counter' ? 'counter' : 'block',
892
939
  task,
940
+ chip,
893
941
  cache,
894
942
  });
895
943
  };
@@ -1410,7 +1458,7 @@ ${t(lang, 'help.body')}`,
1410
1458
 
1411
1459
  // Live progress: one status message per turn, rewritten as the agent works.
1412
1460
  // Without it a long turn and a hung turn looked exactly alike in the chat.
1413
- const progress = await startProgress(chatId, threadId, lang, request);
1461
+ const progress = await startProgress(chatId, threadId, lang, request, settingsChipOf(key));
1414
1462
  // Turn telemetry for the log: what the agent did, how much it cost, on which
1415
1463
  // model. Without it /logs shows only "in" and "sent" — useless when asking
1416
1464
  // "why did this take 9 minutes".
@@ -1930,6 +1978,17 @@ async function handleCallback(query) {
1930
1978
  const answer = (text, show = false) =>
1931
1979
  tg('answerCallbackQuery', { callback_query_id: query.id, text, show_alert: show }).catch(() => {});
1932
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
+
1933
1992
  // Trim the buttons of the pressed message first: a button that already did
1934
1993
  // its job must not be pressable a second time.
1935
1994
  const clearKeyboard = () =>