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,256 @@
1
+ /**
2
+ * 与宿主 `BlockAssembler` 的**契约级**测试。
3
+ *
4
+ * 宿主 `dsh-llm/lib/index.js` 的 `BlockAssembler` 逐字如下:
5
+ *
6
+ * ```js
7
+ * case "block-start": partials.set(index, { blockType: chunk.blockType, text: "", toolCallArguments: "" })
8
+ * case "text-delta":
9
+ * case "reasoning-delta": partial.text += chunk.text
10
+ * case "tool-call-delta": toolCallId = chunk.id; toolCallName = chunk.name; toolCallArguments += chunk.argumentsDelta
11
+ * case "block-end": partial.block = chunk.block
12
+ * ```
13
+ *
14
+ * ⚠ 三处形状必须严格对上,否则宿主侧炸:
15
+ * - `block-start` 用 **`blockType`(字符串)**,不是 `block`(对象);
16
+ * - `block-end` **必须带 `block`**(assemble 直接返回它);
17
+ * - `tool-call-delta` 的字段名是 `id` / `name` / **`argumentsDelta`**。
18
+ *
19
+ * 另有一处「不炸但静默出错」的形状:`finish` 块的 kind 必须包在 **`reason`
20
+ * 对象**里(`{ type: 'finish', reason: { kind, failure? } }`)—— 宿主
21
+ * `BlockAssembler` 读 `chunk.reason`;kind 放顶层时错误会被吞成正常结束。
22
+ */
23
+
24
+ import test from 'node:test'
25
+ import assert from 'node:assert/strict'
26
+
27
+ import { AnthropicStreamTranslator } from '../lib/stream-translator.js'
28
+
29
+ /** 宿主 `BlockAssembler` 的忠实复刻(用于验证我们的 chunk 形状)。 */
30
+ class HostBlockAssembler {
31
+ partials = new Map()
32
+ order = []
33
+ _usage
34
+ _finish
35
+
36
+ push(chunk) {
37
+ switch (chunk.type) {
38
+ case 'block-start':
39
+ if (!this.partials.has(chunk.index)) {
40
+ this.order.push(chunk.index)
41
+ this.partials.set(chunk.index, { blockType: chunk.blockType, text: '', toolCallArguments: '' })
42
+ }
43
+ return
44
+ case 'text-delta':
45
+ case 'reasoning-delta': {
46
+ const partial = this.ensure(chunk.index, chunk.type === 'text-delta' ? 'text' : 'reasoning')
47
+ if (partial.block) return
48
+ partial.text += chunk.text
49
+ return
50
+ }
51
+ case 'tool-call-delta': {
52
+ const partial = this.ensure(chunk.index, 'tool-call')
53
+ if (partial.block) return
54
+ partial.toolCallId = chunk.id
55
+ if (chunk.name) partial.toolCallName = chunk.name
56
+ partial.toolCallArguments += chunk.argumentsDelta
57
+ return
58
+ }
59
+ case 'block-end': {
60
+ const partial = this.ensure(chunk.index, chunk.block.type)
61
+ if (partial.block) return
62
+ partial.block = chunk.block
63
+ return
64
+ }
65
+ case 'usage':
66
+ this._usage = chunk.usage
67
+ return
68
+ case 'finish':
69
+ this._finish = chunk.reason
70
+ return
71
+ default:
72
+ throw new Error(`unknown chunk type "${chunk.type}"`)
73
+ }
74
+ }
75
+
76
+ ensure(index, blockType) {
77
+ let partial = this.partials.get(index)
78
+ if (!partial) {
79
+ partial = { blockType, text: '', toolCallArguments: '' }
80
+ this.partials.set(index, partial)
81
+ this.order.push(index)
82
+ }
83
+ return partial
84
+ }
85
+
86
+ assemble(partial) {
87
+ if (partial.block) return partial.block
88
+ switch (partial.blockType) {
89
+ case 'text':
90
+ return { type: 'text', text: partial.text }
91
+ case 'reasoning':
92
+ return { type: 'reasoning', text: partial.text }
93
+ case 'tool-call':
94
+ return {
95
+ type: 'tool-call',
96
+ id: partial.toolCallId ?? 'call',
97
+ name: partial.toolCallName ?? '',
98
+ arguments: partial.toolCallArguments,
99
+ }
100
+ default:
101
+ throw new Error(`cannot assemble incomplete block of type "${partial.blockType}"`)
102
+ }
103
+ }
104
+
105
+ assembled() {
106
+ return this.order.map((index) => this.assemble(this.partials.get(index)))
107
+ }
108
+ }
109
+
110
+ /** 思考型模型的一次完整流(reasoning + text + tool_use)。 */
111
+ const thinkingModelStream = () => [
112
+ { data: { type: 'message_start', message: { model: 'GLM-5.3-Flash', usage: { input_tokens: 10 } } } },
113
+ { data: { type: 'content_block_start', index: 0, content_block: { type: 'thinking', thinking: '' } } },
114
+ { data: { type: 'content_block_delta', index: 0, delta: { type: 'thinking_delta', thinking: '先想一下' } } },
115
+ { data: { type: 'content_block_stop', index: 0 } },
116
+ { data: { type: 'content_block_start', index: 1, content_block: { type: 'text', text: '' } } },
117
+ { data: { type: 'content_block_delta', index: 1, delta: { type: 'text_delta', text: '答案' } } },
118
+ { data: { type: 'content_block_stop', index: 1 } },
119
+ { data: { type: 'content_block_start', index: 2, content_block: { type: 'tool_use', id: 'toolu_1', name: 'pwsh', input: {} } } },
120
+ { data: { type: 'content_block_delta', index: 2, delta: { type: 'input_json_delta', partial_json: '{"cmd":' } } },
121
+ { data: { type: 'content_block_delta', index: 2, delta: { type: 'input_json_delta', partial_json: '"ls"}' } } },
122
+ { data: { type: 'content_block_stop', index: 2 } },
123
+ { data: { type: 'message_delta', delta: { stop_reason: 'tool_use' }, usage: { output_tokens: 5 } } },
124
+ ]
125
+
126
+ /** 把一条流跑过 translator + 宿主 assembler,返回两边的产物。 */
127
+ const runThrough = (events) => {
128
+ const translator = new AnthropicStreamTranslator()
129
+ const assembler = new HostBlockAssembler()
130
+ const chunks = []
131
+ for (const event of events) {
132
+ for (const chunk of translator.push(event)) {
133
+ chunks.push(chunk)
134
+ assembler.push(chunk)
135
+ }
136
+ }
137
+ for (const chunk of translator.finish()) {
138
+ chunks.push(chunk)
139
+ assembler.push(chunk)
140
+ }
141
+ return { chunks, blocks: assembler.assembled() }
142
+ }
143
+
144
+ test('宿主 assembler 能完整组装思考型模型的三种块(reasoning/text/tool-call)', () => {
145
+ const { chunks, blocks } = runThrough(thinkingModelStream())
146
+
147
+ assert.deepEqual(chunks.map((chunk) => chunk.type), [
148
+ 'block-start',
149
+ 'reasoning-delta',
150
+ 'block-end',
151
+ 'block-start',
152
+ 'text-delta',
153
+ 'block-end',
154
+ 'block-start',
155
+ 'tool-call-delta',
156
+ 'tool-call-delta',
157
+ 'block-end',
158
+ 'usage',
159
+ 'finish',
160
+ ])
161
+
162
+ assert.deepEqual(blocks, [
163
+ { type: 'reasoning', text: '先想一下' },
164
+ { type: 'text', text: '答案' },
165
+ { type: 'tool-call', id: 'toolu_1', name: 'pwsh', arguments: '{"cmd":"ls"}' },
166
+ ])
167
+ })
168
+
169
+ test('finish.reason 必须是 FinishReasonMap 形态的对象(宿主读 chunk.reason)', () => {
170
+ /**
171
+ * 宿主 `BlockAssembler`:`case "finish": this._finish = chunk.reason`。
172
+ * agent-loop 再按 `finish.kind === 'error' | 'aborted'` 判错。
173
+ * kind 放顶层(没有 reason 包裹)时,宿主读到 undefined → 默认 `{ kind: 'stop' }`,
174
+ * 流内错误被静默吞成正常结束。
175
+ */
176
+ const { chunks } = runThrough(thinkingModelStream())
177
+ const finish = chunks.find((c) => c.type === 'finish')
178
+ assert.equal(finish.kind, undefined, 'kind 必须在 reason 里,不能放顶层')
179
+ assert.deepEqual(finish.reason, { kind: 'tool-calls' })
180
+
181
+ /** 流内错误同样要包在 reason 里,且带稳定 failure 码。 */
182
+ const translator = new AnthropicStreamTranslator()
183
+ translator.push({ data: { type: 'error', error: { type: 'api_error', message: '{"code":3012}' } } })
184
+ const errFinish = translator.finish().find((c) => c.type === 'finish')
185
+ assert.equal(errFinish.reason.kind, 'error')
186
+ assert.equal(errFinish.reason.failure.code, 'RATE_LIMIT')
187
+ })
188
+
189
+ test('block-start 必须带 blockType 字符串(不是 block 对象)', () => {
190
+ const { chunks } = runThrough(thinkingModelStream())
191
+ for (const chunk of chunks.filter((c) => c.type === 'block-start')) {
192
+ assert.equal(typeof chunk.blockType, 'string', 'blockType 必须是字符串')
193
+ assert.ok(chunk.blockType.length > 0)
194
+ assert.equal(chunk.block, undefined, 'block-start 不该带 block(那是 block-end 的字段)')
195
+ }
196
+ })
197
+
198
+ test('block-end 必须带完整 block 对象', () => {
199
+ const { chunks } = runThrough(thinkingModelStream())
200
+ for (const chunk of chunks.filter((c) => c.type === 'block-end')) {
201
+ assert.equal(typeof chunk.block, 'object')
202
+ assert.notEqual(chunk.block, null)
203
+ assert.ok(['text', 'reasoning', 'tool-call'].includes(chunk.block.type))
204
+ }
205
+ })
206
+
207
+ test('tool-call-delta 的字段名是 id / name / argumentsDelta', () => {
208
+ const { chunks } = runThrough(thinkingModelStream())
209
+ const deltas = chunks.filter((c) => c.type === 'tool-call-delta')
210
+ assert.equal(deltas.length, 2)
211
+ assert.equal(deltas[0].id, 'toolu_1')
212
+ assert.equal(deltas[0].name, 'pwsh')
213
+ assert.equal(deltas[0].argumentsDelta, '{"cmd":')
214
+ assert.equal(deltas[1].argumentsDelta, '"ls"}')
215
+ assert.equal(deltas[0].arguments, undefined, '字段名是 argumentsDelta,不是 arguments')
216
+ })
217
+
218
+ test('流未正常结束时,finish() 也补齐 block-end + block', () => {
219
+ const translator = new AnthropicStreamTranslator()
220
+ const chunks = []
221
+ for (const chunk of translator.push({
222
+ data: { type: 'content_block_start', index: 0, content_block: { type: 'thinking', thinking: '' } },
223
+ })) {
224
+ chunks.push(chunk)
225
+ }
226
+ for (const chunk of translator.push({
227
+ data: { type: 'content_block_delta', index: 0, delta: { type: 'thinking_delta', thinking: '半截思考' } },
228
+ })) {
229
+ chunks.push(chunk)
230
+ }
231
+ for (const chunk of translator.finish()) chunks.push(chunk)
232
+
233
+ const end = chunks.find((c) => c.type === 'block-end')
234
+ assert.notEqual(end, undefined)
235
+ assert.deepEqual(end.block, { type: 'reasoning', text: '半截思考' })
236
+ })
237
+
238
+ test('工具参数是原始 JSON 字符串(宿主不做解析)', () => {
239
+ const { blocks } = runThrough(thinkingModelStream())
240
+ const tool = blocks.find((block) => block.type === 'tool-call')
241
+ assert.equal(typeof tool.arguments, 'string')
242
+ assert.deepEqual(JSON.parse(tool.arguments), { cmd: 'ls' })
243
+ })
244
+
245
+ test('宿主 assembler 接收只有内联 input 的工具调用且参数不丢失', () => {
246
+ const { blocks } = runThrough([
247
+ { data: { type: 'content_block_start', index: 0, content_block: {
248
+ type: 'tool_use', id: 'toolu_inline', name: 'pwsh',
249
+ input: { description: '列出文件', command: 'Get-ChildItem' },
250
+ } } },
251
+ { data: { type: 'content_block_stop', index: 0 } },
252
+ ])
253
+ assert.deepEqual(JSON.parse(blocks[0].arguments), {
254
+ description: '列出文件', command: 'Get-ChildItem',
255
+ })
256
+ })
@@ -0,0 +1,318 @@
1
+ /**
2
+ * 营销活动发现(marketing/touch)与自动领取状态机。
3
+ *
4
+ * 实证来源:ZCode 客户端 3.16.3 反编译(`createMarketingTouchService` / 分发按钮
5
+ * schema `{type:"claim_zcode_plan", args:{plan_id}}`)。响应形状:
6
+ * `{code:0, data:{server_time, language, deliveries:[{campaign_id, priority,
7
+ * resource_position, banner|popup:{buttons:[…]}]}}}`
8
+ */
9
+
10
+ import test from 'node:test'
11
+ import assert from 'node:assert/strict'
12
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
13
+ import { tmpdir } from 'node:os'
14
+ import { join } from 'node:path'
15
+
16
+ import { fetchClaimablePlans } from '../lib/upstream-api.js'
17
+ import { createAutoClaim, loadAutoClaimState, saveAutoClaimState } from '../lib/auto-claim.js'
18
+
19
+ const CREDENTIAL = { zcode_jwt: 'jwt-1', device_mid: 'dev-1', user_id: 'u-1' }
20
+
21
+ /** 构造一个官方形状的 marketing/touch 响应体。 */
22
+ const touchResponse = (deliveries, { withAuth = false } = {}) => ({
23
+ code: 0,
24
+ data: {
25
+ server_time: 1790000000,
26
+ language: 'zh-CN',
27
+ deliveries,
28
+ },
29
+ })
30
+
31
+ const delivery = ({ planId, campaignId = 'camp-1', priority = 50, position = 'popup', label = '立即领取' }) => ({
32
+ campaign_id: campaignId,
33
+ priority,
34
+ resource_position: position,
35
+ ...(position === 'popup'
36
+ ? { popup: { title: { format: 'plaintext', content: '活动' }, buttons: [
37
+ { text: { format: 'plaintext', content: '关闭' }, action: { type: 'close' } },
38
+ { text: { format: 'plaintext', content: label }, action: { type: 'claim_zcode_plan', args: { plan_id: planId } } },
39
+ ] } }
40
+ : { banner: { background: { type: 'image', image: { default: { src: 'https://x/y.png', sha256: 'a'.repeat(64) } } }, buttons: [
41
+ { text: { format: 'plaintext', content: label }, action: { type: 'claim_zcode_plan', args: { plan_id: planId } } },
42
+ ] } }),
43
+ })
44
+
45
+ const response = (body, { status = 200, seenHeaders } = {}) => ({
46
+ ok: status >= 200 && status < 300,
47
+ status,
48
+ headers: new Headers({ 'content-type': 'application/json' }),
49
+ json: async () => (typeof body === 'string' ? JSON.parse(body) : body),
50
+ text: async () => JSON.stringify(body),
51
+ ...(seenHeaders ? {} : {}),
52
+ })
53
+
54
+ test('fetchClaimablePlans: 从 marketing/touch 投放按钮里提取 plan_id', async () => {
55
+ let seen
56
+ const fetchImpl = async (_url, init) => {
57
+ seen = init.headers
58
+ return response(touchResponse([
59
+ delivery({ planId: 'plan-a', priority: 90 }),
60
+ delivery({ planId: 'plan-b', campaignId: 'camp-2', priority: 30, position: 'banner' }),
61
+ ]))
62
+ }
63
+ const plans = await fetchClaimablePlans(CREDENTIAL, fetchImpl)
64
+ assert.deepEqual(plans.map((plan) => plan.planId), ['plan-a', 'plan-b'], '按 priority 降序')
65
+ assert.equal(plans[0].campaignId, 'camp-1')
66
+ assert.equal(plans[0].name, '立即领取', '按钮文案作为活动名')
67
+ assert.equal(seen['X-Device-Mid'], 'dev-1')
68
+ assert.equal(seen['X-Client-Language'], 'zh-CN', '服务端按语言过滤投放')
69
+ })
70
+
71
+ test('fetchClaimablePlans: 同 planId 去重;非 claim 按钮忽略(双来源后同 plan 保留首见 campaign)', async () => {
72
+ const fetchImpl = async () => response(touchResponse([
73
+ delivery({ planId: 'plan-a', campaignId: 'camp-low', priority: 10 }),
74
+ delivery({ planId: 'plan-a', campaignId: 'camp-high', priority: 80 }),
75
+ delivery({ planId: '', priority: 99 }),
76
+ ]))
77
+ const plans = await fetchClaimablePlans(CREDENTIAL, fetchImpl)
78
+ assert.equal(plans.length, 1)
79
+ /**
80
+ * 0.8.0 对齐参考实现的合并语义:同 planId **preview 优先 / 首见保留**,
81
+ * 只补 campaignId,不再按 priority 覆盖 —— 领取成功后回执要发到
82
+ * 「第一次见到它」的那个 campaign。
83
+ */
84
+ assert.equal(plans[0].campaignId, 'camp-low')
85
+ assert.equal(plans[0].priority, 10)
86
+ })
87
+
88
+ test('fetchClaimablePlans: 非 200 / 坏 JSON / 空投放 → 空数组不抛错', async () => {
89
+ assert.deepEqual(await fetchClaimablePlans(CREDENTIAL, async () => response('no', { status: 500 })), [])
90
+ const badJson = { ok: true, status: 200, headers: new Headers(), json: async () => { throw new Error('x') }, text: async () => 'x' }
91
+ assert.deepEqual(await fetchClaimablePlans(CREDENTIAL, async () => badJson), [])
92
+ assert.deepEqual(await fetchClaimablePlans(CREDENTIAL, async () => response(touchResponse([]))), [])
93
+ const networkFail = async () => { throw new Error('ECONNRESET') }
94
+ assert.deepEqual(await fetchClaimablePlans(CREDENTIAL, networkFail), [])
95
+ })
96
+
97
+ /** autoClaim 的最小池。 */
98
+ function fakePool(credentials = [{ id: 'acct-a', credential: CREDENTIAL }]) {
99
+ const state = credentials.map((entry) => ({ nickname: entry.id, enabled: true, ...entry }))
100
+ return {
101
+ list: (_options) => state,
102
+ get: (id) => state.find((entry) => entry.id === id),
103
+ }
104
+ }
105
+
106
+ /** 开关语义:探测永远自动,**领取是开关项**(用例验证领取侧,故显式开启)。 */
107
+ const enabled = (extra) => ({ enabled: true, ...extra })
108
+
109
+ function withStateDir(fn) {
110
+ return async () => {
111
+ const dir = mkdtempSync(join(tmpdir(), 'zsp-auto-claim-'))
112
+ try {
113
+ await fn(dir)
114
+ } finally {
115
+ rmSync(dir, { recursive: true, force: true })
116
+ }
117
+ }
118
+ }
119
+
120
+ test('autoClaim: 默认关闭 —— tick 空转,绝不代替用户领取;拨盘即时生效', withStateDir(async (dir) => {
121
+ const stateFile = join(dir, 'auto-claim-state.json')
122
+ const pool = fakePool()
123
+ let minted = 0
124
+ let claimed = 0
125
+ let scanned = 0
126
+ const autoClaim = createAutoClaim({
127
+ pool,
128
+ client: { mintCaptcha: async () => { minted += 1; return { param: 'p', region: 'cn' } } },
129
+ fetchClaimablePlans: async () => { scanned += 1; return [{ planId: 'plan-a' }] },
130
+ claimPlan: async () => { claimed += 1; return { ok: true, code: 0 } },
131
+ stateFile,
132
+ })
133
+
134
+ assert.equal(autoClaim.isEnabled(), false, '未显式开启 = 关')
135
+ assert.deepEqual(await autoClaim.tick(), [], '关闭时 tick 不扫、不领')
136
+ assert.equal(scanned, 0, '关闭时连探测都不做(探测由面板/CLI 触发)')
137
+ assert.equal(minted, 0, '绝不烧 captcha')
138
+ assert.equal(claimed, 0)
139
+
140
+ /** 打开后立即生效(无需重启);已领集合从空开始正常记录。 */
141
+ assert.equal(autoClaim.setEnabled(true), true)
142
+ await autoClaim.tick()
143
+ assert.equal(claimed, 1, '开启后才真正领取')
144
+ assert.equal(autoClaim.stats().enabled, true)
145
+
146
+ /** 再关掉:记录保留,不再新增。 */
147
+ assert.equal(autoClaim.setEnabled(false), false)
148
+ assert.deepEqual(await autoClaim.tick(), [])
149
+ assert.equal(claimed, 1)
150
+ assert.equal(autoClaim.stats().seenCount, 1, '关掉不清历史记录')
151
+ assert.equal(autoClaim.stats().enabled, false)
152
+ }))
153
+
154
+ test('autoClaim: 发现新 planId 才烧 captcha;终态码记 seen 不再重试', withStateDir(async (dir) => {
155
+ const stateFile = join(dir, 'auto-claim-state.json')
156
+ const pool = fakePool()
157
+ const mints = []
158
+ const claims = []
159
+ const autoClaim = createAutoClaim(enabled({
160
+ pool,
161
+ client: { mintCaptcha: async () => { mints.push(1); return { param: `p-${mints.length}`, region: 'cn' } } },
162
+ fetchClaimablePlans: async () => [{ planId: 'plan-a', campaignId: 'camp-1', name: '活动A' }],
163
+ claimPlan: async (_credential, planId) => {
164
+ claims.push(planId)
165
+ return { ok: true, code: 0 }
166
+ },
167
+ stateFile,
168
+ now: () => 1_000,
169
+ }))
170
+
171
+ const first = await autoClaim.tick()
172
+ assert.equal(claims.length, 1)
173
+ assert.equal(first[0].ok, true)
174
+ assert.equal(autoClaim.seenSnapshot()['acct-a']['plan-a'].code, 0)
175
+ assert.equal(readFileSync(stateFile, 'utf8').includes('plan-a'), true, '已持久化')
176
+
177
+ /** 第二轮:同一 planId 已是终态 → 不再 mint、不再 claim。 */
178
+ await autoClaim.tick()
179
+ assert.equal(mints.length, 1, 'captcha 不重复烧')
180
+ assert.equal(claims.length, 1)
181
+ }))
182
+
183
+ test('autoClaim: 非终态码(网络/异常)不记 seen,下轮重试', withStateDir(async (dir) => {
184
+ const stateFile = join(dir, 'auto-claim-state.json')
185
+ const pool = fakePool()
186
+ let calls = 0
187
+ const autoClaim = createAutoClaim(enabled({
188
+ pool,
189
+ client: { mintCaptcha: async () => ({ param: 'p', region: 'cn' }) },
190
+ fetchClaimablePlans: async () => [{ planId: 'plan-x' }],
191
+ claimPlan: async () => {
192
+ calls += 1
193
+ return { ok: false, code: 999, message: '服务器开小差' }
194
+ },
195
+ stateFile,
196
+ }))
197
+ await autoClaim.tick()
198
+ await autoClaim.tick()
199
+ assert.equal(calls, 2, '非终态 → 每轮重试')
200
+ assert.equal(autoClaim.seenSnapshot()['acct-a']?.['plan-x'], undefined, '非终态绝不入 seen')
201
+
202
+ /** captcha 失败同样不记 seen。 */
203
+ let mintCalls = 0
204
+ const failingCaptcha = createAutoClaim(enabled({
205
+ pool,
206
+ client: { mintCaptcha: async () => { mintCalls += 1; throw new Error('CDP 不可达') } },
207
+ fetchClaimablePlans: async () => [{ planId: 'plan-y' }],
208
+ claimPlan: async () => { throw new Error('should not be called') },
209
+ stateFile,
210
+ }))
211
+ const results = await failingCaptcha.tick()
212
+ assert.equal(results[0].ok, false)
213
+ assert.match(results[0].error, /CDP 不可达/)
214
+ assert.equal(failingCaptcha.seenSnapshot()['acct-a']?.['plan-y'], undefined, 'captcha 失败绝不入 seen')
215
+ assert.equal(failingCaptcha.stats().seenCount, 0)
216
+ }))
217
+
218
+ test('autoClaim: 1003(已领过)与 1005(领完)同样入终态', withStateDir(async (dir) => {
219
+ const pool = fakePool([
220
+ { id: 'acct-a', credential: CREDENTIAL },
221
+ { id: 'acct-b', credential: { ...CREDENTIAL, user_id: 'u-2' } },
222
+ ])
223
+ const autoClaim = createAutoClaim(enabled({
224
+ pool,
225
+ client: { mintCaptcha: async () => ({ param: 'p', region: 'cn' }) },
226
+ fetchClaimablePlans: async (credential) => [
227
+ { planId: credential.user_id === 'u-1' ? 'plan-claimed' : 'plan-gone' },
228
+ ],
229
+ claimPlan: async (credential) => (credential.user_id === 'u-1' ? { ok: true, code: 1003, alreadyClaimed: true } : { ok: false, code: 1005 }),
230
+ stateFile: join(dir, 'state.json'),
231
+ }))
232
+ await autoClaim.tick()
233
+ const seen = autoClaim.seenSnapshot()
234
+ assert.equal(seen['acct-a']['plan-claimed'].code, 1003)
235
+ assert.equal(seen['acct-b']['plan-gone'].code, 1005)
236
+ assert.equal(autoClaim.stats().seenCount, 2)
237
+ }))
238
+
239
+ /**
240
+ * confirm 回执纪律(docs/upstream-protocol.md「领取与活动发现」):
241
+ * **只在 `0`/`1003` 后发 `confirm`**。失败时发 = 叫服务端别再投了(白丢机会);
242
+ * 成功不发 = 服务端重复投放(每轮白烧 captcha)。
243
+ */
244
+ test('autoClaim: confirm 只在 0/1003 后发;1005/网络失败绝不发', withStateDir(async (dir) => {
245
+ const pool = fakePool([
246
+ { id: 'acct-a', credential: CREDENTIAL },
247
+ { id: 'acct-b', credential: { ...CREDENTIAL, user_id: 'u-2' } },
248
+ { id: 'acct-c', credential: { ...CREDENTIAL, user_id: 'u-3' } },
249
+ ])
250
+ const confirms = []
251
+ const autoClaim = createAutoClaim(enabled({
252
+ pool,
253
+ client: { mintCaptcha: async () => ({ param: 'p', region: 'cn' }) },
254
+ fetchClaimablePlans: async (credential) => [
255
+ { planId: `plan-${credential.user_id}`, campaignId: `camp-${credential.user_id}` },
256
+ ],
257
+ claimPlan: async (credential) => {
258
+ if (credential.user_id === 'u-1') return { ok: true, code: 0 }
259
+ if (credential.user_id === 'u-2') return { ok: true, code: 1003, alreadyClaimed: true }
260
+ return { ok: false, code: 1005 }
261
+ },
262
+ reportMarketingAction: async (_credential, campaignId) => { confirms.push(campaignId) },
263
+ stateFile: join(dir, 'state.json'),
264
+ }))
265
+ await autoClaim.tick()
266
+ assert.deepEqual(confirms.sort(), ['camp-u-1', 'camp-u-2'], '0/1003 发 confirm,1005 不发')
267
+ }))
268
+
269
+ test('autoClaim: 查投放前补活跃上报(不补则 preview 恒空,自动领取静默失效)', withStateDir(async (dir) => {
270
+ const pool = fakePool()
271
+ const activations = []
272
+ let sawPlansFirst = false
273
+ let activationBeforePlans = true
274
+ const autoClaim = createAutoClaim(enabled({
275
+ pool,
276
+ client: { mintCaptcha: async () => ({ param: 'p', region: 'cn' }) },
277
+ reportActivation: async () => { activations.push(1) },
278
+ fetchClaimablePlans: async () => {
279
+ if (activations.length === 0) activationBeforePlans = false
280
+ return []
281
+ },
282
+ stateFile: join(dir, 'state.json'),
283
+ }))
284
+ await autoClaim.tick()
285
+ assert.equal(activations.length, 1, '每个启用账号每轮补一次')
286
+ assert.equal(activationBeforePlans, true, 'reportActivation 必须先于 fetchClaimablePlans')
287
+ assert.equal(sawPlansFirst, false)
288
+ }))
289
+
290
+ test('autoClaim: 状态文件坏 / 版本不识别 → 空状态起跑;禁用账号跳过', withStateDir(async (dir) => {
291
+ const stateFile = join(dir, 'state.json')
292
+ writeFileSync(stateFile, '{broken json')
293
+ assert.deepEqual(loadAutoClaimState(stateFile), {})
294
+ writeFileSync(stateFile, JSON.stringify({ version: 99, seen: { a: { p: { code: 0 } } } }))
295
+ assert.deepEqual(loadAutoClaimState(stateFile), {})
296
+ /** 非终态码(如 999)在加载时被剔除。 */
297
+ writeFileSync(stateFile, JSON.stringify({ version: 1, seen: { acct: { keep: { code: 1003, at: 5 }, drop: { code: 999, at: 5 } } } }))
298
+ assert.deepEqual(loadAutoClaimState(stateFile), { acct: { keep: { code: 1003, at: 5 } } })
299
+
300
+ const pool = fakePool([
301
+ { id: 'acct-on', credential: CREDENTIAL },
302
+ { id: 'acct-off', credential: { ...CREDENTIAL, user_id: 'u-2' }, enabled: false },
303
+ ])
304
+ const probed = []
305
+ const autoClaim = createAutoClaim(enabled({
306
+ pool,
307
+ client: { mintCaptcha: async () => ({ param: 'p', region: 'cn' }) },
308
+ fetchClaimablePlans: async (credential) => { probed.push(credential.user_id); return [] },
309
+ claimPlan: async () => ({}),
310
+ stateFile,
311
+ }))
312
+ await autoClaim.tick()
313
+ assert.deepEqual(probed, ['u-1'], '停用账号不参与扫描')
314
+ /** 父路径是文件 → mkdir 必失败 → 返回 false 而不是抛(轮询链路绝不能崩)。 */
315
+ const blocker = join(dir, 'blocker.txt')
316
+ writeFileSync(blocker, 'x')
317
+ assert.equal(saveAutoClaimState(join(blocker, 'child', 's.json'), {}), false, '目录建不出时报告失败而不是抛')
318
+ }))