dsh-zcode-startplan 0.5.2 → 1.0.3

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 (51) hide show
  1. package/CHANGELOG.md +1963 -672
  2. package/README.md +92 -472
  3. package/bin/cli.mjs +509 -450
  4. package/client.js +2459 -1002
  5. package/cordis.patch.yml +4 -2
  6. package/index.js +109 -11
  7. package/lib/adapter.js +476 -449
  8. package/lib/anthropic-body.js +513 -469
  9. package/lib/assemble.js +808 -542
  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 -652
  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 -611
  23. package/lib/upstream.js +294 -134
  24. package/lib/version-probe.js +110 -0
  25. package/package.json +84 -81
  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 -116
  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/auto-claim.test.mjs +318 -0
  35. package/tests/claim-routes.test.mjs +438 -293
  36. package/tests/client-panel.test.mjs +1141 -356
  37. package/tests/distribution-keys.test.mjs +123 -0
  38. package/tests/e2e.test.mjs +388 -353
  39. package/tests/fallback-scrub.test.mjs +105 -0
  40. package/tests/launch-command.test.mjs +68 -0
  41. package/tests/openai-gateway.test.mjs +454 -0
  42. package/tests/pinned-models.test.mjs +505 -497
  43. package/tests/plan-client.test.mjs +582 -222
  44. package/tests/pool.test.mjs +319 -93
  45. package/tests/quota-blackhole.test.mjs +409 -0
  46. package/tests/restart-script.test.mjs +53 -0
  47. package/tests/routing-quota.test.mjs +251 -0
  48. package/tests/support/hanging-stream.mjs +48 -0
  49. package/tests/upstream-error-200.test.mjs +164 -125
  50. package/tests/upstream.test.mjs +330 -250
  51. package/tests/version-probe.test.mjs +172 -0
