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.
Files changed (58) hide show
  1. package/CHANGELOG.md +1963 -405
  2. package/README.md +88 -405
  3. package/bin/cli.mjs +509 -450
  4. package/client.js +2459 -716
  5. package/cordis.patch.yml +4 -2
  6. package/index.js +144 -14
  7. package/lib/adapter.js +476 -422
  8. package/lib/anthropic-body.js +513 -469
  9. package/lib/assemble.js +808 -420
  10. package/lib/auto-claim.js +229 -0
  11. package/lib/captcha/minter.js +61 -7
  12. package/lib/distribution-keys.js +202 -0
  13. package/lib/errors.js +281 -125
  14. package/lib/fallback.js +120 -0
  15. package/lib/local-endpoint.js +367 -352
  16. package/lib/manage-routes.js +1245 -489
  17. package/lib/model-catalog.js +57 -0
  18. package/lib/openai-gateway.js +776 -0
  19. package/lib/plan-client.js +942 -532
  20. package/lib/pool.js +771 -478
  21. package/lib/sse.js +429 -317
  22. package/lib/upstream-api.js +948 -570
  23. package/lib/upstream.js +294 -134
  24. package/lib/version-probe.js +110 -0
  25. package/package.json +84 -80
  26. package/scripts/analyze-grant-intervals.mjs +171 -0
  27. package/scripts/check-compat-rc3.mjs +21 -11
  28. package/scripts/debug-claimable.mjs +130 -0
  29. package/scripts/probe-marketing.mjs +203 -0
  30. package/scripts/restart-dsh.ps1 +119 -76
  31. package/scripts/test-claimed-pending.mjs +152 -0
  32. package/scripts/verify_compat.mjs +75 -64
  33. package/scripts/watch-marketing.mjs +155 -0
  34. package/tests/anthropic-body.test.mjs +305 -0
  35. package/tests/assembler-contract.test.mjs +256 -0
  36. package/tests/auto-claim.test.mjs +318 -0
  37. package/tests/claim-routes.test.mjs +438 -0
  38. package/tests/client-panel.test.mjs +1141 -0
  39. package/tests/distribution-keys.test.mjs +123 -0
  40. package/tests/e2e.test.mjs +388 -0
  41. package/tests/fallback-scrub.test.mjs +105 -0
  42. package/tests/fixtures/quota-200.json +1 -0
  43. package/tests/launch-command.test.mjs +68 -0
  44. package/tests/login-channel.test.mjs +102 -0
  45. package/tests/openai-gateway.test.mjs +454 -0
  46. package/tests/pinned-models.test.mjs +505 -0
  47. package/tests/plan-client.test.mjs +582 -0
  48. package/tests/pool.test.mjs +319 -0
  49. package/tests/quota-blackhole.test.mjs +409 -0
  50. package/tests/restart-script.test.mjs +53 -0
  51. package/tests/routing-quota.test.mjs +251 -0
  52. package/tests/sse.test.mjs +86 -0
  53. package/tests/stream-translator.test.mjs +137 -0
  54. package/tests/support/hanging-stream.mjs +48 -0
  55. package/tests/support/resolve-profile-deps.mjs +52 -0
  56. package/tests/upstream-error-200.test.mjs +164 -0
  57. package/tests/upstream.test.mjs +330 -0
  58. package/tests/version-probe.test.mjs +172 -0
