dsh-tg-bridge 1.27.0 → 1.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -91,6 +91,27 @@ npx dsh-tg-bridge@latest setup
91
91
  `init` writes the token, your id and the working directory; `setup` registers
92
92
  autostart and starts the bridge.
93
93
 
94
+ ### What it needs from DSH
95
+
96
+ The bridge is a client of the DSH CLI, and the surface it uses is small enough to
97
+ write down: `--profile`, `--json`, `--session-id`, `--expose-internals <cli.js>`
98
+ when the app binary runs the CLI, and the `{"type": ...}` JSON events on stdout.
99
+ Profiles are read as files (`cordis.patch.yml`, `package.json`) under
100
+ `~/.dsh/profiles`. `package.json` spells the supported range out in
101
+ `engines.dsh`, and it is capped below `0.3.0` on purpose: a minor bump may rename
102
+ an event, and a bridge that guesses is a bridge that answers with silence.
103
+
104
+ Two escape hatches, for a moved app or a DSH that ships differently:
105
+
106
+ ```bash
107
+ DSH_BIN=/usr/local/bin/dsh # the CLI itself, no entrypoint argument
108
+ DSH_CLI_JS=/opt/dsh/lib/cli.js # just the CLI entrypoint, run by DSH_BIN
109
+ DSH_APP_DIR=/opt/DeepSeek-Harness # where the desktop app is installed
110
+ ```
111
+
112
+ `/doctor` prints the command a turn would actually run, so a machine where these
113
+ matter says so instead of failing with an empty answer.
114
+
94
115
  **As a DSH plugin** (the package carries a `dsh.bundle`; the catalog entry is
95
116
  pending review):
96
117
 
package/cli-args.mjs CHANGED
@@ -6,11 +6,16 @@
6
6
  // `--json ... --patch x.yml` the app received `--patch`, answered
7
7
  // `{"type":"error","message":"unknown option '--patch'"}` and exited 1 — every
8
8
  // photo turn and every fallback-model attempt died in about five seconds.
9
- export function turnArgs({ cli, profile, extraArgs = [], sessionId = '', task }) {
10
- if (!cli) throw new Error('turnArgs: cli path is required');
9
+ // `lead` is what goes before `--profile`, and it is not always
10
+ // `--expose-internals <cli.js>`: the Electron app needs that, a plain `dsh` on
11
+ // PATH needs nothing (see `dsh-launch.mjs`). Keeping `cli` as a fallback means
12
+ // the old call still reads the way it did.
13
+ export function turnArgs({ lead = null, cli, profile, extraArgs = [], sessionId = '', task }) {
14
+ const prefix = lead || (cli ? ['--expose-internals', cli] : null);
15
+ if (!prefix) throw new Error('turnArgs: lead or cli is required');
11
16
  if (!profile) throw new Error('turnArgs: profile is required');
12
17
  if (typeof task !== 'string' || !task) throw new Error('turnArgs: task is required');
13
- const args = ['--expose-internals', cli, '--profile', profile, ...extraArgs, '--json'];
18
+ const args = [...prefix, '--profile', profile, ...extraArgs, '--json'];
14
19
  if (sessionId) args.push('--session-id', sessionId);
15
20
  args.push(task);
16
21
  return args;
@@ -20,6 +20,8 @@ import { cutSession, isRewindPress } from '../rewind-buttons.mjs';
20
20
  import { renderRewindCard, renderRewindUsage } from '../rewind-card.mjs';
21
21
  import { MENU_GROUPS, commandForName, renderPanel, replyKeyboard } from '../menu-card.mjs';
22
22
  import { chainSummary } from '../fallback-card.mjs';
23
+ import { driveOf, sampleDisk } from '../machine.mjs';
24
+ import { describeLaunch, dshLaunch } from '../dsh-launch.mjs';
23
25
  import { explainCommand } from '../help-explain.mjs';
24
26
  import { profileValues, resolveSettings } from '../settings.mjs';
25
27
  import { UPDATE_DEFAULTS, describeUpdate, modeChange, updateState } from '../update-policy.mjs';
@@ -226,16 +228,23 @@ export async function handleBridgeCommands(ctx) {
226
228
  add(t(lang, 'ctrl.doctor.logLines'), String(lines.length - start));
227
229
  } catch {}
228
230
 
229
- // Disk space: the silent killer of model downloads and OCR.
230
- try {
231
- const drives = execFileSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', '(Get-PSDrive C).Free'], {
232
- encoding: 'utf8',
233
- windowsHide: true,
234
- timeout: 15000,
235
- });
236
- const free = Number(drives) || 0;
237
- add(t(lang, 'ctrl.doctor.disk'), t(lang, 'ctrl.doctor.diskFree', { gb: (free / 1024 ** 3).toFixed(1) }));
238
- } catch {}
231
+ // Disk space: the silent killer of model downloads and OCR. This used to
232
+ // shell out to `powershell (Get-PSDrive C)`, so on macOS and Linux the row
233
+ // simply vanished — a diagnostic that is silent on the platform you are
234
+ // debugging is worse than none.
235
+ const disk = sampleDisk(driveOf(config.cwd || ''));
236
+ if (disk.freeGb !== null) {
237
+ // `C:\` is a path; the row wants the name of a disk, so the separator
238
+ // and its colon both go: "Disk C", "Disk /".
239
+ const label = disk.drive.replace(/[\\/:]+$/, '') || disk.drive;
240
+ add(t(lang, 'ctrl.doctor.disk', { drive: label }), t(lang, 'ctrl.doctor.diskFree', { gb: disk.freeGb.toFixed(1) }));
241
+ }
242
+
243
+ // Which binary a turn would actually start. On a machine where the app is
244
+ // missing but `dsh` is on PATH (or the other way round) this is the row
245
+ // that explains why every turn fails, so it is worth one line always.
246
+ const launch = dshLaunch({ exists: existsSync });
247
+ add(t(lang, 'ctrl.doctor.turnCmd'), `${describeLaunch(launch)}${launch.kind === 'cli' ? t(lang, 'ctrl.doctor.turnCmdPath') : ''}`);
239
248
 
