dsh-tg-bridge 1.12.1 → 1.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md 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/aset-job.mjs ADDED
@@ -0,0 +1,69 @@
1
+ // `dsh-tg aset materialise` — build a bound set's profile outside the turn.
2
+ //
3
+ // A plugin job (or `say.mjs`) runs while the bridge's turn process is alive, and
4
+ // DSH refuses to start a second copy of itself under a live parent: the bridge
5
+ // sees that as a crash, not as a profile. So the one action that must happen
6
+ // before a turn — writing `<base>` + the set's rows into a profile of their own
7
+ // — is spawned as a detached child, and this CLI is that child.
8
+ //
9
+ // Usage (from a job file the agent writes, see docs/AGENTSET.md):
10
+ // node cli.mjs aset materialise <setId> [--base <profile>]
11
+ // Prints one JSON line: {ok, profile, base} or {ok: false, error}.
12
+ import { spawn } from 'node:child_process';
13
+ import { fileURLToPath } from 'node:url';
14
+ import { AgentsetStore } from './agentsets.mjs';
15
+ import { materialiseProfile, pruneDerived } from './aset-profile.mjs';
16
+
17
+ const SELF = fileURLToPath(import.meta.url);
18
+
19
+ /** The store lives next to `state.json`, and only the bridge knows where that is. */
20
+ function storeDir() {
21
+ return process.env.DSH_TG_HOME || process.env.DSH_TG_DIR || '';
22
+ }
23
+
24
+ function run(args) {
25
+ const [verb, id] = args;
26
+ if (verb !== 'materialise') return { ok: false, error: 'usage', usage: 'aset materialise <setId> [--base <profile>]' };
27
+ const dir = storeDir();
28
+ if (!dir) return { ok: false, error: 'no-dir', hint: 'DSH_TG_HOME is not set' };
29
+ const flag = args.indexOf('--base');
30
+ const base = flag >= 0 ? args[flag + 1] : '';
31
+ if (!base) return { ok: false, error: 'no-base' };
32
+ const store = new AgentsetStore(`${dir}/agentsets.json`);
33
+ const set = store.load().get(id);
34
+ if (!set) return { ok: false, error: 'missing', id };
35
+ const profile = materialiseProfile(set, base);
36
+ if (!profile) return { ok: true, profile: '', base, note: 'nothing to materialise' };
37
+ // The sweep keeps every profile a bound set still points at; the caller's own
38
+ // job listed them, so this pass is best-effort and never fails the build.
39
+ try {
40
+ pruneDerived([profile]);
41
+ } catch {
42
+ // A profile in use by a running turn is removed on the next sweep.
43
+ }
44
+ return { ok: true, profile, base, set: id };
45
+ }
46
+
47
+ /**
48
+ * Spawn the same file for one `aset` job and forget about it. A live bridge
49
+ * calls this; nothing inside a turn does.
50
+ */
51
+ export function spawnAset(args, { dir = storeDir(), node = process.execPath } = {}) {
52
+ const child = spawn(node, [SELF, 'aset', ...args], {
53
+ detached: true,
54
+ stdio: 'ignore',
55
+ windowsHide: true,
56
+ env: { ...process.env, DSH_TG_HOME: dir },
57
+ });
58
+ child.unref();
59
+ return child.pid;
60
+ }
61
+
62
+ if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
63
+ const [command, ...rest] = process.argv.slice(2);
64
+ if (command === 'aset') {
65
+ process.stdout.write(`${JSON.stringify(run(rest))}\n`);
66
+ } else {
67
+ process.stdout.write(`${JSON.stringify({ ok: false, error: 'usage', usage: 'aset materialise <setId> --base <profile>' })}\n`);
68
+ }
69
+ }
package/aset-jobs.mjs ADDED
@@ -0,0 +1,57 @@
1
+ // `/agentset` typed as a job file, for the turn that is already running.
2
+ //
3
+ // The bridge is the only writer of `state.json`, so a running turn cannot bind
4
+ // a set by itself. It drops a job instead (say.mjs --aset), and the bridge's
5
+ // drain loop applies it — exactly like `goal.mjs` and the steer queue. Reading
6
+ // jobs from a directory keeps the settings command working during a turn
7
+ // instead of failing with "busy".
8
+ import { mkdirSync, readdirSync, readFileSync, renameSync, unlinkSync } from 'node:fs';
9
+ import { join } from 'node:path';
10
+
11
+ /** Where the bridge looks; the agent's `--aset` writes here. */
12
+ export const asetJobDir = (dir) => join(dir, 'aset-jobs');
13
+
14
+ /**
15
+ * Apply every pending job once. `apply(job)` returns `{ok, text}`; a job that
16
+ * cannot be parsed is dropped with its error rather than retried forever,
17
+ * because a half-newer job file is not written by anything.
18
+ * Returns the applied results, so the caller can answer in the topic.
19
+ */
20
+ export function drainAsetJobs(dir, apply, doneDir = join(asetJobDir(dir), 'done')) {
21
+ const source = asetJobDir(dir);
22
+ let files = [];
23
+ try {
24
+ files = readdirSync(source).filter((name) => name.endsWith('.json')).sort();
25
+ } catch {
26
+ return [];
27
+ }
28
+ const results = [];
29
+ // A refused or broken job still has to leave the queue: `done/` keeps it for
30
+ // the log, and a missing directory is created rather than failing the drain.
31
+ mkdirSync(doneDir, { recursive: true });
32
+ for (const name of files) {
33
+ const path = join(source, name);
34
+ let job;
35
+ try {
36
+ job = JSON.parse(readFileSync(path, 'utf8'));
37
+ } catch {
38
+ unlinkSync(path);
39
+ continue;
40
+ }
41
+ let result;
42
+ try {
43
+ result = apply(job) ?? { ok: false, text: 'not applied' };
44
+ } catch (error) {
45
+ result = { ok: false, text: String(error?.message || error) };
46
+ }
47
+ // A refused job changed nothing, so there is nothing to persist.
48
+ result = { ...result, changed: Boolean(result.changed) };
49
+ results.push({ job, ...result });
50
+ try {
51
+ renameSync(path, join(doneDir, name));
52
+ } catch {
53
+ try { unlinkSync(path); } catch { /* the next pass will try again */ }
54
+ }
55
+ }
56
+ return results;
57
+ }
@@ -0,0 +1,144 @@
1
+ // Materialised settings bundles.
2
+ //
3
+ // A set is a delta over a profile: '' in a field means "whatever the profile
4
+ // says". DSH itself has no per-topic override — a turn runs under one profile
5
+ // and that profile owns the model, the permission table and the agent-preset
6
+ // registry. So the only way to give one topic its own model without touching
7
+ // the profile of every other topic is to hand that topic a profile of its own:
8
+ // a copy of the base with the set's values written into the same rows, exactly
9
+ // like `profiles.mjs` does for the vision overlay. This module builds and
10
+ // prunes those copies.
11
+ //
12
+ // The generated profile is derived data. Its name carries a hash of the input,
13
+ // so a changed set lands in a different directory and a stale copy is simply
14
+ // never selected again; `pruneDerived` keeps only the ones in use.
15
+ import { createHash } from 'node:crypto';
16
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
17
+ import { homedir } from 'node:os';
18
+ import { join } from 'node:path';
19
+ import { setAgentPreset, setModel, setPermissionPreset, setSubagents } from './patch-rows.mjs';
20
+
21
+ const DSH_HOME = process.env.DSH_HOME || join(homedir(), '.dsh');
22
+ const PROFILES = join(DSH_HOME, 'profiles');
23
+
24
+ /** Every generated profile starts with this, so a GC cannot eat a hand-made one. */
25
+ export const DERIVED_PREFIX = 'aset-';
26
+
27
+ /** `aset-` + 10 hex: short enough for a DSH profile name, long enough to collide never. */
28
+ export function derivedName(base, set) {
29
+ const material = JSON.stringify([
30
+ base,
31
+ set?.name || '',
32
+ set?.model || '',
33
+ set?.effort || '',
34
+ set?.permissions || '',
35
+ set?.dshPreset || '',
36
+ set?.agents || null,
37
+ set?.toolFilter || null,
38
+ ]);
39
+ return `${DERIVED_PREFIX}${createHash('sha256').update(material).digest('hex').slice(0, 10)}`;
40
+ }
41
+
42
+ /**
43
+ * The base patch with the set's own values written into the rows DSH reads.
44
+ * A field that already matches the base is skipped, so the copy differs from
45
+ * the base only where the set differs — otherwise every generated profile
46
+ * would pin today's model forever.
47
+ */
48
+ export function overlayPatch(basePatch, set, base = {}) {
49
+ const source = String(basePatch ?? '');
50
+ let next = source;
51
+ const model = String(set?.model || '').trim();
52
+ if (model && model !== base.model) next = setModel(next, model, String(set?.provider || '').trim());
53
+ const permissions = String(set?.permissions || '').trim();
54
+ if (permissions && permissions !== base.permissions) next = setPermissionPreset(next, permissions);
55
+ const preset = String(set?.dshPreset || '').trim();
56
+ if (preset && preset !== base.preset) next = setAgentPreset(next, preset);
57
+ if (set?.agents && typeof set.agents === 'object') next = setSubagents(next, set.agents);
58
+ return { patch: next, changed: next !== source };
59
+ }
60
+
61
+ /**
62
+ * Build `<base>`'s copy for `set` and return the profile name to run under.
63
+ * Returns '' when there is nothing to materialise (the set changes nothing a
64
+ * profile owns) or when the base profile is missing.
65
+ */
66
+ export function materialiseProfile(set, base, { profiles = PROFILES } = {}) {
67
+ if (!set || !base) return '';
68
+ const baseDir = join(profiles, base);
69
+ const basePatchPath = join(baseDir, 'cordis.patch.yml');
70
+ if (!existsSync(basePatchPath)) return '';
71
+ const basePatch = readFileSync(basePatchPath, 'utf8');
72
+ const { patch, changed } = overlayPatch(basePatch, set, baseRowOf(basePatch));
73
+ if (!changed) return '';
74
+ const name = derivedName(base, set);
75
+ const dir = join(profiles, name);
76
+ if (existsSync(join(dir, 'cordis.patch.yml'))) return name;
77
+ mkdirSync(dir, { recursive: true });
78
+ // Everything the base has except its module tree: the plugins are the same,
79
+ // and copying node_modules would duplicate hundreds of megabytes per set.
80
+ for (const entry of readdirSync(baseDir, { withFileTypes: true })) {
81
+ const from = join(baseDir, entry.name);
82
+ if (entry.isFile() && !entry.name.endsWith('.bak') && !entry.name.includes('.bak-')) {
83
+ copyFileSync(from, join(dir, entry.name));
84
+ }
85
+ }
86
+ writeFileSync(join(dir, 'cordis.patch.yml'), patch, 'utf8');
87
+ // A junction keeps the same plugin install instead of booting a bare host.
88
+ const modules = join(dir, 'node_modules');
89
+ if (!existsSync(modules)) {
90
+ try {
91
+ symlinkSync(join(baseDir, 'node_modules'), modules, 'junction');
92
+ } catch {
93
+ // Without the link the profile still boots, just without the plugins.
94
+ }
95
+ }
96
+ return name;
97
+ }
98
+
99
+ /** What the base patch already says, for the "is this a real delta" comparison. */
100
+ export function baseRowOf(patch) {
101
+ const text = String(patch ?? '');
102
+ const row = (id) => {
103
+ const at = text.indexOf(`- id: ${id}`);
104
+ if (at < 0) return '';
105
+ const end = text.indexOf('\n- ', at + 5);
106
+ return end < 0 ? text.slice(at) : text.slice(at, end);
107
+ };
108
+ const modelBlock = row('agent-default-model');
109
+ const permissionBlock = row('permission');
110
+ const presetBlock = row('agent-preset');
111
+ const pick = (block, key) => (new RegExp(`^\\s+${key}:\\s*(\\S+)`, 'm').exec(block) || [])[1] || '';
112
+ return {
113
+ model: pick(modelBlock, 'model'),
114
+ provider: pick(modelBlock, 'provider'),
115
+ permissions: pick(permissionBlock, 'defaultPreset'),
116
+ preset: pick(presetBlock, 'selectedDefault'),
117
+ };
118
+ }
119
+
120
+ /**
121
+ * Delete generated profiles nobody is bound to. `keep` is the set of names the
122
+ * caller still points at, so a profile is removed only when it is derived,
123
+ * stale, and unbound. Returns the names it removed.
124
+ */
125
+ export function pruneDerived(keep = [], { profiles = PROFILES } = {}) {
126
+ const wanted = new Set(keep.filter(Boolean));
127
+ const removed = [];
128
+ let entries = [];
129
+ try {
130
+ entries = readdirSync(profiles, { withFileTypes: true });
131
+ } catch {
132
+ return removed;
133
+ }
134
+ for (const entry of entries) {
135
+ if (!entry.isDirectory() || !entry.name.startsWith(DERIVED_PREFIX) || wanted.has(entry.name)) continue;
136
+ try {
137
+ rmSync(join(profiles, entry.name), { recursive: true, force: true });
138
+ removed.push(entry.name);
139
+ } catch {
140
+ // A profile in use by a running turn stays until the next sweep.
141
+ }
142
+ }
143
+ return removed;
144
+ }
@@ -0,0 +1,74 @@
1
+ // The small schema a set is allowed to carry, and the buttons that edit one.
2
+ //
3
+ // Kept apart from `agentsets.mjs` (which stores whatever it is given) and from
4
+ // `control.mjs` (which is one long command handler) so the wire format can be
5
+ // tested on its own: a callback payload that cannot be parsed must never reach
6
+ // a write.
7
+ import { EDITABLE } from './settings.mjs';
8
+
9
+ /** The fields a set may override; anything else is refused at the door. */
10
+ export const FIELDS = EDITABLE;
11
+
12
+ /** Button data is capped at 64 bytes by Telegram; `as:` + verb + id + slot fits with room. */
13
+ export const CALLBACK_PREFIX = 'as:';
14
+ const VERBS = new Set(['use', 'off', 'edit', 'new', 'rm', 'show']);
15
+
16
+ /**
17
+ * `as:<verb>:<setId>[:<slot>]` -> `{verb, id, slot}`, or null.
18
+ * A slot is one of the editable fields plus the set-level actions; a verb that
19
+ * needs an id without one is refused here rather than by the handler.
20
+ */
21
+ export function parseCallback(data) {
22
+ const text = String(data ?? '');
23
+ if (!text.startsWith(CALLBACK_PREFIX)) return null;
24
+ const [verb, id = '', slot = ''] = text.slice(CALLBACK_PREFIX.length).split(':');
25
+ if (!VERBS.has(verb)) return null;
26
+ // `off` names the set it was drawn for, so a stale button cannot unbind a
27
+ // set bound after the card was sent; an empty id still means "this topic".
28
+ if (verb === 'off') {
29
+ if (id && !/^[a-z0-9][a-z0-9-]{0,23}$/.test(id)) return null;
30
+ return { verb, id, slot };
31
+ }
32
+ if (!/^[a-z0-9][a-z0-9-]{0,23}$/.test(id)) return null;
33
+ return { verb, id, slot };
34
+ }
35
+
36
+ /** The payload for one button, or '' when it would not be understood. */
37
+ export function callbackData(verb, id, slot = '') {
38
+ const data = `${CALLBACK_PREFIX}${verb}:${id}${slot ? `:${slot}` : ''}`;
39
+ return data.length <= 64 ? data : '';
40
+ }
41
+
42
+ /**
43
+ * The keyboard for a set card, as plain data: label + payload, no rendering and
44
+ * no language. `slots` are field edits the caller has already resolved to
45
+ * `<label>|<field>`, so the button says "model" while the payload says `model`.
46
+ * A set the person cannot edit (a builtin) gets only the read-only buttons.
47
+ */
48
+ export function cardKeyboard(set, { bound = false, builtin = false, slots = [] } = {}) {
49
+ if (!set) return [];
50
+ const slotButtons = slots
51
+ .map((slot) => {
52
+ const [label, field = slot] = String(slot).split('|');
53
+ return { text: label.slice(0, 24), data: callbackData('edit', set.id, field) };
54
+ })
55
+ .filter((button) => button.data);
56
+ const rows = [];
57
+ if (!builtin && slotButtons.length > 0) {
58
+ rows.push(
59
+ [{ text: bound ? '✓' : 'Use', data: callbackData('use', set.id) }, ...slotButtons.slice(0, 2)],
60
+ ...(slotButtons.length > 2 ? [slotButtons.slice(2, 5)] : []),
61
+ );
62
+ }
63
+ const last = [{ text: 'show', data: callbackData('show', set.id) }];
64
+ if (bound) last.push({ text: 'off', data: callbackData('off', set.id) });
65
+ if (!builtin) last.push({ text: 'rm', data: callbackData('rm', set.id) });
66
+ rows.push(last);
67
+ return rows.filter((row) => row.length > 0 && row.every((button) => button.data));
68
+ }
69
+
70
+ /** A one-line field edit, the way a person types it: `/agentset model big-m1`. */
71
+ export function parseEditVerb(text) {
72
+ const words = String(text ?? '').trim().split(/\s+/).filter(Boolean);
73
+ return { verb: words[0] || '', args: words.slice(1) };
74
+ }