@@ -0,0 +1,251 @@
1
+ /**
2
+ * `/routing` 的**准入口径**回归测试(1.0.1 审计)。
3
+ *
4
+ * 用户实测故障:「面板显示额度开启,对话却提示额度耗尽」。
5
+ *
6
+ * 根因口径差:
7
+ * - 面板 `/balance` 统计上游 `data.balances` 里**所有已激活 plan 的桶**;
8
+ * - 对话准入看的是**当前生效**的那一桶 + 「账号 × 模型」的 1005 硬过滤标记。
9
+ * 两者可以同时成立 —— 于是出现「显示有余量、下一句话立刻 zero content / 1005」。
10
+ *
11
+ * 本文件锁死两件事:
12
+ * 1. `/routing` 必须把准入判定依据(`quota.available/limited/expired`)显式下发;
13
+ * 2. `preview` 必须带 `?model=` 参与筛选,否则会预测一个 `pick` 根本不会选的账号。
14
+ */
15
+
16
+ import test from 'node:test'
17
+ import assert from 'node:assert/strict'
18
+
19
+ import { makeManageRoutes } from '../lib/manage-routes.js'
20
+ import { AccountPool, SqliteStore } from '../lib/pool.js'
21
+ import { mkdtempSync, rmSync } from 'node:fs'
22
+ import { tmpdir } from 'node:os'
23
+ import { join } from 'node:path'
24
+
25
+ const credential = (id) => ({ zcode_jwt: `jwt-${id}`, device_mid: `dev-${id}`, user_id: `u-${id}` })
26
+
27
+ function makeReqRes({ url = '/' } = {}) {
28
+ const req = {
29
+ method: 'GET',
30
+ url,
31
+ socket: { remoteAddress: '127.0.0.1' },
32
+ headers: { host: '127.0.0.1:58962' },
33
+ on() {
34
+ return req
35
+ },
36
+ destroy() {},
37
+ }
38
+ let captured
39
+ let status = 200
40
+ const res = {
41
+ writableEnded: false,
42
+ destroyed: false,
43
+ writeHead(code) {
44
+ status = code
45
+ },
46
+ end(text) {
47
+ res.writableEnded = true
48
+ captured = text
49
+ },
50
+ get body() {
51
+ return captured === undefined ? undefined : JSON.parse(captured)
52
+ },
53
+ get status() {
54
+ return status
55
+ },
56
+ }
57
+ return { req, res }
58
+ }
59
+
60
+ async function call(routes, path, options) {
61
+ const route = routes.find((item) => item.path === path)
62
+ assert.ok(route !== undefined, `没有注册 ${path}`)
63
+ const { req, res } = makeReqRes(options)
64
+ await route.handler(req, res)
65
+ return res
66
+ }
67
+
68
+ function withPool(fn) {
69
+ return async () => {
70
+ const dir = mkdtempSync(join(tmpdir(), 'zsp-routing-'))
71
+ const store = await new SqliteStore(join(dir, 'accounts.db'))
72
+ try {
73
+ await fn(new AccountPool({ store }), store, dir)
74
+ } finally {
75
+ store.close()
76
+ rmSync(dir, { recursive: true, force: true })
77
+ }
78
+ }
79
+ }
80
+
81
+ /** 上游余额:**已激活** plan 里还有一个 3 亿的桶,但 `balances` 里当前生效桶为 0。 */
82
+ const BALANCE_SHAPES = {
83
+ /** 面板口径「有额度」:生效桶尚有余额。 */
84
+ healthy: { remaining: 300_000_000, total: 300_000_000, expiresAt: Date.now() + 86_400_000 },
85
+ /** 面板口径「有额度」,但实际生效桶为空(未生效领取包还在 balances 里)。 */
86
+ onlyZeroBuckets: { remaining: 0, total: 0 },
87
+ /** 余额接口整体不可用。 */
88
+ failed: undefined,
89
+ }
90
+
91
+ const routesFor = (pool, balance) =>
92
+ makeManageRoutes({
93
+ pool,
94
+ client: {},
95
+ fetchBalance: async () => BALANCE_SHAPES[balance],
96
+ settings: {},
97
+ log: () => {},
98
+ })
99
+
100
+ /** 等待后台余额拉取落进缓存(2s 轮询模型的第一次 tick 就发生在响应之后)。 */
101
+ const settle = () => new Promise((resolve) => setTimeout(resolve, 10))
102
+
103
+ test('/routing: 上游已判额度用尽时,把「显示有额度 / 实际不可用」同时说清楚', withPool(async (pool) => {
104
+ const a = pool.add(credential('a'), '主号').entry
105
+ const model = 'GLM-5.3-Flash'
106
+ /** 对话刚刚在这个账号上吃了 1005 / 零内容 → 当日硬过滤标记落库。 */
107
+ pool.markModelRateLimited(a.id, model, Date.now() + 3_600_000)
108
+
109
+ const routes = routesFor(pool, 'healthy')
110
+ /**
111
+ * 第一次:缓存还空(`source: pending`),只能报「准入层面已拒绝」。
112
+ * 这正是用户看到的那一刻——面板还没刷新,对话已经报错。
113
+ */
114
+ const first = await call(routes, '/api/zcode-start-plan/routing', { url: `/api/zcode-start-plan/routing?model=${model}` })
115
+ assert.equal(first.status, 200)
116
+ const firstAccount = first.body.accounts.find((entry) => entry.accountId === a.id)
117
+ assert.equal(firstAccount.quota.limited, true, '1005 标记必须暴露')
118
+ /**
119
+ * 准入已拒:`usable` 必定 false(即使 `source: pending` 还没拉到余额);
120
+ * `available` 此时是 null(未知),因为面板口径还没数据。
121
+ */
122
+ assert.equal(firstAccount.quota.usable, false, '准入已拒 → 综合结论不可用')
123
+ assert.equal(firstAccount.quota.available, null, '面板口径未知 ≠ 已用光')
124
+ assert.equal(firstAccount.quota.source, 'pending')
125
+
126
+ /** 第二次:后台拉到了「生效桶还有 3 亿」→ 冲突组合完整呈现。 */
127
+ await settle()
128
+ const second = await call(routes, '/api/zcode-start-plan/routing', { url: `/api/zcode-start-plan/routing?model=${model}` })
129
+ const secondAccount = second.body.accounts.find((entry) => entry.accountId === a.id)
130
+ assert.equal(secondAccount.quota.source, 'upstream')
131
+ assert.equal(secondAccount.quota.available, true, '面板口径:上游生效桶有余量')
132
+ assert.equal(secondAccount.quota.limited, true, '对话口径:该账号×模型已被硬过滤')
133
+ assert.equal(secondAccount.quota.usable, false, '综合结论:不可用')
134
+ /** 前端靠 available && limited 判定「需要显式警告」的那个组合。 */
135
+ assert.equal(secondAccount.quota.available === true && secondAccount.quota.limited === true, true)
136
+ assert.match(secondAccount.quota.reason, /额度用尽/)
137
+ /** 绝不下发凭据。 */
138
+ assert.equal(JSON.stringify(second.body).includes('jwt-a'), false)
139
+ assert.equal(JSON.stringify(second.body).includes('dev-a'), false)
140
+ }))
141
+
142
+ test('/routing: preview 必须带 ?model= 才与 pick 同口径', withPool(async (pool) => {
143
+ const a = pool.add(credential('a'), 'A').entry
144
+ const b = pool.add(credential('b'), 'B').entry
145
+ pool.markModelRateLimited(a.id, 'GLM-5.3-Flash', Date.now() + 3_600_000)
146
+
147
+ const routes = routesFor(pool, 'healthy')
148
+ /** 带模型:跳过 A,预测 B(= pick 结果)。 */
149
+ const withModel = await call(routes, '/api/zcode-start-plan/routing', {
150
+ url: '/api/zcode-start-plan/routing?model=GLM-5.3-Flash',
151
+ })
152
+ assert.equal(withModel.body.preview.accountId, b.id)
153
+ assert.equal(withModel.body.preview.model, 'GLM-5.3-Flash')
154
+
155
+ /** 不带模型:语义是「不按模型过滤」,会预测 A —— 这就是 1.0.0 的 bug。 */
156
+ const withoutModel = await call(routes, '/api/zcode-start-plan/routing', { url: '/api/zcode-start-plan/routing' })
157
+ assert.equal(withoutModel.body.preview.accountId, a.id)
158
+ assert.equal(withoutModel.body.preview.model, null, '响应必须标明「这次没有按模型预览」')
159
+ }))
160
+
161
+ /**
162
+ * 判据边界(2026-11-10 变更):`quotaState.limited` **只看 `model_rate_limits`**。
163
+ *
164
+ * `last_error` 是无时间戳的历史文本,已从选号判据中删除;若 `/routing` 仍旧
165
+ * 按它判 limited,面板会与对话**再次矛盾** —— 对话照常发请求(能成功),
166
+ * 面板却红着说「已判额度用尽」。这条锁死两边同口径。
167
+ */
168
+ test('/routing: 只有 last_error 写着 1005、model_rate_limits 为空 → 不判 limited', withPool(async (pool) => {
169
+ const a = pool.add(credential('a'), '主号').entry
170
+ const model = 'GLM-5.3-Flash'
171
+ /** 历史文本(额度次日恢复后仍会留着)—— 不是判据。 */
172
+ pool.noteError(a.id, '额度用尽(1005 exceed quota limit)')
173
+
174
+ assert.deepEqual(pool.list()[0].model_rate_limits, {}, '前置:硬标记表为空')
175
+
176
+ const routes = routesFor(pool, 'healthy')
177
+ /** 等后台余额拉取落进缓存(否则面板口径还是 pending / available=null)。 */
178
+ await call(routes, '/api/zcode-start-plan/routing', { url: `/api/zcode-start-plan/routing?model=${model}` })
179
+ await settle()
180
+ const response = await call(routes, '/api/zcode-start-plan/routing', {
181
+ url: `/api/zcode-start-plan/routing?model=${model}`,
182
+ })
183
+ const account = response.body.accounts.find((entry) => entry.accountId === a.id)
184
+ assert.equal(account.quota.source, 'upstream', '前置:面板口径已拉到上游余额')
185
+ assert.equal(account.quota.limited, false, 'last_error 不是准入判据:没有当日硬标记就不许判 limited')
186
+ assert.equal(account.quota.usable, true, '面板口径有额度 + 无否决位 → 可用(与对话一致)')
187
+ assert.equal(account.quota.reason, null, '不得给出「已判额度用尽」这类结论')
188
+
189
+ /** 对照:同一个账号一旦真的落了硬标记,limited 立刻为 true。 */
190
+ pool.markModelRateLimited(a.id, model, Date.now() + 3_600_000)
191
+ const after = await call(routes, '/api/zcode-start-plan/routing', {
192
+ url: `/api/zcode-start-plan/routing?model=${model}`,
193
+ })
194
+ assert.equal(
195
+ after.body.accounts.find((entry) => entry.accountId === a.id).quota.limited,
196
+ true,
197
+ '硬标记才是 limited 的唯一依据',
198
+ )
199
+ }))
200
+
201
+ test('/routing: 余额接口失败走退避,不把 null 当成「已用光」', withPool(async (pool) => {
202
+ let calls = 0
203
+ pool.add(credential('a'), 'A')
204
+ const routes = makeManageRoutes({
205
+ pool,
206
+ client: {},
207
+ fetchBalance: async () => {
208
+ calls += 1
209
+ return undefined
210
+ },
211
+ settings: {},
212
+ log: () => {},
213
+ })
214
+ await call(routes, '/api/zcode-start-plan/routing', { url: '/api/zcode-start-plan/routing' })
215
+ await settle()
216
+ assert.equal(calls, 1)
217
+ const again = await call(routes, '/api/zcode-start-plan/routing', { url: '/api/zcode-start-plan/routing' })
218
+ /** 失败条目在退避窗口内不再重试(否则 2s 轮询每轮打一次上游)。 */
219
+ assert.equal(calls, 1, '失败后必须退避')
220
+ const account = again.body.accounts[0]
221
+ assert.equal(account.usedRatio, null, '未知不能显示成 100%')
222
+ assert.equal(account.quota.source, 'failed')
223
+ assert.equal(account.quota.available, null, '未知不能显示成「有额度」')
224
+ }))
225
+
226
+ test('/routing: 账号删除后额度缓存同步丢弃', withPool(async (pool) => {
227
+ const a = pool.add(credential('a'), 'A').entry
228
+ const routes = routesFor(pool, 'healthy')
229
+ await call(routes, '/api/zcode-start-plan/routing', { url: '/api/zcode-start-plan/routing' })
230
+ await settle()
231
+
232
+ const req = {
233
+ method: 'POST',
234
+ url: '/api/zcode-start-plan/remove',
235
+ socket: { remoteAddress: '127.0.0.1' },
236
+ headers: { host: '127.0.0.1:58962', 'content-type': 'application/json' },
237
+ on(event, handler) {
238
+ if (event === 'data') handler(Buffer.from(JSON.stringify({ id: a.id })))
239
+ if (event === 'end') handler()
240
+ return req
241
+ },
242
+ destroy() {},
243
+ }
244
+ const res = makeReqRes().res
245
+ await routes.find((item) => item.path === '/api/zcode-start-plan/remove').handler(req, res)
246
+ assert.equal(pool.list().length, 0)
247
+ /** 再查一次不应因残留缓存而崩溃或复活该账号。 */
248
+ const after = await call(routes, '/api/zcode-start-plan/routing', { url: '/api/zcode-start-plan/routing' })
249
+ assert.equal(after.body.accounts.length, 0)
250
+ assert.equal(after.body.preview, null)
251
+ }))
@@ -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,48 @@
1
+ /**
2
+ * 「上游黑洞」测试夹具:一个**永不产出、也永不结束**的响应流。
3
+ *
4
+ * 复刻 issue #4 的真实形态 —— 额度用尽后上游对该账号不再出流:
5
+ * HTTP 200 已经回来了,但 body 里一个字节都没有。谁在等它,就必须有自己的超时,
6
+ * 否则最终只会被宿主 ~300s 的超时收成一句笼统的 `PROVIDER_ERROR`。
7
+ *
8
+ * 用法:
9
+ * ```js
10
+ * const hanging = new HangingStream()
11
+ * ... body: hanging.stream ...
12
+ * t.after(() => hanging.release()) // 让挂起的读操作优雅退出,别把测试进程吊死
13
+ * ```
14
+ */
15
+ export class HangingStream {
16
+ /** @type {ReadableStream<Uint8Array>} */
17
+ stream
18
+ #controllers = []
19
+ #released = false
20
+
21
+ constructor() {
22
+ let captured
23
+ this.stream = new ReadableStream({
24
+ start: (controller) => {
25
+ captured = controller
26
+ this.#controllers.push(controller)
27
+ },
28
+ cancel: () => {
29
+ /** 被消费者取消(超时后 `decoder.cancel()`)—— 标记已释放,避免后续写报错。 */
30
+ this.#released = true
31
+ },
32
+ })
33
+ this.#controller = captured
34
+ }
35
+
36
+ #controller
37
+
38
+ /** 主动结束这条流(测试收尾用;读操作会以 `done` 退出)。 */
39
+ release() {
40
+ if (this.#released) return
41
+ this.#released = true
42
+ try {
43
+ this.#controller?.close()
44
+ } catch {
45
+ /** 已经被取消:无需再关。 */
46
+ }
47
+ }
48
+ }
@@ -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 {}