240
249
  // Project directory bound to this topic and whether it exists. The bridge
241
250
  // default is a fact, not an accident: say when it is being used.
@@ -5,158 +5,155 @@
5
5
  import { spawn, spawnSync } from 'node:child_process';
6
6
  import { existsSync, writeFileSync } from 'node:fs';
7
7
  import { join } from 'node:path';
8
- import { PROFILES, APP, EXE, CLI_JS } from '../paths.mjs';
8
+ import { PROFILES } from '../paths.mjs';
9
+ import { dshLaunch } from '../dsh-launch.mjs';
9
10
 
10
11
  import { read, readJson, pkgPath, disabledIds } from './models.mjs';
11
- /** Live DSH app PIDs (empty when the app is not running). */
12
- export function listPids() {
13
- try {
14
- const r = spawnSync('tasklist', ['/FI', 'IMAGENAME eq DeepSeek Harness.exe', '/NH', '/FO', 'CSV'], {
15
- windowsHide: true,
16
- encoding: 'utf8',
17
- });
18
- return (r.stdout || '')
19
- .split(/\r?\n/)
20
- .map((line) => /^"DeepSeek Harness\.exe","(\d+)"/.exec(line.trim()))
21
- .filter(Boolean)
22
- .map((m) => Number(m[1]));
23
- } catch {
24
- return [];
25
- }
26
- }
27
-
28
- /** Poll until every listed pid is gone; true when they all exited. */
29
- export async function waitForExit(pids, timeoutMs) {
30
- const deadline = Date.now() + timeoutMs;
31
- while (Date.now() < deadline) {
32
- const alive = listPids();
33
- if (!pids.some((pid) => alive.includes(pid))) return true;
34
- await new Promise((resolve) => setTimeout(resolve, 500));
35
- }
36
- return false;
37
- }
38
-
39
- /** Poll until at least one DSH pid appears (new or old); returns them. */
40
- export async function waitForStart(timeoutMs) {
41
- const deadline = Date.now() + timeoutMs;
42
- while (Date.now() < deadline) {
43
- const alive = listPids();
44
- if (alive.length > 0) return alive;
45
- await new Promise((resolve) => setTimeout(resolve, 500));
46
- }
47
- return [];
48
- }
49
-
50
- /** Installed packages plus the bundle list of a profile. */
51
- export function pluginsOf(profile) {
52
- const pkg = readJson(pkgPath(profile)) || {};
53
- const deps = Object.keys(pkg.dependencies || {});
54
- const bundles = ((pkg.dsh || {}).profile || {}).bundles || [];
55
- const disabled = disabledIds(profile);
56
- return { deps, bundles, disabled };
57
- }
58
-
59
- /**
60
- * Loader row ids a bundle installs, read from its own patch file.
61
- * A bundle package name (`@xmanrui/dsh-im`) is not the row id a profile patch
62
- * disables (`xmanrui-dsh-im`), so the mapping has to come from the patch.
63
- */
64
- export function bundleRowIds(profile, name) {
65
- const dir = join(PROFILES, profile, 'node_modules', name);
66
- const pkg = readJson(join(dir, 'package.json'));
67
- const patch = ((pkg || {}).dsh || {}).bundle?.patch || './cordis.patch.yml';
68
- const text = read(join(dir, patch.replace(/^\.\//, '')));
69
- const ids = [];
70
- for (const match of text.matchAll(/^\s*-?\s*id:\s*['"]?([A-Za-z0-9_.@/-]+)['"]?\s*$/gm)) ids.push(match[1]);
71
- return ids;
72
- }
73
-
74
- /** Add a bundle name to `dsh.profile.bundles` when it is not listed yet. */
75
- export function addBundle(profile, name) {
76
- const path = pkgPath(profile);
77
- const pkg = readJson(path);
78
- if (!pkg) return false;
79
- const profileBlock = (pkg.dsh = pkg.dsh || {}).profile || (pkg.dsh.profile = {});
80
- const bundles = profileBlock.bundles || (profileBlock.bundles = []);
81
- if (bundles.includes(name)) return false;
82
- bundles.push(name);
83
- writeFileSync(path, `${JSON.stringify(pkg, null, 2)}\n`, 'utf8');
84
- return true;
85
- }
86
-
87
- export function removeBundle(profile, name) {
88
- const path = pkgPath(profile);
89
- const pkg = readJson(path);
90
- if (!pkg) return false;
91
- const bundles = ((pkg.dsh || {}).profile || {}).bundles || [];
92
- const next = bundles.filter((entry) => entry !== name);
93
- if (next.length === bundles.length) return false;
94
- pkg.dsh.profile.bundles = next;
95
- writeFileSync(path, `${JSON.stringify(pkg, null, 2)}\n`, 'utf8');
96
- return true;
97
- }
98
-
99
- /** Run `dsh plugin ...` (which forwards to pnpm) and collect its output. */
100
- /**
101
- * Create a profile from a shipped template, the same way the GUI does it:
102
- * `dsh <name> --from-default-profile <template>`. `--dump-config` stops right
103
- * after the profile tree is written, so nothing boots and no plugin is loaded.
104
- * Dependencies are installed on the profile's first turn.
105
- */
106
- export function createProfile(name, template, timeoutMs = 180000) {
107
- return new Promise((resolve) => {
108
- const useExe = process.platform === 'win32' && existsSync(EXE) && existsSync(join(APP, 'resources', 'app.asar'));
109
- const args = [name, '--from-default-profile', template, '--dump-config'];
110
- const child = useExe
111
- ? spawn(EXE, ['--expose-internals', CLI_JS, ...args], {
112
- windowsHide: true,
113
- env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
114
- })
115
- : spawn('dsh', args, { windowsHide: true });
116
- const timer = setTimeout(() => child.kill(), timeoutMs);
117
- child.stdout?.setEncoding('utf8');
118
- child.stderr?.setEncoding('utf8');
119
- child.stdout?.on('data', () => {});
120
- child.stderr?.on('data', () => {});
121
- const done = () => {
122
- clearTimeout(timer);
123
- resolve(existsSync(join(PROFILES, name, 'cordis.patch.yml')));
124
- };
125
- child.on('close', done);
126
- child.on('error', done);
127
- });
128
- }
129
-
130
- export function dshPlugin(profile, args, timeoutMs = 180000) {
131
- return new Promise((resolve) => {
132
- // Spawning the .cmd shim with shell:false fails with EINVAL on modern Node.
133
- // Run the real CLI entry through the Electron binary instead, like the
134
- // bridge does for turns; fall back to a plain `dsh` on other platforms.
135
- const useExe = process.platform === 'win32' && existsSync(EXE) && existsSync(join(APP, 'resources', 'app.asar'));
136
- const child = useExe
137
- ? spawn(EXE, ['--expose-internals', CLI_JS, 'plugin', '--profile', profile, ...args], {
138
- windowsHide: true,
139
- env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
140
- })
141
- : spawn('dsh', ['plugin', '--profile', profile, ...args], { windowsHide: true });
142
- let out = '';
143
- const timer = setTimeout(() => child.kill(), timeoutMs);
144
- child.stdout.setEncoding('utf8');
145
- child.stderr.setEncoding('utf8');
146
- child.stdout.on('data', (buf) => {
147
- out += buf;
148
- });
149
- child.stderr.on('data', (buf) => {
150
- out += buf;
151
- });
152
- child.on('close', (code) => {
153
- clearTimeout(timer);
154
- resolve({ code, out: out.trim() });
155
- });
156
- child.on('error', (error) => {
157
- clearTimeout(timer);
158
- resolve({ code: -1, out: error.message });
159
- });
160
- });
161
- }
12
+ /** Live DSH app PIDs (empty when the app is not running). */
13
+ export function listPids() {
14
+ try {
15
+ const r = spawnSync('tasklist', ['/FI', 'IMAGENAME eq DeepSeek Harness.exe', '/NH', '/FO', 'CSV'], {
16
+ windowsHide: true,
17
+ encoding: 'utf8',
18
+ });
19
+ return (r.stdout || '')
20
+ .split(/\r?\n/)
21
+ .map((line) => /^"DeepSeek Harness\.exe","(\d+)"/.exec(line.trim()))
22
+ .filter(Boolean)
23
+ .map((m) => Number(m[1]));
24
+ } catch {
25
+ return [];
26
+ }
27
+ }
28
+
29
+ /** Poll until every listed pid is gone; true when they all exited. */
30
+ export async function waitForExit(pids, timeoutMs) {
31
+ const deadline = Date.now() + timeoutMs;
32
+ while (Date.now() < deadline) {
33
+ const alive = listPids();
34
+ if (!pids.some((pid) => alive.includes(pid))) return true;
35
+ await new Promise((resolve) => setTimeout(resolve, 500));
36
+ }
37
+ return false;
38
+ }
39
+
40
+ /** Poll until at least one DSH pid appears (new or old); returns them. */
41
+ export async function waitForStart(timeoutMs) {
42
+ const deadline = Date.now() + timeoutMs;
43
+ while (Date.now() < deadline) {
44
+ const alive = listPids();
45
+ if (alive.length > 0) return alive;
46
+ await new Promise((resolve) => setTimeout(resolve, 500));
47
+ }
48
+ return [];
49
+ }
50
+
51
+ /** Installed packages plus the bundle list of a profile. */
52
+ export function pluginsOf(profile) {
53
+ const pkg = readJson(pkgPath(profile)) || {};
54
+ const deps = Object.keys(pkg.dependencies || {});
55
+ const bundles = ((pkg.dsh || {}).profile || {}).bundles || [];
56
+ const disabled = disabledIds(profile);
57
+ return { deps, bundles, disabled };
58
+ }
59
+
60
+ /**
61
+ * Loader row ids a bundle installs, read from its own patch file.
62
+ * A bundle package name (`@xmanrui/dsh-im`) is not the row id a profile patch
63
+ * disables (`xmanrui-dsh-im`), so the mapping has to come from the patch.
64
+ */
65
+ export function bundleRowIds(profile, name) {
66
+ const dir = join(PROFILES, profile, 'node_modules', name);
67
+ const pkg = readJson(join(dir, 'package.json'));
68
+ const patch = ((pkg || {}).dsh || {}).bundle?.patch || './cordis.patch.yml';
69
+ const text = read(join(dir, patch.replace(/^\.\//, '')));
70
+ const ids = [];
71
+ for (const match of text.matchAll(/^\s*-?\s*id:\s*['"]?([A-Za-z0-9_.@/-]+)['"]?\s*$/gm)) ids.push(match[1]);
72
+ return ids;
73
+ }
74
+
75
+ /** Add a bundle name to `dsh.profile.bundles` when it is not listed yet. */
76
+ export function addBundle(profile, name) {
77
+ const path = pkgPath(profile);
78
+ const pkg = readJson(path);
79
+ if (!pkg) return false;
80
+ const profileBlock = (pkg.dsh = pkg.dsh || {}).profile || (pkg.dsh.profile = {});
81
+ const bundles = profileBlock.bundles || (profileBlock.bundles = []);
82
+ if (bundles.includes(name)) return false;
83
+ bundles.push(name);
84
+ writeFileSync(path, `${JSON.stringify(pkg, null, 2)}\n`, 'utf8');
85
+ return true;
86
+ }
87
+
88
+ export function removeBundle(profile, name) {
89
+ const path = pkgPath(profile);
90
+ const pkg = readJson(path);
91
+ if (!pkg) return false;
92
+ const bundles = ((pkg.dsh || {}).profile || {}).bundles || [];
93
+ const next = bundles.filter((entry) => entry !== name);
94
+ if (next.length === bundles.length) return false;
95
+ pkg.dsh.profile.bundles = next;
96
+ writeFileSync(path, `${JSON.stringify(pkg, null, 2)}\n`, 'utf8');
97
+ return true;
98
+ }
99
+
100
+ /** How to run the DSH CLI here, the same answer turns get (see `dsh-launch.mjs`). */
101
+ function cliSpawn(args) {
102
+ const launch = dshLaunch({ exists: existsSync });
103
+ // An app that is configured but not installed is not an app: fall back to the
104
+ // command on PATH rather than failing with ENOENT on a path nobody has.
105
+ const usable = launch.kind === 'cli' || existsSync(launch.exe);
106
+ const env = { ...process.env, ...(usable && launch.kind === 'app' ? { ELECTRON_RUN_AS_NODE: '1' } : {}) };
107
+ return spawn(usable ? launch.exe : 'dsh', [...(usable ? launch.lead : []), ...args], { windowsHide: true, env });
108
+ }
109
+
110
+ /**
111
+ * Create a profile from a shipped template, the same way the GUI does it:
112
+ * `dsh <name> --from-default-profile <template>`. `--dump-config` stops right
113
+ * after the profile tree is written, so nothing boots and no plugin is loaded.
114
+ * Dependencies are installed on the profile's first turn.
115
+ */
116
+ export function createProfile(name, template, timeoutMs = 180000) {
117
+ return new Promise((resolve) => {
118
+ const child = cliSpawn([name, '--from-default-profile', template, '--dump-config']);
119
+ const timer = setTimeout(() => child.kill(), timeoutMs);
120
+ child.stdout?.setEncoding('utf8');
121
+ child.stderr?.setEncoding('utf8');
122
+ child.stdout?.on('data', () => {});
123
+ child.stderr?.on('data', () => {});
124
+ const done = () => {
125
+ clearTimeout(timer);
126
+ resolve(existsSync(join(PROFILES, name, 'cordis.patch.yml')));
127
+ };
128
+ child.on('close', done);
129
+ child.on('error', done);
130
+ });
131
+ }
132
+
133
+ export function dshPlugin(profile, args, timeoutMs = 180000) {
134
+ return new Promise((resolve) => {
135
+ // Spawning the .cmd shim with shell:false fails with EINVAL on modern Node,
136
+ // so the app binary runs the CLI entry as Node instead; elsewhere the `dsh`
137
+ // command is already a real executable and needs no entrypoint argument.
138
+ const child = cliSpawn(['plugin', '--profile', profile, ...args]);
139
+ let out = '';
140
+ const timer = setTimeout(() => child.kill(), timeoutMs);
141
+ child.stdout.setEncoding('utf8');
142
+ child.stderr.setEncoding('utf8');
143
+ child.stdout.on('data', (buf) => {
144
+ out += buf;
145
+ });
146
+ child.stderr.on('data', (buf) => {
147
+ out += buf;
148
+ });
149
+ child.on('close', (code) => {
150
+ clearTimeout(timer);
151
+ resolve({ code, out: out.trim() });
152
+ });
153
+ child.on('error', (error) => {
154
+ clearTimeout(timer);
155
+ resolve({ code: -1, out: error.message });
156
+ });
157
+ });
158
+ }
162
159
 
package/dsh-launch.mjs ADDED
@@ -0,0 +1,68 @@
1
+ // How to start one DSH turn on THIS machine.
2
+ //
3
+ // The bridge grew up on Windows, where DSH ships an Electron app: the turn is
4
+ // `[DSH].exe --expose-internals .../cli.js --profile headless --json "<task>"`.
5
+ // That path is a Windows path, and it was the only one in the code, so on macOS
6
+ // and Linux every turn spawned a file that does not exist — the README promised
7
+ // "Windows, macOS or Linux" and the turn runner quietly meant Windows. The
8
+ // plugin commands had already learned the alternative (`dsh` from PATH); this
9
+ // module makes that the one answer both of them share.
10
+ //
11
+ // Pure on purpose: platform, environment and the filesystem question are all
12
+ // arguments, so the table below is a test rather than a story about a machine.
13
+ import { appPaths } from './paths.mjs';
14
+
15
+
16
+ /**
17
+ * @returns {{exe: string, lead: string[], kind: 'app'|'cli', why: string}}
18
+ * `lead` is what goes before `--profile`: the Electron binary needs the CLI
19
+ * entrypoint after `--expose-internals`, a plain `dsh` needs nothing.
20
+ */
21
+ export function dshLaunch({
22
+ platform = process.platform,
23
+ env = process.env,
24
+ exists = null,
25
+ home = undefined,
26
+ } = {}) {
27
+ const has = exists || (() => true);
28
+ // The paths of the platform being asked about, not the one running the code:
29
+ // a Windows machine must still be able to say what a Mac would do.
30
+ const paths = home === undefined ? appPaths(platform, env) : appPaths(platform, env, home);
31
+
32
+ // An explicit answer beats every guess: a user who moved the app, or runs a
33
+ // checkout, should not have to patch the bridge.
34
+ if (env.DSH_CLI_JS) {
35
+ return { exe: env.DSH_BIN || paths.exe, lead: ['--expose-internals', env.DSH_CLI_JS], kind: 'app', why: 'DSH_CLI_JS' };
36
+ }
37
+ if (env.DSH_BIN && !env.DSH_BIN.toLowerCase().endsWith('.js')) {
38
+ // A CLI binary needs no entrypoint argument: it IS the entrypoint.
39
+ return { exe: env.DSH_BIN, lead: [], kind: 'cli', why: 'DSH_BIN' };
40
+ }
41
+
42
+ if (platform === 'win32') {
43
+ // Windows is where DSH ships as an app, and it is where the bridge has
44
+ // always run. If the app is not installed the turn fails with a message
45
+ // naming the path, which beats a bare "dsh not found" from PATH.
46
+ return { exe: paths.exe, lead: ['--expose-internals', paths.cli], kind: 'app', why: 'windows app' };
47
+ }
48
+ if (platform === 'darwin' && has(paths.exe)) {
49
+ // The macOS bundle has the same shape as the Windows app, one directory up
50
+ // from Resources; `appPaths()` already answers for it, so there is no second
51
+ // copy of the layout to keep in step.
52
+ return { exe: paths.exe, lead: ['--expose-internals', paths.cli], kind: 'app', why: 'macOS app' };
53
+ }
54
+ // Everything else: the `dsh` command on PATH. This is what the plugin
55
+ // commands already did, and it is the one form that survives an install
56
+ // method we cannot predict. The Windows `.cmd` shim is not a path that means
57
+ // anything on Linux, so it is not reused here.
58
+ return { exe: 'dsh', lead: [], kind: 'cli', why: `${platform} cli` };
59
+ }
60
+
61
+ /**
62
+ * The binary, for a message a person reads. The CLI entrypoint is not appended:
63
+ * it is a 120-character `app.asar` path that means nothing in a chat row, and
64
+ * `kind` already says whether one is implied.
65
+ */
66
+ export function describeLaunch(launch) {
67
+ return launch.exe;
68
+ }