@@ -1,353 +1,388 @@
1
- /**
2
- * 端到端冒烟:用 CPU 内的真实组件(账号池 / plan-client / SSE 解码 / 流翻译)跑通
3
- *
4
- * ```
5
- * adapter.stream() → plan-client(选号 / captcha 探测 / 切号)→ 上游 SSE → DSH chunks
6
- * ```
7
- *
8
- * 只把「上游 HTTP」与「captcha 载体」换成假实现;`apply()` 的接线也真跑一遍。
9
- */
10
-
11
- import test from 'node:test'
12
- import assert from 'node:assert/strict'
13
- import { mkdtempSync, rmSync } from 'node:fs'
14
- import { tmpdir } from 'node:os'
15
- import { join } from 'node:path'
16
-
17
- import { AccountPool, SqliteStore } from '../lib/pool.js'
18
- import { ZcodePlanClient } from '../lib/plan-client.js'
19
- import { NativeZcodeStartPlanAdapter } from '../lib/adapter.js'
20
- import { resolveConfig, Config, apply } from '../index.js'
21
-
22
- const CREDENTIAL = { zcode_jwt: 'jwt-1', device_mid: 'dev-1', user_id: 'u-1' }
23
-
24
- const sseStream = (events) =>
25
- new ReadableStream({
26
- start(controller) {
27
- const encoder = new TextEncoder()
28
- for (const event of events) controller.enqueue(encoder.encode(`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`))
29
- controller.close()
30
- },
31
- })
32
-
33
- const textStream = () =>
34
- sseStream([
35
- { type: 'message_start', message: { model: 'GLM-5.3-Flash', usage: { input_tokens: 5 } } },
36
- { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } },
37
- { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: '## 交付物' } },
38
- { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: '\n好的' } },
39
- { type: 'content_block_stop', index: 0 },
40
- { type: 'message_delta', delta: { stop_reason: 'end_turn' }, usage: { output_tokens: 2 } },
41
- { type: 'message_stop' },
42
- ])
43
-
44
- const okResponse = (body) => ({
45
- ok: true,
46
- status: 200,
47
- headers: new Headers({ 'content-type': 'text/event-stream' }),
48
- body,
49
- })
50
-
51
- async function makeAdapter(t, options = {}) {
52
- const dir = mkdtempSync(join(tmpdir(), 'zsp-e2e-'))
53
- const store = await new SqliteStore(join(dir, 'accounts.db'))
54
- t.after(() => {
55
- store.close()
56
- rmSync(dir, { recursive: true, force: true })
57
- })
58
- const pool = new AccountPool({ store })
59
- pool.add(CREDENTIAL, '测试账号')
60
-
61
- const minter = {
62
- async mint() {
63
- return { param: 'p-1', interactive: false }
64
- },
65
- async fetchConfig() {
66
- return undefined
67
- },
68
- }
69
- const client = new ZcodePlanClient({ pool, minter, fetchImpl: options.fetchImpl })
70
- const adapter = new NativeZcodeStartPlanAdapter({
71
- client,
72
- models: async () => [
73
- { id: 'GLM-5.3-Flash', name: 'GLM-5.3-Flash', contextWindow: 1_000_000, maxTokens: 65_536, supportsImage: true },
74
- ],
75
- })
76
- return { adapter, pool, store, client }
77
- }
78
-
79
- const streamOptions = {
80
- provider: 'zcode-start-plan',
81
- model: 'GLM-5.3-Flash',
82
- maxTokens: 512,
83
- messages: [{ role: 'user', content: [{ type: 'text', text: '你好' }] }],
84
- }
85
-
86
- test('adapter.stream:产出合法的 DSH chunk 序列(以 usage + finish 收尾)', async (t) => {
87
- const { adapter } = await makeAdapter(t, { fetchImpl: async () => okResponse(textStream()) })
88
-
89
- const chunks = []
90
- for await (const chunk of adapter.stream(streamOptions)) chunks.push(chunk)
91
-
92
- const nonDelta = chunks.map((chunk) => chunk.type).filter((type) => type !== 'text-delta')
93
- assert.deepEqual(nonDelta, ['block-start', 'block-end', 'usage', 'finish'])
94
- assert.equal(
95
- chunks.filter((chunk) => chunk.type === 'text-delta').map((chunk) => chunk.text).join(''),
96
- '## 交付物\n好的',
97
- )
98
- /** finish.reason 是对象(FinishReasonMap),宿主 BlockAssembler 读 chunk.reason。 */
99
- assert.deepEqual(chunks[chunks.length - 1].reason, { kind: 'stop' })
100
- assert.equal(chunks[chunks.length - 2].usage.outputTokens, 2)
101
- })
102
-
103
- test('adapter.stream:上游失败时以 terminal finish 错误 chunk 收尾(不抛异常)', async (t) => {
104
- const { adapter } = await makeAdapter(t, {
105
- fetchImpl: async () => ({
106
- ok: false,
107
- status: 403,
108
- headers: new Headers({ 'content-type': 'application/json' }),
109
- text: async () => '{"code":3012,"msg":"request has been blocked due to unusual activity."}',
110
- }),
111
- })
112
-
113
- const chunks = []
114
- for await (const chunk of adapter.stream(streamOptions)) chunks.push(chunk)
115
- const finish = chunks[chunks.length - 1]
116
- assert.equal(finish.type, 'finish')
117
- /** 宿主读 chunk.reason(BlockAssembler);kind 在顶层会被吞成正常结束。 */
118
- assert.equal(finish.reason.kind, 'error')
119
- assert.equal(finish.reason.failure.code, 'RATE_LIMIT')
120
- assert.match(finish.reason.failure.message, /3012/)
121
- })
122
-
123
- test('adapter.listModels / resolveModel:模型元数据带上下文窗口与输入模态', async (t) => {
124
- const { adapter } = await makeAdapter(t)
125
- const models = await adapter.listModels('zcode-start-plan')
126
- assert.equal(models.length, 1)
127
- assert.equal(models[0].context.contextWindow, 1_000_000)
128
- assert.deepEqual(models[0].inputModalities, ['text', 'image'])
129
-
130
- const resolved = await adapter.resolveModel('zcode-start-plan', 'GLM-5.3-Flash')
131
- assert.equal(resolved.id, 'GLM-5.3-Flash')
132
- assert.equal(resolved.provider, 'zcode-start-plan')
133
- })
134
-
135
- test('adapter 契约:providerRetryPolicy 必须可实现(宿主直接调用它)', async (t) => {
136
- /**
137
- * `ctx.llm.registerAdapter()` 的 `prepareRoutes` 会**不带可选调用保护**地执行
138
- * `adapter.providerRetryPolicy(provider)`;漏掉它在宿主里抛
139
- * `adapter.providerRetryPolicy is not a function`,整条路由注册失败。
140
- * 这条断言把该契约钉住。
141
- */
142
- const { adapter } = await makeAdapter(t)
143
- assert.equal(typeof adapter.providerRetryPolicy, 'function')
144
- assert.equal(adapter.providerRetryPolicy('zcode-start-plan'), undefined)
145
- assert.equal(typeof adapter.providerInfo, 'function')
146
- const info = adapter.providerInfo('zcode-start-plan')
147
- assert.equal(info.id, 'zcode-start-plan')
148
- assert.ok(info.name.length > 0)
149
- })
150
-
151
- test('adapter 契约:prepareCall 必须可实现(宿主选模型后直接调用它)', async (t) => {
152
- /**
153
- * 宿主在真正发起请求前调用 `adapter.prepareCall(provider, model, signal)`。
154
- * 基类 `LlmAdapter` 有默认实现,但本适配器没有 extends 基类(避免与宿主版本耦合),
155
- * 必须自己补 —— 漏掉它表现为
156
- * `registration.adapter.prepareCall is not a function`:**选模型即报错**。
157
- */
158
- const { adapter } = await makeAdapter(t)
159
- assert.equal(typeof adapter.prepareCall, 'function')
160
-
161
- const prepared = await adapter.prepareCall('zcode-start-plan', 'GLM-5.3-Flash')
162
- assert.equal(prepared.model.provider, 'zcode-start-plan')
163
- assert.equal(prepared.model.id, 'GLM-5.3-Flash')
164
- assert.equal(typeof prepared.stream, 'function', 'stream 必须是同一次准备代际的入口')
165
-
166
- /** 流入口要真的能产出 chunk(宿主随后会消费它)。 */
167
- const chunks = []
168
- for await (const chunk of prepared.stream({
169
- provider: 'zcode-start-plan',
170
- model: 'GLM-5.3-Flash',
171
- messages: [{ role: 'user', content: [{ type: 'text', text: 'ping' }] }],
172
- })) {
173
- chunks.push(chunk)
174
- }
175
- assert.ok(chunks.length > 0, 'stream 应产出至少一个 chunk')
176
- assert.equal(chunks[chunks.length - 1].type, 'finish')
177
- })
178
-
179
- test('reasoning efforts:每个 effort 必须有非空 id 与 name,且 id 不重复', async (t) => {
180
- /**
181
- * `dsh-llm` 的 `normalizeModelInfo` 逐项校验:
182
- * typeof effort.id === 'string' && effort.id.length > 0
183
- * typeof effort.name === 'string' && effort.name.length > 0
184
- * !seen.has(effort.id)
185
- * 任一条不中即抛 `INVALID_MODEL_REASONING`
186
- * ("invalid or duplicate reasoning effort metadata"),模型在宿主里不可用。
187
- */
188
- const { toModelInfo } = await import('../lib/adapter.js')
189
-
190
- const info = toModelInfo('zcode-start-plan', {
191
- id: 'GLM-5.3',
192
- name: 'GLM-5.3',
193
- contextWindow: 1_000_000,
194
- maxTokens: 128_000,
195
- supportsImage: false,
196
- reasoningLevels: ['low', 'high', 'max'],
197
- defaultReasoningLevel: 'max',
198
- })
199
-
200
- assert.equal(info.reasoning.efforts.length, 3)
201
- for (const effort of info.reasoning.efforts) {
202
- assert.equal(typeof effort.id, 'string')
203
- assert.ok(effort.id.length > 0, 'effort.id 不能为空')
204
- assert.equal(typeof effort.name, 'string')
205
- assert.ok(effort.name.length > 0, 'effort.name 不能为空')
206
- }
207
- assert.deepEqual(info.reasoning.efforts.map((e) => e.id), ['low', 'high', 'max'])
208
- assert.equal(info.reasoning.defaultEffort, 'max')
209
-
210
- /** 重复 / 空值档位被过滤,不会让整个模型失效。 */
211
- const dirty = toModelInfo('p', { id: 'm', reasoningLevels: ['low', 'low', '', 'high'] })
212
- assert.deepEqual(dirty.reasoning.efforts.map((e) => e.id), ['low', 'high'])
213
-
214
- /** 没有档位信息时完全不带 reasoning 字段。 */
215
- const plain = toModelInfo('p', { id: 'm' })
216
- assert.equal(plain.reasoning, undefined)
217
- })
218
-
219
- test('Config 校验:非法 captcha.mode / debugPort 被拒,合法值补齐默认', () => {
220
- assert.throws(() => Config({ captcha: { mode: 'browser' } }))
221
- assert.throws(() => Config({ captcha: { debugPort: 0 } }))
222
- assert.throws(() => Config({ models: 'GLM' }))
223
-
224
- const good = Config({ captcha: { debugPort: 9333 } })
225
- assert.deepEqual(good.captcha, { mode: 'cdp', debugPort: 9333, origin: 'https://zcode.z.ai/' })
226
- assert.deepEqual(good.models, ['GLM-5.3-Flash', 'GLM-5.3'])
227
- assert.equal(resolveConfig(undefined).provider, 'zcode-start-plan')
228
- })
229
-
230
- test('apply:等 llm 出现后注册 adapter + 状态工具,dispose 时收尾', async (t) => {
231
- const dir = mkdtempSync(join(tmpdir(), 'zsp-apply-'))
232
- t.after(() => rmSync(dir, { recursive: true, force: true }))
233
-
234
- const registered = []
235
- const tools = []
236
- const disposers = []
237
- const intervals = []
238
- const routes = []
239
- /**
240
- * 宿主的 `ctx` 是**沙箱 facade**:只暴露 `inject` 声明过的服务。
241
- * 实测(一次性诊断插件):`Object.keys(ctx)` 仅 `['fiber']`;
242
- * 碰未声明的服务直接抛 `cannot get property "tools" without inject`。
243
- * 因此这里按插件的 `inject` 列表(llm/tools/timer)提供服务,
244
- * 并**不提供** `emit` / `on` / `setInterval`。
245
- *
246
- * ⚠ `webServer` **不在 facade 上**(它走可选注入 `ctx.inject(['webServer'], …)`):
247
- * 这里提供 `inject` 实现来模拟宿主:服务已就绪则立即回调,并把 webServer
248
- * 交进去。0.4.4 的「面板永远 404」正是因为从 facade 上探测 `ctx.webServer`
249
- * —— 永远拿不到 —— 而静默跳过注册。
250
- */
251
- const ctx = {
252
- logger: { info() {}, warn() {} },
253
- llm: {
254
- registerAdapter: (providers, adapter) => {
255
- registered.push({ providers, adapter })
256
- return () => {}
257
- },
258
- /** 沙箱里没有 ctx.emit,改用 llm 自己的发布入口。 */
259
- emitAdaptersUpdated() {},
260
- },
261
- tools: { register: (tool) => { tools.push(tool); return () => {} } },
262
- timer: {
263
- interval: (callback, delay) => {
264
- intervals.push(delay)
265
- return () => {}
266
- },
267
- },
268
- /**
269
- * 可选注入:宿主只把 `{ webServer }` 这一小份 service 交给回调。
270
- * 回调里用的 `webCtx.effect` 由宿主托管,这里同样交给 disposers 收集。
271
- */
272
- inject(services, callback) {
273
- assert.deepEqual(services, ['webServer'])
274
- callback({
275
- webServer: {
276
- register: (route) => {
277
- routes.push(route)
278
- return () => {}
279
- },
280
- },
281
- effect(fn) {
282
- const disposer = fn()
283
- if (typeof disposer === 'function') disposers.push(disposer)
284
- return disposer
285
- },
286
- })
287
- return () => {}
288
- },
289
- effect(fn) {
290
- /**
291
- * 宿主语义:`fn` 同步执行,**返回的 disposer 由 effect 持有**;
292
- * 测试里收集它,模拟 fiber 释放。
293
- */
294
- const disposer = fn()
295
- if (typeof disposer === 'function') disposers.push(disposer)
296
- return disposer
297
- },
298
- }
299
-
300
- const pluginCleanup = apply(ctx, { dataDir: dir })
301
-
302
- for (let i = 0; i < 200 && registered.length === 0; i += 1) {
303
- await new Promise((resolve) => setTimeout(resolve, 20))
304
- }
305
-
306
- assert.equal(registered.length, 1)
307
- assert.deepEqual(registered[0].providers, ['zcode-start-plan'])
308
- assert.equal(typeof registered[0].adapter.stream, 'function')
309
- assert.equal(tools.length, 1)
310
- assert.equal(tools[0].name, 'zcode_start_plan_status')
311
- assert.deepEqual(intervals, [60 * 60_000], '应通过 ctx.timer.interval 注册每小时清理')
312
-
313
- /**
314
- * ⚠ 面板 404 的回归闸:管理路由必须经**可选注入**挂到 `webServer` 上。
315
- * 0.4.4 从 facade 探测 `ctx.webServer` → 拿不到 → 静默跳过 → 面板永远 404。
316
- * 这里断言 15 条 `/api/zcode-start-plan/*` 路由真的注册进了路由表。
317
- */
318
- assert.equal(routes.length, 15, `应注册 15 条账号面板路由,实际 ${routes.length}`)
319
- const paths = routes.map((route) => route.path).sort()
320
- assert.ok(paths.includes('/api/zcode-start-plan/summary'), '缺少 /summary(面板首次加载就靠它)')
321
- assert.ok(paths.includes('/api/zcode-start-plan/login/start'), '缺少 /login/start')
322
- assert.ok(paths.includes('/api/zcode-start-plan/login/poll'), '缺少 /login/poll')
323
- assert.ok(paths.includes('/api/zcode-start-plan/claimable'), '缺少 /claimable(赠送额度查询)')
324
- assert.ok(paths.includes('/api/zcode-start-plan/claim'), '缺少 /claim(赠送额度领取)')
325
- assert.ok(paths.includes('/api/zcode-start-plan/restart-cdp'), '缺少 /restart-cdp(以调试端口重启)')
326
- assert.ok(routes.every((route) => route.kind === 'exact'), '路由必须都是 exact kind')
327
-
328
- const status = await tools[0].execute()
329
- assert.equal(status.provider, 'zcode-start-plan')
330
- assert.equal(status.accountCount, 0)
331
- assert.equal(typeof status.captcha.reachable, 'boolean')
332
- /** 官方标准要求 apply 交出 cleanup,且状态工具能报告适配器是否真的注册上。 */
333
- assert.equal(status.adapterRegistered, true, '状态工具应报告适配器已注册')
334
-
335
- /**
336
- * ⚠ 输出必须**无损 JSON**:宿主把 `JSON.parse(text)` 与原值深比较,
337
- * 带缩进的序列化、以及含 `undefined` 的对象都会被判 `value is not lossless JSON`,
338
- * 整个工具结果被拒。
339
- */
340
- const rendered = tools[0].output.render({}, status)
341
- assert.equal(rendered[0].type, 'text')
342
- const parsed = JSON.parse(rendered[0].text)
343
- assert.deepEqual(parsed, JSON.parse(JSON.stringify(status)))
344
- /** 结果里不得有 undefined 值(会被 stringify 静默丢弃)。 */
345
- assert.equal(JSON.stringify(parsed), JSON.stringify(status))
346
- /** 缺省值一律 null(不是 undefined)—— 否则 round-trip 后键会消失。 */
347
- assert.equal(status.error, null)
348
- assert.equal(status.captcha.reason === null || typeof status.captcha.reason === 'string', true)
349
- assert.equal(typeof pluginCleanup, 'function', 'apply 必须返回 cleanup')
350
-
351
- /** 收尾只走 apply 的返回值(它内部会释放 SQLite / 端点 / captcha)。 */
352
- await pluginCleanup()
353
- })
1
+ /**
2
+ * 端到端冒烟:用 CPU 内的真实组件(账号池 / plan-client / SSE 解码 / 流翻译)跑通
3
+ *
4
+ * ```
5
+ * adapter.stream() → plan-client(选号 / captcha 探测 / 切号)→ 上游 SSE → DSH chunks
6
+ * ```
7
+ *
8
+ * 只把「上游 HTTP」与「captcha 载体」换成假实现;`apply()` 的接线也真跑一遍。
9
+ */
10
+
11
+ import test from 'node:test'
12
+ import assert from 'node:assert/strict'
13
+ import { mkdtempSync, rmSync } from 'node:fs'
14
+ import { tmpdir } from 'node:os'
15
+ import { join } from 'node:path'
16
+
17
+ import { AccountPool, SqliteStore } from '../lib/pool.js'
18
+ import { ZcodePlanClient } from '../lib/plan-client.js'
19
+ import { NativeZcodeStartPlanAdapter } from '../lib/adapter.js'
20
+ import { resolveConfig, Config, apply } from '../index.js'
21
+
22
+ const CREDENTIAL = { zcode_jwt: 'jwt-1', device_mid: 'dev-1', user_id: 'u-1' }
23
+
24
+ const sseStream = (events) =>
25
+ new ReadableStream({
26
+ start(controller) {
27
+ const encoder = new TextEncoder()
28
+ for (const event of events) controller.enqueue(encoder.encode(`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`))
29
+ controller.close()
30
+ },
31
+ })
32
+
33
+ const textStream = () =>
34
+ sseStream([
35
+ { type: 'message_start', message: { model: 'GLM-5.3-Flash', usage: { input_tokens: 5 } } },
36
+ { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } },
37
+ { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: '## 交付物' } },
38
+ { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: '\n好的' } },
39
+ { type: 'content_block_stop', index: 0 },
40
+ { type: 'message_delta', delta: { stop_reason: 'end_turn' }, usage: { output_tokens: 2 } },
41
+ { type: 'message_stop' },
42
+ ])
43
+
44
+ const okResponse = (body) => ({
45
+ ok: true,
46
+ status: 200,
47
+ headers: new Headers({ 'content-type': 'text/event-stream' }),
48
+ body,
49
+ })
50
+
51
+ async function makeAdapter(t, options = {}) {
52
+ const dir = mkdtempSync(join(tmpdir(), 'zsp-e2e-'))
53
+ const store = await new SqliteStore(join(dir, 'accounts.db'))
54
+ t.after(() => {
55
+ store.close()
56
+ rmSync(dir, { recursive: true, force: true })
57
+ })
58
+ const pool = new AccountPool({ store })
59
+ pool.add(CREDENTIAL, '测试账号')
60
+
61
+ const minter = {
62
+ async mint() {
63
+ return { param: 'p-1', interactive: false }
64
+ },
65
+ async fetchConfig() {
66
+ return undefined
67
+ },
68
+ }
69
+ const client = new ZcodePlanClient({ pool, minter, fetchImpl: options.fetchImpl })
70
+ const adapter = new NativeZcodeStartPlanAdapter({
71
+ client,
72
+ models: async () => [
73
+ { id: 'GLM-5.3-Flash', name: 'GLM-5.3-Flash', contextWindow: 1_000_000, maxTokens: 65_536, supportsImage: true },
74
+ ],
75
+ })
76
+ return { adapter, pool, store, client }
77
+ }
78
+
79
+ const streamOptions = {
80
+ provider: 'zcode-start-plan',
81
+ model: 'GLM-5.3-Flash',
82
+ maxTokens: 512,
83
+ messages: [{ role: 'user', content: [{ type: 'text', text: '你好' }] }],
84
+ }
85
+
86
+ test('adapter.stream:产出合法的 DSH chunk 序列(以 usage + finish 收尾)', async (t) => {
87
+ const { adapter } = await makeAdapter(t, { fetchImpl: async () => okResponse(textStream()) })
88
+
89
+ const chunks = []
90
+ for await (const chunk of adapter.stream(streamOptions)) chunks.push(chunk)
91
+
92
+ const nonDelta = chunks.map((chunk) => chunk.type).filter((type) => type !== 'text-delta')
93
+ assert.deepEqual(nonDelta, ['block-start', 'block-end', 'usage', 'finish'])
94
+ assert.equal(
95
+ chunks.filter((chunk) => chunk.type === 'text-delta').map((chunk) => chunk.text).join(''),
96
+ '## 交付物\n好的',
97
+ )
98
+ /** finish.reason 是对象(FinishReasonMap),宿主 BlockAssembler 读 chunk.reason。 */
99
+ assert.deepEqual(chunks[chunks.length - 1].reason, { kind: 'stop' })
100
+ assert.equal(chunks[chunks.length - 2].usage.outputTokens, 2)
101
+ })
102
+
103
+ test('adapter.stream:上游失败时以 terminal finish 错误 chunk 收尾(不抛异常)', async (t) => {
104
+ const { adapter } = await makeAdapter(t, {
105
+ fetchImpl: async () => ({
106
+ ok: false,
107
+ status: 403,
108
+ headers: new Headers({ 'content-type': 'application/json' }),
109
+ text: async () => '{"code":3012,"msg":"request has been blocked due to unusual activity."}',
110
+ }),
111
+ })
112
+
113
+ const chunks = []
114
+ for await (const chunk of adapter.stream(streamOptions)) chunks.push(chunk)
115
+ const finish = chunks[chunks.length - 1]
116
+ assert.equal(finish.type, 'finish')
117
+ /** 宿主读 chunk.reason(BlockAssembler);kind 在顶层会被吞成正常结束。 */
118
+ assert.equal(finish.reason.kind, 'error')
119
+ /**
120
+ * 3012 的码是**独立**的 `RISK_BLOCKED`(不是 RATE_LIMIT):RATE_LIMIT 收窄为
121
+ * 「只表示 3009 并发限流」。宿主按码路由 —— 混同会让它对风控做指数退避重试,
122
+ * 而风控有账号级累积惩罚(30 分钟 → 24 小时 → 停用)。
123
+ */
124
+ assert.equal(finish.reason.failure.code, 'RISK_BLOCKED')
125
+ /**
126
+ * issue #2:**终止块必须已脱敏** —— code 保真,message 只说人话。
127
+ * 上游原文(含 3012 业务码、unusual activity)只该出现在插件日志里;
128
+ * 否则用户会看到「另一个通道的判定文案」,排查方向直接被带偏。
129
+ */
130
+ assert.doesNotMatch(finish.reason.failure.message, /3012/)
131
+ assert.doesNotMatch(finish.reason.failure.message, /unusual\s+activity/i)
132
+ assert.match(finish.reason.failure.message, /风控/)
133
+ /** 文案要能区分「不是额度问题」,并说明已自动清除限流标记(否则用户会去等重置)。 */
134
+ assert.match(finish.reason.failure.message, /非额度问题/)
135
+ assert.match(finish.reason.failure.message, /清除/)
136
+ })
137
+
138
+ test('adapter.listModels / resolveModel:模型元数据带上下文窗口与输入模态', async (t) => {
139
+ const { adapter } = await makeAdapter(t)
140
+ const models = await adapter.listModels('zcode-start-plan')
141
+ assert.equal(models.length, 1)
142
+ assert.equal(models[0].context.contextWindow, 1_000_000)
143
+ assert.deepEqual(models[0].inputModalities, ['text', 'image'])
144
+
145
+ const resolved = await adapter.resolveModel('zcode-start-plan', 'GLM-5.3-Flash')
146
+ assert.equal(resolved.id, 'GLM-5.3-Flash')
147
+ assert.equal(resolved.provider, 'zcode-start-plan')
148
+ })
149
+
150
+ test('adapter 契约:providerRetryPolicy 必须可实现(宿主直接调用它)', async (t) => {
151
+ /**
152
+ * `ctx.llm.registerAdapter()` 的 `prepareRoutes` 会**不带可选调用保护**地执行
153
+ * `adapter.providerRetryPolicy(provider)`;漏掉它在宿主里抛
154
+ * `adapter.providerRetryPolicy is not a function`,整条路由注册失败。
155
+ * 这条断言把该契约钉住。
156
+ */
157
+ const { adapter } = await makeAdapter(t)
158
+ assert.equal(typeof adapter.providerRetryPolicy, 'function')
159
+ assert.equal(adapter.providerRetryPolicy('zcode-start-plan'), undefined)
160
+ assert.equal(typeof adapter.providerInfo, 'function')
161
+ const info = adapter.providerInfo('zcode-start-plan')
162
+ assert.equal(info.id, 'zcode-start-plan')
163
+ assert.ok(info.name.length > 0)
164
+ })
165
+
166
+ test('adapter 契约:prepareCall 必须可实现(宿主选模型后直接调用它)', async (t) => {
167
+ /**
168
+ * 宿主在真正发起请求前调用 `adapter.prepareCall(provider, model, signal)`。
169
+ * 基类 `LlmAdapter` 有默认实现,但本适配器没有 extends 基类(避免与宿主版本耦合),
170
+ * 必须自己补 —— 漏掉它表现为
171
+ * `registration.adapter.prepareCall is not a function`:**选模型即报错**。
172
+ */
173
+ const { adapter } = await makeAdapter(t)
174
+ assert.equal(typeof adapter.prepareCall, 'function')
175
+
176
+ const prepared = await adapter.prepareCall('zcode-start-plan', 'GLM-5.3-Flash')
177
+ assert.equal(prepared.model.provider, 'zcode-start-plan')
178
+ assert.equal(prepared.model.id, 'GLM-5.3-Flash')
179
+ assert.equal(typeof prepared.stream, 'function', 'stream 必须是同一次准备代际的入口')
180
+
181
+ /** 流入口要真的能产出 chunk(宿主随后会消费它)。 */
182
+ const chunks = []
183
+ for await (const chunk of prepared.stream({
184
+ provider: 'zcode-start-plan',
185
+ model: 'GLM-5.3-Flash',
186
+ messages: [{ role: 'user', content: [{ type: 'text', text: 'ping' }] }],
187
+ })) {
188
+ chunks.push(chunk)
189
+ }
190
+ assert.ok(chunks.length > 0, 'stream 应产出至少一个 chunk')
191
+ assert.equal(chunks[chunks.length - 1].type, 'finish')
192
+ })
193
+
194
+ test('reasoning efforts:每个 effort 必须有非空 id 与 name,且 id 不重复', async (t) => {
195
+ /**
196
+ * `dsh-llm` 的 `normalizeModelInfo` 逐项校验:
197
+ * typeof effort.id === 'string' && effort.id.length > 0
198
+ * typeof effort.name === 'string' && effort.name.length > 0
199
+ * !seen.has(effort.id)
200
+ * 任一条不中即抛 `INVALID_MODEL_REASONING`
201
+ * ("invalid or duplicate reasoning effort metadata"),模型在宿主里不可用。
202
+ */
203
+ const { toModelInfo } = await import('../lib/adapter.js')
204
+
205
+ const info = toModelInfo('zcode-start-plan', {
206
+ id: 'GLM-5.3',
207
+ name: 'GLM-5.3',
208
+ contextWindow: 1_000_000,
209
+ maxTokens: 128_000,
210
+ supportsImage: false,
211
+ reasoningLevels: ['low', 'high', 'max'],
212
+ defaultReasoningLevel: 'max',
213
+ })
214
+
215
+ assert.equal(info.reasoning.efforts.length, 3)
216
+ for (const effort of info.reasoning.efforts) {
217
+ assert.equal(typeof effort.id, 'string')
218
+ assert.ok(effort.id.length > 0, 'effort.id 不能为空')
219
+ assert.equal(typeof effort.name, 'string')
220
+ assert.ok(effort.name.length > 0, 'effort.name 不能为空')
221
+ }
222
+ assert.deepEqual(info.reasoning.efforts.map((e) => e.id), ['low', 'high', 'max'])
223
+ assert.equal(info.reasoning.defaultEffort, 'max')
224
+
225
+ /** 重复 / 空值档位被过滤,不会让整个模型失效。 */
226
+ const dirty = toModelInfo('p', { id: 'm', reasoningLevels: ['low', 'low', '', 'high'] })
227
+ assert.deepEqual(dirty.reasoning.efforts.map((e) => e.id), ['low', 'high'])
228
+
229
+ /** 没有档位信息时完全不带 reasoning 字段。 */
230
+ const plain = toModelInfo('p', { id: 'm' })
231
+ assert.equal(plain.reasoning, undefined)
232
+ })
233
+
234
+ test('Config 校验:非法 captcha.mode / debugPort 被拒,合法值补齐默认', () => {
235
+ assert.throws(() => Config({ captcha: { mode: 'browser' } }))
236
+ assert.throws(() => Config({ captcha: { debugPort: 0 } }))
237
+ assert.throws(() => Config({ models: 'GLM' }))
238
+
239
+ const good = Config({ captcha: { debugPort: 9333 } })
240
+ assert.deepEqual(good.captcha, { mode: 'cdp', debugPort: 9333, origin: 'https://zcode.z.ai/' })
241
+ assert.deepEqual(good.models, ['GLM-5.3-Flash', 'GLM-5.3'])
242
+ assert.equal(resolveConfig(undefined).provider, 'zcode-start-plan')
243
+ })
244
+
245
+ test('apply:等 llm 出现后注册 adapter + 状态工具,dispose 时收尾', async (t) => {
246
+ const dir = mkdtempSync(join(tmpdir(), 'zsp-apply-'))
247
+ t.after(() => rmSync(dir, { recursive: true, force: true }))
248
+
249
+ const registered = []
250
+ const tools = []
251
+ const disposers = []
252
+ const intervals = []
253
+ const routes = []
254
+ /**
255
+ * 宿主的 `ctx` 是**沙箱 facade**:只暴露 `inject` 声明过的服务。
256
+ * 实测(一次性诊断插件):`Object.keys(ctx)` 仅 `['fiber']`;
257
+ * 碰未声明的服务直接抛 `cannot get property "tools" without inject`。
258
+ * 因此这里按插件的 `inject` 列表(llm/tools/timer)提供服务,
259
+ * 并**不提供** `emit` / `on` / `setInterval`。
260
+ *
261
+ * ⚠ `webServer` **不在 facade 上**(它走可选注入 `ctx.inject(['webServer'], …)`):
262
+ * 这里提供 `inject` 实现来模拟宿主:服务已就绪则立即回调,并把 webServer
263
+ * 交进去。0.4.4 的「面板永远 404」正是因为从 facade 上探测 `ctx.webServer`
264
+ * —— 永远拿不到 —— 而静默跳过注册。
265
+ */
266
+ const ctx = {
267
+ logger: { info() {}, warn() {} },
268
+ llm: {
269
+ registerAdapter: (providers, adapter) => {
270
+ registered.push({ providers, adapter })
271
+ return () => {}
272
+ },
273
+ /** 沙箱里没有 ctx.emit,改用 llm 自己的发布入口。 */
274
+ emitAdaptersUpdated() {},
275
+ },
276
+ tools: { register: (tool) => { tools.push(tool); return () => {} } },
277
+ timer: {
278
+ interval: (callback, delay) => {
279
+ intervals.push(delay)
280
+ return () => {}
281
+ },
282
+ },
283
+ /**
284
+ * 可选注入:宿主只把 `{ webServer }` 这一小份 service 交给回调。
285
+ * 回调里用的 `webCtx.effect` 由宿主托管,这里同样交给 disposers 收集。
286
+ */
287
+ inject(services, callback) {
288
+ assert.deepEqual(services, ['webServer'])
289
+ callback({
290
+ webServer: {
291
+ register: (route) => {
292
+ routes.push(route)
293
+ return () => {}
294
+ },
295
+ },
296
+ effect(fn) {
297
+ const disposer = fn()
298
+ if (typeof disposer === 'function') disposers.push(disposer)
299
+ return disposer
300
+ },
301
+ })
302
+ return () => {}
303
+ },
304
+ effect(fn) {
305
+ /**
306
+ * 宿主语义:`fn` 同步执行,**返回的 disposer 由 effect 持有**;
307
+ * 测试里收集它,模拟 fiber 释放。
308
+ */
309
+ const disposer = fn()
310
+ if (typeof disposer === 'function') disposers.push(disposer)
311
+ return disposer
312
+ },
313
+ }
314
+
315
+ const pluginCleanup = apply(ctx, { dataDir: dir })
316
+
317
+ for (let i = 0; i < 200 && registered.length === 0; i += 1) {
318
+ await new Promise((resolve) => setTimeout(resolve, 20))
319
+ }
320
+
321
+ assert.equal(registered.length, 1)
322
+ assert.deepEqual(registered[0].providers, ['zcode-start-plan'])
323
+ assert.equal(typeof registered[0].adapter.stream, 'function')
324
+ assert.equal(tools.length, 1)
325
+ assert.equal(tools[0].name, 'zcode_start_plan_status')
326
+ /**
327
+ * 两条定时器:①每小时清过期限流标记;②自动领取心跳(60 秒)。
328
+ * ⚠ 自动领取**必须常驻**只注册一次 —— 拨盘切换不能重启宿主才能生效,
329
+ * 所以不能把它做成「开启时才注册」。
330
+ *
331
+ * ⚠ 心跳周期是 **60 秒**,不是 `autoClaim.intervalMs`:旧实现直接把轮询间隔
332
+ * (默认 30 分钟/6 小时)当定时器周期,而 `ctx.timer.interval` 首轮要等满一个
333
+ * 周期才触发 ⇒ 宿主启动后最长 6 小时内一次都不跑(`lastRunAt` 恒 0),
334
+ * 用户看到的就是「自动领取无作用」。现在心跳只负责「到点了吗」的判定,
335
+ * 真正的节流由 `lastRunAt` 与 `intervalMs` 比较完成。
336
+ */
337
+ assert.deepEqual(
338
+ [...intervals].sort((a, b) => a - b),
339
+ [60_000, 60 * 60_000],
340
+ '应注册每小时清理 + 每分钟自动领取心跳',
341
+ )
342
+
343
+ /**
344
+ * ⚠ 面板 404 的回归闸:管理路由必须经**可选注入**挂到 `webServer` 上。
345
+ * 0.4.4 从 facade 探测 `ctx.webServer` → 拿不到 → 静默跳过 → 面板永远 404。
346
+ * 这里断言 18 条 `/api/zcode-start-plan/*` 路由真的注册进了路由表。
347
+ * (0.9.3 加了 /openai-gateway:状态 + 开关;0.9.7 删了无调用方的 /use;
348
+ * 1.0.0 加了 /routing:模型栏旁「当前使用账号」的实时数据源。)
349
+ */
350
+ assert.equal(routes.length, 18, `应注册 18 条账号面板路由,实际 ${routes.length}`)
351
+ const paths = routes.map((route) => route.path).sort()
352
+ assert.ok(!paths.includes('/api/zcode-start-plan/use'), '/use 已移除(0.7.0 起 expiry 选号,置顶不再决定取号)')
353
+ assert.ok(paths.includes('/api/zcode-start-plan/summary'), '缺少 /summary(面板首次加载就靠它)')
354
+ assert.ok(paths.includes('/api/zcode-start-plan/routing'), '缺少 /routing(模型栏旁的「当前使用账号」靠它)')
355
+ assert.ok(paths.includes('/api/zcode-start-plan/auto-claim'), '缺少 /auto-claim(自动领取开关)')
356
+ assert.ok(paths.includes('/api/zcode-start-plan/login/start'), '缺少 /login/start')
357
+ assert.ok(paths.includes('/api/zcode-start-plan/login/poll'), '缺少 /login/poll')
358
+ assert.ok(paths.includes('/api/zcode-start-plan/claimable'), '缺少 /claimable(赠送额度查询)')
359
+ assert.ok(paths.includes('/api/zcode-start-plan/claim'), '缺少 /claim(赠送额度领取)')
360
+ assert.ok(paths.includes('/api/zcode-start-plan/restart-cdp'), '缺少 /restart-cdp(以调试端口重启)')
361
+ assert.ok(routes.every((route) => route.kind === 'exact'), '路由必须都是 exact kind')
362
+
363
+ const status = await tools[0].execute()
364
+ assert.equal(status.provider, 'zcode-start-plan')
365
+ assert.equal(status.accountCount, 0)
366
+ assert.equal(typeof status.captcha.reachable, 'boolean')
367
+ /** 官方标准要求 apply 交出 cleanup,且状态工具能报告适配器是否真的注册上。 */
368
+ assert.equal(status.adapterRegistered, true, '状态工具应报告适配器已注册')
369
+
370
+ /**
371
+ * ⚠ 输出必须**无损 JSON**:宿主把 `JSON.parse(text)` 与原值深比较,
372
+ * 带缩进的序列化、以及含 `undefined` 的对象都会被判 `value is not lossless JSON`,
373
+ * 整个工具结果被拒。
374
+ */
375
+ const rendered = tools[0].output.render({}, status)
376
+ assert.equal(rendered[0].type, 'text')
377
+ const parsed = JSON.parse(rendered[0].text)
378
+ assert.deepEqual(parsed, JSON.parse(JSON.stringify(status)))
379
+ /** 结果里不得有 undefined 值(会被 stringify 静默丢弃)。 */
380
+ assert.equal(JSON.stringify(parsed), JSON.stringify(status))
381
+ /** 缺省值一律 null(不是 undefined)—— 否则 round-trip 后键会消失。 */
382
+ assert.equal(status.error, null)
383
+ assert.equal(status.captcha.reason === null || typeof status.captcha.reason === 'string', true)
384
+ assert.equal(typeof pluginCleanup, 'function', 'apply 必须返回 cleanup')
385
+
386
+ /** 收尾只走 apply 的返回值(它内部会释放 SQLite / 端点 / captcha)。 */
387
+ await pluginCleanup()
388
+ })