dsh-tg-bridge 1.13.0 → 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/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
+ }