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
@@ -1,64 +1,75 @@
1
- /**
2
- * DSH 兼容性门禁(离线,不发网络请求)。
3
- *
4
- * DSH 在加载 bundle 时会用 `evaluatePluginCompatibility` 检查 `peerDependencies` 里
5
- * 所有 `@deepseek-ai/dsh-*` 项,并用 `includePrerelease: true` 比较版本 ——
6
- * 所以写 `^0.2.0` 会把 `0.2.0-rc.2` 判成**不兼容**并静默跳过本 bundle。
7
- * 本脚本在重启前把这件事提前暴露出来。
8
- *
9
- * ```powershell
10
- * node scripts/verify_compat.mjs
11
- * ```
12
- */
13
-
14
- import { readFileSync } from 'node:fs'
15
- import { fileURLToPath } from 'node:url'
16
- import { dirname, join } from 'node:path'
17
-
18
- const here = dirname(fileURLToPath(import.meta.url))
19
- const root = join(here, '..')
20
- const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'))
21
-
22
- /** 本插件实际使用、且会被门禁检查的宿主包。 */
23
- const REQUIRED_HOST_PACKAGES = ['@deepseek-ai/dsh-llm']
24
-
25
- const failures = []
26
- const notes = []
27
-
28
- const peers = pkg.peerDependencies ?? {}
29
- for (const name of REQUIRED_HOST_PACKAGES) {
30
- if (typeof peers[name] !== 'string') {
31
- failures.push(`peerDependencies 缺 ${name} —— DSH 不会报错,但本插件依赖它的契约`)
32
- }
33
- }
34
-
35
- for (const [name, range] of Object.entries(peers)) {
36
- if (!name.startsWith('@deepseek-ai/dsh-')) continue
37
- /** prerelease 陷阱:区间里没有 prerelease 段时,rc 版会被判为不满足。 */
38
- if (/^\^?\d+\.\d+\.\d+$/.test(range)) {
39
- notes.push(
40
- `${name}: "${range}" 不含 prerelease 段;若宿主是 0.x 的 rc 版本会被判不兼容(建议写成 "^0.2.1-rc.3" 这类)`,
41
- )
42
- }
43
- }
44
-
45
- /** 本地实现必须能 `node --check` 通过(语法错误的 bundle 会被静默跳过)。 */
46
- const entry = join(root, pkg.main ?? 'index.js')
47
- try {
48
- readFileSync(entry)
49
- } catch {
50
- failures.push(`入口文件不存在:${entry}`)
51
- }
52
-
53
- if (notes.length > 0) {
54
- process.stdout.write('注意:\n')
55
- for (const note of notes) process.stdout.write(` · ${note}\n`)
56
- }
57
-
58
- if (failures.length > 0) {
59
- process.stderr.write('兼容性门禁失败:\n')
60
- for (const failure of failures) process.stderr.write(` ✗ ${failure}\n`)
61
- process.exit(1)
62
- }
63
-
64
- process.stdout.write('✓ 兼容性门禁通过(peerDependencies 不会被判不兼容)\n')
1
+ /**
2
+ * DSH 兼容性门禁(离线,不发网络请求)。
3
+ *
4
+ * DSH 在加载 bundle 时会用 `evaluatePluginCompatibility` 检查 `peerDependencies` 里
5
+ * 所有 `@deepseek-ai/dsh-*` 项,并用 `includePrerelease: true` 比较版本 ——
6
+ * 所以写 `^0.2.0` 会把 `0.2.0-rc.2` 判成**不兼容**并静默跳过本 bundle。
7
+ * 本脚本在重启前把这件事提前暴露出来。
8
+ *
9
+ * ```powershell
10
+ * node scripts/verify_compat.mjs
11
+ * ```
12
+ */
13
+
14
+ import { readFileSync } from 'node:fs'
15
+ import { fileURLToPath } from 'node:url'
16
+ import { dirname, join } from 'node:path'
17
+
18
+ const here = dirname(fileURLToPath(import.meta.url))
19
+ const root = join(here, '..')
20
+ const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'))
21
+
22
+ /** 本插件实际使用、且会被门禁检查的宿主包。 */
23
+ const REQUIRED_HOST_PACKAGES = ['@deepseek-ai/dsh-llm']
24
+
25
+ const failures = []
26
+ const notes = []
27
+
28
+ const peers = pkg.peerDependencies ?? {}
29
+ for (const name of REQUIRED_HOST_PACKAGES) {
30
+ if (typeof peers[name] !== 'string') {
31
+ failures.push(`peerDependencies 缺 ${name} —— DSH 不会报错,但本插件依赖它的契约`)
32
+ }
33
+ }
34
+
35
+ for (const [name, range] of Object.entries(peers)) {
36
+ if (!name.startsWith('@deepseek-ai/dsh-')) continue
37
+ /**
38
+ * prerelease 陷阱:区间里没有与宿主 `major.minor.patch` 元组一致的 prerelease
39
+ * 比较符时,rc / alpha 版会被判为不满足 —— 而且 `^0.2.1-rc.3` 这类写法还会漏掉
40
+ * 下一个元组(`0.2.2-rc.1` 不满足它)。正确写法是按元组列出显式 prerelease 分支,
41
+ * 例如 `>=0.2.1-alpha.1 <0.2.2 || >=0.2.2-0 <0.3.0-0`。
42
+ */
43
+ const tuples = [...range.matchAll(/(\d+\.\d+\.\d+)-[0-9A-Za-z.-]+/g)]
44
+ if (/^\^?\d+\.\d+\.\d+$/.test(range)) {
45
+ notes.push(
46
+ `${name}: "${range}" 不含 prerelease 段;若宿主是 0.x 的 rc / alpha 版本会被判不兼容`,
47
+ )
48
+ } else if (tuples.length === 1) {
49
+ notes.push(
50
+ `${name}: "${range}" 只覆盖了 ${tuples[0][1]} 这一个元组;下一个元组的预发布版` +
51
+ `(如 0.2.2-rc.1)会被漏掉,建议改成按元组分列的 || 形式`,
52
+ )
53
+ }
54
+ }
55
+
56
+ /** 本地实现必须能 `node --check` 通过(语法错误的 bundle 会被静默跳过)。 */
57
+ const entry = join(root, pkg.main ?? 'index.js')
58
+ try {
59
+ readFileSync(entry)
60
+ } catch {
61
+ failures.push(`入口文件不存在:${entry}`)
62
+ }
63
+
64
+ if (notes.length > 0) {
65
+ process.stdout.write('注意:\n')
66
+ for (const note of notes) process.stdout.write(` · ${note}\n`)
67
+ }
68
+
69
+ if (failures.length > 0) {
70
+ process.stderr.write('兼容性门禁失败:\n')
71
+ for (const failure of failures) process.stderr.write(` ✗ ${failure}\n`)
72
+ process.exit(1)
73
+ }
74
+
75
+ process.stdout.write('✓ 兼容性门禁通过(peerDependencies 不会被判不兼容)\n')
@@ -0,0 +1,155 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 盯守某个账号是否被投放活动(只读)。
4
+ *
5
+ * 用途:区分「还没轮到」和「不会被轮到」—— 前者 deliveries/plans 会在某次轮询里
6
+ * 变非空,后者永远不会。森也的 1103 是 00:04:53 才被授予的,说明服务端是分批下发,
7
+ * 单次探测为空不足以判断资格。
8
+ *
9
+ * 用法:
10
+ * node scripts/watch-marketing.mjs <ACCOUNT_ID> [--interval 60] [--for 60]
11
+ *
12
+ * --interval 秒,默认 60
13
+ * --for 最多跑多少分钟,默认 60(到点自动停)
14
+ *
15
+ * 只读:不 claim、不 mint captcha、不发 marketing touch/action(confirm/cancel 都会
16
+ * 改变服务端对后续投放的行为,这里一律不碰)。
17
+ */
18
+
19
+ import { existsSync } from 'node:fs'
20
+ import { join } from 'node:path'
21
+
22
+ const GATED_MIN = '3.16.3'
23
+ const ORIGIN = 'https://zcode.z.ai'
24
+
25
+ const accountId = process.argv[2]
26
+ const flag = (name, fallback) => {
27
+ const index = process.argv.indexOf(`--${name}`)
28
+ if (index === -1) return fallback
29
+ const value = Number(process.argv[index + 1])
30
+ return Number.isFinite(value) && value > 0 ? value : fallback
31
+ }
32
+ const intervalSec = flag('interval', 60)
33
+ const forMinutes = flag('for', 60)
34
+
35
+ if (typeof accountId !== 'string' || !/^[0-9a-f-]{36}$/.test(accountId)) {
36
+ console.error('用法:node scripts/watch-marketing.mjs <ACCOUNT_ID> [--interval 60] [--for 60]')
37
+ process.exit(2)
38
+ }
39
+
40
+ function cmpVersion(a, b) {
41
+ const seg = (v) => String(v).split('.').map((p) => { const m = /^\s*(\d+)/.exec(p); return m ? Number(m[1]) : 0 })
42
+ const l = seg(a), r = seg(b)
43
+ for (let i = 0; i < Math.max(l.length, r.length); i += 1) {
44
+ const x = l[i] ?? 0, y = r[i] ?? 0
45
+ if (x !== y) return x < y ? -1 : 1
46
+ }
47
+ return 0
48
+ }
49
+
50
+ function gatedVersion(credential) {
51
+ const v = typeof credential?.app_version === 'string' ? credential.app_version.trim() : ''
52
+ if (!/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/.test(v)) return GATED_MIN
53
+ return cmpVersion(v, GATED_MIN) < 0 ? GATED_MIN : v
54
+ }
55
+
56
+ async function loadCredential(id) {
57
+ const dataDir = [join(process.env.USERPROFILE ?? process.env.HOME ?? '.', '.dsh', 'zcode-start-plan')]
58
+ .find((dir) => existsSync(dir))
59
+ if (dataDir === undefined) throw new Error('找不到 ~/.dsh/zcode-start-plan')
60
+ const { DatabaseSync } = await import('node:sqlite')
61
+ const db = new DatabaseSync(join(dataDir, 'accounts.db'), { readOnly: true })
62
+ const row = db.prepare('select * from accounts where id = ?').get(id)
63
+ db.close()
64
+ if (row === undefined) throw new Error(`账号不存在:${id}`)
65
+ const credential = typeof row.credential === 'string' ? JSON.parse(row.credential) : row.credential
66
+ return { credential, nickname: row.nickname ?? id }
67
+ }
68
+
69
+ function headersFor(credential) {
70
+ const version = gatedVersion(credential)
71
+ return {
72
+ 'User-Agent': `ZCode/${version}`,
73
+ 'HTTP-Referer': ORIGIN,
74
+ 'X-Title': 'Z Code@electron',
75
+ 'X-ZCode-App-Version': version,
76
+ 'X-Release-Channel': 'production',
77
+ 'X-Client-Language': 'zh-CN',
78
+ 'X-Client-Timezone': 'Asia/Shanghai',
79
+ 'X-Device-Mid': credential.device_mid,
80
+ 'X-Platform': 'win32-x64',
81
+ 'X-Os-Category': 'windows',
82
+ 'X-Os-Version': '10.0.19045',
83
+ 'X-ZCode-Agent': 'glm',
84
+ 'X-Session-Id': credential.session_id ?? crypto.randomUUID(),
85
+ 'X-ZCode-Session-Type': 'other',
86
+ 'X-Request-Id': crypto.randomUUID(),
87
+ 'X-ZCode-Trace-Id': crypto.randomUUID(),
88
+ 'anthropic-version': '2023-06-01',
89
+ Accept: 'application/json',
90
+ authorization: `Bearer ${credential.zcode_jwt}`,
91
+ }
92
+ }
93
+
94
+ function findClaimButtons(node, depth = 0, out = []) {
95
+ if (depth > 10 || node === null || typeof node !== 'object') return out
96
+ if (Array.isArray(node)) { for (const item of node) findClaimButtons(item, depth + 1, out); return out }
97
+ const type = node.action?.type ?? node.action_type ?? node.type
98
+ if (typeof type === 'string' && /claim/i.test(type)) out.push(node)
99
+ for (const value of Object.values(node)) findClaimButtons(value, depth + 1, out)
100
+ return out
101
+ }
102
+
103
+ const fmt = (sec) => (typeof sec === 'number' && sec > 0 ? new Date(sec * 1000).toLocaleString([], { hour12: false }) : '-')
104
+
105
+ async function once(credential) {
106
+ const headers = headersFor(credential)
107
+ const [marketing, balance] = await Promise.all([
108
+ fetch(`${ORIGIN}/api/v1/marketing/touch?seq=0`, { headers, signal: AbortSignal.timeout(25_000) })
109
+ .then(async (r) => ({ status: r.status, json: await r.json().catch(() => undefined) }))
110
+ .catch((e) => ({ status: undefined, error: String(e?.message ?? e) })),
111
+ fetch(`${ORIGIN}/api/v1/zcode-plan/billing/balance`, { headers, signal: AbortSignal.timeout(25_000) })
112
+ .then(async (r) => ({ status: r.status, json: await r.json().catch(() => undefined) }))
113
+ .catch((e) => ({ status: undefined, error: String(e?.message ?? e) })),
114
+ ])
115
+ const deliveries = marketing.json?.data?.deliveries
116
+ const plans = Array.isArray(balance.json?.data?.plans) ? balance.json.data.plans : []
117
+ const buckets = Array.isArray(balance.json?.data?.balances) ? balance.json.data.balances : []
118
+ const claims = Array.isArray(deliveries) ? deliveries.flatMap((d) => findClaimButtons(d)) : []
119
+ return {
120
+ serverTime: balance.json?.data?.server_time ?? marketing.json?.data?.server_time,
121
+ marketingStatus: marketing.status,
122
+ deliveries: Array.isArray(deliveries) ? deliveries.length : `非数组(${typeof deliveries})`,
123
+ claimButtons: claims.length,
124
+ plans: plans.map((p) => ({ id: p.plan_id, status: p.status, starts_at: fmt(p.starts_at), ends_at: fmt(p.ends_at) })),
125
+ buckets: buckets.map((b) => ({ plan: b.plan_id, total: b.total_units, used: b.used_units, remaining: b.remaining_units })),
126
+ }
127
+ }
128
+
129
+ const { credential, nickname } = await loadCredential(accountId)
130
+ const deadline = Date.now() + forMinutes * 60_000
131
+ console.log(`盯守 ${nickname} (${accountId}) 间隔 ${intervalSec}s 上限 ${forMinutes} 分钟`)
132
+ console.log('(只读:不 claim、不 mint captcha、不发 confirm/cancel)\n')
133
+
134
+ let round = 0
135
+ while (Date.now() < deadline) {
136
+ round += 1
137
+ const startedAt = new Date().toLocaleTimeString([], { hour12: false })
138
+ const result = await once(credential)
139
+ const hit = result.claimButtons > 0 || result.plans.length > 0 || result.buckets.length > 0
140
+ console.log(
141
+ `[${startedAt}] #${round} server_time=${result.serverTime} ` +
142
+ `deliveries=${result.deliveries} claimButtons=${result.claimButtons} plans=${result.plans.length} buckets=${result.buckets.length}` +
143
+ `${hit ? ' ← 命中' : ''}`,
144
+ )
145
+ if (result.plans.length > 0) console.log(` plans: ${JSON.stringify(result.plans)}`)
146
+ if (result.buckets.length > 0) console.log(` buckets: ${JSON.stringify(result.buckets)}`)
147
+ if (hit) {
148
+ console.log('\n已观察到活动投放/权益,停止盯守。')
149
+ process.exit(0)
150
+ }
151
+ const wait = Math.min(intervalSec * 1000, deadline - Date.now())
152
+ if (wait > 0) await new Promise((resolve) => setTimeout(resolve, wait))
153
+ }
154
+ console.log(`\n${forMinutes} 分钟内未观察到任何投放或权益 —— 该账号在此期间确实没有被下发。`)
155
+ process.exitCode = 0
@@ -0,0 +1,305 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+
4
+ import {
5
+ OFFICIAL_CLI_PREFIX,
6
+ OFFICIAL_STABLE_SECTIONS,
7
+ buildUpstreamBody,
8
+ buildZcodeSystemBlocks,
9
+ convertContent,
10
+ convertTools,
11
+ imageBlockFromAttachment,
12
+ imageOccurrences,
13
+ resolveImages,
14
+ withContextPrefix,
15
+ } from '../lib/anthropic-body.js'
16
+
17
+ const userMessage = (text) => ({ role: 'user', content: [{ type: 'text', text }] })
18
+
19
+ test('身份块必须打头(3012 的准入判据)', () => {
20
+ const blocks = buildZcodeSystemBlocks('CALLER SYSTEM', { cwd: 'C:/w' })
21
+ assert.equal(blocks[0].text, OFFICIAL_CLI_PREFIX)
22
+ assert.equal(blocks[1].text, OFFICIAL_STABLE_SECTIONS.join('\n\n'))
23
+ assert.match(blocks[2].text, /# Environment/)
24
+ /** 调用方内容追加在最后 —— 前置会顶掉官方前缀结构。 */
25
+ assert.equal(blocks[blocks.length - 1].text, 'CALLER SYSTEM')
26
+ })
27
+
28
+ test('只在最后一块打 cache_control(单请求最多 4 个断点)', () => {
29
+ const blocks = buildZcodeSystemBlocks('x', { cwd: '.' })
30
+ const withCache = blocks.filter((block) => block.cache_control !== undefined)
31
+ assert.equal(withCache.length, 1)
32
+ assert.equal(blocks[blocks.length - 1].cache_control.type, 'ephemeral')
33
+ })
34
+
35
+ test('首轮 user 消息插入日期块,且幂等', () => {
36
+ const once = withContextPrefix([userMessage('hi')], new Date(2026, 9, 23))
37
+ const first = once[0].content[0]
38
+ assert.match(first.text, /^<system-reminder>/)
39
+ assert.match(first.text, /Today's date is 2026-10-23\./)
40
+ assert.equal(once[0].content[1].text, 'hi')
41
+
42
+ const twice = withContextPrefix(once, new Date(2026, 9, 24))
43
+ assert.equal(twice[0].content.length, 2, '已带日期块的消息不得重复插入')
44
+ })
45
+
46
+ test('日期块只进第一条 user 消息(纯文本 content 会被转成块数组)', () => {
47
+ const messages = withContextPrefix(
48
+ [
49
+ { role: 'user', content: 'hello' },
50
+ { role: 'assistant', content: 'world' },
51
+ ],
52
+ new Date(2026, 9, 23),
53
+ )
54
+ assert.ok(Array.isArray(messages[0].content))
55
+ assert.match(messages[0].content[0].text, /system-reminder/)
56
+ assert.equal(messages[1].content, 'world')
57
+ })
58
+
59
+ test('convertTools: 只在最后一个 tool 打断点,并剥掉 $schema / additionalProperties', () => {
60
+ const tools = convertTools([
61
+ { name: 'a', description: 'A', parameters: { type: 'object', properties: {}, $schema: 'x', additionalProperties: false } },
62
+ { name: 'b', parameters: { type: 'object', properties: {} } },
63
+ { name: 'no-schema' },
64
+ ])
65
+ assert.equal(tools.length, 2, '缺 parameters 的工具被跳过')
66
+ assert.equal(tools[0].cache_control, undefined)
67
+ assert.deepEqual(tools[1].cache_control, { type: 'ephemeral' })
68
+ assert.equal(tools[0].input_schema.$schema, undefined)
69
+ assert.equal(tools[0].input_schema.additionalProperties, undefined)
70
+ })
71
+
72
+ test('buildUpstreamBody: DSH 工具调用/结果翻成 Anthropic 块', () => {
73
+ const body = buildUpstreamBody({
74
+ options: {
75
+ model: 'GLM-5.3-Flash',
76
+ system: [{ type: 'text', text: 'SYS' }],
77
+ maxTokens: 1000,
78
+ messages: [
79
+ { role: 'user', content: [{ type: 'text', text: 'list files' }] },
80
+ {
81
+ role: 'assistant',
82
+ content: [{ type: 'tool-call', id: 'call_1', name: 'pwsh', arguments: { cmd: 'ls' } }],
83
+ },
84
+ { role: 'user', content: [{ type: 'tool-result', toolCallId: 'call_1', output: 'a.txt' }] },
85
+ ],
86
+ tools: [{ name: 'pwsh', parameters: { type: 'object', properties: {} } }],
87
+ temperature: 0.2,
88
+ },
89
+ cwd: 'C:/w',
90
+ maxTokens: 1000,
91
+ })
92
+
93
+ assert.equal(body.model, 'GLM-5.3-Flash')
94
+ assert.equal(body.stream, true)
95
+ assert.equal(body.max_tokens, 1000)
96
+ assert.equal(body.temperature, 0.2)
97
+ assert.equal(body.messages[0].role, 'user')
98
+ assert.match(body.messages[0].content[0].text, /system-reminder/)
99
+
100
+ const assistant = body.messages[1]
101
+ const toolUse = assistant.content.find((block) => block.type === 'tool_use')
102
+ assert.equal(toolUse.id, 'call_1')
103
+ assert.equal(toolUse.name, 'pwsh')
104
+ assert.deepEqual(toolUse.input, { cmd: 'ls' })
105
+
106
+ const toolResult = body.messages[2].content.find((block) => block.type === 'tool_result')
107
+ assert.equal(toolResult.tool_use_id, 'call_1')
108
+ assert.equal(toolResult.content, 'a.txt')
109
+
110
+ assert.equal(body.tools[0].cache_control.type, 'ephemeral')
111
+ })
112
+
113
+ test('buildUpstreamBody: 回放宿主保存的 JSON 字符串工具参数时,tool_use.input 必须是对象', () => {
114
+ const body = buildUpstreamBody({
115
+ options: {
116
+ model: 'GLM-5.3-Flash',
117
+ messages: [
118
+ userMessage('运行命令'),
119
+ { role: 'assistant', content: [{
120
+ type: 'tool-call', id: 'call_pwsh', name: 'pwsh',
121
+ arguments: '{"description":"列出文件","command":"Get-ChildItem","options":{"cwd":"C:/w"}}',
122
+ }] },
123
+ ],
124
+ },
125
+ now: new Date(2026, 9, 24),
126
+ })
127
+ assert.deepEqual(body.messages[1].content[0].input, {
128
+ description: '列出文件', command: 'Get-ChildItem', options: { cwd: 'C:/w' },
129
+ })
130
+ })
131
+
132
+ test('buildUpstreamBody: 不向历史回放思考块', () => {
133
+ const body = buildUpstreamBody({
134
+ options: {
135
+ model: 'GLM-5.3',
136
+ messages: [
137
+ userMessage('hi'),
138
+ { role: 'assistant', content: [{ type: 'reasoning', text: 'thinking…' }, { type: 'text', text: 'ok' }] },
139
+ ],
140
+ },
141
+ })
142
+ const assistant = body.messages[1]
143
+ assert.deepEqual(assistant.content.map((block) => block.type), ['text'])
144
+ })
145
+
146
+ test('buildUpstreamBody: 不支持图片的模型收到占位文本', () => {
147
+ const body = buildUpstreamBody({
148
+ options: {
149
+ model: 'GLM-5.3',
150
+ messages: [
151
+ {
152
+ role: 'user',
153
+ content: [
154
+ { type: 'text', text: 'see' },
155
+ { type: 'image', source: { type: 'base64', media_type: 'image/png', data: 'AAAA' } },
156
+ ],
157
+ },
158
+ ],
159
+ },
160
+ supportsImages: false,
161
+ })
162
+ const blocks = body.messages[0].content
163
+ assert.equal(blocks.some((block) => block.type === 'image'), false)
164
+ assert.match(blocks.map((block) => block.text).join('|'), /image omitted/)
165
+ })
166
+
167
+ // ---------------------------------------------------------------------------
168
+ // 图片输入:宿主 ImageBlock(持久引用)→ 附件服务字节 → Anthropic base64 块。
169
+ // 宿主契约:`dsh-llm` 的 ImageBlock 是 `{ type:'image', attachment: ref }`,
170
+ // ref = `{ attachmentId:'sha256:<hex>', mediaType, width, height, bytes, name? }`
171
+ // (attachment-local 实测)。此前 convertContent 只认 base64 形态,
172
+ // 引用块被静默丢弃 —— 用户发图但上游什么都没收到。
173
+ // ---------------------------------------------------------------------------
174
+
175
+ const PNG_REF = {
176
+ attachmentId: 'sha256:abcd1234ef567890',
177
+ mediaType: 'image/png',
178
+ width: 64,
179
+ height: 32,
180
+ bytes: 100,
181
+ }
182
+
183
+ const FAKE_BYTES = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10])
184
+
185
+ test('imageOccurrences: 识别宿主持久引用与内联 base64 两种形态', () => {
186
+ const blocks = [
187
+ { type: 'text', text: 'see' },
188
+ { type: 'image', attachment: PNG_REF },
189
+ { type: 'image', source: { type: 'base64', media_type: 'image/jpeg', data: 'QQ==' } },
190
+ { type: 'file', attachment: { attachmentId: 'sha256:file' } },
191
+ ]
192
+ const found = imageOccurrences(blocks)
193
+ assert.equal(found.length, 2)
194
+ assert.equal(found[0].attachmentId, PNG_REF.attachmentId)
195
+ assert.deepEqual(found[0].ref, PNG_REF)
196
+ assert.equal(found[1].attachmentId, 'inline:2')
197
+ assert.equal(found[1].inline.mediaType, 'image/jpeg')
198
+ })
199
+
200
+ test('imageBlockFromAttachment: 字节编码为 Anthropic base64 块', () => {
201
+ const block = imageBlockFromAttachment(PNG_REF, FAKE_BYTES)
202
+ assert.equal(block.type, 'image')
203
+ assert.equal(block.source.type, 'base64')
204
+ assert.equal(block.source.media_type, 'image/png')
205
+ assert.equal(Buffer.from(block.source.data, 'base64').compare(Buffer.from(FAKE_BYTES)), 0)
206
+ })
207
+
208
+ test('convertContent: 持久引用 + 已解析字节 → base64 image 块', () => {
209
+ const blocks = convertContent(
210
+ [
211
+ { type: 'text', text: 'look' },
212
+ { type: 'image', attachment: PNG_REF },
213
+ ],
214
+ { resolvedImages: new Map([[PNG_REF.attachmentId, { data: FAKE_BYTES, ref: PNG_REF }]]) },
215
+ )
216
+ assert.equal(blocks[0].type, 'text')
217
+ assert.equal(blocks[1].type, 'image')
218
+ assert.equal(blocks[1].source.type, 'base64')
219
+ assert.equal(blocks[1].source.media_type, 'image/png')
220
+ })
221
+
222
+ test('convertContent: 引用解析失败 → 占位文本(不再静默丢弃)', () => {
223
+ const blocks = convertContent([{ type: 'image', attachment: PNG_REF }], { resolvedImages: new Map() })
224
+ assert.equal(blocks.length, 1)
225
+ assert.equal(blocks[0].type, 'text')
226
+ assert.match(blocks[0].text, /image omitted/)
227
+ })
228
+
229
+ test('resolveImages: 经附件服务 readImageRequest 解析引用字节', async () => {
230
+ const calls = []
231
+ const attachments = {
232
+ async readImageRequest(ref, target, signal) {
233
+ calls.push({ ref, target, signal })
234
+ return { attachment: ref, data: FAKE_BYTES, mediaType: 'image/png', width: 64, height: 32, bytes: 8 }
235
+ },
236
+ }
237
+ const resolved = await resolveImages(
238
+ [
239
+ {
240
+ role: 'user',
241
+ content: [{ type: 'text', text: 'hi' }, { type: 'image', attachment: PNG_REF }],
242
+ },
243
+ ],
244
+ { resolveAttachments: () => attachments },
245
+ )
246
+ assert.equal(calls.length, 1)
247
+ assert.equal(calls[0].ref.attachmentId, PNG_REF.attachmentId)
248
+ assert.equal(calls[0].target.width, 64)
249
+ assert.equal(calls[0].target.height, 32)
250
+ assert.equal(resolved.get(PNG_REF.attachmentId).data, FAKE_BYTES)
251
+ })
252
+
253
+ test('resolveImages: 附件服务缺席 → 空 Map(图片降级占位)', async () => {
254
+ const resolved = await resolveImages([{ role: 'user', content: [{ type: 'image', attachment: PNG_REF }] }], {})
255
+ assert.equal(resolved.size, 0)
256
+ })
257
+
258
+ test('resolveImages: 单张解析失败不影响其余图片', async () => {
259
+ const badRef = { ...PNG_REF, attachmentId: 'sha256:badbadbadbadbad' }
260
+ const attachments = {
261
+ async readImageRequest(ref) {
262
+ if (ref.attachmentId === badRef.attachmentId) throw new Error('boom')
263
+ return { attachment: ref, data: FAKE_BYTES }
264
+ },
265
+ }
266
+ const resolved = await resolveImages(
267
+ [
268
+ {
269
+ role: 'user',
270
+ content: [{ type: 'image', attachment: PNG_REF }, { type: 'image', attachment: badRef }],
271
+ },
272
+ ],
273
+ { resolveAttachments: () => attachments },
274
+ )
275
+ assert.equal(resolved.size, 1)
276
+ assert.ok(resolved.has(PNG_REF.attachmentId))
277
+ assert.ok(!resolved.has(badRef.attachmentId))
278
+ })
279
+
280
+ test('buildUpstreamBody: 宿主引用图片端到端进入上游请求体', () => {
281
+ const body = buildUpstreamBody({
282
+ options: {
283
+ model: 'GLM-5.3-Flash',
284
+ messages: [
285
+ {
286
+ role: 'user',
287
+ content: [
288
+ { type: 'text', text: '这张图里有什么?' },
289
+ { type: 'image', attachment: PNG_REF },
290
+ ],
291
+ },
292
+ ],
293
+ },
294
+ supportsImages: true,
295
+ resolvedImages: new Map([[PNG_REF.attachmentId, { data: FAKE_BYTES, ref: PNG_REF }]]),
296
+ })
297
+ const content = body.messages[0].content
298
+ assert.deepEqual(
299
+ content.map((block) => block.type),
300
+ ['text', 'text', 'image'],
301
+ '图片必须以 image 块进入上游请求(此前被静默丢弃);首位是日期块',
302
+ )
303
+ assert.equal(content[2].source.type, 'base64')
304
+ assert.equal(content[2].source.media_type, 'image/png')
305
+ })