@grigdesk/dsh 0.0.0-stage → 0.2.2
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/LICENSE +21 -0
- package/README.md +60 -2
- package/bin/deepseek.mjs +10 -0
- package/bin/glm.mjs +10 -0
- package/bin/launcher.mjs +120 -0
- package/bin/qwen.mjs +10 -0
- package/package.json +33 -4
- package/scripts/lib/install.mjs +233 -0
- package/scripts/lib/layout.mjs +121 -0
- package/scripts/lib/platform.mjs +21 -0
- package/scripts/postinstall.mjs +15 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Dmitry Yurchenko (https://evildev.ru)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,61 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @grigdesk/dsh
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Terminal commands for [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) as shipped by
|
|
4
|
+
[GrigDesk](https://app.grigdesk.com): one pinned runtime for DeepSeek, GLM and Qwen.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
npm i -g @grigdesk/dsh
|
|
8
|
+
|
|
9
|
+
deepseek # DeepSeek chat in the current directory
|
|
10
|
+
glm # GLM (Z.ai) chat
|
|
11
|
+
dsh chat -p qwen # Qwen chat
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
The package itself is tiny. `postinstall` downloads the standalone binary for your platform from the
|
|
15
|
+
[GitHub release](https://github.com/EvilDevRu/grigdesk-dsh/releases) of the same version, verifies its
|
|
16
|
+
SHA-256 against `manifest.json`, and keeps every version side by side:
|
|
17
|
+
|
|
18
|
+
```
|
|
19
|
+
~/.local/share/grigdesk-dsh/versions/v1.2.3/deepseek # binary
|
|
20
|
+
~/.local/share/grigdesk-dsh/current -> versions/v1.2.3
|
|
21
|
+
~/.local/bin/dsh, deepseek, glm, qwen # command links (qwen when available)
|
|
22
|
+
~/.deepseek/ # terminal chat sessions and settings
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Supported platforms: Linux x64, Linux ARM64, macOS on Apple Silicon.
|
|
26
|
+
With an existing `qwen` command such as Qwen Code, use `dsh chat -p qwen` to choose DSH explicitly.
|
|
27
|
+
|
|
28
|
+
The chat checks for stable releases in the background and links to available updates in the header.
|
|
29
|
+
Use `npm i -g @grigdesk/dsh@latest` to upgrade, or `deepseek chat --no-update-check` to skip the check.
|
|
30
|
+
|
|
31
|
+
## API keys
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
dsh login # pick a provider, paste the key (hidden input) → ~/.deepseek/credentials.json (0600)
|
|
35
|
+
dsh login --status
|
|
36
|
+
dsh logout qwen
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Keys are resolved in this order: the terminal environment (`DEEPSEEK_API_KEY`, `ZAI_API_KEY` or
|
|
40
|
+
`ZAI_CODING_API_KEY` for GLM API / Coding Plan, `QWEN_API_KEY`) → `~/.deepseek/credentials.json` →
|
|
41
|
+
the `.env` file of an installed GrigDesk. DSH reuses the saved service and region when using GrigDesk's
|
|
42
|
+
Qwen API key (`DASHSCOPE_API_KEY`). A Qwen Code sign-in belongs to Qwen Code. For a separate API key,
|
|
43
|
+
use `dsh login qwen` and choose the corresponding service when opening the chat.
|
|
44
|
+
|
|
45
|
+
## Without network at install time
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
npm i -g --ignore-scripts @grigdesk/dsh
|
|
49
|
+
dsh install # downloads later; repeat any time
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## Options
|
|
53
|
+
|
|
54
|
+
| Variable | Purpose |
|
|
55
|
+
| :--- | :--- |
|
|
56
|
+
| `GRIGDESK_DEEPSEEK_DOWNLOAD_BASE` | Mirror of release assets (HTTPS, or HTTP on loopback for testing) |
|
|
57
|
+
| `GRIGDESK_DEEPSEEK_DATA_HOME` | Where versions live (default `~/.local/share/grigdesk-dsh`) |
|
|
58
|
+
| `GRIGDESK_DEEPSEEK_BIN_DIR` | Where command links are created (default `~/.local/bin`) |
|
|
59
|
+
|
|
60
|
+
GrigDesk finds the same installation through `current/deepseek`, so the terminal and the app share one
|
|
61
|
+
runtime. MIT — see the repository license.
|
package/bin/deepseek.mjs
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Точка входа npm bin для команды `deepseek`; провайдер задаётся только именем файла.
|
|
3
|
+
import { launch } from './launcher.mjs';
|
|
4
|
+
|
|
5
|
+
launch().then((code) => {
|
|
6
|
+
process.exitCode = code;
|
|
7
|
+
}, (error) => {
|
|
8
|
+
process.stderr.write(`${error.message}\n`);
|
|
9
|
+
process.exitCode = 1;
|
|
10
|
+
});
|
package/bin/glm.mjs
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Точка входа npm bin для команды `glm`; провайдер задаётся только именем файла.
|
|
3
|
+
import { launch } from './launcher.mjs';
|
|
4
|
+
|
|
5
|
+
launch('glm').then((code) => {
|
|
6
|
+
process.exitCode = code;
|
|
7
|
+
}, (error) => {
|
|
8
|
+
process.stderr.write(`${error.message}\n`);
|
|
9
|
+
process.exitCode = 1;
|
|
10
|
+
});
|
package/bin/launcher.mjs
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Единый launcher трёх команд. Провайдер задаёт файл входа: glm и qwen открывают чат
|
|
3
|
+
* своего провайдера, deepseek оставляет аргументы ELF без изменений. Служебные флаги
|
|
4
|
+
* ELF (--version, --runtime-info, --verify, --help) всегда идут напрямую.
|
|
5
|
+
*/
|
|
6
|
+
import { spawn } from 'node:child_process';
|
|
7
|
+
import { readFile } from 'node:fs/promises';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
|
|
11
|
+
import {
|
|
12
|
+
commandDirectory, dataHome, readCurrentElf, recordedDataHome, recordDataHome,
|
|
13
|
+
} from '../scripts/lib/layout.mjs';
|
|
14
|
+
import { installVersion, linkCommands } from '../scripts/lib/install.mjs';
|
|
15
|
+
import { describePlatform } from '../scripts/lib/platform.mjs';
|
|
16
|
+
|
|
17
|
+
const ELF_FLAGS = new Set(['-V', '--version', '--runtime-info', '--verify', '--license', '--help', '--json']);
|
|
18
|
+
const SIGNALS = { SIGHUP: 1, SIGINT: 2, SIGQUIT: 3, SIGKILL: 9, SIGPIPE: 13, SIGTERM: 15 };
|
|
19
|
+
export const packageDirectory = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* `install` работает и без ELF: докачивает версию пакета после npm --ignore-scripts
|
|
23
|
+
* или неудачной сети. Остальное — запуск действующего ELF с наследованием терминала.
|
|
24
|
+
*/
|
|
25
|
+
export async function launch(provider) {
|
|
26
|
+
const args = process.argv.slice(2);
|
|
27
|
+
|
|
28
|
+
if (args[0] === 'install') {
|
|
29
|
+
return await install({ log: (line) => process.stderr.write(`${line}\n`) });
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const elf = await readCurrentElf(await resolveHome());
|
|
33
|
+
|
|
34
|
+
if (!elf) {
|
|
35
|
+
process.stderr.write('DeepSeek Harness не установлен. Выполните:\n'
|
|
36
|
+
+ ' dsh install\n');
|
|
37
|
+
|
|
38
|
+
return 1;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
return await run(elf, provider ? forward(provider, args) : args);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Ставит версию этого пакета и связывает команды. Тег берётся из package.json:
|
|
46
|
+
* npm-пакет и релиз ELF выходят под одной версией.
|
|
47
|
+
* @param {{ log?: (line: string) => void, env?: NodeJS.ProcessEnv, fetchImpl?: typeof fetch }} [options]
|
|
48
|
+
*/
|
|
49
|
+
export async function install({ log = () => {}, env = process.env, fetchImpl = fetch } = {}) {
|
|
50
|
+
const platform = describePlatform();
|
|
51
|
+
|
|
52
|
+
if (!platform.supported) {
|
|
53
|
+
throw new Error(platform.reason);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const { version } = JSON.parse(await readFile(path.join(packageDirectory, 'package.json'), 'utf8'));
|
|
57
|
+
|
|
58
|
+
if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u.test(version) || version.startsWith('0.0.0')) {
|
|
59
|
+
throw new Error(`Версия пакета ${version} не опубликована: установите @grigdesk/dsh из npm`);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Явное окружение важнее записанного при установке пути, тот — важнее умолчания:
|
|
63
|
+
// повторный install и запуск находят одни и те же версии без повторения переменных.
|
|
64
|
+
const home = await resolveHome(env);
|
|
65
|
+
const installEnv = { ...env, GRIGDESK_DEEPSEEK_DATA_HOME: home };
|
|
66
|
+
const binary = await installVersion({ tag: `v${version}`, platform, env: installEnv, log, fetchImpl });
|
|
67
|
+
|
|
68
|
+
await recordDataHome(packageDirectory, home);
|
|
69
|
+
|
|
70
|
+
const directory = commandDirectory(env);
|
|
71
|
+
const linked = await linkCommands({ packageDirectory, env, log }).then(() => true, (error) => {
|
|
72
|
+
log(`Команды не созданы: ${error.message}`);
|
|
73
|
+
|
|
74
|
+
return false;
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
if (linked && !(env.PATH ?? '').split(path.delimiter).includes(directory)) {
|
|
78
|
+
log(`Добавьте ${directory} в PATH или откройте новый терминал`);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
log(`DSH ${version}: ${binary}`);
|
|
82
|
+
|
|
83
|
+
return 0;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const ACCOUNT_COMMANDS = new Set(['login', 'logout']);
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* glm/qwen без аргументов открывают чат; с флагами чата — добавляют провайдера;
|
|
90
|
+
* `glm login` сохраняет ключ GLM. Служебные флаги ELF и явный chat -p не переиначиваем.
|
|
91
|
+
*/
|
|
92
|
+
export function forward(provider, args) {
|
|
93
|
+
if (args.length === 0 || ELF_FLAGS.has(args[0]) || args[0] === '--') {
|
|
94
|
+
return args.length === 0 ? ['chat', '-p', provider] : args;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
if (ACCOUNT_COMMANDS.has(args[0])) {
|
|
98
|
+
return args.length > 1 ? args : [args[0], provider];
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
if (args[0] === 'chat') {
|
|
102
|
+
return args.some((arg) => arg === '-p' || arg.startsWith('--provider'))
|
|
103
|
+
? args : ['chat', '-p', provider, ...args.slice(1)];
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
return ['chat', '-p', provider, ...args];
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async function resolveHome(env = process.env) {
|
|
110
|
+
return env.GRIGDESK_DEEPSEEK_DATA_HOME ?? await recordedDataHome(packageDirectory) ?? dataHome(env);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
async function run(command, args) {
|
|
114
|
+
return await new Promise((resolve, reject) => {
|
|
115
|
+
const child = spawn(command, args, { stdio: 'inherit', env: process.env });
|
|
116
|
+
|
|
117
|
+
child.once('error', reject);
|
|
118
|
+
child.once('exit', (code, signal) => resolve(signal ? 128 + (SIGNALS[signal] ?? 0) : code ?? 1));
|
|
119
|
+
});
|
|
120
|
+
}
|
package/bin/qwen.mjs
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Точка входа npm bin для команды `qwen`; провайдер задаётся только именем файла.
|
|
3
|
+
import { launch } from './launcher.mjs';
|
|
4
|
+
|
|
5
|
+
launch('qwen').then((code) => {
|
|
6
|
+
process.exitCode = code;
|
|
7
|
+
}, (error) => {
|
|
8
|
+
process.stderr.write(`${error.message}\n`);
|
|
9
|
+
process.exitCode = 1;
|
|
10
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,35 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@grigdesk/dsh",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.2",
|
|
4
|
+
"description": "DeepSeek Harness CLI for DeepSeek, GLM and Qwen in the terminal",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"engines": {
|
|
8
|
+
"node": ">=18.18"
|
|
9
|
+
},
|
|
10
|
+
"bin": {
|
|
11
|
+
"dsh": "./bin/deepseek.mjs",
|
|
12
|
+
"deepseek": "./bin/deepseek.mjs",
|
|
13
|
+
"glm": "./bin/glm.mjs"
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"bin/",
|
|
17
|
+
"scripts/",
|
|
18
|
+
"README.md"
|
|
19
|
+
],
|
|
20
|
+
"scripts": {
|
|
21
|
+
"postinstall": "node scripts/postinstall.mjs"
|
|
22
|
+
},
|
|
23
|
+
"publishConfig": {
|
|
24
|
+
"access": "public"
|
|
25
|
+
},
|
|
26
|
+
"repository": {
|
|
27
|
+
"type": "git",
|
|
28
|
+
"url": "git+https://github.com/EvilDevRu/grigdesk-dsh.git",
|
|
29
|
+
"directory": "npm"
|
|
30
|
+
},
|
|
31
|
+
"bugs": {
|
|
32
|
+
"url": "https://github.com/EvilDevRu/grigdesk-dsh/issues"
|
|
33
|
+
},
|
|
34
|
+
"homepage": "https://github.com/EvilDevRu/grigdesk-dsh#readme"
|
|
35
|
+
}
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Установка одной версии ELF: manifest релиза → asset платформы → поток во временный
|
|
3
|
+
* файл с SHA-256 → атомарная публикация в versions/<tag> → ссылка current.
|
|
4
|
+
* Уже установленная версия с совпавшей суммой не скачивается повторно.
|
|
5
|
+
*/
|
|
6
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
7
|
+
import { constants, createWriteStream } from 'node:fs';
|
|
8
|
+
import {
|
|
9
|
+
access, chmod, lstat, mkdir, open, readFile, readlink, realpath, rename, rm, stat, symlink, unlink,
|
|
10
|
+
} from 'node:fs/promises';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import { pipeline } from 'node:stream/promises';
|
|
13
|
+
|
|
14
|
+
import {
|
|
15
|
+
binaryPath, commandDirectory, currentLink, dataHome, downloadBase, versionDirectory,
|
|
16
|
+
} from './layout.mjs';
|
|
17
|
+
|
|
18
|
+
const MANIFEST_FORMAT = 1;
|
|
19
|
+
const MANIFEST_TIMEOUT_MS = 30000;
|
|
20
|
+
const DOWNLOAD_TIMEOUT_MS = 20 * 60 * 1000;
|
|
21
|
+
export const COMMANDS = Object.freeze(['dsh', 'deepseek', 'glm', 'qwen']);
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Читает manifest.json релиза и выбирает asset платформы. Только полный SHA-256 и
|
|
25
|
+
* положительный размер из манифеста дают право считать скачанные байты поставкой.
|
|
26
|
+
*/
|
|
27
|
+
export async function selectAsset({ tag, platform, env = process.env, fetchImpl = fetch }) {
|
|
28
|
+
const url = `${downloadBase(env)}/${encodeURIComponent(tag)}/manifest.json`;
|
|
29
|
+
const response = await fetchImpl(url, {
|
|
30
|
+
signal: AbortSignal.timeout(MANIFEST_TIMEOUT_MS),
|
|
31
|
+
headers: { Accept: 'application/json' },
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
if (!response.ok) {
|
|
35
|
+
throw new Error(`Релиз ${tag} не отдал manifest.json (HTTP ${response.status}): ${url}`);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const manifest = await response.json();
|
|
39
|
+
const asset = Array.isArray(manifest?.assets) ? manifest.assets.find((entry) => (
|
|
40
|
+
entry && typeof entry === 'object' && entry.file === platform.asset
|
|
41
|
+
&& /^[a-f0-9]{64}$/u.test(String(entry.sha256))
|
|
42
|
+
&& Number.isSafeInteger(entry.size) && entry.size > 0
|
|
43
|
+
)) : undefined;
|
|
44
|
+
|
|
45
|
+
if (manifest?.format !== MANIFEST_FORMAT || !asset) {
|
|
46
|
+
throw new Error(`В релизе ${tag} нет проверенного asset ${platform.asset} в manifest.json`);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
return { asset, manifest };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Поток во временный файл целевого каталога: rename в пределах одной файловой системы
|
|
54
|
+
* атомарен, поэтому недокачанный или побитый файл никогда не становится deepseek.
|
|
55
|
+
*/
|
|
56
|
+
export async function downloadVerified({ source, directory, name, sha256, size, fetchImpl = fetch }) {
|
|
57
|
+
await mkdir(directory, { recursive: true, mode: 0o755 });
|
|
58
|
+
const partial = path.join(directory, `.partial-${randomBytes(6).toString('hex')}`);
|
|
59
|
+
const response = await fetchImpl(source, { signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS) });
|
|
60
|
+
|
|
61
|
+
if (!response.ok || !response.body) {
|
|
62
|
+
throw new Error(`Не удалось скачать ${source} (HTTP ${response.status})`);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const declared = Number(response.headers.get('content-length'));
|
|
66
|
+
const hash = createHash('sha256');
|
|
67
|
+
let bytes = 0;
|
|
68
|
+
const counter = new TransformStream({
|
|
69
|
+
transform(chunk, controller) {
|
|
70
|
+
bytes += chunk.byteLength;
|
|
71
|
+
hash.update(chunk);
|
|
72
|
+
controller.enqueue(chunk);
|
|
73
|
+
},
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
try {
|
|
77
|
+
await pipeline(response.body.pipeThrough(counter),
|
|
78
|
+
createWriteStream(partial, { mode: 0o700, flags: 'wx' }));
|
|
79
|
+
|
|
80
|
+
if (declared && declared !== bytes) {
|
|
81
|
+
throw new Error(`Размер ${name} не совпал с объявленным: получено ${bytes}, ожидалось ${declared}`);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
if (bytes !== size || hash.digest('hex') !== sha256) {
|
|
85
|
+
throw new Error(`Контрольная сумма ${name} не совпала с manifest.json релиза`);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return partial;
|
|
89
|
+
} catch (error) {
|
|
90
|
+
await rm(partial, { force: true });
|
|
91
|
+
throw error;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Ставит версию, если её ещё нет, и делает её действующей. Возвращает путь к ELF.
|
|
97
|
+
* Рядом с бинарником хранится описание asset: повторный запуск без сети сразу
|
|
98
|
+
* переключает current вместо повторной загрузки.
|
|
99
|
+
* @param {{ tag: string, platform: { asset: string }, env?: NodeJS.ProcessEnv,
|
|
100
|
+
* log?: (line: string) => void, fetchImpl?: typeof fetch }} options
|
|
101
|
+
*/
|
|
102
|
+
export async function installVersion({
|
|
103
|
+
tag, platform, env = process.env, log = () => {}, fetchImpl = fetch,
|
|
104
|
+
}) {
|
|
105
|
+
const home = dataHome(env);
|
|
106
|
+
const { asset } = await selectAsset({ tag, platform, env, fetchImpl });
|
|
107
|
+
const binary = binaryPath(home, tag);
|
|
108
|
+
const receipt = path.join(versionDirectory(home, tag), 'asset.json');
|
|
109
|
+
const present = await readFile(receipt, 'utf8').then(() => asset.sha256, () => null);
|
|
110
|
+
|
|
111
|
+
if (present === asset.sha256 && await executable(binary)) {
|
|
112
|
+
log(`deepseek ${tag} уже установлен: ${binary}`);
|
|
113
|
+
} else {
|
|
114
|
+
const source = `${downloadBase(env)}/${encodeURIComponent(tag)}/${asset.file}`;
|
|
115
|
+
|
|
116
|
+
log(`Скачиваю ${source} (${Math.ceil(asset.size / 1048576)} МБ)…`);
|
|
117
|
+
const partial = await downloadVerified({
|
|
118
|
+
source, directory: versionDirectory(home, tag), name: asset.file,
|
|
119
|
+
sha256: asset.sha256, size: asset.size, fetchImpl,
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
await rm(binary, { force: true });
|
|
123
|
+
await chmod(partial, 0o755);
|
|
124
|
+
await rename(partial, binary);
|
|
125
|
+
await writeReceipt(receipt, `${JSON.stringify({
|
|
126
|
+
tag, file: asset.file, sha256: asset.sha256, size: asset.size,
|
|
127
|
+
}, null, 2)}\n`);
|
|
128
|
+
log(`Готово: ${binary}`);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
await switchCurrent(home, tag);
|
|
132
|
+
|
|
133
|
+
return binary;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Ссылка current меняется через временную: читатель видит либо прежнюю версию,
|
|
138
|
+
* либо новую целиком. Чужой файл или каталог с этим именем не перезаписывается.
|
|
139
|
+
*/
|
|
140
|
+
export async function switchCurrent(home, tag) {
|
|
141
|
+
const link = currentLink(home);
|
|
142
|
+
const temporary = `${link}.${randomBytes(6).toString('hex')}`;
|
|
143
|
+
const info = await lstat(link).catch(() => null);
|
|
144
|
+
|
|
145
|
+
if (info && !info.isSymbolicLink()) {
|
|
146
|
+
throw new Error(`${link} занят обычным файлом или каталогом — уберите его вручную`);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
await symlink(path.relative(home, versionDirectory(home, tag)), temporary);
|
|
150
|
+
await rename(temporary, link);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Команды в ~/.local/bin ссылаются на launcher'ы пакета. Короткий qwen создаётся,
|
|
155
|
+
* только если он свободен в PATH. При совпадении доступна команда dsh chat -p qwen.
|
|
156
|
+
* @param {{ packageDirectory: string, env?: NodeJS.ProcessEnv, log?: (line: string) => void }} options
|
|
157
|
+
*/
|
|
158
|
+
export async function linkCommands({ packageDirectory, env = process.env, log = () => {} }) {
|
|
159
|
+
const directory = commandDirectory(env);
|
|
160
|
+
|
|
161
|
+
await mkdir(directory, { recursive: true, mode: 0o755 });
|
|
162
|
+
|
|
163
|
+
for (const command of COMMANDS) {
|
|
164
|
+
const file = path.join(directory, command);
|
|
165
|
+
const target = path.join(packageDirectory, 'bin', `${command === 'dsh' ? 'deepseek' : command}.mjs`);
|
|
166
|
+
const info = await lstat(file).catch(() => null);
|
|
167
|
+
|
|
168
|
+
if (info?.isSymbolicLink()) {
|
|
169
|
+
const current = await readlink(file).catch(() => null);
|
|
170
|
+
|
|
171
|
+
if (current && path.resolve(directory, current) === target) {
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const pointsToUs = await realpathOrNull(file);
|
|
176
|
+
|
|
177
|
+
if (!pointsToUs?.startsWith(`${path.resolve(packageDirectory)}${path.sep}`)) {
|
|
178
|
+
log(`Пропускаю ${file}: ссылка ведёт на чужую программу`);
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
await unlink(file);
|
|
183
|
+
} else if (info) {
|
|
184
|
+
log(`Пропускаю ${file}: уже существует ${info.isDirectory() ? 'каталог' : 'файл'}`);
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
if (command === 'qwen' && await hasOtherCommand(command, target, env.PATH)) {
|
|
189
|
+
log('Команда qwen уже есть в PATH. Для Qwen в DSH используйте `dsh chat -p qwen`.');
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
await symlink(target, file);
|
|
194
|
+
log(`Команда ${command} → ${file}`);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
return directory;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Смотрим исполняемые файлы во всём PATH перед созданием необязательного алиаса.
|
|
202
|
+
* Символическая ссылка на тот же launcher не считается сторонней командой.
|
|
203
|
+
*/
|
|
204
|
+
async function hasOtherCommand(command, target, searchPath = '') {
|
|
205
|
+
for (const directory of searchPath.split(path.delimiter)) {
|
|
206
|
+
const candidate = path.resolve(directory, command);
|
|
207
|
+
const info = await stat(candidate).catch(() => null);
|
|
208
|
+
|
|
209
|
+
if (info?.isFile() && await access(candidate, constants.X_OK).then(() => true, () => false)
|
|
210
|
+
&& await realpathOrNull(candidate) !== target) {
|
|
211
|
+
return true;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
return false;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
async function executable(file) {
|
|
219
|
+
const info = await lstat(file).catch(() => null);
|
|
220
|
+
|
|
221
|
+
return info?.isFile() && (info.mode & 0o111) !== 0;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
async function writeReceipt(file, content) {
|
|
225
|
+
const handle = await open(file, 'w', 0o644);
|
|
226
|
+
|
|
227
|
+
await handle.writeFile(content);
|
|
228
|
+
await handle.close();
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
async function realpathOrNull(file) {
|
|
232
|
+
return await realpath(file).catch(() => null);
|
|
233
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Каталоги установки по образцу Claude Code: версии ELF лежат в data-home пользователя,
|
|
3
|
+
* а команды — в ~/.local/bin. Переопределения через окружение нужны тестам и GrigDesk.
|
|
4
|
+
*/
|
|
5
|
+
import { access, constants, readFile, readlink, writeFile } from 'node:fs/promises';
|
|
6
|
+
import os from 'node:os';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
|
|
9
|
+
export const DEFAULT_DOWNLOAD_BASE = 'https://github.com/EvilDevRu/grigdesk-dsh/releases/download';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Корень данных ELF: $GRIGDESK_DEEPSEEK_DATA_HOME, иначе путь, записанный install
|
|
13
|
+
* в пакет, иначе XDG_DATA_HOME/grigdesk-dsh или ~/.local/share/grigdesk-dsh.
|
|
14
|
+
* Пользовательские данные чата в этот корень не входят.
|
|
15
|
+
*/
|
|
16
|
+
export function dataHome(env = process.env) {
|
|
17
|
+
return absoluteOverride(env.GRIGDESK_DEEPSEEK_DATA_HOME, 'GRIGDESK_DEEPSEEK_DATA_HOME')
|
|
18
|
+
?? path.join(xdgDataHome(env), 'grigdesk-dsh');
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Установщик запоминает выбранный корень рядом с собой: повторный `install` и
|
|
23
|
+
* обычный запуск находят версии без повторения переменных окружения.
|
|
24
|
+
*/
|
|
25
|
+
export async function recordedDataHome(packageDirectory) {
|
|
26
|
+
const file = path.join(packageDirectory, 'scripts', 'data-home');
|
|
27
|
+
const recorded = (await readFile(file, 'utf8').catch(() => '')).trim();
|
|
28
|
+
|
|
29
|
+
return recorded && path.isAbsolute(recorded) ? recorded : null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export async function recordDataHome(packageDirectory, home) {
|
|
33
|
+
await writeFile(path.join(packageDirectory, 'scripts', 'data-home'), `${home}\n`);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Каталог команд: $GRIGDESK_DEEPSEEK_BIN_DIR, иначе ~/.local/bin.
|
|
38
|
+
*/
|
|
39
|
+
export function commandDirectory(env = process.env) {
|
|
40
|
+
return absoluteOverride(env.GRIGDESK_DEEPSEEK_BIN_DIR, 'GRIGDESK_DEEPSEEK_BIN_DIR')
|
|
41
|
+
?? path.join(os.homedir(), '.local', 'bin');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function downloadBase(env = process.env) {
|
|
45
|
+
const base = env.GRIGDESK_DEEPSEEK_DOWNLOAD_BASE ?? DEFAULT_DOWNLOAD_BASE;
|
|
46
|
+
const url = new URL(base);
|
|
47
|
+
|
|
48
|
+
if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && isLoopback(url.hostname)))
|
|
49
|
+
|| url.username || url.password || url.search || url.hash) {
|
|
50
|
+
throw new Error('GRIGDESK_DEEPSEEK_DOWNLOAD_BASE требует HTTPS или HTTP на loopback '
|
|
51
|
+
+ 'без учётных данных и параметров');
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return url.href.replace(/\/+$/u, '');
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function versionsDirectory(home) {
|
|
58
|
+
return path.join(home, 'versions');
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function versionDirectory(home, tag) {
|
|
62
|
+
return path.join(versionsDirectory(home), tag);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function binaryPath(home, tag) {
|
|
66
|
+
return path.join(versionDirectory(home, tag), 'deepseek');
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function currentLink(home) {
|
|
70
|
+
return path.join(home, 'current');
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Действующая версия — символическая ссылка current на каталог versions/<tag>.
|
|
75
|
+
* Обычный файл или каталог с этим именем считается чужой записью и не читается как наша.
|
|
76
|
+
*/
|
|
77
|
+
export async function readCurrentElf(home) {
|
|
78
|
+
let target;
|
|
79
|
+
|
|
80
|
+
try {
|
|
81
|
+
target = await readlink(currentLink(home));
|
|
82
|
+
} catch (error) {
|
|
83
|
+
if (error.code === 'ENOENT' || error.code === 'EINVAL') {
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
throw error;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const binary = path.join(path.resolve(path.dirname(currentLink(home)), target), 'deepseek');
|
|
91
|
+
|
|
92
|
+
try {
|
|
93
|
+
await access(binary, constants.X_OK);
|
|
94
|
+
|
|
95
|
+
return binary;
|
|
96
|
+
} catch {
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function isLoopback(hostname) {
|
|
102
|
+
return ['127.0.0.1', '[::1]', 'localhost'].includes(hostname);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function xdgDataHome(env) {
|
|
106
|
+
const xdg = env.XDG_DATA_HOME;
|
|
107
|
+
|
|
108
|
+
return xdg && path.isAbsolute(xdg) ? xdg : path.join(os.homedir(), '.local', 'share');
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function absoluteOverride(value, name) {
|
|
112
|
+
if (value === undefined) {
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
if (!path.isAbsolute(value) || value === '/') {
|
|
117
|
+
throw new Error(`${name} требует абсолютный путь`);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
return value;
|
|
121
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Платформа npm-пакета должна совпадать с одним из ELF релиза. Имена сборок
|
|
3
|
+
* совпадают с assets manifest.json: dsh-<platform>-<arch>.
|
|
4
|
+
*/
|
|
5
|
+
const supported = new Set(['linux-x64', 'linux-arm64', 'darwin-arm64']);
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Ключ платформы или null там, где поставка не собирается; причина — для сообщения.
|
|
9
|
+
*/
|
|
10
|
+
export function describePlatform(platform = process.platform, arch = process.arch) {
|
|
11
|
+
const key = `${platform}-${arch}`;
|
|
12
|
+
|
|
13
|
+
return {
|
|
14
|
+
key,
|
|
15
|
+
supported: supported.has(key),
|
|
16
|
+
asset: `dsh-${key}`,
|
|
17
|
+
reason: platform === 'win32'
|
|
18
|
+
? 'Windows не поддерживается: поставка собирается для Linux x64/arm64 и macOS Apple Silicon'
|
|
19
|
+
: `Нет сборки для ${key}: доступны ${[...supported].sort().join(', ')}`,
|
|
20
|
+
};
|
|
21
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* postinstall npm-пакета: ставит ELF версии пакета и связывает команды в ~/.local/bin.
|
|
4
|
+
* Отказ сети или контрольной суммы завершает установку кодом 1: пакет без ELF бесполезен,
|
|
5
|
+
* а `dsh install` повторяет попытку позже без переустановки пакета.
|
|
6
|
+
*/
|
|
7
|
+
import { install } from '../bin/launcher.mjs';
|
|
8
|
+
|
|
9
|
+
install({ log: (line) => process.stderr.write(`${line}\n`) }).then((code) => {
|
|
10
|
+
process.exitCode = code;
|
|
11
|
+
}, (error) => {
|
|
12
|
+
process.stderr.write(`Установка DeepSeek Harness не завершена: ${error.message}\n`
|
|
13
|
+
+ 'Повторите позже командой `dsh install` (нужна сеть до GitHub Releases).\n');
|
|
14
|
+
process.exitCode = 1;
|
|
15
|
+
});
|