dsh-zcode-startplan 0.0.0-stage → 0.4.5
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/CHANGELOG.md +405 -0
- package/LICENSE +674 -0
- package/README.md +404 -2
- package/bin/cli.mjs +450 -0
- package/client.js +716 -0
- package/cordis.patch.yml +32 -0
- package/icon.svg +18 -0
- package/index.js +335 -0
- package/lib/adapter.js +422 -0
- package/lib/anthropic-body.js +469 -0
- package/lib/assemble.js +420 -0
- package/lib/captcha/minter.js +654 -0
- package/lib/captcha/sdk-page.js +20 -0
- package/lib/errors.js +125 -0
- package/lib/local-endpoint.js +352 -0
- package/lib/manage-routes.js +489 -0
- package/lib/pinned-model.js +56 -0
- package/lib/plan-client.js +532 -0
- package/lib/pool.js +478 -0
- package/lib/sse.js +317 -0
- package/lib/stream-translator.js +301 -0
- package/lib/text-heuristics.js +35 -0
- package/lib/upstream-api.js +570 -0
- package/lib/upstream.js +134 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +78 -4
- package/scripts/_cdp-inspect.mjs +54 -0
- package/scripts/asar-list.mjs +66 -0
- package/scripts/bench-toks.mjs +138 -0
- package/scripts/check-compat-rc3.mjs +11 -0
- package/scripts/check-data-dir.mjs +31 -0
- package/scripts/restart-dsh.ps1 +76 -0
- package/scripts/run-tests.mjs +68 -0
- package/scripts/smoke-install.mjs +204 -0
- package/scripts/verify_compat.mjs +64 -0
package/lib/upstream.js
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 上游协议常量与请求头构造。
|
|
3
|
+
*
|
|
4
|
+
* 全部取自参考实现 bonus-plan-4-open-zcode(`src/pool/upstream.ts`)的实测结论:
|
|
5
|
+
*
|
|
6
|
+
* | 端点 | 需要 Authorization | 需要 X-Device-Mid |
|
|
7
|
+
* |---|---|---|
|
|
8
|
+
* | GET /api/v1/zcode-plan/billing/balance | 是(缺则 401) | 是(缺则 400 code 3001) |
|
|
9
|
+
* | GET /api/v1/zcode-plan/billing/preview | 否 | 是 |
|
|
10
|
+
* | POST /api/v1/event/report | 否 | 是 |
|
|
11
|
+
* | POST /api/v1/zcode-plan/billing/claim | 是 | 是(另需 captcha 头) |
|
|
12
|
+
* | GET /api/v1/client/configs | 是 | 是 |
|
|
13
|
+
* | POST /api/v1/zcode-plan/anthropic/v1/messages | 是(Bearer zcode_jwt) | 是(captcha 视情况) |
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/** ZCode 平台 origin。 */
|
|
17
|
+
export const ZCODE_ORIGIN = 'https://zcode.z.ai'
|
|
18
|
+
|
|
19
|
+
/** 免费额度通道的 Anthropic Messages 端点(推理主链路)。 */
|
|
20
|
+
export const ZCODE_PLAN_MESSAGES_URL = `${ZCODE_ORIGIN}/api/v1/zcode-plan/anthropic/v1/messages`
|
|
21
|
+
|
|
22
|
+
/** 额度余额。 */
|
|
23
|
+
export const ZCODE_BILLING_BALANCE_URL = `${ZCODE_ORIGIN}/api/v1/zcode-plan/billing/balance`
|
|
24
|
+
|
|
25
|
+
/** 可领活动预览(不需要 Authorization)。 */
|
|
26
|
+
export const ZCODE_BILLING_PREVIEW_URL = `${ZCODE_ORIGIN}/api/v1/zcode-plan/billing/preview`
|
|
27
|
+
|
|
28
|
+
/** 领取活动(需要 Authorization + 一次性 captcha)。 */
|
|
29
|
+
export const ZCODE_BILLING_CLAIM_URL = `${ZCODE_ORIGIN}/api/v1/zcode-plan/billing/claim`
|
|
30
|
+
|
|
31
|
+
/** 客户端活跃上报(不补则 preview 恒为空 plans)。 */
|
|
32
|
+
export const ZCODE_EVENT_REPORT_URL = `${ZCODE_ORIGIN}/api/v1/event/report`
|
|
33
|
+
|
|
34
|
+
/** 客户端配置(captcha 配置 + 模型池)。 */
|
|
35
|
+
export const ZCODE_CLIENT_CONFIGS_URL = `${ZCODE_ORIGIN}/api/v1/client/configs`
|
|
36
|
+
|
|
37
|
+
/** 设备授权流:发起。 */
|
|
38
|
+
export const ZCODE_OAUTH_CLI_INIT_URL = `${ZCODE_ORIGIN}/api/v1/oauth/cli/init`
|
|
39
|
+
|
|
40
|
+
/** 设备授权流:轮询。 */
|
|
41
|
+
export const zcodeOauthCliPollUrl = (flowId) =>
|
|
42
|
+
`${ZCODE_ORIGIN}/api/v1/oauth/cli/poll/${encodeURIComponent(flowId)}`
|
|
43
|
+
|
|
44
|
+
/** 客户端版本兜底值(官方 3.14.3 时代的取值;服务端只当展示/统计用)。 */
|
|
45
|
+
export const ZCODE_APP_VERSION_FALLBACK = '3.14.3'
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* 构造 ZCode 的来源标识请求头。
|
|
49
|
+
*
|
|
50
|
+
* ⚠ `X-Device-Mid` 是 billing/* 与推理端点的硬需求(缺则 400 code 3001),
|
|
51
|
+
* 但**不是账号标识**:同一账号重新登录会换一个,去重必须用 `user_id`。
|
|
52
|
+
*
|
|
53
|
+
* @param {{ device_mid: string, app_version?: string }} credential 凭据(或任何带 device_mid 的对象)
|
|
54
|
+
* @param {{ authorization?: string, json?: boolean, captcha?: { param: string, region: string }, extra?: Record<string,string>, authHeader?: string }} [options]
|
|
55
|
+
* @returns {Record<string, string>}
|
|
56
|
+
*/
|
|
57
|
+
export function buildZcodeHeaders(credential, options = {}) {
|
|
58
|
+
const appVersion = credential.app_version ?? ZCODE_APP_VERSION_FALLBACK
|
|
59
|
+
/** @type {Record<string, string>} */
|
|
60
|
+
const headers = {
|
|
61
|
+
'User-Agent': `ZCode/${appVersion}`,
|
|
62
|
+
'HTTP-Referer': ZCODE_ORIGIN,
|
|
63
|
+
'X-ZCode-App-Version': appVersion,
|
|
64
|
+
'X-Release-Channel': 'stable',
|
|
65
|
+
'X-Client-Language': 'zh-CN',
|
|
66
|
+
'X-Client-Timezone': 'Asia/Shanghai',
|
|
67
|
+
'X-Device-Mid': credential.device_mid,
|
|
68
|
+
'X-Platform': 'win32',
|
|
69
|
+
'X-Os-Category': 'windows',
|
|
70
|
+
'anthropic-version': '2023-06-01',
|
|
71
|
+
}
|
|
72
|
+
if (options.json !== false) headers['Content-Type'] = 'application/json'
|
|
73
|
+
if (options.authorization !== undefined) headers['Authorization'] = options.authorization
|
|
74
|
+
if (options.authHeader !== undefined) headers['Authorization'] = options.authHeader
|
|
75
|
+
if (options.captcha !== undefined) {
|
|
76
|
+
headers['x-aliyun-captcha-verify-param'] = options.captcha.param
|
|
77
|
+
headers['x-aliyun-captcha-verify-region'] = options.captcha.region
|
|
78
|
+
}
|
|
79
|
+
if (options.extra !== undefined) Object.assign(headers, options.extra)
|
|
80
|
+
return headers
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** 生成自用的稳定设备标识。 */
|
|
84
|
+
export function generateDeviceMid() {
|
|
85
|
+
return globalThis.crypto.randomUUID()
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* 把服务端时间戳归一成毫秒。
|
|
90
|
+
*
|
|
91
|
+
* ⚠ 服务端的 `expires_at` 是**秒级**(实测 1790746234);与 `Date.now()` 直接比会
|
|
92
|
+
* 立即判超时。小于 1e12 视为秒。
|
|
93
|
+
*/
|
|
94
|
+
export function toEpochMs(value) {
|
|
95
|
+
if (!Number.isFinite(value) || value <= 0) return 0
|
|
96
|
+
return value < 1e12 ? Math.round(value * 1000) : Math.round(value)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** 下一个 UTC+8 零点(毫秒):免费额度按自然日结算。 */
|
|
100
|
+
export function nextUtc8DayStartMs(now = new Date()) {
|
|
101
|
+
const OFFSET = 8 * 60 * 60 * 1000
|
|
102
|
+
const shifted = now.getTime() + OFFSET
|
|
103
|
+
const dayStartShifted = Math.floor(shifted / 86_400_000) * 86_400_000
|
|
104
|
+
return dayStartShifted + 86_400_000 - OFFSET
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* 兜底模型表(上游 client/configs 不可达时用;数值抄自实测,不是估值)。
|
|
109
|
+
*
|
|
110
|
+
* ⚠ `reasoningLevels` / `defaultReasoningLevel` 与上游目录一致(2026-10-25 实测)。
|
|
111
|
+
* 缺它们时宿主拿到的模型无思考档位元数据:选档即抛 `UNSUPPORTED_REASONING_EFFORT`
|
|
112
|
+
* (UI 报「不支持当前档位」且无输出)—— 这是 0.3.1 修复前「GLM-5.3 思考等级失效」
|
|
113
|
+
* 的直接成因(目录间歇拉取失败 → 兜底表无档位 → 校验拒绝)。
|
|
114
|
+
*/
|
|
115
|
+
export const ZCODE_FALLBACK_MODELS = Object.freeze([
|
|
116
|
+
Object.freeze({
|
|
117
|
+
id: 'GLM-5.3-Flash',
|
|
118
|
+
name: 'GLM-5.3-Flash',
|
|
119
|
+
contextWindow: 1_000_000,
|
|
120
|
+
maxTokens: 128_000,
|
|
121
|
+
supportsImage: true,
|
|
122
|
+
reasoningLevels: ['low', 'high', 'max'],
|
|
123
|
+
defaultReasoningLevel: 'max',
|
|
124
|
+
}),
|
|
125
|
+
Object.freeze({
|
|
126
|
+
id: 'GLM-5.3',
|
|
127
|
+
name: 'GLM-5.3',
|
|
128
|
+
contextWindow: 1_000_000,
|
|
129
|
+
maxTokens: 128_000,
|
|
130
|
+
supportsImage: false,
|
|
131
|
+
reasoningLevels: ['low', 'high', 'max'],
|
|
132
|
+
defaultReasoningLevel: 'max',
|
|
133
|
+
}),
|
|
134
|
+
])
|
package/locale/en.json
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
{
|
|
2
|
+
"meta": {
|
|
3
|
+
"title": "ZCode Start Plan",
|
|
4
|
+
"description": "Route model calls through the ZCode free-plan channel (account:bigmodel-start-plan): multi-account pool, on-demand Aliyun captcha, and automatic account switching on quota exhaustion. Log in with a domestic bigmodel.cn or international z.ai account."
|
|
5
|
+
}
|
|
6
|
+
}
|
package/locale/zh.json
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,80 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-zcode-startplan",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.4.5",
|
|
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.1-rc.3"
|
|
60
|
+
},
|
|
61
|
+
"engines": {
|
|
62
|
+
"node": "^22.19 || >=24"
|
|
63
|
+
},
|
|
64
|
+
"dsh": {
|
|
65
|
+
"id": "dsh-zcode-startplan",
|
|
66
|
+
"name": "ZCode Start Plan",
|
|
67
|
+
"version": "0.4.5",
|
|
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,54 @@
|
|
|
1
|
+
/** 临时诊断:连宿主 CDP,量插件面板里开关与按钮的实际右缘坐标。 */
|
|
2
|
+
const DEBUG_PORT = 9229
|
|
3
|
+
|
|
4
|
+
const list = await (await fetch(`http://127.0.0.1:${DEBUG_PORT}/json/list`)).json()
|
|
5
|
+
const pages = list.filter((t) => t.type === 'page' && String(t.url).startsWith('http://127.0.0.1:'))
|
|
6
|
+
if (pages.length === 0) {
|
|
7
|
+
console.log('NO_PAGE_TARGET', list.map((t) => ({ type: t.type, url: t.url })))
|
|
8
|
+
process.exit(0)
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const expr = `(() => {
|
|
12
|
+
const panel = document.querySelector('.zsp-panel')
|
|
13
|
+
if (!panel) return { present: false, url: location.href }
|
|
14
|
+
const rect = (el) => { const r = el.getBoundingClientRect(); return { left: +r.left.toFixed(1), right: +r.right.toFixed(1), top: +r.top.toFixed(1), width: +r.width.toFixed(1) } }
|
|
15
|
+
const toggles = [...panel.querySelectorAll('.zsp-toggle')].map((t) => ({ ...rect(t), checked: t.querySelector('input')?.checked ?? null }))
|
|
16
|
+
const buttons = [...panel.querySelectorAll('.zsp-actions .zsp-btn')].map((b) => ({ text: b.textContent, ...rect(b) }))
|
|
17
|
+
const spacers = [...panel.querySelectorAll('.zsp-actions .zsp-spacer')].map((s) => ({ ...rect(s), flex: getComputedStyle(s).flex }))
|
|
18
|
+
const css = [...panel.querySelectorAll('style')].map((s) => s.textContent).join('')
|
|
19
|
+
return {
|
|
20
|
+
present: true,
|
|
21
|
+
url: location.href,
|
|
22
|
+
hasGroup: !!panel.querySelector('.zsp-group'),
|
|
23
|
+
hasUnifiedRow: !!panel.querySelector('.zsp-unified'),
|
|
24
|
+
cssHasActionsSpacerRule: css.includes('.zsp-actions .zsp-spacer'),
|
|
25
|
+
cssSpacerFlex: css.includes('flex:1 1 auto'),
|
|
26
|
+
toggles,
|
|
27
|
+
buttons,
|
|
28
|
+
spacers,
|
|
29
|
+
}
|
|
30
|
+
})()`
|
|
31
|
+
|
|
32
|
+
const page = pages[0]
|
|
33
|
+
const ws = new WebSocket(page.webSocketDebuggerUrl)
|
|
34
|
+
const timeout = setTimeout(() => {
|
|
35
|
+
console.log('TIMEOUT waiting for CDP response')
|
|
36
|
+
process.exit(1)
|
|
37
|
+
}, 10_000)
|
|
38
|
+
|
|
39
|
+
await new Promise((resolve, reject) => {
|
|
40
|
+
ws.onopen = resolve
|
|
41
|
+
ws.onerror = (e) => reject(new Error('ws error'))
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
const result = await new Promise((resolve) => {
|
|
45
|
+
ws.onmessage = (ev) => {
|
|
46
|
+
const msg = JSON.parse(ev.data)
|
|
47
|
+
if (msg.id === 1) resolve(msg.result)
|
|
48
|
+
}
|
|
49
|
+
ws.send(JSON.stringify({ id: 1, method: 'Runtime.evaluate', params: { expression: expr, returnByValue: true } }))
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
clearTimeout(timeout)
|
|
53
|
+
ws.close()
|
|
54
|
+
console.log(JSON.stringify(result.result?.value ?? result, null, 2))
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// Minimal asar reader: list or extract a subtree from an Electron asar archive.
|
|
2
|
+
// Usage: node asar-list.mjs <archive> <prefix> [outDir]
|
|
3
|
+
// - no outDir: list entries under prefix
|
|
4
|
+
// - with outDir: extract entries under prefix (incl. unpacked siblings from .unpacked)
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
|
|
8
|
+
const [archive, prefix = '', outDir] = process.argv.slice(2);
|
|
9
|
+
if (!archive) {
|
|
10
|
+
console.error('usage: node asar-list.mjs <archive> [prefix] [outDir]');
|
|
11
|
+
process.exit(1);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const fd = fs.openSync(archive, 'r');
|
|
15
|
+
const pickle = Buffer.alloc(16);
|
|
16
|
+
fs.readSync(fd, pickle, 0, 16, 0);
|
|
17
|
+
const jsonLen = pickle.readUInt32LE(12);
|
|
18
|
+
const jsonBuf = Buffer.alloc(jsonLen);
|
|
19
|
+
fs.readSync(fd, jsonBuf, 0, jsonLen, 16);
|
|
20
|
+
const header = JSON.parse(jsonBuf.toString('utf8'));
|
|
21
|
+
const baseOffset = 16 + jsonLen;
|
|
22
|
+
|
|
23
|
+
function walk(node, rel, cb) {
|
|
24
|
+
if (node.files) {
|
|
25
|
+
for (const [name, child] of Object.entries(node.files)) walk(child, rel ? rel + '/' + name : name, cb);
|
|
26
|
+
} else if (node.unpacked) {
|
|
27
|
+
cb(rel, null, true);
|
|
28
|
+
} else {
|
|
29
|
+
cb(rel, { offset: baseOffset + Number(node.offset), size: node.size }, false);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
if (outDir) {
|
|
34
|
+
fs.mkdirSync(outDir, { recursive: true });
|
|
35
|
+
walk(header, '', (rel, file, unpacked) => {
|
|
36
|
+
if (!(rel === prefix || rel.startsWith(prefix + '/'))) return;
|
|
37
|
+
const relInside = rel === prefix ? '' : rel.slice(prefix.length + 1);
|
|
38
|
+
if (!relInside) return;
|
|
39
|
+
const dest = path.join(outDir, relInside);
|
|
40
|
+
if (unpacked) {
|
|
41
|
+
const src = path.join(path.dirname(archive), path.basename(archive) + '.unpacked', rel);
|
|
42
|
+
if (fs.existsSync(src)) {
|
|
43
|
+
if (fs.statSync(src).isDirectory()) fs.cpSync(src, dest, { recursive: true });
|
|
44
|
+
else {
|
|
45
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
46
|
+
fs.copyFileSync(src, dest);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
if (!file) return;
|
|
52
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
53
|
+
const buf = Buffer.alloc(file.size);
|
|
54
|
+
fs.readSync(fd, buf, 0, file.size, file.offset);
|
|
55
|
+
fs.writeFileSync(dest, buf);
|
|
56
|
+
});
|
|
57
|
+
console.log('extracted ' + prefix + ' to ' + outDir);
|
|
58
|
+
} else {
|
|
59
|
+
const entries = [];
|
|
60
|
+
walk(header, '', (rel, file, unpacked) => {
|
|
61
|
+
if (rel === prefix || rel.startsWith(prefix + '/')) {
|
|
62
|
+
entries.push((unpacked ? 'U ' : file ? 'F ' : 'D ') + rel);
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
console.log(entries.join('\n'));
|
|
66
|
+
}
|
|
@@ -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,11 @@
|
|
|
1
|
+
// 用宿主自带的 evaluatePluginCompatibility 校验本插件 manifest(rc.2 / rc.3 / 0.3.0)。
|
|
2
|
+
import { readFileSync } from 'node:fs'
|
|
3
|
+
import { pathToFileURL } from 'node:url'
|
|
4
|
+
|
|
5
|
+
const host = pathToFileURL(process.cwd() + '/.tmp-dsh-extract-full/node_modules/@deepseek-ai/dsh-app-boot/lib/index.js').href
|
|
6
|
+
const m = await import(host)
|
|
7
|
+
const pkg = JSON.parse(readFileSync(process.cwd() + '/package.json', 'utf8'))
|
|
8
|
+
for (const rv of ['0.2.1-rc.2', '0.2.1-rc.3', '0.3.0']) {
|
|
9
|
+
const issue = m.evaluatePluginCompatibility(pkg, {}, rv)
|
|
10
|
+
console.log(rv, '=>', issue === undefined ? 'COMPATIBLE' : JSON.stringify(issue.requirements))
|
|
11
|
+
}
|
|
@@ -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
|
+
}
|