dsh-zcode-startplan 0.4.5 → 0.5.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 +267 -0
- package/README.md +73 -6
- package/client.js +299 -13
- package/index.js +35 -3
- package/lib/adapter.js +27 -0
- package/lib/assemble.js +164 -42
- package/lib/manage-routes.js +164 -1
- package/lib/plan-client.js +4 -4
- package/lib/upstream-api.js +45 -4
- package/package.json +3 -2
- package/scripts/restart-dsh.ps1 +41 -1
- package/tests/anthropic-body.test.mjs +305 -0
- package/tests/assembler-contract.test.mjs +256 -0
- package/tests/claim-routes.test.mjs +293 -0
- package/tests/client-panel.test.mjs +356 -0
- package/tests/e2e.test.mjs +353 -0
- package/tests/fixtures/quota-200.json +1 -0
- package/tests/login-channel.test.mjs +102 -0
- package/tests/pinned-models.test.mjs +497 -0
- package/tests/plan-client.test.mjs +222 -0
- package/tests/pool.test.mjs +93 -0
- package/tests/sse.test.mjs +86 -0
- package/tests/stream-translator.test.mjs +137 -0
- package/tests/support/resolve-profile-deps.mjs +52 -0
- package/tests/upstream-error-200.test.mjs +125 -0
- package/tests/upstream.test.mjs +250 -0
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
import test from 'node:test'
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
|
|
4
|
+
import { ZcodePlanClient } from '../lib/plan-client.js'
|
|
5
|
+
|
|
6
|
+
const CREDENTIAL = { zcode_jwt: 'jwt-1', device_mid: 'dev-1', user_id: 'u-1' }
|
|
7
|
+
|
|
8
|
+
/** 内存版账号池(只实现 plan-client 用到的三个方法)。 */
|
|
9
|
+
function fakePool(credentials = [{ id: 'acct-a', credential: CREDENTIAL }]) {
|
|
10
|
+
const state = credentials.map((entry) => ({ nickname: entry.id, enabled: true, model_rate_limits: {}, ...entry }))
|
|
11
|
+
return {
|
|
12
|
+
list: () => state,
|
|
13
|
+
pick(model, exclude) {
|
|
14
|
+
const excluded = exclude ?? new Set()
|
|
15
|
+
const hit = state.find((entry) => entry.enabled && !excluded.has(entry.id))
|
|
16
|
+
return hit === undefined ? null : { entry: hit, credential: hit.credential }
|
|
17
|
+
},
|
|
18
|
+
markModelRateLimited(accountId, modelId, resetAt) {
|
|
19
|
+
const hit = state.find((entry) => entry.id === accountId)
|
|
20
|
+
if (hit !== undefined) hit.model_rate_limits[modelId] = resetAt
|
|
21
|
+
},
|
|
22
|
+
noteError() {},
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const fakeMinter = (params = ['param-1', 'param-2', 'param-3']) => {
|
|
27
|
+
let index = 0
|
|
28
|
+
return {
|
|
29
|
+
calls: 0,
|
|
30
|
+
async mint() {
|
|
31
|
+
this.calls += 1
|
|
32
|
+
return { param: params[Math.min(index++, params.length - 1)], interactive: false }
|
|
33
|
+
},
|
|
34
|
+
async fetchConfig() {
|
|
35
|
+
return { region: 'cn', prefix: 'no8xfe', sceneId: 'scene' }
|
|
36
|
+
},
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const sseStream = (events) =>
|
|
41
|
+
new ReadableStream({
|
|
42
|
+
start(controller) {
|
|
43
|
+
const encoder = new TextEncoder()
|
|
44
|
+
for (const event of events) controller.enqueue(encoder.encode(`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`))
|
|
45
|
+
controller.close()
|
|
46
|
+
},
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
const textStream = () =>
|
|
50
|
+
sseStream([
|
|
51
|
+
{ type: 'message_start', message: { model: 'GLM-5.3-Flash', usage: { input_tokens: 1 } } },
|
|
52
|
+
{ type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } },
|
|
53
|
+
{ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'ok' } },
|
|
54
|
+
{ type: 'message_stop' },
|
|
55
|
+
])
|
|
56
|
+
|
|
57
|
+
const emptyStream = () =>
|
|
58
|
+
sseStream([
|
|
59
|
+
{ type: 'message_start', message: { model: 'GLM-5.3-Flash' } },
|
|
60
|
+
{ type: 'message_stop' },
|
|
61
|
+
])
|
|
62
|
+
|
|
63
|
+
const response = (status, body, contentType = 'text/event-stream') => ({
|
|
64
|
+
ok: status >= 200 && status < 300,
|
|
65
|
+
status,
|
|
66
|
+
headers: new Headers({ 'content-type': contentType }),
|
|
67
|
+
body,
|
|
68
|
+
text: async () => (typeof body === 'string' ? body : ''),
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
const baseOptions = { model: 'GLM-5.3-Flash', messages: [{ role: 'user', content: [{ type: 'text', text: 'hi' }] }] }
|
|
72
|
+
|
|
73
|
+
test('先不带 captcha 探测;被 3007 拒后才产出并重试', async () => {
|
|
74
|
+
const seen = []
|
|
75
|
+
const fetchImpl = async (_url, init) => {
|
|
76
|
+
seen.push(init.headers)
|
|
77
|
+
if (seen.length === 1) return response(403, JSON.stringify({ code: 3007, msg: 'captcha verify failed' }), 'application/json')
|
|
78
|
+
return response(200, textStream())
|
|
79
|
+
}
|
|
80
|
+
const minter = fakeMinter()
|
|
81
|
+
const client = new ZcodePlanClient({ pool: fakePool(), minter, fetchImpl })
|
|
82
|
+
|
|
83
|
+
const result = await client.call({ options: baseOptions })
|
|
84
|
+
assert.equal(seen.length, 2)
|
|
85
|
+
assert.equal(seen[0]['x-aliyun-captcha-verify-param'], undefined, '第一次不带 captcha')
|
|
86
|
+
assert.equal(seen[1]['x-aliyun-captcha-verify-param'], 'param-1', '被拒后才产出')
|
|
87
|
+
assert.equal(minter.calls, 1)
|
|
88
|
+
assert.equal(result.accountId, 'acct-a')
|
|
89
|
+
})
|
|
90
|
+
|
|
91
|
+
test('已知需要 captcha 时直接带上(省掉一次 3007 往返)', async () => {
|
|
92
|
+
const seen = []
|
|
93
|
+
let call = 0
|
|
94
|
+
const fetchImpl = async (_url, init) => {
|
|
95
|
+
seen.push(init.headers)
|
|
96
|
+
call += 1
|
|
97
|
+
if (call === 1) return response(403, '{"code":3007}', 'application/json')
|
|
98
|
+
return response(200, textStream())
|
|
99
|
+
}
|
|
100
|
+
const minter = fakeMinter()
|
|
101
|
+
const client = new ZcodePlanClient({ pool: fakePool(), minter, fetchImpl })
|
|
102
|
+
|
|
103
|
+
/** 第一次:探测被拒 → 产出并重试成功(2 次尝试)。 */
|
|
104
|
+
await client.call({ options: baseOptions })
|
|
105
|
+
assert.equal(seen.length, 2)
|
|
106
|
+
assert.equal(seen[0]['x-aliyun-captcha-verify-param'], undefined)
|
|
107
|
+
assert.equal(seen[1]['x-aliyun-captcha-verify-param'], 'param-1')
|
|
108
|
+
|
|
109
|
+
/** 第二次(同一 client、2 分钟窗口内):直接带头,只发一次。 */
|
|
110
|
+
const result = await client.call({ options: baseOptions })
|
|
111
|
+
assert.equal(seen.length, 3, '第二次请求不应再吃 3007')
|
|
112
|
+
assert.equal(seen[2]['x-aliyun-captcha-verify-param'], 'param-2')
|
|
113
|
+
assert.equal(result.accountId, 'acct-a')
|
|
114
|
+
})
|
|
115
|
+
|
|
116
|
+
test('200 但零内容 → 标记该账号并换号(调用方零 chunk)', async () => {
|
|
117
|
+
const pool = fakePool([
|
|
118
|
+
{ id: 'acct-a', credential: CREDENTIAL },
|
|
119
|
+
{ id: 'acct-b', credential: { ...CREDENTIAL, user_id: 'u-2' } },
|
|
120
|
+
])
|
|
121
|
+
let call = 0
|
|
122
|
+
const fetchImpl = async () => {
|
|
123
|
+
call += 1
|
|
124
|
+
return response(200, call === 1 ? emptyStream() : textStream())
|
|
125
|
+
}
|
|
126
|
+
const client = new ZcodePlanClient({ pool, minter: fakeMinter(), fetchImpl })
|
|
127
|
+
const picked = []
|
|
128
|
+
const originalPick = pool.pick.bind(pool)
|
|
129
|
+
pool.pick = (model, exclude) => {
|
|
130
|
+
const hit = originalPick(model, exclude)
|
|
131
|
+
if (hit !== null) picked.push(hit.entry.id)
|
|
132
|
+
return hit
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const result = await client.call({ options: baseOptions })
|
|
136
|
+
assert.equal(result.accountId, 'acct-b')
|
|
137
|
+
assert.deepEqual(picked, ['acct-a', 'acct-b'])
|
|
138
|
+
assert.equal(pool.list()[0].model_rate_limits['GLM-5.3-Flash'] > Date.now(), true, 'acct-a 被标记到当日结束')
|
|
139
|
+
})
|
|
140
|
+
|
|
141
|
+
test('额度用尽(1005)→ 换号;两个号都用尽 → QUOTA 失败', async () => {
|
|
142
|
+
const pool = fakePool([
|
|
143
|
+
{ id: 'acct-a', credential: CREDENTIAL },
|
|
144
|
+
{ id: 'acct-b', credential: { ...CREDENTIAL, user_id: 'u-2' } },
|
|
145
|
+
])
|
|
146
|
+
const client = new ZcodePlanClient({
|
|
147
|
+
pool,
|
|
148
|
+
minter: fakeMinter(),
|
|
149
|
+
fetchImpl: async () => response(429, '{"code":1005,"msg":"exceed quota limit"}', 'application/json'),
|
|
150
|
+
})
|
|
151
|
+
await assert.rejects(
|
|
152
|
+
() => client.call({ options: baseOptions }),
|
|
153
|
+
(error) => {
|
|
154
|
+
assert.equal(error.code, 'QUOTA')
|
|
155
|
+
return true
|
|
156
|
+
},
|
|
157
|
+
)
|
|
158
|
+
assert.equal(pool.list().every((entry) => entry.model_rate_limits['GLM-5.3-Flash'] > Date.now()), true)
|
|
159
|
+
})
|
|
160
|
+
|
|
161
|
+
test('风控 3012 不重试、不换号,直接失败', async () => {
|
|
162
|
+
let calls = 0
|
|
163
|
+
const client = new ZcodePlanClient({
|
|
164
|
+
pool: fakePool(),
|
|
165
|
+
minter: fakeMinter(),
|
|
166
|
+
fetchImpl: async () => {
|
|
167
|
+
calls += 1
|
|
168
|
+
return response(403, '{"code":3012,"msg":"unusual activity"}', 'application/json')
|
|
169
|
+
},
|
|
170
|
+
})
|
|
171
|
+
await assert.rejects(
|
|
172
|
+
() => client.call({ options: baseOptions }),
|
|
173
|
+
(error) => {
|
|
174
|
+
assert.equal(error.code, 'RATE_LIMIT')
|
|
175
|
+
assert.match(error.message, /3012/)
|
|
176
|
+
return true
|
|
177
|
+
},
|
|
178
|
+
)
|
|
179
|
+
assert.equal(calls, 1, '3012 有冷却惩罚:绝不能连续重试')
|
|
180
|
+
})
|
|
181
|
+
|
|
182
|
+
test('并发限流 3009 退避重试但不换号', async () => {
|
|
183
|
+
let calls = 0
|
|
184
|
+
const client = new ZcodePlanClient({
|
|
185
|
+
pool: fakePool(),
|
|
186
|
+
minter: fakeMinter(),
|
|
187
|
+
fetchImpl: async () => {
|
|
188
|
+
calls += 1
|
|
189
|
+
return calls === 1 ? response(429, '{"code":3009}', 'application/json') : response(200, textStream())
|
|
190
|
+
},
|
|
191
|
+
})
|
|
192
|
+
const result = await client.call({ options: baseOptions })
|
|
193
|
+
assert.equal(calls, 2)
|
|
194
|
+
assert.equal(result.accountId, 'acct-a')
|
|
195
|
+
})
|
|
196
|
+
|
|
197
|
+
test('账号池为空 → QUOTA 并提示登录命令', async () => {
|
|
198
|
+
const client = new ZcodePlanClient({ pool: fakePool([]), minter: fakeMinter(), fetchImpl: async () => response(200, textStream()) })
|
|
199
|
+
await assert.rejects(
|
|
200
|
+
() => client.call({ options: baseOptions }),
|
|
201
|
+
(error) => {
|
|
202
|
+
assert.equal(error.code, 'QUOTA')
|
|
203
|
+
assert.match(error.message, /zcode-start-plan login/)
|
|
204
|
+
return true
|
|
205
|
+
},
|
|
206
|
+
)
|
|
207
|
+
})
|
|
208
|
+
|
|
209
|
+
test('401 凭据失效 → AUTH,不换号', async () => {
|
|
210
|
+
const client = new ZcodePlanClient({
|
|
211
|
+
pool: fakePool(),
|
|
212
|
+
minter: fakeMinter(),
|
|
213
|
+
fetchImpl: async () => response(401, '{"code":1002}', 'application/json'),
|
|
214
|
+
})
|
|
215
|
+
await assert.rejects(
|
|
216
|
+
() => client.call({ options: baseOptions }),
|
|
217
|
+
(error) => {
|
|
218
|
+
assert.equal(error.code, 'AUTH')
|
|
219
|
+
return true
|
|
220
|
+
},
|
|
221
|
+
)
|
|
222
|
+
})
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import test from 'node:test'
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
import { mkdtempSync, rmSync } from 'node:fs'
|
|
4
|
+
import { tmpdir } from 'node:os'
|
|
5
|
+
import { join } from 'node:path'
|
|
6
|
+
|
|
7
|
+
import { AccountPool, SqliteStore, isUsableCredential } from '../lib/pool.js'
|
|
8
|
+
|
|
9
|
+
const credential = (id) => ({ zcode_jwt: `jwt-${id}`, device_mid: `dev-${id}`, user_id: `u-${id}` })
|
|
10
|
+
|
|
11
|
+
function withPool(fn) {
|
|
12
|
+
return async () => {
|
|
13
|
+
const dir = mkdtempSync(join(tmpdir(), 'zsp-pool-'))
|
|
14
|
+
try {
|
|
15
|
+
const store = await new SqliteStore(join(dir, 'accounts.db'))
|
|
16
|
+
const pool = new AccountPool({ store })
|
|
17
|
+
await fn(pool, store)
|
|
18
|
+
store.close()
|
|
19
|
+
} finally {
|
|
20
|
+
rmSync(dir, { recursive: true, force: true })
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
test('add 以 user_id 去重:同账号再登录只更新凭据', withPool(async (pool, store) => {
|
|
26
|
+
const first = pool.add(credential('a'), '账号A')
|
|
27
|
+
assert.equal(first.created, true)
|
|
28
|
+
const second = pool.add({ ...credential('a'), zcode_jwt: 'jwt-renewed' }, '账号A-改名')
|
|
29
|
+
assert.equal(second.created, false)
|
|
30
|
+
assert.equal(pool.list().length, 1)
|
|
31
|
+
const stored = store.get(first.entry.id)
|
|
32
|
+
assert.equal(stored.credential.zcode_jwt, 'jwt-renewed')
|
|
33
|
+
assert.equal(stored.nickname, '账号A-改名')
|
|
34
|
+
}))
|
|
35
|
+
|
|
36
|
+
test('pick 遵守手动顺序,并跳过 exclude 中的账号', withPool(async (pool) => {
|
|
37
|
+
pool.add(credential('a'), 'A')
|
|
38
|
+
pool.add(credential('b'), 'B')
|
|
39
|
+
const first = pool.pick('GLM-5.3-Flash')
|
|
40
|
+
assert.equal(first.entry.nickname, 'A')
|
|
41
|
+
const second = pool.pick('GLM-5.3-Flash', new Set([first.entry.id]))
|
|
42
|
+
assert.equal(second.entry.nickname, 'B')
|
|
43
|
+
assert.equal(pool.pick('GLM-5.3-Flash', new Set([first.entry.id, second.entry.id])), null)
|
|
44
|
+
}))
|
|
45
|
+
|
|
46
|
+
test('markModelRateLimited 只影响那一对「账号×模型」,且到期后恢复', withPool(async (pool, store) => {
|
|
47
|
+
const { entry } = pool.add(credential('a'), 'A')
|
|
48
|
+
const now = Date.now()
|
|
49
|
+
pool.markModelRateLimited(entry.id, 'GLM-5.3-Flash', now + 60_000)
|
|
50
|
+
assert.equal(pool.pick('GLM-5.3-Flash'), null)
|
|
51
|
+
assert.notEqual(pool.pick('GLM-5.3'), null, '另一个模型不受影响')
|
|
52
|
+
|
|
53
|
+
/** 模拟时间流逝:把标记改成已过期再 sweep。 */
|
|
54
|
+
store.patch(entry.id, { model_rate_limits: { 'GLM-5.3-Flash': now - 1 } })
|
|
55
|
+
pool.sweepExpired()
|
|
56
|
+
assert.notEqual(pool.pick('GLM-5.3-Flash'), null)
|
|
57
|
+
}))
|
|
58
|
+
|
|
59
|
+
test('停用的账号不参与选号;reorder 改变优先级', withPool(async (pool) => {
|
|
60
|
+
const a = pool.add(credential('a'), 'A').entry
|
|
61
|
+
pool.add(credential('b'), 'B')
|
|
62
|
+
pool.setEnabled(a.id, false)
|
|
63
|
+
assert.equal(pool.pick('GLM-5.3-Flash').entry.nickname, 'B')
|
|
64
|
+
pool.setEnabled(a.id, true)
|
|
65
|
+
|
|
66
|
+
const ids = pool.list().map((entry) => entry.id)
|
|
67
|
+
pool.reorder([...ids].reverse())
|
|
68
|
+
assert.equal(pool.pick('GLM-5.3-Flash').entry.nickname, 'B', '反转后 B 排到最前')
|
|
69
|
+
}))
|
|
70
|
+
|
|
71
|
+
test('reorder 拒绝不同集合(而不是尽力而为)', withPool(async (pool) => {
|
|
72
|
+
pool.add(credential('a'), 'A')
|
|
73
|
+
assert.throws(() => pool.reorder(['not-an-id']), /账号列表已变化/)
|
|
74
|
+
}))
|
|
75
|
+
|
|
76
|
+
test('resolve 支持序号 / id 前缀 / 昵称片段', withPool(async (pool) => {
|
|
77
|
+
const a = pool.add(credential('a'), '尾号1234').entry
|
|
78
|
+
assert.equal(pool.resolve('1').id, a.id)
|
|
79
|
+
assert.equal(pool.resolve(a.id.slice(0, 8)).id, a.id)
|
|
80
|
+
assert.equal(pool.resolve('1234').id, a.id)
|
|
81
|
+
assert.equal(pool.resolve('nope'), undefined)
|
|
82
|
+
}))
|
|
83
|
+
|
|
84
|
+
test('isUsableCredential: 缺 zcode_jwt 或 device_mid 一律不可用', () => {
|
|
85
|
+
assert.equal(isUsableCredential({ zcode_jwt: 'x', device_mid: 'y' }), true)
|
|
86
|
+
assert.equal(isUsableCredential({ zcode_jwt: '', device_mid: 'y' }), false)
|
|
87
|
+
assert.equal(isUsableCredential({ zcode_jwt: 'x' }), false)
|
|
88
|
+
assert.equal(isUsableCredential(null), false)
|
|
89
|
+
})
|
|
90
|
+
|
|
91
|
+
test('add 拒绝形状不合法的凭据(写入侧也要校验)', withPool(async (pool) => {
|
|
92
|
+
assert.throws(() => pool.add({ zcode_jwt: 'x' }), /凭据形状不合法/)
|
|
93
|
+
}))
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import test from 'node:test'
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
|
|
4
|
+
import { isJsonContentType, jsonHasContent, makeSseDecoder, parseSseEvent, readContentHead } from '../lib/sse.js'
|
|
5
|
+
|
|
6
|
+
const streamOf = (chunks) =>
|
|
7
|
+
new ReadableStream({
|
|
8
|
+
start(controller) {
|
|
9
|
+
for (const chunk of chunks) controller.enqueue(new TextEncoder().encode(chunk))
|
|
10
|
+
controller.close()
|
|
11
|
+
},
|
|
12
|
+
})
|
|
13
|
+
|
|
14
|
+
const sse = (event, data) => `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`
|
|
15
|
+
|
|
16
|
+
test('parseSseEvent: 多行 data 拼接、注释与 [DONE] 处理', () => {
|
|
17
|
+
assert.deepEqual(parseSseEvent('data: {"a":1}').data, { a: 1 })
|
|
18
|
+
assert.equal(parseSseEvent('data: [DONE]').data, '[DONE]')
|
|
19
|
+
assert.equal(parseSseEvent(': keep-alive'), undefined)
|
|
20
|
+
assert.equal(parseSseEvent('event: ping'), undefined)
|
|
21
|
+
assert.equal(parseSseEvent('data: not-json').unparsed, true)
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
test('content-type 分流:非流式 JSON 不当 SSE 扫', () => {
|
|
25
|
+
assert.equal(isJsonContentType('application/json'), true)
|
|
26
|
+
assert.equal(isJsonContentType('text/event-stream; charset=utf-8'), false)
|
|
27
|
+
assert.equal(isJsonContentType(undefined), false)
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
test('jsonHasContent: 空 content 视为无权益,错误载荷视为有响应', () => {
|
|
31
|
+
assert.equal(jsonHasContent(JSON.stringify({ content: [] })), false)
|
|
32
|
+
assert.equal(jsonHasContent(JSON.stringify({ content: [{ type: 'text', text: '' }] })), false)
|
|
33
|
+
assert.equal(jsonHasContent(JSON.stringify({ content: [{ type: 'text', text: 'hi' }] })), true)
|
|
34
|
+
assert.equal(jsonHasContent(JSON.stringify({ content: [{ type: 'tool_use', id: 'x' }] })), true)
|
|
35
|
+
assert.equal(jsonHasContent(JSON.stringify({ type: 'error', error: { message: 'x' } })), true)
|
|
36
|
+
/** 注意:`usage.server_tool_use` 不应被误判成有内容的工具调用。 */
|
|
37
|
+
assert.equal(jsonHasContent(JSON.stringify({ content: [], usage: { server_tool_use: {} } })), false)
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
test('readContentHead: 零内容 SSE 流判为无权益', async () => {
|
|
41
|
+
const body = streamOf([
|
|
42
|
+
sse('message_start', { type: 'message_start', message: { model: 'GLM-5.3-Flash', usage: { input_tokens: 3 } } }),
|
|
43
|
+
sse('message_stop', { type: 'message_stop' }),
|
|
44
|
+
])
|
|
45
|
+
const head = await readContentHead(body, { contentType: 'text/event-stream' })
|
|
46
|
+
assert.equal(head.hasContent, false)
|
|
47
|
+
assert.equal(head.head.length, 2)
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
test('readContentHead: 见到首个内容帧即返回,并把解码器交给调用方继续读', async () => {
|
|
51
|
+
const body = streamOf([
|
|
52
|
+
sse('message_start', { type: 'message_start', message: {} }),
|
|
53
|
+
sse('content_block_start', { type: 'content_block_start', index: 0, content_block: { type: 'text', text: 'Hel' } }),
|
|
54
|
+
sse('content_block_delta', { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'lo' } }),
|
|
55
|
+
sse('message_stop', { type: 'message_stop' }),
|
|
56
|
+
])
|
|
57
|
+
const head = await readContentHead(body, { contentType: 'text/event-stream' })
|
|
58
|
+
assert.equal(head.hasContent, true)
|
|
59
|
+
assert.equal(head.head.length, 2)
|
|
60
|
+
|
|
61
|
+
const rest = []
|
|
62
|
+
for (;;) {
|
|
63
|
+
const next = await head.decoder.read()
|
|
64
|
+
if (next.done === true) break
|
|
65
|
+
rest.push(next.value.data.type)
|
|
66
|
+
}
|
|
67
|
+
assert.deepEqual(rest, ['content_block_delta', 'message_stop'])
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
test('makeSseDecoder: 跨 chunk 切分的事件仍能拼回来', async () => {
|
|
71
|
+
const body = streamOf(['event: content_block_delta\ndata: {"type":"content', '_block_delta"}\n\n'])
|
|
72
|
+
const decoder = makeSseDecoder(body)
|
|
73
|
+
const first = await decoder.read()
|
|
74
|
+
assert.equal(first.done, false)
|
|
75
|
+
assert.equal(first.value.data.type, 'content_block_delta')
|
|
76
|
+
const second = await decoder.read()
|
|
77
|
+
assert.equal(second.done, true)
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
test('readContentHead: 非流式 JSON 走结构判定', async () => {
|
|
81
|
+
const body = streamOf([JSON.stringify({ content: [{ type: 'text', text: 'ok' }] })])
|
|
82
|
+
const head = await readContentHead(body, { contentType: 'application/json' })
|
|
83
|
+
assert.equal(head.hasContent, true)
|
|
84
|
+
assert.equal(head.jsonMode, true)
|
|
85
|
+
assert.equal(head.head[0].data.content[0].text, 'ok')
|
|
86
|
+
})
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import test from 'node:test'
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
|
|
4
|
+
import { AnthropicStreamTranslator, mapErrorCode, mapStopReason } from '../lib/stream-translator.js'
|
|
5
|
+
|
|
6
|
+
const ev = (type, payload) => ({ event: type, data: { type, ...payload } })
|
|
7
|
+
|
|
8
|
+
test('text 块:block-start → text-delta → block-end,最后 usage → finish', () => {
|
|
9
|
+
const translator = new AnthropicStreamTranslator()
|
|
10
|
+
const out = []
|
|
11
|
+
out.push(...translator.push(ev('message_start', { message: { model: 'GLM-5.3-Flash', usage: { input_tokens: 11 } } })))
|
|
12
|
+
out.push(...translator.push(ev('content_block_start', { index: 0, content_block: { type: 'text', text: '' } })))
|
|
13
|
+
out.push(...translator.push(ev('content_block_delta', { index: 0, delta: { type: 'text_delta', text: 'Hi' } })))
|
|
14
|
+
out.push(...translator.push(ev('content_block_stop', { index: 0 })))
|
|
15
|
+
out.push(...translator.push(ev('message_delta', { delta: { stop_reason: 'end_turn' }, usage: { output_tokens: 7 } })))
|
|
16
|
+
out.push(...translator.finish())
|
|
17
|
+
|
|
18
|
+
assert.deepEqual(out.map((chunk) => chunk.type), [
|
|
19
|
+
'block-start',
|
|
20
|
+
'text-delta',
|
|
21
|
+
'block-end',
|
|
22
|
+
'usage',
|
|
23
|
+
'finish',
|
|
24
|
+
])
|
|
25
|
+
assert.equal(out[1].text, 'Hi')
|
|
26
|
+
assert.deepEqual(out[3].usage, { inputTokens: 11, outputTokens: 7, cacheReadTokens: 0, cacheWriteTokens: 0 })
|
|
27
|
+
/** 官方契约:finish.reason 是对象(FinishReasonMap),宿主 BlockAssembler 读 chunk.reason。 */
|
|
28
|
+
assert.deepEqual(out[4], { type: 'finish', reason: { kind: 'stop' } })
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
test('tool_use:参数以原始 JSON 字符串增量下发,stop_reason=tool_use → tool-calls', () => {
|
|
32
|
+
const translator = new AnthropicStreamTranslator()
|
|
33
|
+
const out = []
|
|
34
|
+
out.push(...translator.push(ev('content_block_start', {
|
|
35
|
+
index: 0,
|
|
36
|
+
content_block: { type: 'tool_use', id: 'toolu_1', name: 'pwsh', input: {} },
|
|
37
|
+
})))
|
|
38
|
+
out.push(...translator.push(ev('content_block_delta', { index: 0, delta: { type: 'input_json_delta', partial_json: '{"cmd":' } })))
|
|
39
|
+
out.push(...translator.push(ev('content_block_delta', { index: 0, delta: { type: 'input_json_delta', partial_json: '"ls"}' } })))
|
|
40
|
+
out.push(...translator.push(ev('message_delta', { delta: { stop_reason: 'tool_use' } })))
|
|
41
|
+
out.push(...translator.finish())
|
|
42
|
+
|
|
43
|
+
/** ⚠ 宿主 assembler 读 `blockType`(字符串),不是 `block`(对象)。 */
|
|
44
|
+
assert.equal(out[0].blockType, 'tool-call')
|
|
45
|
+
assert.deepEqual(
|
|
46
|
+
out.filter((chunk) => chunk.type === 'tool-call-delta').map((chunk) => chunk.argumentsDelta),
|
|
47
|
+
['{"cmd":', '"ls"}'],
|
|
48
|
+
)
|
|
49
|
+
/** 工具名/id 走 tool-call-delta 的 `name` / `id` 字段。 */
|
|
50
|
+
const firstDelta = out.find((chunk) => chunk.type === 'tool-call-delta')
|
|
51
|
+
assert.equal(firstDelta.id, 'toolu_1')
|
|
52
|
+
assert.equal(firstDelta.name, 'pwsh')
|
|
53
|
+
/** block-end 必须带完整 block。 */
|
|
54
|
+
const end = out.find((chunk) => chunk.type === 'block-end')
|
|
55
|
+
assert.deepEqual(end.block, { type: 'tool-call', id: 'toolu_1', name: 'pwsh', arguments: '{"cmd":"ls"}' })
|
|
56
|
+
assert.equal(out[out.length - 1].reason.kind, 'tool-calls')
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
test('tool_use:只有 start 内联 input 时,结束块保留完整工具参数', () => {
|
|
60
|
+
const translator = new AnthropicStreamTranslator()
|
|
61
|
+
translator.push(ev('content_block_start', {
|
|
62
|
+
index: 0,
|
|
63
|
+
content_block: { type: 'tool_use', id: 'toolu_inline', name: 'pwsh',
|
|
64
|
+
input: { description: '列出文件', command: 'Get-ChildItem' } },
|
|
65
|
+
}))
|
|
66
|
+
const out = translator.push(ev('content_block_stop', { index: 0 }))
|
|
67
|
+
assert.deepEqual(JSON.parse(out[0].block.arguments), {
|
|
68
|
+
description: '列出文件', command: 'Get-ChildItem',
|
|
69
|
+
})
|
|
70
|
+
})
|
|
71
|
+
|
|
72
|
+
test('tool_use:同时有内联 input 和 JSON 增量时,以完整增量为准', () => {
|
|
73
|
+
const translator = new AnthropicStreamTranslator()
|
|
74
|
+
translator.push(ev('content_block_start', {
|
|
75
|
+
index: 0,
|
|
76
|
+
content_block: { type: 'tool_use', id: 'toolu_delta', name: 'pwsh',
|
|
77
|
+
input: { description: '旧值', command: 'old' } },
|
|
78
|
+
}))
|
|
79
|
+
translator.push(ev('content_block_delta', {
|
|
80
|
+
index: 0, delta: { type: 'input_json_delta', partial_json: '{"description":"新值",' },
|
|
81
|
+
}))
|
|
82
|
+
translator.push(ev('content_block_delta', {
|
|
83
|
+
index: 0, delta: { type: 'input_json_delta', partial_json: '"command":"new"}' },
|
|
84
|
+
}))
|
|
85
|
+
const out = translator.push(ev('content_block_stop', { index: 0 }))
|
|
86
|
+
assert.deepEqual(JSON.parse(out[0].block.arguments), { description: '新值', command: 'new' })
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
test('thinking → reasoning-delta', () => {
|
|
90
|
+
const translator = new AnthropicStreamTranslator()
|
|
91
|
+
const out = []
|
|
92
|
+
out.push(...translator.push(ev('content_block_start', { index: 0, content_block: { type: 'thinking', thinking: '' } })))
|
|
93
|
+
out.push(...translator.push(ev('content_block_delta', { index: 0, delta: { type: 'thinking_delta', thinking: 'hmm' } })))
|
|
94
|
+
assert.equal(out[0].blockType, 'reasoning')
|
|
95
|
+
assert.equal(out[1].type, 'reasoning-delta')
|
|
96
|
+
})
|
|
97
|
+
|
|
98
|
+
test('多块顺序:chunk index 与上游 index 解耦(1,2,3 连续递增)', () => {
|
|
99
|
+
const translator = new AnthropicStreamTranslator()
|
|
100
|
+
const out = []
|
|
101
|
+
out.push(...translator.push(ev('content_block_start', { index: 0, content_block: { type: 'text' } })))
|
|
102
|
+
out.push(...translator.push(ev('content_block_stop', { index: 0 })))
|
|
103
|
+
out.push(...translator.push(ev('content_block_start', { index: 5, content_block: { type: 'text' } })))
|
|
104
|
+
out.push(...translator.push(ev('content_block_stop', { index: 5 })))
|
|
105
|
+
const indices = out.filter((chunk) => chunk.type === 'block-start').map((chunk) => chunk.index)
|
|
106
|
+
assert.deepEqual(indices, [0, 1])
|
|
107
|
+
})
|
|
108
|
+
|
|
109
|
+
test('流内 error 事件 → terminal finish 错误 chunk(带稳定失败码)', () => {
|
|
110
|
+
const translator = new AnthropicStreamTranslator()
|
|
111
|
+
translator.push(ev('error', { error: { type: 'api_error', message: '{"code":3012,"msg":"unusual activity"}' } }))
|
|
112
|
+
const out = translator.finish()
|
|
113
|
+
const finish = out[out.length - 1]
|
|
114
|
+
assert.equal(finish.type, 'finish')
|
|
115
|
+
/** 宿主读 chunk.reason(BlockAssembler: this._finish = chunk.reason)。 */
|
|
116
|
+
assert.deepEqual(finish.reason, { kind: 'error', failure: { code: 'RATE_LIMIT', message: finish.reason.failure.message } })
|
|
117
|
+
assert.equal(finish.reason.failure.code, 'RATE_LIMIT')
|
|
118
|
+
assert.match(finish.reason.failure.message, /3012/)
|
|
119
|
+
})
|
|
120
|
+
|
|
121
|
+
test('finish 之前必定先发 usage(DSH 协议顺序)', () => {
|
|
122
|
+
const translator = new AnthropicStreamTranslator()
|
|
123
|
+
const out = translator.finish()
|
|
124
|
+
assert.deepEqual(out.map((chunk) => chunk.type), ['usage', 'finish'])
|
|
125
|
+
})
|
|
126
|
+
|
|
127
|
+
test('mapStopReason / mapErrorCode', () => {
|
|
128
|
+
/** mapStopReason 返回 FinishReasonMap 形态的 reason 对象。 */
|
|
129
|
+
assert.deepEqual(mapStopReason('max_tokens'), { kind: 'max-tokens' })
|
|
130
|
+
assert.deepEqual(mapStopReason('tool_use'), { kind: 'tool-calls' })
|
|
131
|
+
assert.deepEqual(mapStopReason('end_turn'), { kind: 'stop' })
|
|
132
|
+
assert.deepEqual(mapStopReason('unknown'), { kind: 'stop' })
|
|
133
|
+
assert.equal(mapErrorCode({ message: '{"code":1005}' }), 'QUOTA')
|
|
134
|
+
assert.equal(mapErrorCode({ message: 'token expired' }), 'AUTH')
|
|
135
|
+
assert.equal(mapErrorCode({ type: 'rate_limit_error', message: 'x' }), 'RATE_LIMIT')
|
|
136
|
+
assert.equal(mapErrorCode({ message: 'boom' }), 'PROVIDER_ERROR')
|
|
137
|
+
})
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 让源码目录里的测试也能解析到宿主依赖(`@deepseek-ai/schemastery`)。
|
|
3
|
+
*
|
|
4
|
+
* ## 为什么需要
|
|
5
|
+
*
|
|
6
|
+
* 插件在**安装位置**运行:`~/.dsh/profiles/desktop/node_modules/dsh-zcode-startplan`,
|
|
7
|
+
* 于是 Node 从那里向上查找 `node_modules` 能命中 profile 的依赖。
|
|
8
|
+
* 但在**源码目录**跑测试时,`import '@deepseek-ai/schemastery'` 无处可寻 ——
|
|
9
|
+
* 这不是插件的 bug,而是测试不在真实运行位置。
|
|
10
|
+
*
|
|
11
|
+
* 本文件用 `module.registerHooks`(Node ≥22.15)把裸包说明符重定向到 profile 的
|
|
12
|
+
* `node_modules`。只对**未被正常解析**的 `@deepseek-ai/*` 生效,其余解析完全不变。
|
|
13
|
+
*
|
|
14
|
+
* 用法(由 `scripts/run-tests.mjs` 以 `--import` 预加载):
|
|
15
|
+
* ```powershell
|
|
16
|
+
* node --import ./tests/support/resolve-profile-deps.mjs scripts/run-tests.mjs
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { registerHooks } from 'node:module'
|
|
21
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
22
|
+
import { join } from 'node:path'
|
|
23
|
+
import { pathToFileURL } from 'node:url'
|
|
24
|
+
|
|
25
|
+
const profileModules = join(process.env.USERPROFILE ?? process.env.HOME ?? '', '.dsh', 'profiles', 'desktop', 'node_modules')
|
|
26
|
+
|
|
27
|
+
/** 只接管 `@deepseek-ai/*` 裸说明符(相对路径与 node: 内置模块一律放行)。 */
|
|
28
|
+
function isHostBareSpecifier(specifier) {
|
|
29
|
+
return typeof specifier === 'string' && specifier.startsWith('@deepseek-ai/')
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
registerHooks({
|
|
33
|
+
resolve(specifier, context, nextResolve) {
|
|
34
|
+
try {
|
|
35
|
+
return nextResolve(specifier, context)
|
|
36
|
+
} catch (error) {
|
|
37
|
+
if (!isHostBareSpecifier(specifier)) throw error
|
|
38
|
+
/** 兜底:按 profile 的 node_modules 目录 + package.json exports 解析入口。 */
|
|
39
|
+
const dir = join(profileModules, ...specifier.split('/'))
|
|
40
|
+
const manifestPath = join(dir, 'package.json')
|
|
41
|
+
if (!existsSync(manifestPath)) throw error
|
|
42
|
+
const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'))
|
|
43
|
+
const entry = typeof manifest.exports === 'string'
|
|
44
|
+
? manifest.exports
|
|
45
|
+
: manifest.exports?.import ?? manifest.exports?.['.']?.import ?? manifest.main ?? 'index.js'
|
|
46
|
+
return { url: pathToFileURL(join(dir, entry)).href, shortCircuit: true }
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
/** 本文件只为副作用(注册钩子)。 */
|
|
52
|
+
export {}
|