dsh-zcode-startplan 0.0.0-stage → 0.2.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/package.json CHANGED
@@ -1,6 +1,80 @@
1
- {
2
- "name": "dsh-zcode-startplan",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "dsh-zcode-startplan",
3
+ "version": "0.2.0",
4
+ "description": "DSH 接入 ZCode 赠送免费 plan(account:bigmodel-start-plan):多账号池 + 按需阿里云 captcha + 直连 zcode-plan/anthropic 的 llm 适配器。移植自 gitee.com/iJetLi/bonus-plan-4-open-zcode。",
5
+ "type": "module",
6
+ "license": "GPL-3.0-or-later",
7
+ "author": "Venshell",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/Venshell/dsh-zcode-startplan.git"
11
+ },
12
+ "homepage": "https://github.com/Venshell/dsh-zcode-startplan#readme",
13
+ "bugs": "https://github.com/Venshell/dsh-zcode-startplan/issues",
14
+ "keywords": [
15
+ "dsh-plugin",
16
+ "deepseek-harness",
17
+ "zcode",
18
+ "zhipu",
19
+ "glm",
20
+ "model-provider",
21
+ "captcha",
22
+ "anthropic-messages"
23
+ ],
24
+ "main": "./index.js",
25
+ "exports": {
26
+ ".": "./index.js",
27
+ "./client": "./client.js",
28
+ "./cordis.patch.yml": "./cordis.patch.yml",
29
+ "./package.json": "./package.json",
30
+ "./locale/*.json": "./locale/*.json",
31
+ "./icon": "./icon.svg"
32
+ },
33
+ "files": [
34
+ "index.js",
35
+ "client.js",
36
+ "lib",
37
+ "bin",
38
+ "scripts",
39
+ "locale/*.json",
40
+ "icon.svg",
41
+ "cordis.patch.yml",
42
+ "README.md",
43
+ "CHANGELOG.md",
44
+ "LICENSE"
45
+ ],
46
+ "bin": {
47
+ "zcode-start-plan": "./bin/cli.mjs"
48
+ },
49
+ "scripts": {
50
+ "check": "node --check index.js && node --check bin/cli.mjs",
51
+ "test": "node scripts/run-tests.mjs",
52
+ "smoke": "node scripts/smoke-install.mjs",
53
+ "verify:compat": "node scripts/verify_compat.mjs",
54
+ "login": "node bin/cli.mjs login",
55
+ "status": "node bin/cli.mjs status",
56
+ "probe": "node bin/cli.mjs probe"
57
+ },
58
+ "peerDependencies": {
59
+ "@deepseek-ai/dsh-llm": "^0.2.0-rc.2"
60
+ },
61
+ "engines": {
62
+ "node": "^22.19 || >=24"
63
+ },
64
+ "dsh": {
65
+ "id": "dsh-zcode-startplan",
66
+ "name": "ZCode Start Plan",
67
+ "version": "0.2.0",
68
+ "permissions": "模型供应商接入, 账号池管理",
69
+ "bundle": {
70
+ "patch": "./cordis.patch.yml"
71
+ },
72
+ "client": {
73
+ "platform": "web",
74
+ "immediately": true,
75
+ "inject": [
76
+ "@deepseek-ai/dsh-client-ui-renderer"
77
+ ]
78
+ }
79
+ }
80
+ }
@@ -0,0 +1,138 @@
1
+ /**
2
+ * tok/s 基准:复用插件自身的完整调用链(账号池 → plan-client → 上游 SSE),
3
+ * 跑真实流式请求,用上游 usage.output_tokens / 流式生成时长计算 tok/s。
4
+ *
5
+ * ⚠ 凭据安全:脚本把真实账号库**复制**到工作区临时目录后使用(避免沙箱写 Home),
6
+ * 运行结束(含失败)一律删除副本,凭据不落任何第二份。
7
+ *
8
+ * 用法:node scripts/bench-toks.mjs [运行次数,默认 2]
9
+ */
10
+
11
+ import { copyFileSync, existsSync, mkdirSync, rmSync } from 'node:fs'
12
+ import { join } from 'node:path'
13
+ import { homedir } from 'node:os'
14
+ import { SqliteStore, AccountPool } from '../lib/pool.js'
15
+ import { ZcodePlanClient } from '../lib/plan-client.js'
16
+
17
+ const srcDir = join(homedir(), '.dsh', 'zcode-start-plan')
18
+ const tmpDir = join(process.cwd(), '.bench-tmp')
19
+
20
+ /** 上游事件扫描:抽取 usage 与文本增量。 */
21
+ function scanEvent(ev, acc) {
22
+ const d = ev?.data
23
+ if (d === null || typeof d !== 'object') return
24
+ if (d.type === 'message_start') {
25
+ const u = d.message?.usage
26
+ if (u !== undefined && u !== null) {
27
+ acc.inTokens = u.input_tokens ?? acc.inTokens
28
+ acc.cacheReadTokens = u.cache_read_input_tokens ?? acc.cacheReadTokens
29
+ acc.cacheWriteTokens = u.cache_creation_input_tokens ?? acc.cacheWriteTokens
30
+ }
31
+ } else if (d.type === 'message_delta') {
32
+ if (typeof d.usage?.output_tokens === 'number') acc.outTokens = d.usage.output_tokens
33
+ } else if (d.type === 'content_block_delta') {
34
+ if (d.delta?.type === 'text_delta') acc.textChars += (d.delta.text ?? '').length
35
+ if (d.delta?.type === 'thinking_delta') acc.thinkChars += (d.delta.thinking ?? '').length
36
+ } else if (d.type === 'error') {
37
+ acc.streamError = JSON.stringify(d).slice(0, 300)
38
+ }
39
+ }
40
+
41
+ async function runOnce(client, pool, model, runIndex) {
42
+ const acc = { inTokens: 0, outTokens: 0, textChars: 0, thinkChars: 0, cacheReadTokens: 0, cacheWriteTokens: 0, streamError: undefined }
43
+ const prompt = '请从 1 数到 300,每行输出一个数字,不要输出任何其他文字。'
44
+ const t0 = Date.now()
45
+ const res = await client.call({
46
+ options: {
47
+ model,
48
+ messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }],
49
+ tools: [],
50
+ },
51
+ model: { id: model, name: model, supportsImage: false },
52
+ maxTokens: 2048,
53
+ })
54
+ const tFirst = Date.now() // readContentHead 返回 = 首个内容帧已到达
55
+ for (const ev of res.head) scanEvent(ev, acc)
56
+ if (res.decoder !== undefined) {
57
+ for (;;) {
58
+ const next = await res.decoder.read()
59
+ if (next.done === true) break
60
+ scanEvent(next.value, acc)
61
+ }
62
+ }
63
+ const tEnd = Date.now()
64
+ const nick = pool.list().find((entry) => entry.id === res.accountId)?.nickname ?? res.accountId
65
+ const genSec = (tEnd - tFirst) / 1000
66
+ return {
67
+ run: runIndex,
68
+ model,
69
+ account: nick,
70
+ ttftMs: tFirst - t0,
71
+ genMs: tEnd - tFirst,
72
+ inTokens: acc.inTokens,
73
+ outTokens: acc.outTokens,
74
+ cacheReadTokens: acc.cacheReadTokens,
75
+ cacheWriteTokens: acc.cacheWriteTokens,
76
+ textChars: acc.textChars,
77
+ thinkChars: acc.thinkChars,
78
+ tokPerSec: genSec > 0 ? Math.round((acc.outTokens / genSec) * 10) / 10 : 0,
79
+ streamError: acc.streamError ?? null,
80
+ }
81
+ }
82
+
83
+ const runs = Number(process.argv[2] ?? '2')
84
+ const plan = [
85
+ { model: 'GLM-5.3-Flash', times: runs },
86
+ { model: 'GLM-5.3', times: 1 },
87
+ ]
88
+
89
+ mkdirSync(tmpDir, { recursive: true })
90
+ try {
91
+ for (const f of ['accounts.db', 'accounts.db-wal', 'accounts.db-shm']) {
92
+ const src = join(srcDir, f)
93
+ if (existsSync(src)) copyFileSync(src, join(tmpDir, f))
94
+ }
95
+ const store = await new SqliteStore(join(tmpDir, 'accounts.db'))
96
+ try {
97
+ const pool = new AccountPool({ store, log: () => {} })
98
+ pool.sweepExpired()
99
+ const accounts = pool.list()
100
+ console.log(`账号池:${accounts.length} 个(启用 ${accounts.filter((e) => e.enabled).length} 个):${accounts.map((e) => e.nickname).join(' / ')}`)
101
+ if (accounts.length === 0) throw new Error('账号池为空:无法基准(真实账号库读取失败或为空)')
102
+
103
+ const logs = []
104
+ const client = new ZcodePlanClient({
105
+ pool,
106
+ minter: { mint: async () => { throw new Error('bench 模式不产出 captcha') } },
107
+ log: (m) => logs.push(m),
108
+ })
109
+
110
+ const results = []
111
+ let index = 1
112
+ for (const item of plan) {
113
+ for (let i = 0; i < item.times; i += 1) {
114
+ const r = await runOnce(client, pool, item.model, index)
115
+ results.push(r)
116
+ console.log(JSON.stringify(r))
117
+ index += 1
118
+ }
119
+ }
120
+
121
+ console.log('--- 关键日志 ---')
122
+ for (const line of logs.filter((m) => m.includes('命中') || m.includes('零内容') || m.includes('上游') || m.includes('重试'))) {
123
+ console.log(line)
124
+ }
125
+ console.log('--- 汇总 ---')
126
+ for (const model of [...new Set(results.map((r) => r.model))]) {
127
+ const rs = results.filter((r) => r.model === model)
128
+ const avg = Math.round((rs.reduce((s, r) => s + r.tokPerSec, 0) / rs.length) * 10) / 10
129
+ const avgTtft = Math.round(rs.reduce((s, r) => s + r.ttftMs, 0) / rs.length)
130
+ console.log(`${model}: 平均 ${avg} tok/s(流式生成段),平均首帧 ${avgTtft}ms,共 ${rs.length} 次`)
131
+ }
132
+ } finally {
133
+ // ⚠ Windows:SQLite WAL 句柄不关,rmSync 会 EPERM。
134
+ try { store?.close() } catch { /* 已关闭 */ }
135
+ try { rmSync(tmpDir, { recursive: true, force: true }) } catch (error) {
136
+ console.warn(`[bench] 临时目录清理失败(可手动删除 ${tmpDir}):${error instanceof Error ? error.message : String(error)}`)
137
+ }
138
+ }
@@ -0,0 +1,31 @@
1
+ /** 一次性检查:账号库能否在真实数据目录落盘(不写入假账号)。 */
2
+ import { join } from 'node:path'
3
+ import { existsSync, rmSync, statSync } from 'node:fs'
4
+ import { pathToFileURL } from 'node:url'
5
+
6
+ const root = process.argv[2]
7
+ const { SqliteStore, AccountPool, isUsableCredential } = await import(pathToFileURL(join(root, 'lib', 'pool.js')).href)
8
+
9
+ const home = process.env.USERPROFILE
10
+ const dbFile = join(home, '.dsh', 'zcode-start-plan', 'accounts.db')
11
+
12
+ const store = await new SqliteStore(dbFile)
13
+ console.log(`dataDir=${join(home, '.dsh', 'zcode-start-plan')}`)
14
+ console.log(`dbFile=${dbFile}`)
15
+ console.log(`inMemory=${store.inMemory} mkdirError=${store.mkdirError ? store.mkdirError.message : 'none'}`)
16
+ console.log(`exists=${existsSync(dbFile)}`)
17
+
18
+ const pool = new AccountPool({ store })
19
+ pool.add({ zcode_jwt: 'probe-jwt-not-real', device_mid: 'probe-device', user_id: 'probe-user' }, '落盘探测')
20
+ const listed = pool.list({ withCredentials: true })
21
+ console.log(`roundtrip accounts=${listed.length} credentialUsable=${isUsableCredential(listed[0]?.credential)}`)
22
+ console.log(`nickname=${listed[0]?.nickname}`)
23
+
24
+ pool.remove(listed[0].id)
25
+ console.log(`cleaned accounts=${pool.list().length}`)
26
+ store.close()
27
+
28
+ if (existsSync(dbFile)) {
29
+ const size = statSync(dbFile).size
30
+ console.log(`fileSize=${size}B`)
31
+ }
@@ -0,0 +1,76 @@
1
+ # 重启 DSH 桌面端(带 CDP 端口),让新装的 dsh-zcode-startplan 被加载。
2
+ #
3
+ # 为什么不直接在当前 shell 里 kill:本脚本由**独立的 powershell 进程**执行,
4
+ # 不随 DSH 的子进程树一起死;DSH 主进程退出后它仍在跑,负责拉起新实例。
5
+ #
6
+ # 用法(由 agent 以 Start-Process 分离启动):
7
+ # powershell -NoProfile -File restart-dsh.ps1 -WaitSeconds 25 -DebugPort 9229
8
+
9
+ param(
10
+ [int]$WaitSeconds = 25,
11
+ [int]$DebugPort = 9229,
12
+ [string]$Exe = 'D:\software\dsh\DeepSeek Harness.exe',
13
+ [string]$Log = "$env:TEMP\dsh-restart.log"
14
+ )
15
+
16
+ function Write-Log([string]$Message) {
17
+ $line = '{0:yyyy-MM-dd HH:mm:ss} {1}' -f (Get-Date), $Message
18
+ Add-Content -Path $Log -Value $line -Encoding utf8
19
+ }
20
+
21
+ try {
22
+ Write-Log "restart scheduled in ${WaitSeconds}s (debug port $DebugPort)"
23
+
24
+ # 等这一轮 agent 回复写完,避免把正在进行的会话截断在半句上。
25
+ Start-Sleep -Seconds $WaitSeconds
26
+
27
+ $main = Get-CimInstance Win32_Process -Filter "Name='DeepSeek Harness.exe'" |
28
+ Where-Object { $_.CommandLine -notmatch '--type=' }
29
+
30
+ if ($main) {
31
+ foreach ($proc in $main) {
32
+ Write-Log "stopping pid $($proc.ProcessId)"
33
+ try { Stop-Process -Id $proc.ProcessId -Force -ErrorAction Stop } catch { Write-Log "stop failed: $($_.Exception.Message)" }
34
+ }
35
+ # 给 Electron 一点收尾时间(它自己会清理子进程)。
36
+ Start-Sleep -Seconds 6
37
+ } else {
38
+ Write-Log 'no main process found (already closed)'
39
+ }
40
+
41
+ # 确认端口空出来。
42
+ for ($i = 0; $i -lt 20; $i++) {
43
+ $busy = Get-NetTCPConnection -LocalPort $DebugPort -State Listen -ErrorAction SilentlyContinue
44
+ if (-not $busy) { break }
45
+ Start-Sleep -Milliseconds 500
46
+ }
47
+
48
+ Write-Log "starting $Exe --remote-debugging-port=$DebugPort"
49
+ Start-Process -FilePath $Exe -ArgumentList "--remote-debugging-port=$DebugPort" -WorkingDirectory (Split-Path $Exe)
50
+
51
+ # 等 CDP 端口就绪,验证带上来了。
52
+ $ready = $false
53
+ for ($i = 0; $i -lt 60; $i++) {
54
+ Start-Sleep -Milliseconds 500
55
+ try {
56
+ $resp = Invoke-WebRequest -Uri "http://127.0.0.1:$DebugPort/json/version" -UseBasicParsing -TimeoutSec 2
57
+ if ($resp.StatusCode -eq 200) { $ready = $true; break }
58
+ } catch { }
59
+ }
60
+ Write-Log "cdp ready=$ready"
61
+
62
+ if (-not $ready) {
63
+ Write-Log 'CDP not reachable; relaunching WITHOUT the flag so the app stays usable'
64
+ $still = Get-CimInstance Win32_Process -Filter "Name='DeepSeek Harness.exe'" |
65
+ Where-Object { $_.CommandLine -notmatch '--type=' }
66
+ foreach ($proc in $still) { try { Stop-Process -Id $proc.ProcessId -Force } catch { } }
67
+ Start-Sleep -Seconds 4
68
+ Start-Process -FilePath $Exe -WorkingDirectory (Split-Path $Exe)
69
+ Write-Log 'relaunched without debug port'
70
+ }
71
+
72
+ Write-Log 'done'
73
+ }
74
+ catch {
75
+ Write-Log "fatal: $($_.Exception.Message)"
76
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * 在**单进程内**跑完全部测试文件。
3
+ *
4
+ * 为什么不用 `node --test tests/`:那会让 runner 为每个文件 `spawn` 子进程,
5
+ * 而沙箱/受限环境下 `spawn` 返回 `EPERM`(`node:test` 的 runner 无法降级)。
6
+ * 本脚本用 `run()`(同进程,in-process)跑同一批文件,结果与文件数无关。
7
+ *
8
+ * ```powershell
9
+ * node scripts/run-tests.mjs
10
+ * ```
11
+ */
12
+
13
+ import { readdirSync } from 'node:fs'
14
+ import { fileURLToPath, pathToFileURL } from 'node:url'
15
+ import { dirname, join } from 'node:path'
16
+ import { run } from 'node:test'
17
+
18
+ /**
19
+ * ⚠ 先注册宿主依赖解析钩子:源码目录不在 profile 里,
20
+ * 裸包 `@deepseek-ai/schemastery` 只有从安装位置才能解析到。
21
+ * 钩子只对「解析失败」的 `@deepseek-ai/*` 生效,不改变其余解析。
22
+ */
23
+ await import('../tests/support/resolve-profile-deps.mjs')
24
+
25
+ const here = dirname(fileURLToPath(import.meta.url))
26
+ const testsDir = join(here, '..', 'tests')
27
+
28
+ const files = readdirSync(testsDir)
29
+ .filter((name) => name.endsWith('.test.mjs'))
30
+ .sort()
31
+ .map((name) => join(testsDir, name))
32
+
33
+ if (files.length === 0) {
34
+ process.stderr.write('没有找到 tests/*.test.mjs\n')
35
+ process.exit(1)
36
+ }
37
+
38
+ let failures = 0
39
+ let total = 0
40
+
41
+ const stream = run({
42
+ files,
43
+ concurrency: 1,
44
+ isolation: 'none',
45
+ })
46
+
47
+ for await (const event of stream) {
48
+ if (event.type === 'test:fail') {
49
+ failures += 1
50
+ total += 1
51
+ process.stderr.write(`✗ ${event.data.name}\n`)
52
+ const error = event.data.details?.error
53
+ if (error !== undefined) process.stderr.write(`${indent(error.stack ?? String(error))}\n`)
54
+ } else if (event.type === 'test:pass') {
55
+ total += 1
56
+ if (event.data.nesting === 0) process.stdout.write(`· ${event.data.name}\n`)
57
+ }
58
+ }
59
+
60
+ process.stdout.write(`\n${total - failures}/${total} 通过${failures === 0 ? '' : `(${failures} 失败)`}\n`)
61
+ if (failures > 0) process.exitCode = 1
62
+
63
+ function indent(text) {
64
+ return String(text)
65
+ .split('\n')
66
+ .map((line) => ` ${line}`)
67
+ .join('\n')
68
+ }
@@ -0,0 +1,204 @@
1
+ /**
2
+ * 冒烟:对**已安装**的插件跑一次真实接线(不联网、不建账号)。
3
+ *
4
+ * 为什么需要它:`apply()` 的正确性依赖几个只有「真装进 profile」才暴露的细节 ——
5
+ * `package.json` 的 `dsh.bundle.patch` 声明、`Config` 契约形状、`inject: ['llm']`
6
+ * 的晚到服务、以及 `dispose` 是否被正确挂上。这些在单元测试里是假的 ctx,在这里是真的。
7
+ *
8
+ * ```powershell
9
+ * node scripts/smoke-install.mjs
10
+ * node scripts/smoke-install.mjs "C:\path\to\dsh-zcode-startplan" # 指定安装位置
11
+ * ```
12
+ *
13
+ * 退出码:0 = 全部通过;1 = 有失败项。
14
+ */
15
+
16
+ import { readFile } from 'node:fs/promises'
17
+ import { join } from 'node:path'
18
+ import { pathToFileURL } from 'node:url'
19
+
20
+ const entryRoot =
21
+ process.argv[2] ??
22
+ join(process.env.USERPROFILE ?? process.env.HOME ?? '.', '.dsh', 'profiles', 'desktop', 'node_modules', 'dsh-zcode-startplan')
23
+
24
+ const checks = []
25
+ const ok = (name, pass, detail = '') => checks.push({ name, pass: Boolean(pass), detail })
26
+
27
+ let mod
28
+ try {
29
+ mod = await import(pathToFileURL(join(entryRoot, 'index.js')).href)
30
+ } catch (error) {
31
+ console.error(`✗ 无法 import ${entryRoot}/index.js:${error instanceof Error ? error.message : String(error)}`)
32
+ process.exit(1)
33
+ }
34
+
35
+ const pkg = JSON.parse(await readFile(join(entryRoot, 'package.json'), 'utf8'))
36
+
37
+ ok('导出 name', mod.name === 'zcode-start-plan', String(mod.name))
38
+ /**
39
+ * ⚠ 宿主 ctx 是**沙箱 façade**:只挂 `inject` 声明过的服务。
40
+ * 这条断言把「用到哪些服务就声明哪些」钉住 —— 漏一个,
41
+ * `apply` 里一碰就抛 `cannot get property "X" without inject`,
42
+ * 插件静默失效(工具与模型全都没有)。
43
+ */
44
+ const inject = Array.isArray(mod.inject) ? mod.inject : []
45
+ for (const required of ['llm', 'tools', 'timer']) {
46
+ ok(`inject 声明 ${required}`, inject.includes(required), JSON.stringify(inject))
47
+ }
48
+ /**
49
+ * ⚠ 这一条是「插件进不进模型选择器」的生死线:DSH 用 `isNativeConfigSchema`
50
+ * (`Symbol.for('schemastery') === true` + string `type` + object `meta`)判定,
51
+ * 不符合就得到 `status: 'unsupported'`,provider 不会出现在模型列表里。
52
+ */
53
+ const configMeta = Reflect.get(mod.Config ?? {}, 'meta')
54
+ const native = Reflect.get(mod.Config ?? {}, Symbol.for('schemastery')) === true
55
+ && typeof Reflect.get(mod.Config ?? {}, 'type') === 'string'
56
+ && typeof configMeta === 'object'
57
+ && configMeta !== null
58
+ ok('Config 是 schemastery 原生 schema(否则进不了模型列表)', native)
59
+ ok('导出 apply', typeof mod.apply === 'function')
60
+ ok('dsh.bundle.patch 已声明', pkg.dsh?.bundle?.patch === './cordis.patch.yml', String(pkg.dsh?.bundle?.patch))
61
+ ok('peerDependencies 含 dsh-llm', typeof pkg.peerDependencies?.['@deepseek-ai/dsh-llm'] === 'string')
62
+ /**
63
+ * 官方标准:Host-only bundle **零运行时依赖**。插件用自制的 schemastery 兼容
64
+ * schema,所以这里断言**不**声明 schemastery 依赖 —— 声明了反而会在
65
+ * `link:` 安装时解析失败、把宿主 host 进程掀翻。
66
+ */
67
+ ok('peerDependencies 不含 schemastery(零运行时依赖)', pkg.peerDependencies?.['@deepseek-ai/schemastery'] === undefined)
68
+
69
+ const defaults = mod.Config({ captcha: { debugPort: 9229 } })
70
+ ok('Config 补齐默认值', defaults.provider === 'zcode-start-plan' && defaults.captcha.debugPort === 9229)
71
+ let rejected = false
72
+ try {
73
+ mod.Config({ captcha: { mode: 'browser' } })
74
+ } catch {
75
+ rejected = true
76
+ }
77
+ ok('Config 拒绝非法 captcha.mode', rejected)
78
+
79
+ /**
80
+ * 仿宿主沙箱 ctx:**只提供 `inject` 声明过的三个服务**,
81
+ * 不提供 `emit` / `on` / `inject` / `setInterval` —— 沙箱里没有它们
82
+ * (提供了反而掩盖真实缺陷)。
83
+ */
84
+ const registered = []
85
+ const tools = []
86
+ const disposers = []
87
+ const intervals = []
88
+ const ctx = {
89
+ logger: {
90
+ info: (message) => process.stdout.write(` [info] ${message}\n`),
91
+ warn: (message) => process.stdout.write(` [warn] ${message}\n`),
92
+ },
93
+ llm: {
94
+ registerAdapter: (providers, adapter) => {
95
+ registered.push({ providers, adapter })
96
+ return () => {}
97
+ },
98
+ emitAdaptersUpdated() {},
99
+ },
100
+ tools: { register: (tool) => { tools.push(tool); return () => {} } },
101
+ timer: { interval: (_cb, delay) => { intervals.push(delay); return () => {} } },
102
+ effect(fn) {
103
+ const disposer = fn()
104
+ if (typeof disposer === 'function') disposers.push(disposer)
105
+ return disposer
106
+ },
107
+ }
108
+
109
+ const dataDir = join(process.env.TEMP ?? '/tmp', `zsp-smoke-${Date.now()}`)
110
+ const cleanup = mod.apply(ctx, { dataDir })
111
+
112
+ for (let i = 0; i < 300 && registered.length === 0; i += 1) {
113
+ await new Promise((resolve) => setTimeout(resolve, 20))
114
+ }
115
+
116
+ ok('apply 返回 cleanup(官方标准)', typeof cleanup === 'function', typeof cleanup)
117
+ ok('registerAdapter 被调用一次', registered.length === 1, String(registered.length))
118
+ ok('路由名正确', JSON.stringify(registered[0]?.providers) === '["zcode-start-plan"]')
119
+ ok(
120
+ 'adapter 具备 stream / listModels / resolveModel',
121
+ typeof registered[0]?.adapter?.stream === 'function' &&
122
+ typeof registered[0]?.adapter?.listModels === 'function' &&
123
+ typeof registered[0]?.adapter?.resolveModel === 'function',
124
+ )
125
+ ok(
126
+ '注册了状态工具 zcode_start_plan_status',
127
+ tools.length === 1 && tools[0].name === 'zcode_start_plan_status',
128
+ JSON.stringify(tools.map((tool) => tool.name)),
129
+ )
130
+
131
+ if (tools[0] !== undefined) {
132
+ const status = await tools[0].execute()
133
+ ok('status.provider 正确', status.provider === 'zcode-start-plan')
134
+ ok('status 不泄露凭据', !JSON.stringify(status).includes('zcode_jwt'))
135
+ ok('status.captcha.reachable 是布尔值', typeof status.captcha.reachable === 'boolean')
136
+ /** 诊断字段:模型没进选择器时,先看这两个。 */
137
+ ok('status.adapterRegistered 为真', status.adapterRegistered === true, String(status.error ?? ''))
138
+ process.stdout.write(
139
+ ` [status] models=${JSON.stringify(status.models)} accounts=${status.accountCount} ` +
140
+ `captcha=${status.captcha.reachable}${status.captcha.reason ? ` (${status.captcha.reason})` : ''}\n`,
141
+ )
142
+ }
143
+
144
+ /**
145
+ * ⚠ 模型元数据契约:`dsh-llm` 的 `normalizeModelInfo` 要求每个 reasoning effort
146
+ * **同时有非空 id 与非空 name**,且 id 不重复 —— 缺任一条就抛
147
+ * `INVALID_MODEL_REASONING`("invalid or duplicate reasoning effort metadata"),
148
+ * 该模型在宿主里直接不可用。
149
+ */
150
+ if (registered[0]?.adapter !== undefined) {
151
+ const listed = await registered[0].adapter.listModels('zcode-start-plan')
152
+ ok('listModels 返回非空目录', listed.length > 0, String(listed.length))
153
+ let effortsValid = true
154
+ let detail = ''
155
+ for (const model of listed) {
156
+ for (const effort of model.reasoning?.efforts ?? []) {
157
+ if (typeof effort.id !== 'string' || effort.id.length === 0
158
+ || typeof effort.name !== 'string' || effort.name.length === 0) {
159
+ effortsValid = false
160
+ detail = `${model.id} → ${JSON.stringify(effort)}`
161
+ }
162
+ }
163
+ }
164
+ ok('reasoning efforts 均有非空 id 与 name', effortsValid, detail)
165
+ ok('adapter 实现 providerRetryPolicy', typeof registered[0].adapter.providerRetryPolicy === 'function')
166
+ /**
167
+ * ⚠ 宿主选模型后**直接**调用 `adapter.prepareCall(provider, model, signal)`;
168
+ * 漏掉它表现为 `registration.adapter.prepareCall is not a function`(选模型即报错)。
169
+ */
170
+ ok('adapter 实现 prepareCall', typeof registered[0].adapter.prepareCall === 'function')
171
+ const prepared = await registered[0].adapter.prepareCall('zcode-start-plan', 'GLM-5.3-Flash')
172
+ ok(
173
+ 'prepareCall 返回 model 与 stream 入口',
174
+ prepared?.model?.id === 'GLM-5.3-Flash' && typeof prepared.stream === 'function',
175
+ JSON.stringify(prepared?.model?.id),
176
+ )
177
+ }
178
+
179
+ /** 收尾只走 `apply` 返回的 cleanup(它负责释放 SQLite / 端点 / captcha)。 */
180
+ try {
181
+ await cleanup()
182
+ ok('cleanup 不抛错', true)
183
+ } catch (error) {
184
+ ok('cleanup 不抛错', false, error instanceof Error ? error.message : String(error))
185
+ }
186
+ for (const dispose of disposers) {
187
+ try {
188
+ dispose()
189
+ } catch {
190
+ // 收尾不应抛错;下面的检查项只关心「本脚本没有崩」。
191
+ }
192
+ }
193
+
194
+ let failed = 0
195
+ for (const check of checks) {
196
+ process.stdout.write(`${check.pass ? ' ok ' : ' FAIL'} ${check.name}${check.pass ? '' : ` → ${check.detail}`}\n`)
197
+ if (!check.pass) failed += 1
198
+ }
199
+ process.stdout.write(
200
+ failed === 0
201
+ ? `\nSMOKE PASS(${checks.length} 项,安装位置:${entryRoot})\n`
202
+ : `\nSMOKE FAIL(${failed}/${checks.length} 失败,安装位置:${entryRoot})\n`,
203
+ )
204
+ process.exit(failed === 0 ? 0 : 1)
@@ -0,0 +1,64 @@
1
+ /**
2
+ * DSH 兼容性门禁(离线,不发网络请求)。
3
+ *
4
+ * DSH 在加载 bundle 时会用 `evaluatePluginCompatibility` 检查 `peerDependencies` 里
5
+ * 所有 `@deepseek-ai/dsh-*` 项,并用 `includePrerelease: true` 比较版本 ——
6
+ * 所以写 `^0.2.0` 会把 `0.2.0-rc.2` 判成**不兼容**并静默跳过本 bundle。
7
+ * 本脚本在重启前把这件事提前暴露出来。
8
+ *
9
+ * ```powershell
10
+ * node scripts/verify_compat.mjs
11
+ * ```
12
+ */
13
+
14
+ import { readFileSync } from 'node:fs'
15
+ import { fileURLToPath } from 'node:url'
16
+ import { dirname, join } from 'node:path'
17
+
18
+ const here = dirname(fileURLToPath(import.meta.url))
19
+ const root = join(here, '..')
20
+ const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'))
21
+
22
+ /** 本插件实际使用、且会被门禁检查的宿主包。 */
23
+ const REQUIRED_HOST_PACKAGES = ['@deepseek-ai/dsh-llm']
24
+
25
+ const failures = []
26
+ const notes = []
27
+
28
+ const peers = pkg.peerDependencies ?? {}
29
+ for (const name of REQUIRED_HOST_PACKAGES) {
30
+ if (typeof peers[name] !== 'string') {
31
+ failures.push(`peerDependencies 缺 ${name} —— DSH 不会报错,但本插件依赖它的契约`)
32
+ }
33
+ }
34
+
35
+ for (const [name, range] of Object.entries(peers)) {
36
+ if (!name.startsWith('@deepseek-ai/dsh-')) continue
37
+ /** prerelease 陷阱:区间里没有 prerelease 段时,rc 版会被判为不满足。 */
38
+ if (/^\^?\d+\.\d+\.\d+$/.test(range)) {
39
+ notes.push(
40
+ `${name}: "${range}" 不含 prerelease 段;若宿主是 0.x 的 rc 版本会被判不兼容(建议写成 "^0.2.0-rc.2" 这类)`,
41
+ )
42
+ }
43
+ }
44
+
45
+ /** 本地实现必须能 `node --check` 通过(语法错误的 bundle 会被静默跳过)。 */
46
+ const entry = join(root, pkg.main ?? 'index.js')
47
+ try {
48
+ readFileSync(entry)
49
+ } catch {
50
+ failures.push(`入口文件不存在:${entry}`)
51
+ }
52
+
53
+ if (notes.length > 0) {
54
+ process.stdout.write('注意:\n')
55
+ for (const note of notes) process.stdout.write(` · ${note}\n`)
56
+ }
57
+
58
+ if (failures.length > 0) {
59
+ process.stderr.write('兼容性门禁失败:\n')
60
+ for (const failure of failures) process.stderr.write(` ✗ ${failure}\n`)
61
+ process.exit(1)
62
+ }
63
+
64
+ process.stdout.write('✓ 兼容性门禁通过(peerDependencies 不会被判不兼容)\n')