dsh-zcode-startplan 0.4.5 → 1.0.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/CHANGELOG.md +1963 -405
- package/README.md +88 -405
- package/bin/cli.mjs +509 -450
- package/client.js +2459 -716
- package/cordis.patch.yml +4 -2
- package/index.js +144 -14
- package/lib/adapter.js +476 -422
- package/lib/anthropic-body.js +513 -469
- package/lib/assemble.js +808 -420
- package/lib/auto-claim.js +229 -0
- package/lib/captcha/minter.js +61 -7
- package/lib/distribution-keys.js +202 -0
- package/lib/errors.js +281 -125
- package/lib/fallback.js +120 -0
- package/lib/local-endpoint.js +367 -352
- package/lib/manage-routes.js +1245 -489
- package/lib/model-catalog.js +57 -0
- package/lib/openai-gateway.js +776 -0
- package/lib/plan-client.js +942 -532
- package/lib/pool.js +771 -478
- package/lib/sse.js +429 -317
- package/lib/upstream-api.js +948 -570
- package/lib/upstream.js +294 -134
- package/lib/version-probe.js +110 -0
- package/package.json +84 -80
- package/scripts/analyze-grant-intervals.mjs +171 -0
- package/scripts/check-compat-rc3.mjs +21 -11
- package/scripts/debug-claimable.mjs +130 -0
- package/scripts/probe-marketing.mjs +203 -0
- package/scripts/restart-dsh.ps1 +119 -76
- package/scripts/test-claimed-pending.mjs +152 -0
- package/scripts/verify_compat.mjs +75 -64
- package/scripts/watch-marketing.mjs +155 -0
- package/tests/anthropic-body.test.mjs +305 -0
- package/tests/assembler-contract.test.mjs +256 -0
- package/tests/auto-claim.test.mjs +318 -0
- package/tests/claim-routes.test.mjs +438 -0
- package/tests/client-panel.test.mjs +1141 -0
- package/tests/distribution-keys.test.mjs +123 -0
- package/tests/e2e.test.mjs +388 -0
- package/tests/fallback-scrub.test.mjs +105 -0
- package/tests/fixtures/quota-200.json +1 -0
- package/tests/launch-command.test.mjs +68 -0
- package/tests/login-channel.test.mjs +102 -0
- package/tests/openai-gateway.test.mjs +454 -0
- package/tests/pinned-models.test.mjs +505 -0
- package/tests/plan-client.test.mjs +582 -0
- package/tests/pool.test.mjs +319 -0
- package/tests/quota-blackhole.test.mjs +409 -0
- package/tests/restart-script.test.mjs +53 -0
- package/tests/routing-quota.test.mjs +251 -0
- package/tests/sse.test.mjs +86 -0
- package/tests/stream-translator.test.mjs +137 -0
- package/tests/support/hanging-stream.mjs +48 -0
- package/tests/support/resolve-profile-deps.mjs +52 -0
- package/tests/upstream-error-200.test.mjs +164 -0
- package/tests/upstream.test.mjs +330 -0
- package/tests/version-probe.test.mjs +172 -0
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 「开调试端口」指引文案的契约测试。
|
|
3
|
+
*
|
|
4
|
+
* ## 背景(2026-11-02 报障)
|
|
5
|
+
*
|
|
6
|
+
* 面板 tooltip / status 工具 / 领取失败三处共用 `CaptchaMinter.probe()` 的
|
|
7
|
+
* reason 串,而它原文只写了「请以 --remote-debugging-port 启动 DSH 桌面端」:
|
|
8
|
+
* 没给可复制的一行、没提「必须先退出旧实例」(单实例锁会让参数静默失效)、
|
|
9
|
+
* 也没提 PowerShell 的 `&` 前缀(漏了必报「意外的标记 remote-debugging-port」)。
|
|
10
|
+
*
|
|
11
|
+
* 这些用例锁住三件事:
|
|
12
|
+
* 1. 命令必须是**绝对路径**(插件 cwd 是工作区,相对路径必错);
|
|
13
|
+
* 2. 命令必须带 `&` 调用运算符(否则 PowerShell 只把它当字符串输出);
|
|
14
|
+
* 3. 探不到安装位置时返回**占位符**,绝不猜一个会误跑的路径。
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import test from 'node:test'
|
|
18
|
+
import assert from 'node:assert/strict'
|
|
19
|
+
import { isAbsolute, win32 } from 'node:path'
|
|
20
|
+
|
|
21
|
+
import { CaptchaMinter, launchCommand } from '../lib/captcha/minter.js'
|
|
22
|
+
|
|
23
|
+
test('launchCommand: 命中的安装路径必须是绝对路径(插件 cwd 在工作区,相对路径必错)', () => {
|
|
24
|
+
const command = launchCommand(9229)
|
|
25
|
+
const match = /^& "(.+)" --remote-debugging-port=9229$/.exec(command)
|
|
26
|
+
assert.ok(match, `命令形状不对:${command}`)
|
|
27
|
+
const exe = match[1]
|
|
28
|
+
const absolute = isAbsolute(exe) || (process.platform === 'win32' && win32.isAbsolute(exe))
|
|
29
|
+
assert.ok(absolute, `安装路径必须是绝对路径,实际:${exe}`)
|
|
30
|
+
assert.match(exe, /DeepSeek Harness\.exe$/, '必须以宿主 exe 结尾')
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
test('launchCommand: 前缀 & 必须在(漏了 PowerShell 会报「意外的标记 remote-debugging-port」)', () => {
|
|
34
|
+
const command = launchCommand(9229, () => false)
|
|
35
|
+
assert.ok(command.startsWith('& "'), `必须以 & 开头,实际:${command}`)
|
|
36
|
+
assert.match(command, /--remote-debugging-port=9229$/, '端口要跟着参数走,不能是硬编码 9229')
|
|
37
|
+
assert.match(launchCommand(9333, () => false), /--remote-debugging-port=9333$/, '端口要透传')
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
test('launchCommand: 探不到安装位置时给占位符,不猜路径', () => {
|
|
41
|
+
const command = launchCommand(9229, () => false)
|
|
42
|
+
assert.match(command, /<DSH 安装路径>/, '探不到就给占位符,让用户补全')
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
test('launchCommand: exists 抛错也不炸(权限/盘点失败按「未命中」处理)', () => {
|
|
46
|
+
const command = launchCommand(9229, () => {
|
|
47
|
+
throw new Error('EACCES')
|
|
48
|
+
})
|
|
49
|
+
assert.match(command, /<DSH 安装路径>/, '探测失败退化为占位符,不能抛')
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
test('probe 原因串:连不上端口时必须自带可复制的启动命令与「先退出旧实例」', async () => {
|
|
53
|
+
const minter = new CaptchaMinter({
|
|
54
|
+
debugPort: 19999,
|
|
55
|
+
fetchImpl: async () => {
|
|
56
|
+
throw new Error('fetch failed')
|
|
57
|
+
},
|
|
58
|
+
})
|
|
59
|
+
const outcome = await minter.probe()
|
|
60
|
+
assert.equal(outcome.ok, false)
|
|
61
|
+
const reason = outcome.reason
|
|
62
|
+
assert.match(reason, /127\.0\.0\.1:19999/, '要指明探测的是哪个端口')
|
|
63
|
+
assert.match(reason, /--remote-debugging-port=19999/, '要给出带正确端口的可复制命令')
|
|
64
|
+
assert.match(reason, /& "/, 'PowerShell 调用运算符不能省')
|
|
65
|
+
assert.match(reason, /退出/, '必须提示先退出旧实例(单实例锁会吞掉参数)')
|
|
66
|
+
assert.match(reason, /manual/, '要给出不走 CDP 的出口')
|
|
67
|
+
assert.doesNotMatch(reason, /fetch failed/, '不把底层异常原文抛给用户')
|
|
68
|
+
})
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 登录渠道(国内 智谱 / 国际 Z.AI)的归一化与配置校验。
|
|
3
|
+
*
|
|
4
|
+
* 依据(实测 2026-10-23):两条渠道共用同一个 `oauth/cli/init` 协议,
|
|
5
|
+
* 只在 `provider` 与授权站点上不同;非法 provider 返回 500 code=1000。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import test from 'node:test'
|
|
9
|
+
import assert from 'node:assert/strict'
|
|
10
|
+
|
|
11
|
+
import {
|
|
12
|
+
DEFAULT_LOGIN_CHANNEL,
|
|
13
|
+
LOGIN_CHANNELS,
|
|
14
|
+
normalizeLoginChannel,
|
|
15
|
+
resolveLoginChannel,
|
|
16
|
+
} from '../lib/upstream-api.js'
|
|
17
|
+
import { Config } from '../index.js'
|
|
18
|
+
|
|
19
|
+
test('默认渠道是国内站', () => {
|
|
20
|
+
assert.equal(DEFAULT_LOGIN_CHANNEL, 'bigmodel')
|
|
21
|
+
assert.equal(normalizeLoginChannel(undefined), 'bigmodel')
|
|
22
|
+
assert.equal(normalizeLoginChannel(''), 'bigmodel')
|
|
23
|
+
assert.equal(normalizeLoginChannel(' '), 'bigmodel')
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
test('国内渠道的别名(含中文与我自己的简写 cn)', () => {
|
|
27
|
+
for (const input of ['bigmodel', 'cn', 'china', 'domestic', '国内', '智谱', 'CN', 'BigModel']) {
|
|
28
|
+
assert.equal(normalizeLoginChannel(input), 'bigmodel', input)
|
|
29
|
+
}
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
test('国际渠道的别名(含中文与我自己的简写 intl)', () => {
|
|
33
|
+
for (const input of ['zai', 'z-ai', 'intl', 'international', 'global', '国际', '海外', 'ZAI', 'INTL']) {
|
|
34
|
+
assert.equal(normalizeLoginChannel(input), 'zai', input)
|
|
35
|
+
}
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
test('非法渠道回退默认,不抛错(避免把用户挡住)', () => {
|
|
39
|
+
assert.equal(normalizeLoginChannel('bigmodel-intl'), 'bigmodel')
|
|
40
|
+
assert.equal(normalizeLoginChannel('openai'), 'bigmodel')
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
test('渠道描述:provider 是上游真实取值,站点与 API Key 地址不同', () => {
|
|
44
|
+
const cn = resolveLoginChannel('cn')
|
|
45
|
+
const intl = resolveLoginChannel('intl')
|
|
46
|
+
assert.equal(cn.provider, 'bigmodel')
|
|
47
|
+
assert.equal(intl.provider, 'zai')
|
|
48
|
+
assert.equal(cn.site, 'bigmodel.cn')
|
|
49
|
+
assert.equal(intl.site, 'z.ai')
|
|
50
|
+
assert.notEqual(cn.apiKeyUrl, intl.apiKeyUrl)
|
|
51
|
+
assert.match(cn.label, /国内/)
|
|
52
|
+
assert.match(intl.label, /国际/)
|
|
53
|
+
/** 上游只认这两个 provider 值。 */
|
|
54
|
+
assert.deepEqual(Object.keys(LOGIN_CHANNELS).sort(), ['bigmodel', 'zai'])
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
test('Config 是 schemastery 原生 schema(DSH 用 isNativeConfigSchema 判定)', () => {
|
|
58
|
+
/** 与宿主 `isNativeConfigSchema` 完全同构的判据。 */
|
|
59
|
+
const meta = Reflect.get(Config, 'meta')
|
|
60
|
+
assert.equal(Reflect.get(Config, Symbol.for('schemastery')), true)
|
|
61
|
+
assert.equal(typeof Reflect.get(Config, 'type'), 'string')
|
|
62
|
+
assert.equal(typeof meta, 'object')
|
|
63
|
+
assert.notEqual(meta, null)
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
test('Config 校验:channel 只接受 cn/intl 及其别名', () => {
|
|
67
|
+
const accept = (value) => {
|
|
68
|
+
try {
|
|
69
|
+
Config({ channel: value })
|
|
70
|
+
return true
|
|
71
|
+
} catch {
|
|
72
|
+
return false
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
for (const good of ['cn', 'intl', 'bigmodel', 'zai', '国内', '国际']) {
|
|
76
|
+
assert.equal(accept(good), true, `应接受 ${good}`)
|
|
77
|
+
}
|
|
78
|
+
for (const bad of ['bigmodel-intl', 'openai', ' ', 'z-ai-x']) {
|
|
79
|
+
assert.equal(accept(bad), false, `应拒绝 ${bad}`)
|
|
80
|
+
}
|
|
81
|
+
})
|
|
82
|
+
|
|
83
|
+
test('Config 校验:默认 channel 是 cn,且未写时也补齐', () => {
|
|
84
|
+
assert.equal(Config({}).channel, 'cn')
|
|
85
|
+
/** 覆盖值原样生效。 */
|
|
86
|
+
assert.equal(Config({ channel: 'intl' }).channel, 'intl')
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
test('Config 其余字段:默认值补齐 + 非法值报错', () => {
|
|
90
|
+
const defaults = Config({})
|
|
91
|
+
assert.deepEqual(defaults.models, ['GLM-5.3-Flash', 'GLM-5.3'])
|
|
92
|
+
assert.deepEqual(defaults.captcha, { mode: 'cdp', debugPort: 9229, origin: 'https://zcode.z.ai/' })
|
|
93
|
+
assert.deepEqual(defaults.endpoint, { enabled: false, port: 17899 })
|
|
94
|
+
assert.equal(defaults.statusTool, true)
|
|
95
|
+
assert.equal(defaults.provider, 'zcode-start-plan')
|
|
96
|
+
|
|
97
|
+
assert.throws(() => Config({ captcha: { mode: 'browser' } }))
|
|
98
|
+
assert.throws(() => Config({ captcha: { debugPort: 0 } }))
|
|
99
|
+
assert.throws(() => Config({ models: 'GLM' }))
|
|
100
|
+
assert.equal(Config({ captcha: { debugPort: 9333 } }).captcha.debugPort, 9333)
|
|
101
|
+
})
|
|
102
|
+
|
|
@@ -0,0 +1,454 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 本地 OpenAI 兼容端点(`lib/openai-gateway.js`)的纯函数契约。
|
|
3
|
+
*
|
|
4
|
+
* 覆盖的都是**参考实现用真机流量换来的坑**,每一条都对应一个真实故障:
|
|
5
|
+
*
|
|
6
|
+
* | 用例 | 对应故障 |
|
|
7
|
+
* |---|---|
|
|
8
|
+
* | `null` 的 content/reasoning 不崩 | 真实 SSE 里两者永远一侧为 null ⇒ 首帧 `Cannot read properties of null` |
|
|
9
|
+
* | 空 `function.name` 不覆盖已有名字 | 后续分片带空串 → `unknown tool ""` |
|
|
10
|
+
* | 孤儿 tool 结果被剔除 | 坏历史每轮原样重放 ⇒ 会话永久 400 |
|
|
11
|
+
* | 同 id 有可用调用时结果**保留** | 只看 dropped 会把好调用的回执误删 ⇒ 孤儿 tool-call |
|
|
12
|
+
* | 空 assistant 整条剔除 | 变 wire 上的开头发言 ⇒ 上游 `model_param_invalid` |
|
|
13
|
+
* | `{status:200}` 的门禁 | 业务失败被读成成功 |
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import test from 'node:test'
|
|
17
|
+
import assert from 'node:assert/strict'
|
|
18
|
+
|
|
19
|
+
import {
|
|
20
|
+
collectChatCompletion,
|
|
21
|
+
contentToText,
|
|
22
|
+
toGenerateOptions,
|
|
23
|
+
toOpenAiSse,
|
|
24
|
+
} from '../lib/openai-gateway.js'
|
|
25
|
+
|
|
26
|
+
/** 把异步生成器收成数组。 */
|
|
27
|
+
async function drain(iter) {
|
|
28
|
+
const out = []
|
|
29
|
+
for await (const item of iter) out.push(item)
|
|
30
|
+
return out
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** SSE 行 → 解析后的 JSON 对象数组(跳过 [DONE])。 */
|
|
34
|
+
function parseSse(lines) {
|
|
35
|
+
return lines
|
|
36
|
+
.map((line) => line.replace(/^data: /, '').replace(/\n\n$/, ''))
|
|
37
|
+
.filter((payload) => payload !== '[DONE]')
|
|
38
|
+
.map((payload) => JSON.parse(payload))
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// ── 请求侧 ─────────────────────────────────────────────────────────────────
|
|
42
|
+
|
|
43
|
+
test('toGenerateOptions: system/user/assistant 基本映射', () => {
|
|
44
|
+
const options = toGenerateOptions({
|
|
45
|
+
model: 'GLM-5.3',
|
|
46
|
+
messages: [
|
|
47
|
+
{ role: 'system', content: '你是助手' },
|
|
48
|
+
{ role: 'user', content: '你好' },
|
|
49
|
+
{ role: 'assistant', content: '你好呀' },
|
|
50
|
+
{ role: 'user', content: '继续' },
|
|
51
|
+
],
|
|
52
|
+
max_tokens: 1024,
|
|
53
|
+
temperature: 0.3,
|
|
54
|
+
})
|
|
55
|
+
assert.equal(options.maxTokens, 1024)
|
|
56
|
+
assert.equal(options.temperature, 0.3)
|
|
57
|
+
assert.deepEqual(options.messages[0], { role: 'system', content: [{ type: 'text', text: '你是助手' }] })
|
|
58
|
+
assert.deepEqual(options.messages[1], { role: 'user', content: [{ type: 'text', text: '你好' }] })
|
|
59
|
+
assert.deepEqual(options.messages[2], { role: 'assistant', content: [{ type: 'text', text: '你好呀' }] })
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
test('toGenerateOptions: 空 messages / 非法 tool_choice 被拒', () => {
|
|
63
|
+
assert.throws(() => toGenerateOptions({ messages: [] }), /non-empty/)
|
|
64
|
+
assert.throws(() => toGenerateOptions({}), /non-empty/)
|
|
65
|
+
assert.throws(
|
|
66
|
+
() => toGenerateOptions({ messages: [{ role: 'user', content: 'x' }], tool_choice: 'required' }),
|
|
67
|
+
/only tool_choice auto and none/,
|
|
68
|
+
)
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
test('toGenerateOptions: tool_choice none 与 tools 同时出现被拒(DSH 表达不出)', () => {
|
|
72
|
+
assert.throws(
|
|
73
|
+
() => toGenerateOptions({
|
|
74
|
+
messages: [{ role: 'user', content: 'x' }],
|
|
75
|
+
tool_choice: 'none',
|
|
76
|
+
tools: [{ type: 'function', function: { name: 'read', parameters: {} } }],
|
|
77
|
+
}),
|
|
78
|
+
/cannot be represented/,
|
|
79
|
+
)
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
test('toGenerateOptions: 工具定义转 ToolSchema;非 function 类型跳过', () => {
|
|
83
|
+
const options = toGenerateOptions({
|
|
84
|
+
messages: [{ role: 'user', content: 'x' }],
|
|
85
|
+
tools: [
|
|
86
|
+
{ type: 'function', function: { name: 'read', description: '读文件', parameters: { type: 'object' } } },
|
|
87
|
+
{ type: 'web_search' },
|
|
88
|
+
],
|
|
89
|
+
})
|
|
90
|
+
assert.deepEqual(options.tools, [{ name: 'read', description: '读文件', parameters: { type: 'object' } }])
|
|
91
|
+
})
|
|
92
|
+
|
|
93
|
+
test('toGenerateOptions: assistant.tool_calls 与 tool 结果配对成 DSH 块', () => {
|
|
94
|
+
const options = toGenerateOptions({
|
|
95
|
+
messages: [
|
|
96
|
+
{ role: 'user', content: '看下文件' },
|
|
97
|
+
{
|
|
98
|
+
role: 'assistant',
|
|
99
|
+
content: null,
|
|
100
|
+
tool_calls: [{ id: 'call_1', type: 'function', function: { name: 'read', arguments: '{"p":"a.txt"}' } }],
|
|
101
|
+
},
|
|
102
|
+
{ role: 'tool', tool_call_id: 'call_1', content: '文件内容' },
|
|
103
|
+
],
|
|
104
|
+
})
|
|
105
|
+
assert.deepEqual(options.messages[1], {
|
|
106
|
+
role: 'assistant',
|
|
107
|
+
content: [{ type: 'tool-call', id: 'call_1', name: 'read', arguments: '{"p":"a.txt"}' }],
|
|
108
|
+
})
|
|
109
|
+
assert.deepEqual(options.messages[2], {
|
|
110
|
+
role: 'user',
|
|
111
|
+
content: [{ type: 'tool-result', toolCallId: 'call_1', content: [{ type: 'text', text: '文件内容' }] }],
|
|
112
|
+
})
|
|
113
|
+
})
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* ⚠ 真实故障(参考实现 issue IKLRIK):历史里 `function.name: ""` 的调用会被客户端
|
|
117
|
+
* **每轮原样重放**。网关若回 400,整条会话永久不可用(用户没法自愈)。
|
|
118
|
+
* 正确做法:剔除坏调用 + 剔除它的孤儿结果,会话自愈。
|
|
119
|
+
*/
|
|
120
|
+
test('toGenerateOptions: 名字为空的 tool_call 被剔除,其孤儿结果一并剔除', () => {
|
|
121
|
+
const options = toGenerateOptions({
|
|
122
|
+
messages: [
|
|
123
|
+
{ role: 'user', content: 'x' },
|
|
124
|
+
{ role: 'assistant', content: '我来调用', tool_calls: [{ id: 'bad', type: 'function', function: { name: '', arguments: '{}' } }] },
|
|
125
|
+
{ role: 'tool', tool_call_id: 'bad', content: 'No such tool' },
|
|
126
|
+
{ role: 'user', content: 'y' },
|
|
127
|
+
],
|
|
128
|
+
})
|
|
129
|
+
/** assistant 正文保留(那是用户真看到的内容),坏调用没了。 */
|
|
130
|
+
assert.deepEqual(options.messages[1], { role: 'assistant', content: [{ type: 'text', text: '我来调用' }] })
|
|
131
|
+
/** 孤儿结果整条剔除。 */
|
|
132
|
+
/** user(0) / assistant(1) / user(3) —— 孤儿 tool 与坏调用都没了。 */
|
|
133
|
+
assert.equal(options.messages.length, 3, 'user + assistant(正文保留) + user')
|
|
134
|
+
assert.ok(!options.messages.some((m) => JSON.stringify(m).includes('"bad"')))
|
|
135
|
+
})
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* ⚠ 同一 id 上既有坏调用又有好调用时,结果必须**保留** —— 否则好调用变孤儿,
|
|
139
|
+
* 上游照样 400(参考实现对抗审计实测打穿的第一版修法)。
|
|
140
|
+
*/
|
|
141
|
+
test('toGenerateOptions: 同 id 存在可用调用时,该 id 的工具结果必须保留', () => {
|
|
142
|
+
const options = toGenerateOptions({
|
|
143
|
+
messages: [
|
|
144
|
+
{ role: 'user', content: 'x' },
|
|
145
|
+
{
|
|
146
|
+
role: 'assistant',
|
|
147
|
+
content: '两批',
|
|
148
|
+
tool_calls: [
|
|
149
|
+
{ id: 'dup', type: 'function', function: { name: '', arguments: '{}' } },
|
|
150
|
+
{ id: 'dup', type: 'function', function: { name: 'read', arguments: '{}' } },
|
|
151
|
+
],
|
|
152
|
+
},
|
|
153
|
+
{ role: 'tool', tool_call_id: 'dup', content: '结果' },
|
|
154
|
+
],
|
|
155
|
+
})
|
|
156
|
+
assert.ok(
|
|
157
|
+
options.messages.some((m) => JSON.stringify(m).includes('"tool-result"')),
|
|
158
|
+
'该 id 上还有可用调用 ⇒ 结果必须留下',
|
|
159
|
+
)
|
|
160
|
+
})
|
|
161
|
+
|
|
162
|
+
test('toGenerateOptions: 正文为空的 assistant 且调用被剔光 ⇒ 整条剔除', () => {
|
|
163
|
+
const options = toGenerateOptions({
|
|
164
|
+
messages: [
|
|
165
|
+
{ role: 'user', content: 'x' },
|
|
166
|
+
{ role: 'assistant', content: '', tool_calls: [{ id: 'bad', type: 'function', function: { name: ' ', arguments: '{}' } }] },
|
|
167
|
+
],
|
|
168
|
+
})
|
|
169
|
+
assert.equal(options.messages.length, 1, '空 assistant 会造成 wire 上的空开头发言')
|
|
170
|
+
})
|
|
171
|
+
|
|
172
|
+
test('toGenerateOptions: tool 消息缺 tool_call_id 报错(真形状错误不该被吞)', () => {
|
|
173
|
+
assert.throws(
|
|
174
|
+
() => toGenerateOptions({ messages: [{ role: 'user', content: 'x' }, { role: 'tool', content: 'y' }] }),
|
|
175
|
+
/require tool_call_id/,
|
|
176
|
+
)
|
|
177
|
+
})
|
|
178
|
+
|
|
179
|
+
test('toGenerateOptions: user 多模态图片转 image 块', () => {
|
|
180
|
+
const options = toGenerateOptions({
|
|
181
|
+
messages: [{
|
|
182
|
+
role: 'user',
|
|
183
|
+
content: [
|
|
184
|
+
{ type: 'text', text: '看图' },
|
|
185
|
+
{ type: 'image_url', image_url: { url: 'data:image/png;base64,AAA' } },
|
|
186
|
+
],
|
|
187
|
+
}],
|
|
188
|
+
})
|
|
189
|
+
assert.deepEqual(options.messages[0].content, [
|
|
190
|
+
{ type: 'text', text: '看图' },
|
|
191
|
+
{ type: 'image', url: 'data:image/png;base64,AAA' },
|
|
192
|
+
])
|
|
193
|
+
})
|
|
194
|
+
|
|
195
|
+
test('contentToText: 字符串直通,块数组只拼 text', () => {
|
|
196
|
+
assert.equal(contentToText('hi'), 'hi')
|
|
197
|
+
assert.equal(contentToText([{ type: 'text', text: 'a' }, { type: 'image_url', image_url: {} }]), 'a')
|
|
198
|
+
assert.equal(contentToText(null), '')
|
|
199
|
+
assert.equal(contentToText(undefined), '')
|
|
200
|
+
})
|
|
201
|
+
|
|
202
|
+
// ── 响应侧 ─────────────────────────────────────────────────────────────────
|
|
203
|
+
|
|
204
|
+
test('toOpenAiSse: text-delta → content 帧;finish 带 finish_reason', async () => {
|
|
205
|
+
const chunks = [
|
|
206
|
+
{ type: 'text-delta', index: 0, text: '你' },
|
|
207
|
+
{ type: 'text-delta', index: 0, text: '好' },
|
|
208
|
+
{ type: 'usage', usage: { inputTokens: 10, outputTokens: 2 } },
|
|
209
|
+
{ type: 'finish', reason: { kind: 'stop' } },
|
|
210
|
+
]
|
|
211
|
+
const frames = parseSse(await drain(toOpenAiSse(chunks, 'chatcmpl-x', 'GLM-5.3')))
|
|
212
|
+
assert.equal(frames[0].object, 'chat.completion.chunk')
|
|
213
|
+
assert.deepEqual(frames[0].choices[0].delta, { content: '你' })
|
|
214
|
+
assert.deepEqual(frames[1].choices[0].delta, { content: '好' })
|
|
215
|
+
/** finish 帧在 usage 帧**之前**发出(usage 是独立的收尾帧,choices 为空)。 */
|
|
216
|
+
const finishFrame = frames.find((f) => f.choices?.[0]?.finish_reason === 'stop')
|
|
217
|
+
assert.ok(finishFrame, '必须有 finish_reason=stop 的帧')
|
|
218
|
+
/** 用量作为独立一帧(choices 为空)。 */
|
|
219
|
+
const usageFrame = frames.find((f) => f.usage !== undefined)
|
|
220
|
+
assert.equal(usageFrame.usage.prompt_tokens, 10)
|
|
221
|
+
assert.equal(usageFrame.usage.completion_tokens, 2)
|
|
222
|
+
assert.equal(usageFrame.usage.total_tokens, 12)
|
|
223
|
+
})
|
|
224
|
+
|
|
225
|
+
test('toOpenAiSse: reasoning-delta → reasoning_content(不是 reasoning)', async () => {
|
|
226
|
+
const frames = parseSse(await drain(toOpenAiSse(
|
|
227
|
+
[{ type: 'reasoning-delta', index: 0, text: '想想' }, { type: 'finish', reason: { kind: 'stop' } }],
|
|
228
|
+
'id', 'm',
|
|
229
|
+
)))
|
|
230
|
+
assert.deepEqual(frames[0].choices[0].delta, { reasoning_content: '想想' })
|
|
231
|
+
assert.equal(frames[0].choices[0].delta.reasoning, undefined, '两边同时发会让部分客户端重复渲染')
|
|
232
|
+
})
|
|
233
|
+
|
|
234
|
+
test('toOpenAiSse: 工具分片带空 name 不清空已解析的名字', async () => {
|
|
235
|
+
const frames = parseSse(await drain(toOpenAiSse([
|
|
236
|
+
{ type: 'tool-call-delta', index: 0, id: 'c1', name: 'read', argumentsDelta: '{"p"' },
|
|
237
|
+
/** 后续分片 name 为空串 —— 真实上游会这样。 */
|
|
238
|
+
{ type: 'tool-call-delta', index: 0, id: 'c1', name: '', argumentsDelta: ':1}' },
|
|
239
|
+
{ type: 'finish', reason: { kind: 'tool-calls' } },
|
|
240
|
+
], 'id', 'm')))
|
|
241
|
+
assert.equal(frames[0].choices[0].delta.tool_calls[0].function.name, 'read')
|
|
242
|
+
assert.equal(frames[1].choices[0].delta.tool_calls[0].function.name, 'read', '空串不得覆盖')
|
|
243
|
+
assert.equal(frames.at(-1).choices[0].finish_reason, 'tool_calls')
|
|
244
|
+
})
|
|
245
|
+
|
|
246
|
+
test('toOpenAiSse: 上游错误帧 + 不抛异常', async () => {
|
|
247
|
+
const frames = parseSse(await drain(toOpenAiSse(
|
|
248
|
+
[{ type: 'finish', reason: { kind: 'error', failure: { message: '额度用尽', code: 'QUOTA', status: 429 } } }],
|
|
249
|
+
'id', 'm',
|
|
250
|
+
)))
|
|
251
|
+
assert.equal(frames.length, 1)
|
|
252
|
+
assert.equal(frames[0].choices.length, 0)
|
|
253
|
+
assert.equal(frames[0].error.message, '额度用尽')
|
|
254
|
+
})
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* ⚠ finish 门禁的**流式侧**(0.9.7 补齐,与非流式 collectChatCompletion 同口径):
|
|
258
|
+
* 流结束但没收到 finish chunk = 上游半截断开。此时发 usage/[DONE] 会让客户端
|
|
259
|
+
* 把半截输出当完整结果持久化 —— 必须发 error chunk 且不发 usage 帧。
|
|
260
|
+
*/
|
|
261
|
+
test('toOpenAiSse: 流缺 finish 时发 error 帧,不发 usage/[DONE] 假装成功', async () => {
|
|
262
|
+
const frames = parseSse(await drain(toOpenAiSse(
|
|
263
|
+
[{ type: 'text-delta', index: 0, text: '半截' }, { type: 'usage', usage: { inputTokens: 1, outputTokens: 1 } }],
|
|
264
|
+
'id', 'm',
|
|
265
|
+
)))
|
|
266
|
+
assert.equal(frames.length, 2, 'text-delta 一帧 + error 一帧,无 usage 帧')
|
|
267
|
+
assert.equal(frames[0].choices[0].delta.content, '半截')
|
|
268
|
+
assert.equal(frames[1].choices.length, 0)
|
|
269
|
+
assert.match(frames[1].error.message, /ended before finish/)
|
|
270
|
+
assert.equal(frames[1].error.code, 'upstream_error')
|
|
271
|
+
})
|
|
272
|
+
|
|
273
|
+
test('collectChatCompletion: 折叠成 chat.completion(content + tool_calls + usage)', async () => {
|
|
274
|
+
const payload = await collectChatCompletion([
|
|
275
|
+
{ type: 'text-delta', index: 0, text: '答' },
|
|
276
|
+
{ type: 'tool-call-delta', index: 1, id: 'c1', name: 'read', argumentsDelta: '{"p":1}' },
|
|
277
|
+
{ type: 'usage', usage: { inputTokens: 5, outputTokens: 3, cachedInputTokens: 2 } },
|
|
278
|
+
{ type: 'finish', reason: { kind: 'tool-calls' } },
|
|
279
|
+
], 'chatcmpl-y', 'GLM-5.3')
|
|
280
|
+
assert.equal(payload.object, 'chat.completion')
|
|
281
|
+
assert.equal(payload.choices[0].message.content, '答')
|
|
282
|
+
assert.equal(payload.choices[0].finish_reason, 'tool_calls')
|
|
283
|
+
assert.deepEqual(payload.choices[0].message.tool_calls, [
|
|
284
|
+
{ id: 'c1', type: 'function', function: { name: 'read', arguments: '{"p":1}' } },
|
|
285
|
+
])
|
|
286
|
+
assert.equal(payload.usage.prompt_tokens_details.cached_tokens, 2)
|
|
287
|
+
assert.equal(payload.usage.prompt_cache_hit_tokens, 2)
|
|
288
|
+
})
|
|
289
|
+
|
|
290
|
+
test('collectChatCompletion: 无正文时 content=null(不是空串)', async () => {
|
|
291
|
+
const payload = await collectChatCompletion(
|
|
292
|
+
[{ type: 'finish', reason: { kind: 'stop' } }],
|
|
293
|
+
'id', 'm',
|
|
294
|
+
)
|
|
295
|
+
assert.equal(payload.choices[0].message.content, null)
|
|
296
|
+
})
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* ⚠ 流没有 finish ⇒ 上游半截断开。**必须报错**:谎报成功会让客户端把半截输出
|
|
300
|
+
* 当完整结果持久化(参考实现踩过的同一个坑)。
|
|
301
|
+
*/
|
|
302
|
+
test('collectChatCompletion: 流缺 finish 时报错(不假装成功)', async () => {
|
|
303
|
+
await assert.rejects(
|
|
304
|
+
() => collectChatCompletion([{ type: 'text-delta', index: 0, text: '半截' }], 'id', 'm'),
|
|
305
|
+
/ended before finish/,
|
|
306
|
+
)
|
|
307
|
+
})
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* ⚠ 真实 bug(实现期踩到):`result.decoder` 是
|
|
312
|
+
* `{ read(): Promise<{done, value?}> }`(plan-client.js 的返回类型注释),
|
|
313
|
+
* **不是**异步生成器。误当生成器 `for await` 消费会报
|
|
314
|
+
* `result.decoder.read is not a function` —— 被 catch 兜住后只发一帧 error
|
|
315
|
+
* chunk,表现为「流式回答只有一个 reasoning 帧就断了」。
|
|
316
|
+
*
|
|
317
|
+
* 本用例用**真实 decoder 形状**驱动整条 HTTP 路径。
|
|
318
|
+
*/
|
|
319
|
+
test('HTTP: 流式走真实 decoder 形状(read() 而非 for await),帧完整', async () => {
|
|
320
|
+
const { startOpenAiGateway } = await import('../lib/openai-gateway.js')
|
|
321
|
+
/** 分发 key 形态(网关 0.9.5 起只认它)。 */
|
|
322
|
+
const key = `zsp-${(await import('node:crypto')).randomBytes(16).toString('base64url')}`
|
|
323
|
+
const all = [
|
|
324
|
+
{ type: 'reasoning-delta', index: 0, text: '思考' },
|
|
325
|
+
{ type: 'text-delta', index: 0, text: '回答' },
|
|
326
|
+
{ type: 'finish', reason: { kind: 'stop' } },
|
|
327
|
+
]
|
|
328
|
+
/** 按 plan-client **真实形状**造 decoder:read() 逐个吐,末次 done。 */
|
|
329
|
+
let cursor = 1
|
|
330
|
+
const decoder = {
|
|
331
|
+
async read() {
|
|
332
|
+
if (cursor >= all.length) return { done: true }
|
|
333
|
+
return { done: false, value: all[cursor++] }
|
|
334
|
+
},
|
|
335
|
+
async cancel() {},
|
|
336
|
+
}
|
|
337
|
+
const gateway = await startOpenAiGateway({
|
|
338
|
+
port: 0,
|
|
339
|
+
/** 目录必须有这个模型:0.10.0 起网关按目录做准入(未知模型 → 400,见 S6)。 */
|
|
340
|
+
models: async () => [{ id: 'GLM-5.3-Flash' }],
|
|
341
|
+
log: () => {},
|
|
342
|
+
planClient: { call: async () => ({ head: all.slice(0, 1), decoder }) },
|
|
343
|
+
/** 0.9.5 起鉴权只认分发 key:让本测试的随机 key 有效。 */
|
|
344
|
+
findDistributionKey: (presented) => (presented === key ? { token: key, enabled: true, usage: {} } : undefined),
|
|
345
|
+
})
|
|
346
|
+
try {
|
|
347
|
+
const response = await fetch(`${gateway.baseUrl}/chat/completions`, {
|
|
348
|
+
method: 'POST',
|
|
349
|
+
headers: { authorization: `Bearer ${key}`, 'content-type': 'application/json' },
|
|
350
|
+
body: JSON.stringify({ stream: true, model: 'GLM-5.3-Flash', messages: [{ role: 'user', content: 'hi' }] }),
|
|
351
|
+
})
|
|
352
|
+
const raw = await response.text()
|
|
353
|
+
assert.doesNotMatch(raw, /is not a function/, 'decoder 必须是 read() 形状')
|
|
354
|
+
const frames = raw.split('\n\n').filter((chunk) => chunk.startsWith('data: ') && !chunk.includes('[DONE]'))
|
|
355
|
+
.map((chunk) => JSON.parse(chunk.slice('data: '.length)))
|
|
356
|
+
const deltas = frames.map((frame) => frame.choices?.[0]?.delta).filter(Boolean)
|
|
357
|
+
assert.ok(deltas.some((delta) => delta.reasoning_content === '思考'), 'reasoning 帧')
|
|
358
|
+
assert.ok(deltas.some((delta) => delta.content === '回答'), 'content 帧必须真的发出来')
|
|
359
|
+
assert.ok(frames.some((frame) => frame.choices?.[0]?.finish_reason === 'stop'), 'finish 帧')
|
|
360
|
+
} finally {
|
|
361
|
+
await gateway.close()
|
|
362
|
+
}
|
|
363
|
+
})
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* 0.10.0 审计 S6:未知模型必须**在选号之前**被拒。
|
|
367
|
+
*
|
|
368
|
+
* 上游对不存在的模型回 200 + 零内容,`plan-client` 会把它判成「该账号×模型
|
|
369
|
+
* 当日用尽」并 `markModelRateLimited` —— 一次拼错的模型名就能把整个池子标限流到
|
|
370
|
+
* 当日。故网关必须在 `planClient.call` 之前按目录拦住。
|
|
371
|
+
*/
|
|
372
|
+
test('HTTP: 未知模型返回 400 且绝不触碰 planClient', async () => {
|
|
373
|
+
const { startOpenAiGateway } = await import('../lib/openai-gateway.js')
|
|
374
|
+
const key = `zsp-${(await import('node:crypto')).randomBytes(16).toString('base64url')}`
|
|
375
|
+
let called = 0
|
|
376
|
+
const gateway = await startOpenAiGateway({
|
|
377
|
+
port: 0,
|
|
378
|
+
models: async () => [{ id: 'GLM-5.3-Flash' }, { id: 'GLM-5.3' }],
|
|
379
|
+
log: () => {},
|
|
380
|
+
planClient: {
|
|
381
|
+
call: async () => {
|
|
382
|
+
called += 1
|
|
383
|
+
return { head: [], decoder: undefined }
|
|
384
|
+
},
|
|
385
|
+
},
|
|
386
|
+
findDistributionKey: (presented) => (presented === key ? { token: key, enabled: true, usage: {} } : undefined),
|
|
387
|
+
})
|
|
388
|
+
try {
|
|
389
|
+
const response = await fetch(`${gateway.baseUrl}/chat/completions`, {
|
|
390
|
+
method: 'POST',
|
|
391
|
+
headers: { authorization: `Bearer ${key}`, 'content-type': 'application/json' },
|
|
392
|
+
body: JSON.stringify({ model: 'GLM-5.3-Flas(拼错)', messages: [{ role: 'user', content: 'hi' }] }),
|
|
393
|
+
})
|
|
394
|
+
assert.equal(response.status, 400)
|
|
395
|
+
const payload = await response.json()
|
|
396
|
+
assert.equal(payload.error.code, 'model_not_found')
|
|
397
|
+
assert.deepEqual(payload.error.available, ['GLM-5.3-Flash', 'GLM-5.3'])
|
|
398
|
+
assert.equal(called, 0, '未知模型不得进入选号链路(否则账号会被标限流到当日)')
|
|
399
|
+
|
|
400
|
+
/** 大小写不敏感匹配成功,且下发的是目录里的规范大小写。 */
|
|
401
|
+
let seenModel
|
|
402
|
+
const okGateway = await startOpenAiGateway({
|
|
403
|
+
port: 0,
|
|
404
|
+
models: async () => [{ id: 'GLM-5.3-Flash' }],
|
|
405
|
+
log: () => {},
|
|
406
|
+
planClient: {
|
|
407
|
+
call: async ({ options }) => {
|
|
408
|
+
seenModel = options.model
|
|
409
|
+
return { head: [{ type: 'text-delta', text: 'x' }, { type: 'finish', reason: { kind: 'stop' } }], decoder: undefined }
|
|
410
|
+
},
|
|
411
|
+
},
|
|
412
|
+
findDistributionKey: (presented) => (presented === key ? { token: key, enabled: true, usage: {} } : undefined),
|
|
413
|
+
})
|
|
414
|
+
try {
|
|
415
|
+
const res2 = await fetch(`${okGateway.baseUrl}/chat/completions`, {
|
|
416
|
+
method: 'POST',
|
|
417
|
+
headers: { authorization: `Bearer ${key}`, 'content-type': 'application/json' },
|
|
418
|
+
body: JSON.stringify({ model: 'glm-5.3-flash', messages: [{ role: 'user', content: 'hi' }] }),
|
|
419
|
+
})
|
|
420
|
+
assert.equal(res2.status, 200)
|
|
421
|
+
assert.equal(seenModel, 'GLM-5.3-Flash', '上游应看到目录里的规范 id')
|
|
422
|
+
} finally {
|
|
423
|
+
await okGateway.close()
|
|
424
|
+
}
|
|
425
|
+
} finally {
|
|
426
|
+
await gateway.close()
|
|
427
|
+
}
|
|
428
|
+
})
|
|
429
|
+
|
|
430
|
+
/**
|
|
431
|
+
* 0.10.0 审计 S5:网关**刻意不设 CORS**。
|
|
432
|
+
* 预检不带 Authorization ⇒ 任何 `Access-Control-Allow-Origin: *` 都在鉴权之前生效,
|
|
433
|
+
* 而分发 key 是静态 Bearer:浏览器持钥即可跨源烧额度。
|
|
434
|
+
*/
|
|
435
|
+
test('HTTP: 预检不再回 Access-Control-Allow-Origin', async () => {
|
|
436
|
+
const { startOpenAiGateway } = await import('../lib/openai-gateway.js')
|
|
437
|
+
const gateway = await startOpenAiGateway({
|
|
438
|
+
port: 0,
|
|
439
|
+
models: async () => [{ id: 'GLM-5.3-Flash' }],
|
|
440
|
+
log: () => {},
|
|
441
|
+
planClient: { call: async () => ({ head: [], decoder: undefined }) },
|
|
442
|
+
findDistributionKey: () => undefined,
|
|
443
|
+
})
|
|
444
|
+
try {
|
|
445
|
+
const response = await fetch(`${gateway.baseUrl}/v1/chat/completions`, {
|
|
446
|
+
method: 'OPTIONS',
|
|
447
|
+
headers: { origin: 'https://evil.example', 'access-control-request-method': 'POST' },
|
|
448
|
+
})
|
|
449
|
+
assert.equal(response.headers.get('access-control-allow-origin'), null)
|
|
450
|
+
assert.notEqual(response.status, 204)
|
|
451
|
+
} finally {
|
|
452
|
+
await gateway.close()
|
|
453
|
+
}
|
|
454
|
+
})
|